Files
sam-react-prod/src/app/api/proxy/[...path]/route.ts

290 lines
9.2 KiB
TypeScript
Raw Normal View History

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();
console.log('🔵 [PROXY] Request:', method, url.toString());
console.log('🔵 [PROXY] Request Body:', body);
} else if (contentType.includes('multipart/form-data')) {
console.log('📎 [PROXY] Processing multipart/form-data request');
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);
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. 헤더 구성
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) {
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)
console.log('🔵 [PROXY] Response status:', backendResponse.status);
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) {
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 {
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);
});
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');
}