자료관 앱을 원앤올 공통 패키지 기준으로 최신화

This commit is contained in:
2026-12-05 10:57:47 +09:00
parent 9497b9c7db
commit 3ef863e329
270 changed files with 38735 additions and 2256 deletions
@@ -0,0 +1,153 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const cookieGet = vi.fn();
const cookieSet = vi.fn();
vi.mock("next/headers", () => ({
cookies: vi.fn(async () => ({
get: cookieGet,
set: cookieSet,
})),
}));
describe("DC login API proxy", () => {
beforeEach(() => {
vi.resetModules();
cookieGet.mockReset();
cookieSet.mockReset();
vi.stubEnv("SERVER_API_URL", "https://backend.example");
});
afterEach(() => {
vi.unstubAllEnvs();
vi.unstubAllGlobals();
});
it.each([
[undefined, "DC"],
["custom-site", "custom-site"],
])("sends the archive site ID for login and refresh (%s)", async (configured, expected) => {
vi.stubEnv("NEXT_PUBLIC_SITE_ID", configured);
cookieGet.mockReturnValue({ value: "test-refresh-token" });
const fetchMock = vi.fn().mockImplementation(async () => new Response(null, { status: 401 }));
vi.stubGlobal("fetch", fetchMock);
const { POST } = await import("./route");
for (const suffix of [["login"], ["token", "refresh"]]) {
const url = ["user-service", "api", "v1", ...suffix];
const response = await POST(new Request(`https://frontend.example/api/proxy/${url.join("/")}`, {
method: "POST", body: "{}",
}), { params: Promise.resolve({ url }) });
expect(response.status).toBe(401);
}
expect(fetchMock).toHaveBeenCalledTimes(2);
for (const [, options] of fetchMock.mock.calls) {
expect(new Headers(options.headers).get("x-site-id")).toBe(expected);
}
});
it.each([
["", "https://legacy.example"],
["https://server.example", "https://server.example"],
])("routes login with both gateway variable conventions (%s)", async (server, expected) => {
vi.stubEnv("SERVER_API_URL", server);
vi.stubEnv("NEXT_PUBLIC_SERVER_API_URL", "https://legacy.example");
const fetchMock = vi.fn().mockResolvedValue(new Response("{}", { status: 401 }));
vi.stubGlobal("fetch", fetchMock);
const { POST } = await import("./route");
const response = await POST(new Request("https://frontend.example/api/proxy/user-service/login", {
method: "POST", body: "{}",
}), { params: Promise.resolve({ url: ["user-service", "login"] }) });
expect(response.status).toBe(401);
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(fetchMock).toHaveBeenCalledWith(
`${expected}/user-service/login`,
expect.objectContaining({ method: "POST" }),
);
});
it("forwards the ingress IP and device ID while preserving the login body and tokens", async () => {
const fetchMock = vi.fn().mockResolvedValue(
new Response(null, {
status: 200,
headers: {
"access-token": "access-token-value",
"token-id": "token-id-value",
"refresh-token": "refresh-token-value",
},
}),
);
vi.stubGlobal("fetch", fetchMock);
const { POST } = await import("./route");
const request = new Request(
"https://frontend.example/api/proxy/user-service/login",
{
method: "POST",
headers: {
"Content-Type": "application/json",
"X-Device-Id": "device-id-value",
"X-Forwarded-For": "192.0.2.20, 192.0.2.21",
"X-Real-IP": "192.0.2.22",
"X-Client-IP": "192.0.2.99",
},
body: JSON.stringify({ username: "user" }),
},
);
const response = await POST(request, {
params: Promise.resolve({ url: ["user-service", "login"] }),
});
expect(response.status).toBe(200);
expect(fetchMock).toHaveBeenCalledOnce();
expect(fetchMock.mock.calls[0]?.[0]).toBe(
"https://backend.example/user-service/login",
);
expect(fetchMock.mock.calls[0]?.[1]).toMatchObject({
method: "POST",
body: JSON.stringify({ username: "user" }),
headers: expect.objectContaining({
"X-Device-Id": "device-id-value",
}),
});
const forwarded = new Headers(fetchMock.mock.calls[0]?.[1]?.headers);
expect(forwarded.get("x-client-ip")).toBe("192.0.2.20");
expect(await response.json()).toEqual({ "access-token": "access-token-value", "token-id": "token-id-value" });
expect(cookieSet).toHaveBeenCalledWith("refresh-token", "refresh-token-value", { httpOnly: true, sameSite: "lax", path: "/" });
});
it("omits absent device and ingress identity headers, even if a client IP was supplied", async () => {
const fetchMock = vi.fn().mockResolvedValue(
new Response(null, {
status: 200,
headers: {
"access-token": "access-token-value",
"token-id": "token-id-value",
},
}),
);
vi.stubGlobal("fetch", fetchMock);
const { POST } = await import("./route");
const request = new Request(
"https://frontend.example/api/proxy/user-service/login",
{
method: "POST",
headers: { "Content-Type": "application/json", "X-Client-IP": "192.0.2.99" },
body: JSON.stringify({ username: "user" }),
},
);
const response = await POST(request, {
params: Promise.resolve({ url: ["user-service", "login"] }),
});
const forwardedHeaders = fetchMock.mock.calls[0]?.[1]?.headers as Record<
string,
string
>;
expect(response.status).toBe(200);
expect(forwardedHeaders).not.toHaveProperty("X-Device-Id");
expect(new Headers(forwardedHeaders).has("x-client-ip")).toBe(false);
});
});
+40 -14
View File
@@ -1,29 +1,48 @@
import {
ACCESS_TOKEN,
AUTH_USER_ID,
CLAIM_NAME,
REFRESH_TOKEN,
SERVER_API_URL,
SITE_ID,
} from "@/shared/config";
/**
* 📄 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<string, string> = {
"Content-Type": "application/json",
"X-Site-Id": SITE_ID,
// 브라우저 IP (로그인/접속 로그용)
...clientIpHeaders(request),
};
const deviceId = request.headers.get("X-Device-Id");
if (deviceId) {
headers["X-Device-Id"] = deviceId;
}
let body = {};
const isRefreshHandler = params.url.includes("refresh");
if (!isRefreshHandler) {
headers["Content-Type"] = "application/json";
}
// silent refresh
if (isRefreshHandler) {
@@ -43,13 +62,20 @@ async function handler(
const result = await fetch(`${SERVER_API_URL}/${params.url.join("/")}`, {
method,
headers,
body: JSON.stringify(body),
...(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(
{ message: "Invalid Credentials" },
{ status: 401 },
typeof errorBody === "object" && errorBody !== null
? errorBody
: { message: errorBody || result.statusText || "Server Error" },
{ status: result.status },
);
}