- 품목 상세/수정 페이지 파일 다운로드 기능 개선 - DynamicItemForm 파일 업로드 UI/UX 개선 (시방서, 인정서) - BendingDiagramSection 조립/절곡 부품 전개도 통합 - API proxy route 품목 타입별 라우팅 개선 - ItemListClient 파일 다운로드 유틸리티 적용 - 품목코드 중복 체크 및 다이얼로그 추가 문서화: - DynamicItemForm 훅 분리 계획서 추가 (2161줄 → 900줄 목표) - 백엔드 API 마이그레이션 문서 추가 - 대용량 파일 처리 전략 가이드 추가 - 테넌트 데이터 격리 감사 문서 추가 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
372 lines
12 KiB
TypeScript
372 lines
12 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server';
|
|
|
|
/**
|
|
* 🔵 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
|
|
*
|
|
* ⚠️ 주의:
|
|
* - 로그아웃 API(/api/auth/logout)와 동일한 패턴
|
|
* - 모든 HTTP 메서드 지원 (GET, POST, PUT, DELETE)
|
|
* - 쿼리 파라미터와 요청 바디 모두 전달
|
|
*/
|
|
|
|
/**
|
|
* 토큰 갱신 함수 (access_token 만료 시 refresh_token으로 갱신)
|
|
*/
|
|
async function refreshAccessToken(refreshToken: string): Promise<{
|
|
success: boolean;
|
|
accessToken?: string;
|
|
refreshToken?: string;
|
|
expiresIn?: number;
|
|
}> {
|
|
try {
|
|
const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/v1/refresh`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'Accept': 'application/json',
|
|
'X-API-KEY': process.env.NEXT_PUBLIC_API_KEY || '',
|
|
},
|
|
body: JSON.stringify({
|
|
refresh_token: refreshToken,
|
|
}),
|
|
});
|
|
|
|
if (!response.ok) {
|
|
console.warn('🔴 [PROXY] Token refresh failed');
|
|
return { success: false };
|
|
}
|
|
|
|
const data = await response.json();
|
|
console.log('✅ [PROXY] Token refreshed successfully');
|
|
|
|
return {
|
|
success: true,
|
|
accessToken: data.access_token,
|
|
refreshToken: data.refresh_token,
|
|
expiresIn: data.expires_in,
|
|
};
|
|
} catch (error) {
|
|
console.error('🔴 [PROXY] Token refresh error:', error);
|
|
return { success: false };
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 백엔드 API 요청 실행 함수
|
|
*
|
|
* @param isFormData - true인 경우 Content-Type 헤더를 생략 (브라우저가 boundary 자동 설정)
|
|
*/
|
|
async function executeBackendRequest(
|
|
url: URL,
|
|
method: string,
|
|
token: string | undefined,
|
|
body: string | FormData | undefined,
|
|
contentType: string,
|
|
isFormData: boolean = false
|
|
): Promise<Response> {
|
|
// FormData인 경우 Content-Type을 생략해야 브라우저가 boundary를 자동 설정
|
|
const headers: Record<string, string> = {
|
|
'Accept': 'application/json',
|
|
'X-API-KEY': process.env.NEXT_PUBLIC_API_KEY || '',
|
|
'Authorization': token ? `Bearer ${token}` : '',
|
|
};
|
|
|
|
// FormData가 아닌 경우에만 Content-Type 설정
|
|
if (!isFormData) {
|
|
headers['Content-Type'] = contentType;
|
|
}
|
|
|
|
return fetch(url.toString(), {
|
|
method,
|
|
headers,
|
|
body,
|
|
});
|
|
}
|
|
|
|
/**
|
|
* 쿠키 생성 헬퍼 함수
|
|
*/
|
|
function createTokenCookies(tokens: { accessToken?: string; refreshToken?: string; expiresIn?: number }) {
|
|
const cookies: string[] = [];
|
|
|
|
if (tokens.accessToken) {
|
|
cookies.push([
|
|
`access_token=${tokens.accessToken}`,
|
|
'HttpOnly',
|
|
'Secure',
|
|
'SameSite=Strict',
|
|
'Path=/',
|
|
`Max-Age=${tokens.expiresIn || 7200}`,
|
|
].join('; '));
|
|
}
|
|
|
|
if (tokens.refreshToken) {
|
|
cookies.push([
|
|
`refresh_token=${tokens.refreshToken}`,
|
|
'HttpOnly',
|
|
'Secure',
|
|
'SameSite=Strict',
|
|
'Path=/',
|
|
'Max-Age=604800', // 7 days
|
|
].join('; '));
|
|
}
|
|
|
|
return cookies;
|
|
}
|
|
|
|
/**
|
|
* 쿠키 삭제 헬퍼 함수 (토큰 만료 시)
|
|
*/
|
|
function createClearTokenCookies(): string[] {
|
|
return [
|
|
'access_token=; HttpOnly; Secure; SameSite=Strict; Path=/; Max-Age=0',
|
|
'refresh_token=; HttpOnly; Secure; SameSite=Strict; Path=/; Max-Age=0',
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Catch-all proxy handler for all HTTP methods
|
|
*
|
|
* 🔄 토큰 갱신 로직:
|
|
* 1. 현재 access_token으로 백엔드 요청
|
|
* 2. 401 응답 시 → refresh_token으로 새 토큰 발급
|
|
* 3. 새 토큰으로 원래 요청 재시도
|
|
* 4. 재시도도 실패하면 → 쿠키 삭제 후 401 반환
|
|
*/
|
|
async function proxyRequest(
|
|
request: NextRequest,
|
|
params: { path: string[] },
|
|
method: string
|
|
) {
|
|
try {
|
|
// 1. HttpOnly 쿠키에서 토큰 읽기 (서버에서만 가능!)
|
|
let 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();
|
|
console.log('🔵 [PROXY] Request:', method, url.toString());
|
|
console.log('🔵 [PROXY] Request Body:', body); // 디버깅용
|
|
} else if (contentType.includes('multipart/form-data')) {
|
|
// multipart/form-data 처리: FormData를 그대로 전달
|
|
console.log('📎 [PROXY] Processing multipart/form-data request');
|
|
isFormData = true;
|
|
|
|
// 원본 요청의 FormData 읽기
|
|
const originalFormData = await request.formData();
|
|
|
|
// 새 FormData 생성 (백엔드 전송용)
|
|
const newFormData = new FormData();
|
|
|
|
// 모든 필드 복사
|
|
for (const [key, value] of originalFormData.entries()) {
|
|
if (value instanceof File) {
|
|
// File 객체는 그대로 추가
|
|
newFormData.append(key, value, value.name);
|
|
console.log(`📎 [PROXY] File field: ${key} = ${value.name} (${value.size} bytes)`);
|
|
} else {
|
|
// 일반 필드
|
|
newFormData.append(key, value);
|
|
console.log(`📎 [PROXY] Form field: ${key} = ${value}`);
|
|
}
|
|
}
|
|
|
|
body = newFormData;
|
|
console.log('🔵 [PROXY] Request:', method, url.toString());
|
|
}
|
|
} else {
|
|
console.log('🔵 [PROXY] Request:', method, url.toString());
|
|
}
|
|
|
|
// 4. 백엔드로 프록시 요청
|
|
let backendResponse = await executeBackendRequest(url, method, token, body, contentType, isFormData);
|
|
let newTokens: { accessToken?: string; refreshToken?: string; expiresIn?: number } | null = null;
|
|
|
|
// 5. 🔄 401 응답 시 토큰 갱신 후 재시도
|
|
if (backendResponse.status === 401 && refreshToken) {
|
|
console.log('🔄 [PROXY] Got 401, attempting token refresh...');
|
|
|
|
const refreshResult = await refreshAccessToken(refreshToken);
|
|
|
|
if (refreshResult.success && refreshResult.accessToken) {
|
|
console.log('✅ [PROXY] Token refreshed, retrying original request...');
|
|
|
|
// 새 토큰으로 원래 요청 재시도
|
|
token = refreshResult.accessToken;
|
|
newTokens = refreshResult;
|
|
backendResponse = await executeBackendRequest(url, method, token, body, contentType, isFormData);
|
|
|
|
console.log('🔵 [PROXY] Retry response status:', backendResponse.status);
|
|
} else {
|
|
// 리프레시 실패 → 쿠키 삭제하고 401 반환
|
|
console.warn('🔴 [PROXY] Token refresh 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;
|
|
}
|
|
}
|
|
|
|
// 6. 응답 데이터 읽기
|
|
console.log('🔵 [PROXY] Response status:', backendResponse.status);
|
|
const responseContentType = backendResponse.headers.get('content-type') || 'application/json';
|
|
|
|
// 7. 바이너리 파일 vs 텍스트/JSON 구분
|
|
// 파일 다운로드 (PDF, 이미지, 등)는 바이너리로 처리해야 손상되지 않음
|
|
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) {
|
|
// 바이너리 파일: arrayBuffer로 읽어서 그대로 전달
|
|
console.log('📄 [PROXY] Binary response detected:', responseContentType);
|
|
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 {
|
|
// JSON/텍스트: text로 읽어서 전달
|
|
const responseData = await backendResponse.text();
|
|
|
|
clientResponse = new NextResponse(responseData, {
|
|
status: backendResponse.status,
|
|
headers: {
|
|
'Content-Type': responseContentType,
|
|
},
|
|
});
|
|
}
|
|
|
|
// 8. 토큰이 갱신되었으면 새 쿠키 설정
|
|
if (newTokens && newTokens.accessToken) {
|
|
createTokenCookies(newTokens).forEach(cookie => {
|
|
clientResponse.headers.append('Set-Cookie', cookie);
|
|
});
|
|
console.log('🍪 [PROXY] New tokens set in cookies');
|
|
}
|
|
|
|
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');
|
|
}
|