fix(cloud): harden edge gateways, api-server ssrf, supabase fail-closed quota, and web/admin lifecycle

This commit is contained in:
Yun Chan 2026-11-14 15:10:32 +09:00
parent 2a009e421a
commit c68e81e0aa
46 changed files with 2553 additions and 294 deletions

View file

@ -3,21 +3,33 @@
import { NextResponse, type NextRequest } from 'next/server'
import { createServerClient, type CookieOptions } from '@supabase/ssr'
import { resolveAdminCallbackOrigin, safeAdminRedirectPath } from '@/lib/admin-url-safety'
export async function GET(request: NextRequest): Promise<NextResponse> {
const { searchParams, origin } = new URL(request.url)
const { searchParams } = new URL(request.url)
const origin = resolveAdminCallbackOrigin(
request.url,
process.env.ADMIN_PUBLIC_ORIGIN ?? process.env.NEXT_PUBLIC_ADMIN_ORIGIN,
)
const code = searchParams.get('code')
const nextPath = safeAdminRedirectPath(searchParams.get('next'))
if (!code) {
return NextResponse.redirect(`${origin}/login?error=no_code`)
}
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL?.trim()
const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY?.trim()
if (!supabaseUrl || !supabaseAnonKey) {
return NextResponse.redirect(`${origin}/login?error=auth_unavailable`)
}
// 쿠키를 수집할 배열
const cookiesToSet: Array<{ name: string; value: string; options: CookieOptions }> = []
const supabase = createServerClient(
process.env.NEXT_PUBLIC_SUPABASE_URL ?? '',
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY ?? '',
supabaseUrl,
supabaseAnonKey,
{
cookies: {
getAll() {
@ -33,11 +45,11 @@ export async function GET(request: NextRequest): Promise<NextResponse> {
const { error } = await supabase.auth.exchangeCodeForSession(code)
if (error) {
return NextResponse.redirect(`${origin}/login?error=${encodeURIComponent(error.message)}`)
return NextResponse.redirect(`${origin}/login?error=oauth_callback_failed`)
}
// 세션 교환 성공 후 response 생성 + 수집된 쿠키 적용
const response = NextResponse.redirect(`${origin}/`)
const response = NextResponse.redirect(`${origin}${nextPath}`)
for (const { name, value, options } of cookiesToSet) {
response.cookies.set({ name, value, ...options })
}

View file

@ -9,13 +9,14 @@ import GoogleIcon from '@mui/icons-material/Google'
import LockOutlinedIcon from '@mui/icons-material/LockOutlined'
import { DoubleBezelCard, TactileBadge } from '@d3ro/ui/components/ds'
import { C, FONT_SANS, FONT_MONO, primaryButtonSx } from '@/lib/console-theme'
import { safeAdminRedirectPath } from '@/lib/admin-url-safety'
import { getSupabaseBrowserClient } from '@/lib/supabase-browser'
import { useRouter, useSearchParams } from 'next/navigation'
function LoginForm(): React.ReactElement {
const router = useRouter()
const searchParams = useSearchParams()
const redirectPath = searchParams.get('redirect') || '/'
const redirectPath = safeAdminRedirectPath(searchParams.get('redirect'))
const [usernameOrEmail, setUsernameOrEmail] = useState('')
const [password, setPassword] = useState('')

View file

@ -3,7 +3,7 @@
// apps/admin/src/components/subscription-form.tsx
// 구독 생성/수정 공용 폼
import { useState } from 'react'
import { useEffect, useRef, useState } from 'react'
import {
Box,
TextField,
@ -17,6 +17,7 @@ import {
import { MetalCard, PhosphorText } from '@d3ro/ui/components/ds'
import { d3roPalette, d3roFontMono } from '@d3ro/ui/theme'
import { callAdminApi } from '@/lib/admin-api'
import { parseOptionalIsoDate } from '@/lib/admin-url-safety'
type Tier = 'free' | 'pro' | 'pro_plus'
type SubStatus = 'active' | 'canceled' | 'past_due' | 'expired'
@ -44,10 +45,24 @@ export function SubscriptionForm({ mode, userId, initial, onSuccess }: Subscript
const [loading, setLoading] = useState(false)
const [error, setError] = useState<string | null>(null)
const [success, setSuccess] = useState(false)
const mountedRef = useRef(true)
useEffect(() => {
mountedRef.current = true
return () => {
mountedRef.current = false
}
}, [])
const handleSubmit = async (): Promise<void> => {
if (!memo.trim()) return
const parsedEnd = parseOptionalIsoDate(periodEnd)
if (!parsedEnd.ok) {
setError(parsedEnd.message)
return
}
setLoading(true)
setError(null)
setSuccess(false)
@ -60,31 +75,36 @@ export function SubscriptionForm({ mode, userId, initial, onSuccess }: Subscript
userId,
tier,
status,
currentPeriodEnd: periodEnd ? new Date(periodEnd).toISOString() : undefined,
currentPeriodEnd: parsedEnd.iso,
adminNote: adminNote || undefined,
memo: memo.trim(),
}),
})
} else {
await callAdminApi(`admin-subscriptions?userId=${userId}`, {
await callAdminApi(`admin-subscriptions?userId=${encodeURIComponent(userId)}`, {
method: 'PATCH',
body: JSON.stringify({
tier,
status,
currentPeriodEnd: periodEnd ? new Date(periodEnd).toISOString() : undefined,
currentPeriodEnd: parsedEnd.iso,
overageCredits,
adminNote: adminNote || undefined,
memo: memo.trim(),
}),
})
}
if (!mountedRef.current) return
setSuccess(true)
setMemo('')
onSuccess()
} catch (err) {
setError(err instanceof Error ? err.message : 'Operation failed')
if (mountedRef.current) {
setError(err instanceof Error ? err.message : 'Operation failed')
}
} finally {
setLoading(false)
if (mountedRef.current) {
setLoading(false)
}
}
}

View file

@ -0,0 +1,70 @@
const STATIC_ASSET_EXT_RE =
/\.(?:ico|png|jpg|jpeg|gif|svg|webp|woff2?|ttf|eot|css|js|map|txt|xml|webmanifest)$/i
function hasUnsafeControlOrBackslash(value: string): boolean {
for (let i = 0; i < value.length; i += 1) {
const code = value.charCodeAt(i)
if (code <= 0x1f || code === 0x7f || code === 0x5c) {
return true
}
}
return false
}
/**
* 관리자 콘솔 내부 경로만 허용한다.
* `//evil.example`, `https://evil.example`, `/\evil.example`, 제어문자는 `/`로 폴백한다.
*/
export function safeAdminRedirectPath(value: string | null | undefined): string {
if (!value || !value.startsWith('/') || value.startsWith('//') || hasUnsafeControlOrBackslash(value)) {
return '/'
}
try {
const parsed = new URL(value, 'https://d3ro-admin.local')
if (parsed.origin !== 'https://d3ro-admin.local' || parsed.pathname.startsWith('//')) {
return '/'
}
} catch {
return '/'
}
return value
}
/** 정적 에셋 확장자 경로만 인증 우회 정적 경로로 간주한다. `/api/*`는 절대 면제하지 않는다. */
export function isStaticAssetPath(pathname: string): boolean {
if (pathname.startsWith('/_next/') || pathname === '/_next') return true
if (pathname.startsWith('/static/') || pathname === '/static') return true
if (pathname.startsWith('/api/') || pathname === '/api') return false
return STATIC_ASSET_EXT_RE.test(pathname)
}
/** 관리자 OAuth 콜백 리다이렉트 기준 origin을 반환한다. 설정값이 유효하면 우선한다. */
export function resolveAdminCallbackOrigin(requestUrl: string, configuredOrigin?: string): string {
const configured = configuredOrigin?.trim()
if (configured) {
try {
const parsed = new URL(configured)
if (parsed.protocol === 'https:' || parsed.protocol === 'http:') {
return parsed.origin
}
} catch {
// 잘못된 설정값은 요청 URL origin으로 폴백한다.
}
}
return new URL(requestUrl).origin
}
/** 선택적 날짜 입력을 ISO-8601 문자열로 검증·변환한다. */
export function parseOptionalIsoDate(
raw: string,
): { ok: true; iso: string | undefined } | { ok: false; message: string } {
const trimmed = raw.trim()
if (!trimmed) {
return { ok: true, iso: undefined }
}
const timestamp = Date.parse(trimmed)
if (!Number.isFinite(timestamp)) {
return { ok: false, message: '올바른 종료일 형식이 아닙니다.' }
}
return { ok: true, iso: new Date(timestamp).toISOString() }
}

View file

@ -1,6 +1,7 @@
// D3RO Voice — Industrial Grade Admin Route & Security Guard
import { NextResponse, type NextRequest } from 'next/server'
import { isStaticAssetPath, safeAdminRedirectPath } from '@/lib/admin-url-safety'
import { verifyEdgeSession } from '@/lib/edge-session'
const PUBLIC_PATHS = [
@ -15,15 +16,15 @@ const PUBLIC_PATHS = [
export async function proxy(request: NextRequest): Promise<NextResponse> {
const { pathname } = request.nextUrl
const isPublic = PUBLIC_PATHS.some((path) => pathname === path || pathname.startsWith(path + '/'))
const isStatic =
pathname.startsWith('/_next') || pathname.startsWith('/static') || pathname.includes('.')
const isStatic = isStaticAssetPath(pathname)
const sessionCookie = request.cookies.get('d3ro_admin_session')?.value
const isAuthenticated = sessionCookie ? (await verifyEdgeSession(sessionCookie)) !== null : false
if (!isAuthenticated && !isPublic && !isStatic) {
const loginUrl = new URL('/login', request.url)
if (pathname !== '/') loginUrl.searchParams.set('redirect', pathname)
const safeRedirect = safeAdminRedirectPath(pathname)
if (safeRedirect !== '/') loginUrl.searchParams.set('redirect', safeRedirect)
const redirectResponse = NextResponse.redirect(loginUrl)
addSecurityHeaders(redirectResponse)
return redirectResponse