- 미사용 import/변수/console.log 대량 정리 (100+개 파일) - ItemMasterContext 간소화 (미사용 로직 제거) - IntegratedListTemplateV2 / UniversalListPage 개선 - 결재 컴포넌트(ApprovalBox, DraftBox, ReferenceBox) 정리 - HR 컴포넌트(급여/휴가/부서) 코드 간소화 - globals.css 스타일 정리 및 개선 - AuthenticatedLayout 개선 - middleware CSP 정리 - proxy route 불필요 로깅 제거 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
281 lines
8.5 KiB
TypeScript
281 lines
8.5 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server';
|
|
import { authenticatedFetch } from '@/lib/api/authenticated-fetch';
|
|
|
|
/**
|
|
* 🔵 Catch-All API Proxy (HttpOnly Cookie Pattern)
|
|
*
|
|
* ⚡ 설계 목적:
|
|
* - HttpOnly 쿠키 보안 유지: JavaScript 접근 차단
|
|
* - 모든 백엔드 API를 단일 프록시로 처리
|
|
* - 서버에서 쿠키 읽어 Authorization 헤더 자동 추가
|
|
*
|
|
* 🔄 동작 흐름:
|
|
* 1. 클라이언트 → Next.js /api/proxy/* (토큰 없이)
|
|
* 2. Next.js: HttpOnly 쿠키에서 access_token 읽기 (서버에서만 가능)
|
|
* 3. Next.js → PHP Backend /api/v1/* (Authorization 헤더 포함)
|
|
* 4. PHP Backend → Next.js (응답)
|
|
* 5. Next.js → 클라이언트 (응답 전달)
|
|
*
|
|
* 🔐 보안 특징:
|
|
* - HttpOnly 쿠키: JavaScript 접근 불가 (XSS 방지)
|
|
* - 서버 사이드 토큰 처리: 브라우저에 토큰 노출 안됨
|
|
* - 자동 인증 헤더 추가: 클라이언트는 신경 쓸 필요 없음
|
|
*
|
|
* 📍 사용 예시:
|
|
* - Frontend: fetch('/api/proxy/item-master/init')
|
|
* - Backend: GET https://api.codebridge-x.com/api/v1/item-master/init
|
|
*
|
|
* 🔄 인증 처리:
|
|
* - 401 감지 → refresh → retry 는 authenticatedFetch 게이트웨이에 위임
|
|
* - PROXY는 쿠키 읽기/설정/삭제만 담당
|
|
*/
|
|
|
|
/**
|
|
* 쿠키 생성 헬퍼 함수
|
|
*/
|
|
function createTokenCookies(tokens: { accessToken?: string; refreshToken?: string; expiresIn?: number }) {
|
|
const cookies: string[] = [];
|
|
const isProduction = process.env.NODE_ENV === 'production';
|
|
|
|
if (tokens.accessToken) {
|
|
cookies.push([
|
|
`access_token=${tokens.accessToken}`,
|
|
'HttpOnly',
|
|
...(isProduction ? ['Secure'] : []),
|
|
'SameSite=Lax',
|
|
'Path=/',
|
|
`Max-Age=${tokens.expiresIn || 7200}`,
|
|
].join('; '));
|
|
|
|
// FCM 등에서 인증 상태 확인용 (non-HttpOnly)
|
|
cookies.push([
|
|
'is_authenticated=true',
|
|
...(isProduction ? ['Secure'] : []),
|
|
'SameSite=Lax',
|
|
'Path=/',
|
|
`Max-Age=${tokens.expiresIn || 7200}`,
|
|
].join('; '));
|
|
}
|
|
|
|
if (tokens.refreshToken) {
|
|
cookies.push([
|
|
`refresh_token=${tokens.refreshToken}`,
|
|
'HttpOnly',
|
|
...(isProduction ? ['Secure'] : []),
|
|
'SameSite=Lax',
|
|
'Path=/',
|
|
'Max-Age=604800', // 7 days
|
|
].join('; '));
|
|
}
|
|
|
|
return cookies;
|
|
}
|
|
|
|
/**
|
|
* 쿠키 삭제 헬퍼 함수 (토큰 만료 시)
|
|
*/
|
|
function createClearTokenCookies(): string[] {
|
|
const isProduction = process.env.NODE_ENV === 'production';
|
|
const secureFlag = isProduction ? '; Secure' : '';
|
|
return [
|
|
`access_token=; HttpOnly${secureFlag}; SameSite=Lax; Path=/; Max-Age=0`,
|
|
`refresh_token=; HttpOnly${secureFlag}; SameSite=Lax; Path=/; Max-Age=0`,
|
|
`is_authenticated=${secureFlag}; SameSite=Lax; Path=/; Max-Age=0`,
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Catch-all proxy handler for all HTTP methods
|
|
*/
|
|
async function proxyRequest(
|
|
request: NextRequest,
|
|
params: { path: string[] },
|
|
method: string
|
|
) {
|
|
try {
|
|
// 1. HttpOnly 쿠키에서 토큰 읽기
|
|
const token = request.cookies.get('access_token')?.value;
|
|
const refreshToken = request.cookies.get('refresh_token')?.value;
|
|
|
|
// 2. 백엔드 URL 구성
|
|
const backendUrl = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/${params.path.join('/')}`;
|
|
const url = new URL(backendUrl);
|
|
request.nextUrl.searchParams.forEach((value, key) => {
|
|
url.searchParams.append(key, value);
|
|
});
|
|
|
|
// 3. 요청 바디 읽기 (POST, PUT, DELETE, PATCH)
|
|
let body: string | FormData | undefined;
|
|
const contentType = request.headers.get('content-type') || 'application/json';
|
|
let isFormData = false;
|
|
|
|
if (['POST', 'PUT', 'DELETE', 'PATCH'].includes(method)) {
|
|
if (contentType.includes('application/json')) {
|
|
body = await request.text();
|
|
} else if (contentType.includes('multipart/form-data')) {
|
|
isFormData = true;
|
|
|
|
const originalFormData = await request.formData();
|
|
const newFormData = new FormData();
|
|
|
|
for (const [key, value] of originalFormData.entries()) {
|
|
if (value instanceof File) {
|
|
newFormData.append(key, value, value.name);
|
|
} else {
|
|
newFormData.append(key, value);
|
|
}
|
|
}
|
|
|
|
body = newFormData;
|
|
}
|
|
}
|
|
|
|
// 4. 헤더 구성
|
|
const headers: Record<string, string> = {
|
|
'Accept': 'application/json',
|
|
'X-API-KEY': process.env.API_KEY || '',
|
|
'Authorization': token ? `Bearer ${token}` : '',
|
|
};
|
|
if (!isFormData) {
|
|
headers['Content-Type'] = contentType;
|
|
}
|
|
|
|
// 5. authenticatedFetch 게이트웨이로 요청 실행
|
|
// 401 감지 → refresh → retry 모두 게이트웨이가 처리
|
|
const { response: backendResponse, newTokens, authFailed } = await authenticatedFetch(
|
|
url.toString(),
|
|
{ method, headers, body },
|
|
refreshToken,
|
|
'PROXY'
|
|
);
|
|
|
|
// 6. 인증 실패 → 쿠키 삭제 + 401 반환
|
|
if (authFailed) {
|
|
if (process.env.NODE_ENV === 'development') {
|
|
console.warn('🔴 [PROXY] Auth failed, clearing cookies...');
|
|
}
|
|
const clearResponse = NextResponse.json(
|
|
{ error: 'Authentication failed', needsReauth: true },
|
|
{ status: 401 }
|
|
);
|
|
createClearTokenCookies().forEach(cookie => {
|
|
clearResponse.headers.append('Set-Cookie', cookie);
|
|
});
|
|
return clearResponse;
|
|
}
|
|
|
|
// 7. 응답 처리 (바이너리 vs 텍스트/JSON)
|
|
const responseContentType = backendResponse.headers.get('content-type') || 'application/json';
|
|
|
|
const isBinaryResponse =
|
|
responseContentType.includes('application/pdf') ||
|
|
responseContentType.includes('application/octet-stream') ||
|
|
responseContentType.includes('image/') ||
|
|
responseContentType.includes('application/zip') ||
|
|
responseContentType.includes('application/vnd') ||
|
|
responseContentType.includes('application/msword') ||
|
|
responseContentType.includes('application/x-');
|
|
|
|
let clientResponse: NextResponse;
|
|
|
|
if (isBinaryResponse) {
|
|
const binaryData = await backendResponse.arrayBuffer();
|
|
|
|
clientResponse = new NextResponse(binaryData, {
|
|
status: backendResponse.status,
|
|
headers: {
|
|
'Content-Type': responseContentType,
|
|
'Content-Disposition': backendResponse.headers.get('content-disposition') || '',
|
|
'Content-Length': backendResponse.headers.get('content-length') || '',
|
|
},
|
|
});
|
|
} else {
|
|
const responseData = await backendResponse.text();
|
|
|
|
clientResponse = new NextResponse(responseData, {
|
|
status: backendResponse.status,
|
|
headers: {
|
|
'Content-Type': responseContentType,
|
|
},
|
|
});
|
|
}
|
|
|
|
// 8. 토큰이 갱신되었으면 새 쿠키 설정
|
|
if (newTokens?.accessToken) {
|
|
createTokenCookies(newTokens).forEach(cookie => {
|
|
clientResponse.headers.append('Set-Cookie', cookie);
|
|
});
|
|
}
|
|
|
|
return clientResponse;
|
|
|
|
} catch (error) {
|
|
console.error('Proxy request error:', error);
|
|
return NextResponse.json(
|
|
{ error: 'Proxy server error' },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* GET 요청 프록시
|
|
* Next.js 15: params는 Promise이므로 await 필요
|
|
*/
|
|
export async function GET(
|
|
request: NextRequest,
|
|
{ params }: { params: Promise<{ path: string[] }> }
|
|
) {
|
|
const resolvedParams = await params;
|
|
return proxyRequest(request, resolvedParams, 'GET');
|
|
}
|
|
|
|
/**
|
|
* POST 요청 프록시
|
|
* Next.js 15: params는 Promise이므로 await 필요
|
|
*/
|
|
export async function POST(
|
|
request: NextRequest,
|
|
{ params }: { params: Promise<{ path: string[] }> }
|
|
) {
|
|
const resolvedParams = await params;
|
|
return proxyRequest(request, resolvedParams, 'POST');
|
|
}
|
|
|
|
/**
|
|
* PUT 요청 프록시
|
|
* Next.js 15: params는 Promise이므로 await 필요
|
|
*/
|
|
export async function PUT(
|
|
request: NextRequest,
|
|
{ params }: { params: Promise<{ path: string[] }> }
|
|
) {
|
|
const resolvedParams = await params;
|
|
return proxyRequest(request, resolvedParams, 'PUT');
|
|
}
|
|
|
|
/**
|
|
* DELETE 요청 프록시
|
|
* Next.js 15: params는 Promise이므로 await 필요
|
|
*/
|
|
export async function DELETE(
|
|
request: NextRequest,
|
|
{ params }: { params: Promise<{ path: string[] }> }
|
|
) {
|
|
const resolvedParams = await params;
|
|
return proxyRequest(request, resolvedParams, 'DELETE');
|
|
}
|
|
|
|
/**
|
|
* PATCH 요청 프록시
|
|
* Next.js 15: params는 Promise이므로 await 필요
|
|
* 용도: toggle 엔드포인트 (/clients/{id}/toggle, /client-groups/{id}/toggle)
|
|
*/
|
|
export async function PATCH(
|
|
request: NextRequest,
|
|
{ params }: { params: Promise<{ path: string[] }> }
|
|
) {
|
|
const resolvedParams = await params;
|
|
return proxyRequest(request, resolvedParams, 'PATCH');
|
|
}
|