d3ro-voice/apps/admin/src/lib/admin-session.ts
Yun Chan 5a34f66981 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
2026-08-23 23:38:08 +09:00

72 lines
2.6 KiB
TypeScript

export type AdminRole = 'manager' | 'admin' | 'super_admin'
export interface AdminSession {
email: string
role: AdminRole
token: string
loginAt: string
expiresAt: number
}
const BASE64URL_PATTERN = /^[A-Za-z0-9_-]+$/
export function requireAdminSessionSecret(): string {
const value = process.env.ADMIN_SESSION_SECRET?.trim()
if (!value || new TextEncoder().encode(value).byteLength < 32) {
throw new Error('ADMIN_SESSION_SECRET must contain at least 32 bytes')
}
return value
}
export function parseAdminSession(value: unknown, now = Date.now()): AdminSession | null {
if (!value || typeof value !== 'object' || Array.isArray(value)) return null
const candidate = value as Record<string, unknown>
const email = typeof candidate.email === 'string' ? candidate.email.trim().toLowerCase() : ''
const role = candidate.role
const token = candidate.token
const loginAt = candidate.loginAt
const expiresAt = candidate.expiresAt
if (!email || email.length > 150 || !email.includes('@')) return null
if (role !== 'manager' && role !== 'admin' && role !== 'super_admin') return null
if (typeof token !== 'string' || token.length < 80 || token.length > 8_192) return null
if (typeof loginAt !== 'string' || !Number.isFinite(Date.parse(loginAt))) return null
if (typeof expiresAt !== 'number' || !Number.isFinite(expiresAt) || expiresAt <= now) return null
return { email, role, token, loginAt, expiresAt }
}
export function decodeBase64Url(value: string): Uint8Array | null {
if (!value || !BASE64URL_PATTERN.test(value)) return null
try {
const padding = '='.repeat((4 - (value.length % 4)) % 4)
const binary = atob(value.replace(/-/g, '+').replace(/_/g, '/') + padding)
const bytes = new Uint8Array(binary.length)
for (let index = 0; index < binary.length; index += 1) {
bytes[index] = binary.charCodeAt(index)
}
return bytes
} catch {
return null
}
}
export function decodeAdminSessionPayload(encodedPayload: string): AdminSession | null {
const bytes = decodeBase64Url(encodedPayload)
if (!bytes || bytes.byteLength === 0 || bytes.byteLength > 16_384) return null
try {
return parseAdminSession(JSON.parse(new TextDecoder().decode(bytes)))
} catch {
return null
}
}
// ADMIN_COOKIE_SECURE=false: TLS 종료 프록시 없이 LAN HTTP(예: http://NAS_IP:3001)로
// 직접 접속하는 배포에서만 사용. Secure 쿠키는 HTTP에서 브라우저가 버려 로그인이 유지되지 않는다.
export function adminCookieSecure(): boolean {
if (process.env.ADMIN_COOKIE_SECURE === 'false') return false
return process.env.NODE_ENV === 'production'
}