SPB Git

Repository Public

images.ts 4.9 KB 84 lines typescript

1// Mandataire d'images distantes : utilisé seulement quand la personne choisit d'afficher les images d'un message.2// Le serveur d'images ne voit ni l'adresse IP, ni les cookies, ni le navigateur du lecteur. Protégé contre le SSRF.3import type { FastifyInstance } from "fastify"4import dns from "node:dns/promises"5import net from "node:net"6import { requireUser } from "./session.js"7import { bad, rateLimit } from "./util.js"89const blocked = new net.BlockList()10for (const [net4, 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.168.0.0", 16], ["198.18.0.0", 15], ["224.0.0.0", 3]] as const)11  blocked.addSubnet(net4, bits, "ipv4")12// fc00::/7 (ULA), fe80::/10 (lien local), ff00::/8 (multidiffusion), et les préfixes qui embarquent une adresse IPv4 (NAT64, 6to4).13for (const [net6, bits] of [["fc00::", 7], ["fe80::", 10], ["ff00::", 8], ["64:ff9b::", 96], ["2002::", 16]] as const) blocked.addSubnet(net6, bits, "ipv6")14blocked.addAddress("::", "ipv6")15blocked.addAddress("::1", "ipv6")1617/** Octets d'une adresse IPv6 (gère « :: » et la forme à quatre décimales pointées finale) ; null si mal formée. */18function v6bytes(ip: string): number[] | null {19  let s = ip.toLowerCase().split("%")[0]20  const tail: number[] = []21  const m = /^(.*:)(\d+\.\d+\.\d+\.\d+)$/.exec(s)22  if (m) {23    const q = m[2].split(".").map(Number)24    if (q.some((x) => x > 255)) return null25    tail.push(...q)26    s = m[1] === "::" ? "::" : m[1].replace(/:$/, m[1].endsWith("::") ? ":" : "")27  }28  const [head, rest] = s.includes("::") ? s.split("::") : [s, null]29  const part = (x: string) => (x ? x.split(":").flatMap((h) => { const v = parseInt(h || "0", 16); return [v >> 8, v & 255] }) : [])30  const a = part(head), b = rest === null ? [] : part(rest)31  const total = 16 - tail.length32  if (rest === null ? a.length !== total : a.length + b.length > total) return null33  return [...a, ...new Array(total - a.length - b.length).fill(0), ...b, ...tail]34}3536/** Vrai pour toute adresse privée, locale, de lien local, CGNAT, multidiffusion ou réservée — y compris une IPv4 projetée dans une IPv6 (::ffff:a.b.c.d sous toutes ses écritures). */37export function isPrivate(ip: string): boolean {38  if (net.isIPv4(ip)) return blocked.check(ip, "ipv4")39  if (!net.isIPv6(ip)) return true // ni IPv4 ni IPv6 : refusé40  const b = v6bytes(ip)41  if (!b || b.length !== 16) return true42  // ::ffff:a.b.c.d (projetée) et ::a.b.c.d (compatible, obsolète) : jugées comme l'IPv4 qu'elles portent43  if (b.slice(0, 10).every((x) => x === 0) && ((b[10] === 255 && b[11] === 255) || (b[10] === 0 && b[11] === 0 && (b[12] | b[13] | b[14]) !== 0))) return blocked.check(b.slice(12).join("."), "ipv4")44  return blocked.check(ip.split("%")[0], "ipv6")45}4647export async function assertPublicUrl(raw: string): Promise<URL> {48  let u: URL49  try { u = new URL(raw) } catch { throw bad("invalid_url", 400) }50  if (u.protocol !== "https:" && u.protocol !== "http:") throw bad("invalid_url", 400)51  if (u.username || u.password) throw bad("invalid_url", 400)52  if (u.port && !["80", "443", ""].includes(u.port)) throw bad("invalid_url", 400)53  const host = u.hostname.replace(/^\[|\]$/g, "")54  const addrs = net.isIP(host) ? [{ address: host }] : await dns.lookup(host, { all: true }).catch(() => [])55  if (!addrs.length || addrs.some((a) => isPrivate(a.address))) throw bad("forbidden_destination", 403)56  return u57}5859const MAX = 10 * 1024 * 102460export function imageRoutes(app: FastifyInstance) {61  app.get("/api/img", async (req, reply) => {62    const a = await requireUser(req)63    rateLimit(`img:${a.sessionId}`, 300, 60_000)64    let url = await assertPublicUrl(String((req.query as { u?: string }).u ?? ""))65    let r: Response | undefined66    for (let hop = 0; hop < 4; hop++) {67      r = await fetch(url, { redirect: "manual", headers: { accept: "image/*", "user-agent": "SPMail-ImageProxy" }, signal: AbortSignal.timeout(15_000) }).catch(() => undefined)68      if (!r) throw bad("fetch_failed", 502)69      if (r.status >= 300 && r.status < 400 && r.headers.get("location")) {70        url = await assertPublicUrl(new URL(r.headers.get("location")!, url).toString()) // chaque redirection est revérifiée71        continue72      }73      break74    }75    if (!r || !r.ok) throw bad("fetch_failed", 502)76    const type = (r.headers.get("content-type") ?? "").split(";")[0].trim().toLowerCase()77    if (!/^image\/(png|jpeg|gif|webp|avif|bmp|x-icon|vnd\.microsoft\.icon)$/.test(type)) throw bad("not_an_image", 415) // SVG exclu (scripts)78    if (Number(r.headers.get("content-length") ?? 0) > MAX) throw bad("too_large", 413)79    const buf = Buffer.from(await r.arrayBuffer())80    if (buf.length > MAX) throw bad("too_large", 413)81    return reply.header("content-type", type).header("cache-control", "private, max-age=86400").header("content-security-policy", "sandbox; default-src 'none'").send(buf)82  })83}84
Files main
Menu

Theme