feat(admin): 예전/최신 어드민 통합 — 실데이터 복원 + 인증 아키텍처 정리

예전 배포본(HEAD)의 상세 기능을 새 아키텍처(인증=.NET 백엔드, 데이터=Supabase)
위에 실데이터로 복원. 예전 HEAD는 서명 쿠키를 거부하고 위조 쿠키는 통과시키는
인증 결함이 있었고, 삭제된 페이지 다수는 백엔드 호출 0인 하드코딩 목업이었음.

인증/세션
- 로그인 이메일 전용화(username 폐지), 에러 키별 안내 메시지
- ADMIN_COOKIE_SECURE 옵션: TLS 없는 LAN HTTP 배포에서 Secure 쿠키 유실로
  로그인이 유지되지 않던 문제 해결 (login/logout route, admin-session, compose, .env.example)
- Supabase 미설정 시 우아한 저하: isSupabaseAdminConfigured + UnavailableAdminPanel

기능 복원 (실데이터)
- Release Hub: Forgejo API 실데이터(다운로드 수/SHA-256 체크섬/릴리스 이력)
- Ad Monetization: 데스크톱 미디에이션 10개 어댑터 로스터(fail-closed) + ad_reward_claims 통계
- License Issuer: 서버사이드 Ed25519 서명(/api/admin/license, super_admin 전용),
  개인키는 ADMIN_LICENSE_PRIVATE_KEY env로만, 발급 감사를 .NET AdminAuditEntries에 기록
- Service Models: STT 7종/LLM 5종 프리셋 드롭다운 + 자동채움
- 대시보드 ARR/MRR KPI: Supabase 구독 실집계(티어 월단가 기반)
- 사용자 상세 티어별 기능 배지(pro_plus 조건부)

.NET
- SuperAdminOnly 정책 추가, /api/admin/license-audit 엔드포인트, LicenseAuditDto
This commit is contained in:
Yun Chan 2026-08-23 23:38:08 +09:00
parent a9c9a1ca6e
commit 5a34f66981
66 changed files with 4471 additions and 3501 deletions

View file

@ -0,0 +1,116 @@
import { NextRequest, NextResponse } from 'next/server'
import { AdminBackendError, fetchAdminBackend } from '@/lib/backend-session'
import type { AdminRole } from '@/lib/admin-session'
export const runtime = 'nodejs'
const READ_PATHS = [
/^\/stats$/,
/^\/users$/,
/^\/endpoints$/,
/^\/stt-endpoints$/,
/^\/stt-usage$/,
/^\/usage$/
]
const MANAGER_POST_PATHS = [/^\/stt-endpoints\/\d+\/test$/]
const ADMIN_POST_PATHS = [
/^\/endpoints$/,
/^\/stt-endpoints$/,
/^\/stt-endpoints\/\d+\/set-default$/,
/^\/stt-endpoints\/test-direct$/
]
const ADMIN_MUTATION_PATHS = [/^\/endpoints\/\d+$/, /^\/stt-endpoints\/\d+$/]
const IDEMPOTENT_POST_PATHS = [/^\/endpoints$/, /^\/stt-endpoints$/, /^\/stt-endpoints\/\d+\/set-default$/]
function pathFor(segments: string[]): string | null {
if (!segments.length || segments.some((segment) => !/^[A-Za-z0-9-]+$/.test(segment))) {
return null
}
return `/${segments.join('/')}`
}
function requiredRole(method: string, path: string): AdminRole | null {
if (method === 'GET' && READ_PATHS.some((pattern) => pattern.test(path))) return 'manager'
if (method === 'POST' && MANAGER_POST_PATHS.some((pattern) => pattern.test(path))) return 'manager'
if (method === 'POST' && ADMIN_POST_PATHS.some((pattern) => pattern.test(path))) return 'admin'
if ((method === 'PUT' || method === 'DELETE') && ADMIN_MUTATION_PATHS.some((pattern) => pattern.test(path))) {
return 'admin'
}
return null
}
function isSameOrigin(request: NextRequest): boolean {
const origin = request.headers.get('origin')
if (!origin) return request.headers.get('sec-fetch-site') !== 'cross-site'
try {
const requestOrigin = new URL(origin).origin
if (requestOrigin === request.nextUrl.origin) return true
const forwardedProto = request.headers.get('x-forwarded-proto')?.split(',')[0]?.trim().toLowerCase()
const forwardedHost = request.headers.get('x-forwarded-host')?.split(',')[0]?.trim()
?? request.headers.get('host')?.trim()
if ((forwardedProto !== 'http' && forwardedProto !== 'https') ||
!forwardedHost || !/^[A-Za-z0-9.:[\]-]+$/.test(forwardedHost)) {
return false
}
return requestOrigin === `${forwardedProto}://${forwardedHost}`
} catch {
return false
}
}
async function proxy(
request: NextRequest,
context: { params: Promise<{ segments: string[] }> }
): Promise<NextResponse> {
const { segments } = await context.params
const path = pathFor(segments)
const role = path ? requiredRole(request.method, path) : null
if (!path || !role) return NextResponse.json({ error: 'admin_route_not_allowed' }, { status: 404 })
if (request.method !== 'GET' && !isSameOrigin(request)) {
return NextResponse.json({ error: 'cross_site_request_rejected' }, { status: 403 })
}
let body: string | undefined
if (request.method !== 'GET') {
body = await request.text()
if (new TextEncoder().encode(body).byteLength > 64 * 1024) {
return NextResponse.json({ error: 'request_too_large' }, { status: 413 })
}
}
const mutatesState =
(request.method === 'POST' && IDEMPOTENT_POST_PATHS.some((pattern) => pattern.test(path))) ||
((request.method === 'PUT' || request.method === 'DELETE') && ADMIN_MUTATION_PATHS.some((pattern) => pattern.test(path)))
const idempotencyKey = request.headers.get('idempotency-key')?.trim() ?? ''
if (mutatesState && !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(idempotencyKey)) {
return NextResponse.json({ error: 'valid_idempotency_key_required' }, { status: 400 })
}
try {
const backend = await fetchAdminBackend(`${path}${request.nextUrl.search}`, {
method: request.method,
body,
headers: mutatesState ? { 'Idempotency-Key': idempotencyKey } : undefined
}, role)
const text = await backend.text()
return new NextResponse(text || null, {
status: backend.status,
headers: {
'Content-Type': backend.headers.get('content-type') ?? 'application/json',
'Cache-Control': 'no-store'
}
})
} catch (error) {
if (error instanceof AdminBackendError) {
return NextResponse.json({ error: error.message }, { status: error.status })
}
return NextResponse.json({ error: 'admin_backend_unavailable' }, { status: 503 })
}
}
export const GET = proxy
export const POST = proxy
export const PUT = proxy
export const DELETE = proxy

View file

@ -0,0 +1,157 @@
// apps/admin/src/app/api/admin/license/route.ts
// Ed25519 라이선스 발급 — 서명 개인키는 서버 환경변수로만 공급한다.
import { randomUUID } from 'node:crypto'
import { NextRequest, NextResponse } from 'next/server'
import {
issueSignedLicenseKey,
DEFAULT_LICENSE_PRIVATE_KEY,
type SignedLicensePayload
} from '@d3ro/core/utils/crypto-license'
import type { LicenseTier } from '@d3ro/core/types'
import { AdminBackendError, fetchAdminBackend, requireVerifiedBackendSession } from '@/lib/backend-session'
export const runtime = 'nodejs'
const ISSUABLE_TIERS: readonly LicenseTier[] = ['pro', 'pro_plus', 'team', 'enterprise']
const VALIDITY_MS: Record<string, number | null> = {
'30d': 30 * 24 * 60 * 60 * 1_000,
'365d': 365 * 24 * 60 * 60 * 1_000,
lifetime: null
}
const MAX_DEVICES: Record<LicenseTier, number> = {
free: 1,
pro: 3,
pro_plus: 5,
team: 25,
enterprise: 999
}
interface SigningKey {
privateKeyPem: string
usedDefaultKey: boolean
}
// 저장소에 포함된 기본 키쌍은 공개된 것이므로 위조 방어력이 없다. 운영 발급은
// ADMIN_LICENSE_PRIVATE_KEY(전용 키 로테이션)로만 하고, 기본 키 사용은 명시적 opt-in.
function resolveSigningKey(): SigningKey | null {
const configured = process.env.ADMIN_LICENSE_PRIVATE_KEY?.trim()
if (configured) {
return { privateKeyPem: configured.replace(/\\n/g, '\n'), usedDefaultKey: false }
}
if (process.env.ADMIN_LICENSE_ALLOW_DEFAULT_KEY === 'true') {
return { privateKeyPem: DEFAULT_LICENSE_PRIVATE_KEY, usedDefaultKey: true }
}
return null
}
function isSameOrigin(request: NextRequest): boolean {
const origin = request.headers.get('origin')
if (!origin) return request.headers.get('sec-fetch-site') !== 'cross-site'
try {
return new URL(origin).origin === request.nextUrl.origin
} catch {
return false
}
}
export async function POST(request: NextRequest): Promise<NextResponse> {
if (!isSameOrigin(request)) {
return NextResponse.json({ error: 'cross_site_request_rejected' }, { status: 403 })
}
try {
await requireVerifiedBackendSession('super_admin')
} catch (error) {
const status = error instanceof AdminBackendError ? error.status : 401
const message = error instanceof AdminBackendError ? error.message : 'admin_session_invalid'
return NextResponse.json({ error: message }, { status })
}
let body: unknown
try {
body = await request.json()
} catch {
return NextResponse.json({ error: 'invalid_request' }, { status: 400 })
}
if (!body || typeof body !== 'object' || Array.isArray(body)) {
return NextResponse.json({ error: 'invalid_request' }, { status: 400 })
}
const candidate = body as Record<string, unknown>
const customerEmail = typeof candidate.customerEmail === 'string' ? candidate.customerEmail.trim().toLowerCase() : ''
const tier = candidate.tier
const validity = typeof candidate.validity === 'string' ? candidate.validity : ''
const machineId = typeof candidate.machineId === 'string' ? candidate.machineId.trim() : ''
const teamId = typeof candidate.teamId === 'string' ? candidate.teamId.trim() : ''
if (!customerEmail || customerEmail.length > 150 || !customerEmail.includes('@')) {
return NextResponse.json({ error: 'invalid_customer_email' }, { status: 400 })
}
if (typeof tier !== 'string' || !ISSUABLE_TIERS.includes(tier as LicenseTier)) {
return NextResponse.json({ error: 'invalid_tier' }, { status: 400 })
}
if (!(validity in VALIDITY_MS)) {
return NextResponse.json({ error: 'invalid_validity' }, { status: 400 })
}
if (machineId.length > 128 || teamId.length > 64) {
return NextResponse.json({ error: 'invalid_request' }, { status: 400 })
}
const signingKey = resolveSigningKey()
if (!signingKey) {
return NextResponse.json({ error: 'license_signing_unavailable' }, { status: 503 })
}
const issuedTier = tier as LicenseTier
const now = Date.now()
const validityMs = VALIDITY_MS[validity]
const payload: SignedLicensePayload = {
licenseId: `lic-${randomUUID()}`,
tier: issuedTier,
customerEmail,
issuedAt: now,
expiresAt: validityMs === null ? null : now + validityMs,
machineId: machineId || null,
...(teamId ? { teamId } : {}),
maxDevices: MAX_DEVICES[issuedTier]
}
let licenseKey: string
try {
licenseKey = issueSignedLicenseKey(payload, signingKey.privateKeyPem)
} catch {
return NextResponse.json({ error: 'license_signing_failed' }, { status: 500 })
}
// 발급 감사 기록(best-effort). 감사가 실패해도 이미 서명된 라이선스는 반환하되 상태를 알린다.
let auditRecorded = false
try {
const auditResponse = await fetchAdminBackend(
'/license-audit',
{
method: 'POST',
body: JSON.stringify({
licenseId: payload.licenseId,
customerEmail: payload.customerEmail,
tier: payload.tier,
validity,
expiresAt: payload.expiresAt
})
},
'super_admin'
)
auditRecorded = auditResponse.ok
} catch {
auditRecorded = false
}
return NextResponse.json({
success: true,
licenseKey,
licenseId: payload.licenseId,
expiresAt: payload.expiresAt,
usedDefaultKey: signingKey.usedDefaultKey,
auditRecorded
})
}

View file

@ -0,0 +1,243 @@
import { NextRequest, NextResponse } from 'next/server'
import { AdminBackendError, requireVerifiedBackendSession } from '@/lib/backend-session'
import { getSupabaseAdminClient } from '@/lib/supabase-admin'
export const runtime = 'nodejs'
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
const ROLES = new Set(['user', 'manager', 'admin', 'super_admin'])
const TIERS = new Set(['free', 'pro', 'pro_plus'])
const STATUSES = new Set(['active', 'canceled', 'past_due', 'expired'])
function sameOrigin(request: NextRequest): boolean {
const origin = request.headers.get('origin')
if (!origin) return request.headers.get('sec-fetch-site') !== 'cross-site'
try {
const requestOrigin = new URL(origin).origin
if (requestOrigin === request.nextUrl.origin) return true
const forwardedProto = request.headers.get('x-forwarded-proto')?.split(',')[0]?.trim().toLowerCase()
const forwardedHost = request.headers.get('x-forwarded-host')?.split(',')[0]?.trim()
?? request.headers.get('host')?.trim()
if ((forwardedProto !== 'http' && forwardedProto !== 'https') ||
!forwardedHost || !/^[A-Za-z0-9.:[\]-]+$/.test(forwardedHost)) {
return false
}
return requestOrigin === `${forwardedProto}://${forwardedHost}`
} catch {
return false
}
}
async function bodyObject(request: NextRequest): Promise<Record<string, unknown>> {
if (request.headers.get('content-type')?.split(';', 1)[0]?.trim().toLowerCase() !== 'application/json') {
throw new AdminBackendError('application_json_required', 415)
}
const text = await request.text()
if (new TextEncoder().encode(text).byteLength > 32 * 1024) throw new AdminBackendError('request_too_large', 413)
try {
const parsed = JSON.parse(text) as unknown
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error()
return parsed as Record<string, unknown>
} catch {
throw new AdminBackendError('invalid_request', 400)
}
}
function onlyKeys(body: Record<string, unknown>, allowed: readonly string[]): void {
const keys = new Set(allowed)
if (Object.keys(body).some((key) => !keys.has(key))) {
throw new AdminBackendError('unexpected_request_field', 400)
}
}
function onlyQuery(request: NextRequest, allowed: readonly string[]): void {
const keys = new Set(allowed)
for (const key of request.nextUrl.searchParams.keys()) {
if (!keys.has(key)) throw new AdminBackendError('unexpected_query_parameter', 400)
}
}
function memo(value: unknown): string {
const normalized = typeof value === 'string' ? value.trim() : ''
if (normalized.length < 3 || normalized.length > 1000) {
throw new AdminBackendError('invalid_memo', 400)
}
return normalized
}
function optionalDateTime(value: unknown): string | null {
if (value === undefined) return null
if (typeof value !== 'string' || value.length > 40 || !/^\d{4}-\d{2}-\d{2}T/.test(value)) {
throw new AdminBackendError('invalid_current_period_end', 400)
}
const parsed = Date.parse(value)
if (!Number.isFinite(parsed)) throw new AdminBackendError('invalid_current_period_end', 400)
return new Date(parsed).toISOString()
}
function idempotencyKey(request: NextRequest): string {
const value = request.headers.get('idempotency-key')?.trim() ?? ''
if (!UUID.test(value)) throw new AdminBackendError('valid_idempotency_key_required', 400)
return value
}
function uuid(value: unknown, field: string): string {
if (typeof value !== 'string' || !UUID.test(value)) throw new AdminBackendError(`${field}_invalid`, 400)
return value
}
function rpcFailure(error: { code?: string | null; message?: string | null }): AdminBackendError {
const message = error.message ?? ''
if (/admin_identity_not_linked|insufficient_admin_role|super_admin_required|admin_role_required/i.test(message) || error.code === '42501') {
return new AdminBackendError('admin_forbidden', 403)
}
if (/target_user_not_found|subscription_not_found/i.test(message) || error.code === 'P0002') {
return new AdminBackendError('record_not_found', 404)
}
if (/already_exists|idempotency_key_reused|operation_in_progress|cannot_demote_last/i.test(message) ||
error.code === '23505' || error.code === '23514' || error.code === '55P03') {
return new AdminBackendError('record_conflict', 409)
}
if (/^invalid_|memo_must_be|tier_required/i.test(message) || error.code === '22023') {
return new AdminBackendError('invalid_request', 400)
}
return new AdminBackendError('supabase_admin_operation_failed', 500)
}
async function handleUsers(request: NextRequest): Promise<NextResponse> {
if (request.method !== 'PATCH') return NextResponse.json({ error: 'method_not_allowed' }, { status: 405 })
onlyQuery(request, [])
const session = await requireVerifiedBackendSession('admin')
const body = await bodyObject(request)
onlyKeys(body, ['userId', 'newRole', 'memo'])
const targetUserId = uuid(body.userId, 'user_id')
const newRole = typeof body.newRole === 'string' ? body.newRole : ''
if (!ROLES.has(newRole)) throw new AdminBackendError('role_invalid', 400)
const auditMemo = memo(body.memo)
const supabase = await getSupabaseAdminClient('admin')
const { data, error } = await supabase.rpc('admin_change_user_role_v1', {
p_actor_email: session.email,
p_idempotency_key: idempotencyKey(request),
p_target_user_id: targetUserId,
p_new_role: newRole,
p_memo: auditMemo
})
if (error) throw rpcFailure(error)
if (!data || typeof data !== 'object' || Array.isArray(data) ||
data.success !== true || data.userId !== targetUserId || data.newRole !== newRole) {
throw new AdminBackendError('invalid_admin_rpc_response', 502)
}
return NextResponse.json({ success: true, userId: targetUserId, newRole }, { headers: { 'Cache-Control': 'no-store' } })
}
async function handleSubscriptions(request: NextRequest): Promise<NextResponse> {
if (!['POST', 'PATCH', 'DELETE'].includes(request.method)) {
return NextResponse.json({ error: 'method_not_allowed' }, { status: 405 })
}
const minimumRole = request.method === 'PATCH' ? 'manager' : 'admin'
const session = await requireVerifiedBackendSession(minimumRole)
const body = await bodyObject(request)
const action = request.method === 'POST' ? 'create' : request.method === 'PATCH' ? 'update' : 'delete'
onlyQuery(request, action === 'create' ? [] : ['userId'])
onlyKeys(body, action === 'create'
? ['userId', 'tier', 'status', 'currentPeriodEnd', 'overageCredits', 'adminNote', 'memo']
: action === 'update'
? ['tier', 'status', 'currentPeriodEnd', 'overageCredits', 'adminNote', 'memo']
: ['memo'])
const requestedUserId = request.method === 'POST' ? body.userId : request.nextUrl.searchParams.get('userId')
const userId = uuid(requestedUserId, 'user_id')
const tier = typeof body.tier === 'string' ? body.tier : null
const status = typeof body.status === 'string' ? body.status : null
if (tier !== null && !TIERS.has(tier)) throw new AdminBackendError('tier_invalid', 400)
if (action === 'create' && tier === null) throw new AdminBackendError('tier_required', 400)
if (status !== null && !STATUSES.has(status)) throw new AdminBackendError('status_invalid', 400)
const overageCredits = body.overageCredits
if (overageCredits !== undefined &&
(!Number.isInteger(overageCredits) || (overageCredits as number) < 0 || (overageCredits as number) > 1_000_000)) {
throw new AdminBackendError('overage_credits_invalid', 400)
}
const adminNote = body.adminNote
if (adminNote !== undefined && (typeof adminNote !== 'string' || adminNote.length > 2000)) {
throw new AdminBackendError('admin_note_invalid', 400)
}
const supabase = await getSupabaseAdminClient(minimumRole)
const { data, error } = await supabase.rpc('admin_mutate_subscription_v1', {
p_actor_email: session.email,
p_idempotency_key: idempotencyKey(request),
p_action: action,
p_user_id: userId,
p_tier: tier,
p_status: status,
p_current_period_end: optionalDateTime(body.currentPeriodEnd),
p_overage_credits: typeof overageCredits === 'number' ? overageCredits : null,
p_admin_note: typeof adminNote === 'string' ? adminNote : null,
p_memo: memo(body.memo)
})
if (error) throw rpcFailure(error)
if (!data || typeof data !== 'object' || Array.isArray(data) || data.success !== true ||
!data.subscription || typeof data.subscription !== 'object' || Array.isArray(data.subscription) ||
data.subscription.user_id !== userId || !TIERS.has(String(data.subscription.tier)) || !STATUSES.has(String(data.subscription.status))) {
throw new AdminBackendError('invalid_admin_rpc_response', 502)
}
return NextResponse.json({ success: true, subscription: data.subscription }, { status: request.method === 'POST' ? 201 : 200, headers: { 'Cache-Control': 'no-store' } })
}
async function handlePayments(request: NextRequest): Promise<NextResponse> {
if (request.method !== 'GET') return NextResponse.json({ error: 'method_not_allowed' }, { status: 405 })
await requireVerifiedBackendSession('manager')
onlyQuery(request, ['userId', 'source'])
const userId = uuid(request.nextUrl.searchParams.get('userId'), 'user_id')
const source = request.nextUrl.searchParams.get('source') ?? 'db'
if (source !== 'db' && source !== 'payple') throw new AdminBackendError('payment_source_invalid', 400)
if (source === 'payple') {
return NextResponse.json({ error: 'payple_live_history_not_configured' }, { status: 501 })
}
const supabase = await getSupabaseAdminClient()
const [subscriptionResult, auditResult, eventsResult, operationsResult] = await Promise.all([
supabase.from('subscriptions')
.select('id, user_id, tier, status, provider, payment_provider, current_period_start, current_period_end, cancel_at, created_at, updated_at')
.eq('user_id', userId).maybeSingle(),
supabase.from('audit_log')
.select('id, admin_id, action, target_type, target_id, memo, created_at')
.eq('target_id', userId).eq('target_type', 'subscription').order('created_at', { ascending: false }).limit(50),
supabase.from('payment_provider_events')
.select('id, provider, event_type, event_created_at, disposition, received_at, processed_at')
.eq('user_id', userId).order('event_created_at', { ascending: false }).limit(50),
supabase.from('payment_provider_operations')
.select('id, provider, operation_type, requested_tier, state, error_code, expires_at, created_at, updated_at')
.eq('user_id', userId).order('created_at', { ascending: false }).limit(50)
])
if (subscriptionResult.error || auditResult.error || eventsResult.error || operationsResult.error) {
throw new AdminBackendError('payment_query_failed', 500)
}
return NextResponse.json({
subscription: subscriptionResult.data ?? null,
auditLogs: auditResult.data ?? [],
providerEvents: eventsResult.data ?? [],
providerOperations: operationsResult.data ?? [],
liveProviderHistoryAvailable: false
}, { headers: { 'Cache-Control': 'no-store' } })
}
async function route(request: NextRequest, context: { params: Promise<{ operation: string }> }): Promise<NextResponse> {
if (request.method !== 'GET' && !sameOrigin(request)) {
return NextResponse.json({ error: 'cross_site_request_rejected' }, { status: 403 })
}
try {
const { operation } = await context.params
if (operation === 'admin-users') return await handleUsers(request)
if (operation === 'admin-subscriptions') return await handleSubscriptions(request)
if (operation === 'admin-payments') return await handlePayments(request)
return NextResponse.json({ error: 'admin_operation_not_allowed' }, { status: 404 })
} catch (error) {
if (error instanceof AdminBackendError) {
return NextResponse.json({ error: error.message }, { status: error.status })
}
return NextResponse.json({ error: 'admin_operation_failed' }, { status: 500 })
}
}
export const GET = route
export const POST = route
export const PATCH = route
export const DELETE = route

View file

@ -1,157 +1,149 @@
// apps/admin/src/app/api/auth/login/route.ts
// D3RO Voice — Fortified Admin Authentication Handler
import { NextResponse } from 'next/server'
import { checkRateLimit, recordFailedAttempt, resetFailedAttempts, signSession } from '@/lib/security'
import {
checkRateLimit,
recordFailedAttempt,
resetFailedAttempts,
signSession
} from '@/lib/security'
import { adminCookieSecure } from '@/lib/admin-session'
const API_BASE = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:5000'
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<NextResponse> {
let body: unknown
try {
// 1. Extract Client IP & Identifier for Rate Limiting
const forwardedFor = request.headers.get('x-forwarded-for') || request.headers.get('cf-connecting-ip') || '127.0.0.1'
const clientIp = forwardedFor.split(',')[0].trim()
const body = await request.json()
const { usernameOrEmail, password, trap } = body
// 2. Honeypot Bot Trap: If hidden bot field is filled, silently reject
if (trap) {
await new Promise((resolve) => setTimeout(resolve, 1000))
return NextResponse.json({ success: false, message: 'Access denied' }, { status: 403 })
}
if (!usernameOrEmail || !password) {
return NextResponse.json(
{ success: false, message: '아이디와 비밀번호를 입력해주세요.' },
{ status: 400 }
)
}
const trimmedUser = String(usernameOrEmail).trim().toLowerCase()
const trimmedPass = String(password).trim()
const rateLimitKey = `${clientIp}:${trimmedUser}`
// 3. Check Sliding-Window Rate Limiter
const rateCheck = checkRateLimit(rateLimitKey)
if (!rateCheck.allowed) {
return NextResponse.json(
{
success: false,
message: `로그인 시도 횟수를 초과했습니다. 보안을 위해 ${rateCheck.retryAfterSeconds}초 후 다시 시도해주세요.`,
retryAfter: rateCheck.retryAfterSeconds,
},
{
status: 429,
headers: { 'Retry-After': String(rateCheck.retryAfterSeconds) },
}
)
}
let authenticated = false
let userRole = 'super_admin'
let userEmail = 'admin@d3ro.voice'
let token = ''
// 4. Master Admin Verification (admin / Test1234!)
if (
(trimmedUser === 'admin' || trimmedUser === 'admin@d3ro.voice' || trimmedUser === 'admin@d3ro.dev') &&
trimmedPass === 'Test1234!'
) {
authenticated = true
userRole = 'super_admin'
userEmail = 'admin@d3ro.voice'
token = `d3ro_tok_${Date.now()}`
}
// 5. Backend C# API Verification
if (!authenticated) {
try {
const apiRes = await fetch(`${API_BASE}/api/auth/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email: trimmedUser, password: trimmedPass }),
})
if (apiRes.ok) {
const data = await apiRes.json()
if (data.token) {
authenticated = true
token = data.token
userEmail = data.email || trimmedUser
userRole = (data.role || '').toLowerCase() === 'admin' ? 'admin' : 'super_admin'
}
}
} catch {
// Fallback catch
}
}
// 6. Handle Authentication Failure (Anti-Brute Force Tracking)
if (!authenticated) {
const lockResult = recordFailedAttempt(rateLimitKey)
// Dynamic delay to prevent timing analysis
await new Promise((resolve) => setTimeout(resolve, 600))
if (lockResult.locked) {
return NextResponse.json(
{
success: false,
message: `5회 이상 잘못된 비밀번호가 입력되었습니다. 보안을 위해 계정이 ${lockResult.retryAfterSeconds}초 동안 잠깁니다.`,
retryAfter: lockResult.retryAfterSeconds,
},
{
status: 429,
headers: { 'Retry-After': String(lockResult.retryAfterSeconds) },
}
)
}
return NextResponse.json(
{ success: false, message: '아이디 또는 비밀번호가 올바르지 않습니다.' },
{ status: 401 }
)
}
// 7. Successful Authentication -> Clear Rate Limiting
resetFailedAttempts(rateLimitKey)
// 8. Generate Cryptographically Signed HMAC Session Token
const sessionData = {
id: 'admin-usr-1',
username: 'admin',
email: userEmail,
role: userRole,
token,
loginAt: new Date().toISOString(),
expiresAt: Date.now() + 30 * 24 * 60 * 60 * 1000, // 30 days
}
const signedCookieValue = signSession(sessionData)
const response = NextResponse.json({
success: true,
user: {
id: sessionData.id,
email: sessionData.email,
role: sessionData.role,
},
})
// 9. Set Hardened HttpOnly SameSite=Strict Cookie
response.cookies.set({
name: 'd3ro_admin_session',
value: signedCookieValue,
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
path: '/',
maxAge: 30 * 24 * 60 * 60,
})
return response
} catch (error) {
const message = error instanceof Error ? error.message : 'Internal server error'
return NextResponse.json({ success: false, message }, { status: 500 })
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<string, unknown>
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
}

View file

@ -2,6 +2,7 @@
// D3RO Voice — Admin Session Logout Handler
import { NextResponse } from 'next/server'
import { adminCookieSecure } from '@/lib/admin-session'
export async function POST(): Promise<NextResponse> {
const response = NextResponse.json({ success: true, message: 'Logged out successfully' })
@ -10,7 +11,7 @@ export async function POST(): Promise<NextResponse> {
name: 'd3ro_admin_session',
value: '',
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
secure: adminCookieSecure(),
sameSite: 'lax',
path: '/',
maxAge: 0,
@ -28,7 +29,7 @@ export async function GET(request: Request): Promise<NextResponse> {
name: 'd3ro_admin_session',
value: '',
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
secure: adminCookieSecure(),
sameSite: 'lax',
path: '/',
maxAge: 0,