import { NextRequest, NextResponse } from "next/server"; import { AUTH_USER_ID, CLAIM_NAME } from "@/shared/config"; import { buildDcServiceRequestHeaders, DC_PREVIEW_RELAY_HEADER, resolveDcServiceUrl } from "@/shared/api/dc-service-request"; import { FileRegistryError, ragInternalHeaders, registryAuthHeaders } from "@/server/file-registry-attestation"; import { DC_SEARCH_RELAY_PATH, dcGatewayContext } from "@/shared/api/dc-search-relay"; import { authenticatedSubjectSha256 } from "@/server/rag-forward-context"; import { conversationSearchResponse } from "@/server/conversation-search-preview"; export const runtime = "nodejs"; export const dynamic = "force-dynamic"; const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; const KEYS = ["version", "session_id", "project_ids", "selected_file_sns", "selected_sources", "natural_domain", "messages"]; function failure(status: number): NextResponse { return NextResponse.json({ message: status === 401 ? "로그인이 필요합니다." : status === 403 ? "이 대화의 자료관 범위에 접근할 수 없습니다." : status === 404 ? "저장된 대화를 찾을 수 없습니다." : status === 409 ? "대화의 저장 상태가 변경되었습니다. 다시 불러와 주세요." : [400, 413, 422].includes(status) ? "대화 저장 요청을 확인해 주세요." : "저장된 대화를 처리하지 못했습니다. 잠시 후 다시 시도해 주세요." }, { status, headers: { "Cache-Control": "no-store" }, }); } async function authorizedHeaders(request: NextRequest): Promise { const authenticated = registryAuthHeaders(request); const headers = buildDcServiceRequestHeaders(request, { mode: "browser", forGet: true }); headers.set(DC_PREVIEW_RELAY_HEADER, "1"); headers.set("Authorization", authenticated.get("Authorization")!); headers.set("X-Site-Id", authenticated.get("X-Site-Id")!); for (const name of ["X-Conversation-Context", "X-Rag-V2-Internal-Key"]) headers.delete(name); if (authenticated.has(AUTH_USER_ID)) headers.set(AUTH_USER_ID, authenticated.get(AUTH_USER_ID)!); else headers.delete(AUTH_USER_ID); const base = process.env.NEXT_PUBLIC_DC_SERVICE_API_URL ?? process.env.DC_SERVICE_API_URL; if (!base) throw new FileRegistryError(503, "UPSTREAM_NOT_CONFIGURED", "자료관 연결 설정이 없습니다."); const response = await fetch(resolveDcServiceUrl("/dc-service/api/v1/clsf", undefined, base), { headers, cache: "no-store", redirect: "error", signal: request.signal, }); if (!response.ok) throw new FileRegistryError([401, 403].includes(response.status) ? response.status : 502, "CLASSIFICATION_UNAVAILABLE", "자료관 범위를 확인하지 못했습니다."); let data: unknown; try { data = await response.json(); } catch { throw new Error("invalid classification response"); } const rows = data && typeof data === "object" && "data" in data ? (data as { data: unknown }).data : data; if (!Array.isArray(rows)) throw new Error("invalid classification rows"); const roots = new Set(); const seen = new Set(); const stack: Array<{ node: unknown; parent?: string }> = rows.map(node => ({ node })); while (stack.length) { const { node, parent } = stack.pop()!; if (!node || typeof node !== "object" || Array.isArray(node)) throw new Error("invalid classification"); const row = node as Record; const id = ["string", "number"].includes(typeof row.clsfSystmSn) ? String(row.clsfSystmSn).trim() : ""; const up = row.upClsfSystmSn == null ? "" : String(row.upClsfSystmSn).trim(); if (!id || id.length > 256 || seen.has(id) || seen.size >= 100_000 || (parent && up && parent !== up)) throw new Error("invalid classification tree"); seen.add(id); if (!parent && (!up || up === "0")) roots.add(id); if (row.children !== undefined && !Array.isArray(row.children)) throw new Error("invalid classification children"); for (const child of (row.children as unknown[] | undefined) ?? []) stack.push({ node: child, parent: id }); } if (!roots.size || roots.size > 64) throw new FileRegistryError(403, "CLASSIFICATION_NOT_AVAILABLE", "사용 가능한 자료관 범위가 없습니다."); const ragHeaders = ragInternalHeaders(authenticated); ragHeaders.set("X-Conversation-Context", JSON.stringify({ version: 1, subjectSha256: authenticatedSubjectSha256(authenticated), projectIds: [...roots].sort() })); return ragHeaders; } async function forward(request: NextRequest, method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE"): Promise { try { const id = request.nextUrl.searchParams.get("session_id"); const operation = method === "POST" || (method === "GET" && id === null) ? "conversation-sessions" : "conversation-memory"; if (request.nextUrl.pathname.startsWith(DC_SEARCH_RELAY_PATH + "/") && request.nextUrl.pathname !== `${DC_SEARCH_RELAY_PATH}/${operation}`) return failure(400); if ((id !== null && !UUID.test(id)) || ((method === "DELETE" || method === "PATCH") && !id) || (method === "POST" && id !== null)) return failure(400); let body: Record | undefined; if (method === "PUT" || method === "PATCH" || method === "POST") { const budget = method === "POST" ? 4096 : 1_048_576; if (Number(request.headers.get("content-length") ?? 0) > budget) return failure(413); const text = await request.text(); if (Buffer.byteLength(text, "utf8") > budget) return failure(413); const raw: unknown = JSON.parse(text); if (!raw || typeof raw !== "object" || Array.isArray(raw)) return failure(400); if (method === "POST") { if (Object.keys(raw).some(key => !["query", "sort", "offset", "limit"].includes(key))) return failure(400); const values = raw as Record; const { query = "", sort = "recent", offset = 0, limit = 50 } = values; if (typeof query !== "string" || Array.from(query).length > 200 || typeof sort !== "string" || !["recent", "oldest", "title"].includes(sort) || !Number.isSafeInteger(offset) || (offset as number) < 0 || !Number.isSafeInteger(limit) || (limit as number) < 1 || (limit as number) > 100) return failure(400); body = { query: query.trim(), sort, offset, limit }; } else if (method === "PATCH") { const title = (raw as Record).title; if (Object.keys(raw).length !== 1 || typeof title !== "string" || /[\u0000-\u001f\u007f]/.test(title)) return failure(400); const trimmed = title.trim(); if (!trimmed || Array.from(trimmed).length > 120) return failure(400); body = { title: trimmed }; } else { body = Object.fromEntries(KEYS.filter(key => key in raw).map(key => [key, (raw as Record)[key]])); if (typeof body.session_id !== "string" || !UUID.test(body.session_id) || !Array.isArray(body.project_ids) || !body.project_ids.length || body.project_ids.length > 64) return failure(400); } } const headers = await authorizedHeaders(request); if (body) { if (method === "PUT") { const allowed = new Set((JSON.parse(headers.get("X-Conversation-Context")!) as { projectIds: string[] }).projectIds); if (!(body.project_ids as unknown[]).every(value => typeof value === "string" && allowed.has(value))) return failure(403); } headers.set("Content-Type", "application/json"); } for (const [name, value] of Object.entries(dcGatewayContext(request.headers))) headers.set(name, value); headers.set(CLAIM_NAME, headers.get("Authorization")!); const url = resolveDcServiceUrl(`${DC_SEARCH_RELAY_PATH}/${operation}`); if (id) url.searchParams.set("session_id", id); const response = await fetch(url, { method, headers, ...(body ? { body: JSON.stringify(body) } : {}), cache: "no-store", redirect: "error", signal: request.signal }); if (!response.ok) return failure([400, 401, 403, 404, 409, 413, 422, 429].includes(response.status) ? response.status : 502); if (method === "POST") { let value: unknown; try { value = await response.json(); } catch { throw new Error("invalid conversation search response"); } return NextResponse.json(await conversationSearchResponse(value, body!.query as string), { headers: { "Cache-Control": "no-store" } }); } return new Response(response.body, { status: response.status, headers: { "Content-Type": "application/json", "Cache-Control": "no-store" } }); } catch (error) { if (error instanceof FileRegistryError) return failure(error.status); if (error instanceof SyntaxError) return failure(400); return failure(request.signal.aborted ? 504 : 502); } } export function GET(request: NextRequest) { return forward(request, "GET"); } export function POST(request: NextRequest) { return forward(request, "POST"); } export function PUT(request: NextRequest) { return forward(request, "PUT"); } export function PATCH(request: NextRequest) { return forward(request, "PATCH"); } export function DELETE(request: NextRequest) { return forward(request, "DELETE"); }