/** * 📄 Proxy Route * API 프록시 라우트 * * - 서버 API로의 요청 프록시 처리 * - 쿠키 기반 인증 토큰 및 리프레시 토큰 관리 * - POST 및 PUT 요청 핸들링 * - 사용자 인증 정보 검증 및 응답 처리 * - 에러 핸들링 및 상태 코드 반환 * - 사이트 ID 및 헤더 설정 */ import { cookies } from "next/headers"; import { NextResponse } from "next/server"; import { clientIpHeaders } from "../../../../client-ip"; import { protectedRagProxyRoute } from "@/shared/api/rag-proxy-boundary"; import { SERVER_API_URL, SITE_ID } from "@/shared/config/env"; const ACCESS_TOKEN = process.env.NEXT_PUBLIC_ACCESS_TOKEN || "access-token"; const AUTH_USER_ID = process.env.NEXT_PUBLIC_AUTH_USER_ID || "token-id"; const CLAIM_NAME = process.env.NEXT_PUBLIC_CLAIM_NAME || "Authorization"; const REFRESH_TOKEN = process.env.NEXT_PUBLIC_REFRESH_TOKEN || "refresh-token"; async function handler( request: Request, params: { url: string[] }, method: "GET" | "POST" | "PUT" | "DELETE", ) { if (protectedRagProxyRoute(`/${params.url.join("/")}`)) { return NextResponse.json({ message: "RAG_FRONTEND_ROUTE_REQUIRED" }, { status: 403 }); } const cookieStore = await cookies(); const isRefreshHandler = params.url.includes("refresh"); const headers: Record = { "X-Site-Id": SITE_ID, ...clientIpHeaders(request), }; const deviceId = request.headers.get("X-Device-Id"); if (deviceId) { headers["X-Device-Id"] = deviceId; } let body = {}; if (!isRefreshHandler) { headers["Content-Type"] = "application/json"; } // silent refresh if (isRefreshHandler) { const refreshToken = cookieStore.get(REFRESH_TOKEN); headers[CLAIM_NAME] = refreshToken?.value ?? ""; if (!headers[CLAIM_NAME]) { return NextResponse.json({ message: "Can't refresh" }, { status: 401 }); } } try { if (!isRefreshHandler) { body = await request.json(); } const result = await fetch(`${SERVER_API_URL}/${params.url.join("/")}`, { method, headers, ...(isRefreshHandler ? {} : { body: JSON.stringify(body) }), }); if (!result.ok) { const contentType = result.headers.get("content-type") ?? ""; const errorBody = contentType.includes("application/json") ? await result.json().catch(() => null) : await result.text().catch(() => ""); return NextResponse.json( typeof errorBody === "object" && errorBody !== null ? errorBody : { message: errorBody || result.statusText || "Server Error" }, { status: result.status }, ); } const accessToken = result.headers.get(ACCESS_TOKEN); const refreshToken = result.headers.get(REFRESH_TOKEN); const userId = result.headers.get(AUTH_USER_ID); if (accessToken && userId) { const response = NextResponse.json({ [ACCESS_TOKEN]: accessToken, [AUTH_USER_ID]: userId, }); if (refreshToken) { cookieStore.set(REFRESH_TOKEN, refreshToken, { httpOnly: true, sameSite: "lax", path: "/", }); } return response; } return NextResponse.json( { message: "Invalid Credentials" }, { status: 401 }, ); } catch (error) { return NextResponse.json( { message: "Server Error", error }, { status: 500 }, ); } } export async function POST( request: Request, props: { params: Promise<{ url: string[] }> }, ) { const params = await props.params; return handler(request, params, "POST"); } export async function PUT( request: Request, props: { params: Promise<{ url: string[] }> }, ) { const params = await props.params; return handler(request, params, "PUT"); }