Files
co-lite/solvway-admin-portal/app/lib/server/publicProxy.ts
T

26 lines
1.4 KiB
TypeScript

import "server-only";
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { clientIp } from "@/app/lib/server/clientContext";
import { errorResponse } from "@/app/lib/server/apiRoute";
// Public (signed-out) proxy to mobile-api: no session token.
// X-Forwarded-For is rebuilt from clientIp(req) only (the LAST hop, same trusted rule as X-Client-Ip):
// client-written entries in an incoming header are never forwarded, so the rate-limit key cannot be spoofed.
export type TokenCtx = { params: Promise<{ token: string }> };
export async function forwardPublic(req: NextRequest, path: string, method: "GET" | "POST") {
const xff = clientIp(req);
const headers: Record<string, string> = xff ? { "X-Forwarded-For": xff } : {};
const result = await callMobileApi<Record<string, unknown>>(
path,
method === "GET" ? { headers } : { method, body: await req.json().catch(() => ({})), headers },
);
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data);
}
/** Route handler for `/api/public/<prefix>/<token><suffix>`. */
export const publicRoute = (prefix: string, suffix: string, method: "GET" | "POST") =>
async (req: NextRequest, { params }: TokenCtx) => forwardPublic(req, `/api/public/${prefix}/${encodeURIComponent((await params).token)}${suffix}`, method);