/** * หา "origin" ของคำขอนี้ (เช่น `https://alterflixhub.hobbypj.com`, `http://localhost:8080`) * * ใช้แทนการฮาร์ดโค้ดโดเมน: canonical / OG / sitemap / robots มาจาก request จริงทุกครั้ง * รองรับหลัง reverse proxy (Cloudflare, Nginx, Vercel) ที่ส่ง `x-forwarded-host` / `x-forwarded-proto` */ /** header ที่อ่านได้ — รองรับทั้ง `Headers`, plain object ของ h3 และค่า undefined */ export type HeaderSource = | { get(name: string): string | null } | Record; /** ตัด `/` ท้าย, เติม scheme ให้ถ้าไม่มี, คืน "" ถ้าว่าง */ export function normalizeOrigin(value: string): string { const trimmed = value.trim().replace(/\/+$/, ""); if (trimmed === "") return ""; return /^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}`; } function readHeader(source: HeaderSource, name: string): string { if (typeof (source as { get?: unknown }).get === "function") { const value = (source as { get(n: string): string | null }).get(name); return typeof value === "string" ? value : ""; } const record = source as Record; const value = record[name.toLowerCase()] ?? record[name]; if (Array.isArray(value)) return value[0] ?? ""; return typeof value === "string" ? value : ""; } /** ค่าแรกก่อนจุลภาค (`a, b` → `a`) — proxy บางตัวต่อ host หลายชั้น */ function firstValue(value: string): string { return value.split(",")[0]?.trim() ?? ""; } export function originFromHeaders( source: HeaderSource, fallbackProto = "https", ): string { const forwardedHost = firstValue(readHeader(source, "x-forwarded-host")); const host = forwardedHost !== "" ? forwardedHost : firstValue(readHeader(source, "host")); if (host === "") return ""; // proxy ที่ไม่ส่ง x-forwarded-proto → ใช้โปรโตคอลจริงของคำขอ (dev = http) const forwardedProto = firstValue(readHeader(source, "x-forwarded-proto")); const proto = forwardedProto !== "" ? forwardedProto : fallbackProto; return normalizeOrigin(`${proto}://${host}`); } /** origin ของ Request (ใช้ใน loader / resource route) */ export function originFromRequest(request: Request): string { let protocol = "https"; try { protocol = new URL(request.url).protocol.replace(":", ""); } catch { // URL เพี้ยน → ใช้ค่าเริ่มต้น } const fromHeaders = originFromHeaders(request.headers, protocol); if (fromHeaders !== "") return fromHeaders; // ไม่มี header host (เช่นเรียกภายใน) → ใช้ URL ที่ framework สร้างให้ try { return normalizeOrigin(new URL(request.url).origin); } catch { return ""; } }