|
| 1 | +import { NextRequest, NextResponse } from "next/server"; |
| 2 | + |
| 3 | +export const runtime = "nodejs"; |
| 4 | + |
| 5 | +function extractMeta(html: string, property: string): string | null { |
| 6 | + const patterns = [ |
| 7 | + new RegExp( |
| 8 | + `<meta[^>]+(?:property|name)=["']${property}["'][^>]+content=["']([^"']*)["']`, |
| 9 | + "i", |
| 10 | + ), |
| 11 | + new RegExp( |
| 12 | + `<meta[^>]+content=["']([^"']*)["'][^>]+(?:property|name)=["']${property}["']`, |
| 13 | + "i", |
| 14 | + ), |
| 15 | + ]; |
| 16 | + for (const pattern of patterns) { |
| 17 | + const match = html.match(pattern); |
| 18 | + if (match) return match[1]; |
| 19 | + } |
| 20 | + return null; |
| 21 | +} |
| 22 | + |
| 23 | +function extractTitleTag(html: string): string | null { |
| 24 | + const match = html.match(/<title[^>]*>([^<]+)<\/title>/i); |
| 25 | + return match ? match[1] : null; |
| 26 | +} |
| 27 | + |
| 28 | +function decodeHtmlEntities(str: string): string { |
| 29 | + return str |
| 30 | + .replace(/&/g, "&") |
| 31 | + .replace(/"/g, '"') |
| 32 | + .replace(/'/g, "'") |
| 33 | + .replace(/</g, "<") |
| 34 | + .replace(/>/g, ">"); |
| 35 | +} |
| 36 | + |
| 37 | +const PRIVATE_HOSTNAME_PATTERNS = [ |
| 38 | + /^localhost$/i, |
| 39 | + /^0\.0\.0\.0$/, |
| 40 | + /^127\./, |
| 41 | + /^10\./, |
| 42 | + /^172\.(1[6-9]|2[0-9]|3[0-1])\./, |
| 43 | + /^192\.168\./, |
| 44 | + /^169\.254\./, |
| 45 | + /^::1$/, |
| 46 | + /^fc00:/i, |
| 47 | + /^fe80:/i, |
| 48 | +]; |
| 49 | + |
| 50 | +function isSafeUrl(candidate: string): boolean { |
| 51 | + let parsed: URL; |
| 52 | + try { |
| 53 | + parsed = new URL(candidate); |
| 54 | + } catch { |
| 55 | + return false; |
| 56 | + } |
| 57 | + if (!["http:", "https:"].includes(parsed.protocol)) { |
| 58 | + return false; |
| 59 | + } |
| 60 | + const hostname = parsed.hostname.toLowerCase(); |
| 61 | + return !PRIVATE_HOSTNAME_PATTERNS.some((pattern) => pattern.test(hostname)); |
| 62 | +} |
| 63 | + |
| 64 | +export async function GET(request: NextRequest) { |
| 65 | + const { searchParams } = new URL(request.url); |
| 66 | + const url = searchParams.get("url"); |
| 67 | + |
| 68 | + if (!url) { |
| 69 | + return NextResponse.json({ error: "missing url" }, { status: 400 }); |
| 70 | + } |
| 71 | + |
| 72 | + if (!isSafeUrl(url)) { |
| 73 | + return NextResponse.json( |
| 74 | + { error: "invalid or disallowed url" }, |
| 75 | + { status: 400 }, |
| 76 | + ); |
| 77 | + } |
| 78 | + |
| 79 | + try { |
| 80 | + const controller = new AbortController(); |
| 81 | + const timeout = setTimeout(() => controller.abort(), 5000); |
| 82 | + |
| 83 | + const res = await fetch(url, { |
| 84 | + signal: controller.signal, |
| 85 | + redirect: "error", |
| 86 | + headers: { |
| 87 | + "User-Agent": |
| 88 | + "Mozilla/5.0 (compatible; LinkPreviewBot/1.0; +https://example.com/bot)", |
| 89 | + }, |
| 90 | + }); |
| 91 | + |
| 92 | + clearTimeout(timeout); |
| 93 | + |
| 94 | + if (!res.ok) { |
| 95 | + return NextResponse.json({ error: "failed to fetch" }, { status: 502 }); |
| 96 | + } |
| 97 | + |
| 98 | + const contentLength = res.headers.get("content-length"); |
| 99 | + if (contentLength && parseInt(contentLength, 10) > 1024 * 1024) { |
| 100 | + return NextResponse.json( |
| 101 | + { error: "response too large" }, |
| 102 | + { status: 502 }, |
| 103 | + ); |
| 104 | + } |
| 105 | + |
| 106 | + const html = await res.text(); |
| 107 | + if (html.length > 1024 * 1024) { |
| 108 | + return NextResponse.json( |
| 109 | + { error: "response too large" }, |
| 110 | + { status: 502 }, |
| 111 | + ); |
| 112 | + } |
| 113 | + |
| 114 | + const rawTitle = extractMeta(html, "og:title") || extractTitleTag(html); |
| 115 | + const rawDescription = |
| 116 | + extractMeta(html, "og:description") || extractMeta(html, "description"); |
| 117 | + const rawImage = extractMeta(html, "og:image"); |
| 118 | + |
| 119 | + let image: string | null = null; |
| 120 | + if (rawImage) { |
| 121 | + try { |
| 122 | + const resolvedImage = new URL(rawImage, url).toString(); |
| 123 | + image = isSafeUrl(resolvedImage) ? resolvedImage : null; |
| 124 | + } catch { |
| 125 | + image = null; |
| 126 | + } |
| 127 | + } |
| 128 | + |
| 129 | + return NextResponse.json( |
| 130 | + { |
| 131 | + title: rawTitle ? decodeHtmlEntities(rawTitle).trim() : null, |
| 132 | + description: rawDescription |
| 133 | + ? decodeHtmlEntities(rawDescription).trim() |
| 134 | + : null, |
| 135 | + image, |
| 136 | + url, |
| 137 | + }, |
| 138 | + { headers: { "Cache-Control": "public, max-age=3600" } }, |
| 139 | + ); |
| 140 | + } catch { |
| 141 | + return NextResponse.json({ error: "failed to fetch" }, { status: 502 }); |
| 142 | + } |
| 143 | +} |
0 commit comments