import { NextResponse } from 'next/server' import { checkRateLimit, recordFailedAttempt, resetFailedAttempts, signSession } from '@/lib/security' import { adminCookieSecure } from '@/lib/admin-session' export const runtime = 'nodejs' interface BackendAuthResponse { token?: unknown email?: unknown role?: unknown expiresAt?: unknown } type AdminRole = 'manager' | 'admin' | 'super_admin' function apiBase(): string { const value = process.env.API_SERVER_URL?.trim() if (!value) throw new Error('admin_auth_unavailable') const parsed = new URL(value) if (process.env.NODE_ENV === 'production' && parsed.protocol !== 'https:') { throw new Error('admin_auth_unavailable') } return parsed.origin } function normalizeRole(value: unknown): AdminRole | null { if (typeof value !== 'string') return null const normalized = value.replace(/[_-]/g, '').toLowerCase() if (normalized === 'superadmin') return 'super_admin' if (normalized === 'admin') return 'admin' if (normalized === 'manager') return 'manager' return null } function clientIdentifier(request: Request, email: string): string { const forwarded = request.headers.get('x-forwarded-for') ?? request.headers.get('cf-connecting-ip') ?? 'unknown' return `${forwarded.split(',')[0].trim().slice(0, 64)}:${email}` } function failure(key: string, status: number, retryAfterSeconds?: number): NextResponse { return NextResponse.json( { success: false, error: key, ...(retryAfterSeconds ? { retryAfter: retryAfterSeconds } : {}) }, { status, headers: retryAfterSeconds ? { 'Retry-After': String(retryAfterSeconds) } : undefined } ) } export async function POST(request: Request): Promise { let body: unknown try { body = await request.json() } catch { return failure('invalid_request', 400) } if (!body || typeof body !== 'object' || Array.isArray(body)) { return failure('invalid_request', 400) } const candidate = body as Record if (candidate.trap) return failure('access_denied', 403) const email = typeof candidate.usernameOrEmail === 'string' ? candidate.usernameOrEmail.trim().toLowerCase() : '' const password = typeof candidate.password === 'string' ? candidate.password : '' if (!email || email.length > 150 || !password || password.length > 256) { return failure('invalid_request', 400) } const rateLimitKey = clientIdentifier(request, email) const rateCheck = checkRateLimit(rateLimitKey) if (!rateCheck.allowed) { return failure('rate_limited', 429, rateCheck.retryAfterSeconds) } let backend: BackendAuthResponse try { const response = await fetch(`${apiBase()}/api/auth/login`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email, password }), cache: 'no-store', signal: AbortSignal.timeout(7_000) }) if (!response.ok) throw new Error('invalid_credentials') backend = (await response.json()) as BackendAuthResponse } catch { const lock = recordFailedAttempt(rateLimitKey) if (!lock.locked) await new Promise((resolve) => setTimeout(resolve, 600)) return lock.locked ? failure('rate_limited', 429, lock.retryAfterSeconds) : failure('invalid_credentials', 401) } const role = normalizeRole(backend.role) const token = typeof backend.token === 'string' ? backend.token : '' const authenticatedEmail = typeof backend.email === 'string' ? backend.email.trim().toLowerCase() : '' const backendExpiry = typeof backend.expiresAt === 'string' ? Date.parse(backend.expiresAt) : Number.NaN if ( !role || token.length < 80 || token.length > 8_192 || !authenticatedEmail || authenticatedEmail !== email || !Number.isFinite(backendExpiry) || backendExpiry <= Date.now() ) { return failure('invalid_auth_response', 502) } resetFailedAttempts(rateLimitKey) const expiresAt = Math.min(backendExpiry, Date.now() + 8 * 60 * 60 * 1_000) const signedCookieValue = signSession({ email: authenticatedEmail, role, token, loginAt: new Date().toISOString(), expiresAt }) const response = NextResponse.json({ success: true, user: { email: authenticatedEmail, role } }) response.cookies.set({ name: 'd3ro_admin_session', value: signedCookieValue, httpOnly: true, secure: adminCookieSecure(), sameSite: 'strict', path: '/', maxAge: Math.max(1, Math.floor((expiresAt - Date.now()) / 1_000)) }) return response }