Part of tasks 5.1/5.2 (not ticked): one catch-all proxy at /api/whatsapp (media served with nosniff and a sandbox CSP), typed client calls, and usePolling that pauses while the tab is hidden. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
42 lines
2.0 KiB
TypeScript
42 lines
2.0 KiB
TypeScript
import { NextResponse, type NextRequest } from "next/server";
|
|
import { callMobileApi, callMobileApiBinary } from "@/app/lib/server/mobileApi";
|
|
import { getToken } from "@/app/lib/server/session";
|
|
import { badRequest, errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
|
|
|
|
// One proxy for every /api/admin/whatsapp endpoint; mobile-api owns validation and the BO_WHATSAPP guards.
|
|
type Ctx = { params: Promise<{ path?: string[] }> };
|
|
|
|
async function forward(req: NextRequest, { params }: Ctx, method?: "POST") {
|
|
const token = await getToken();
|
|
if (!token) return unauthorized();
|
|
const { path = [] } = await params;
|
|
if (path.some((s) => s === "." || s === "..")) return badRequest("Invalid path.");
|
|
const target = `/api/admin/whatsapp${path.map(encodeURIComponent).map((s) => `/${s}`).join("")}${new URL(req.url).search}`;
|
|
|
|
if (!method && path[0] === "media") {
|
|
// ponytail: buffers the file (mobile-api caps it at 100 MB); stream the upstream body if large documents become common.
|
|
const media = await callMobileApiBinary(target, { token });
|
|
if (!media.ok) return errorResponse(media);
|
|
const { body, contentType, contentDisposition } = media.data;
|
|
return new NextResponse(body, {
|
|
headers: {
|
|
"Content-Type": contentType ?? "application/octet-stream",
|
|
...(contentDisposition ? { "Content-Disposition": contentDisposition } : {}),
|
|
// The type is whatever the sender declared: never let it run as a page on this origin.
|
|
"X-Content-Type-Options": "nosniff",
|
|
"Content-Security-Policy": "sandbox",
|
|
"Cache-Control": "private, no-store",
|
|
},
|
|
});
|
|
}
|
|
|
|
const result = method
|
|
? await callMobileApi<unknown>(target, { method, body: await req.json().catch(() => ({})), token })
|
|
: await callMobileApi<unknown>(target, { token });
|
|
if (!result.ok) return errorResponse(result);
|
|
return NextResponse.json(result.data ?? null);
|
|
}
|
|
|
|
export const GET = (req: NextRequest, ctx: Ctx) => forward(req, ctx);
|
|
export const POST = (req: NextRequest, ctx: Ctx) => forward(req, ctx, "POST");
|