import { withBase } from "@/lib/base-path"; import { NextResponse } from "next/server"; import { safeFacebookErrorMessage, UserFacingError, FacebookApiError } from "@/lib/facebook/client"; export async function readJson(req: Request): Promise> { const body = await req.json().catch(() => null); return body && typeof body === "object" ? (body as Record) : {}; } export const str = (v: unknown): string => (typeof v === "string" ? v : ""); export const optStr = (v: unknown): string | null => (typeof v === "string" && v.trim() ? v.trim() : null); /** Maps thrown errors to a safe JSON response: UserFacingError → 400, Graph → 502, other → 500. */ export function errorResponse(e: unknown, context: string): NextResponse { const message = safeFacebookErrorMessage(e, context); const status = e instanceof UserFacingError ? 400 : e instanceof FacebookApiError ? 502 : 500; return NextResponse.json({ error: message }, { status }); } /** * 200 HTML page that meta-refreshes to `path`. OAuth callbacks arrive as a * cross-site navigation, so a 302 onward would still be cross-site and the * SameSite=Strict session cookie would not be sent; a navigation started by * this page is same-site. `path` must already be a validated same-origin path. */ export function htmlRedirect(path: string): Response { const safe = withBase(path).replace(/&/g, "&").replace(/"/g, """).replace(//g, ">"); const html = `กำลังกลับสู่ระบบ…

กำลังกลับสู่ระบบ… ไปต่อ

`; return new Response(html, { headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" } }); } /** * Sends the browser to an absolute external URL (Facebook / Google dialogs) with * a 200 HTML meta-refresh instead of a 3xx `Location`. Behind an IIS ARR reverse * proxy (loma.chat/pagiva) the machine-level `reverseRewriteHostInResponseHeaders` * rewrites the host of any `Location` header to the public host, which turned * https://www.facebook.com/v21.0/dialog/oauth into https://loma.chat/v21.0/... * A response body is never rewritten. Returns a NextResponse so callers can set cookies. */ export function externalRedirect(url: string): NextResponse { const target = new URL(url); if (target.protocol !== "https:") throw new Error("externalRedirect requires an https URL"); const safe = target.toString().replace(/&/g, "&").replace(/"/g, """).replace(//g, ">"); const html = `กำลังไปยังหน้าเข้าสู่ระบบ…

กำลังไปยังหน้าเข้าสู่ระบบ… ไปต่อ

`; return new NextResponse(html, { headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" } }); } /** Cron routes authenticate with `Authorization: Bearer ${CRON_SECRET}` (Vercel Cron sends it). */ export function cronAuthorized(req: Request): boolean { const secret = process.env.CRON_SECRET; return Boolean(secret) && req.headers.get("authorization") === `Bearer ${secret}`; }