import { NextRequest, NextResponse } from 'next/server' import { validateSAMLResponse, mapSAMLProfileToUser } from '../../auth/[...nextauth]/saml/utils' import { authenticateSAMLUser, createNextAuthToken, getSessionCookieName } from '../../auth/[...nextauth]/saml/provider' import { debugLog, debugError, debugSuccess, debugProcess } from '@/lib/debug-utils' // IdP가 인증처리 후 POST 요청을 콜백 URL로 날려준다. // 이 라우트가 그 요청을 받아준다. // GET 요청시 SP 메타데이터를 반환해주는데, 이건 필요 없으면 지우면 된다. export async function POST(request: NextRequest) { try { const isMockMode = process.env.SAML_MOCKING_IDP === 'true'; debugProcess(`SAML Callback received at /api/saml/callback ${isMockMode ? '(🎭 Mock Mode)' : ''}`) debugLog('Request info:', { url: request.url, nextUrl: request.nextUrl?.toString(), mockMode: isMockMode, headers: { host: request.headers.get('host'), origin: request.headers.get('origin'), referer: request.headers.get('referer') } }) // FormData에서 SAML Response 추출 const formData = await request.formData() const samlResponse = formData.get('SAMLResponse') as string const relayState = formData.get('RelayState') as string debugLog('SAML Response received:', { hasResponse: !!samlResponse, relayState: relayState || 'none', responseLength: samlResponse?.length || 0 }) // 🔍 SAML Response 디코딩 및 분석 if (samlResponse) { try { debugLog('🔍 SAML Response 분석:') debugLog('원본 SAMLResponse (일부):', samlResponse.substring(0, 100) + '...') try { // Base64 디코딩 시도 const base64Decoded = Buffer.from(samlResponse, 'base64').toString('utf-8') debugLog('Base64 디코딩된 XML:') debugLog('───────────────────────────────────') debugLog(base64Decoded) debugLog('───────────────────────────────────') // XML 구조 분석 const xmlLines = base64Decoded.split('\n').filter(line => line.trim()) debugLog('XML 구조 요약:') xmlLines.forEach((line, index) => { const trimmed = line.trim() if (trimmed.includes('