fix(cloud): harden edge gateways, api-server ssrf, supabase fail-closed quota, and web/admin lifecycle
This commit is contained in:
parent
2a009e421a
commit
c68e81e0aa
46 changed files with 2553 additions and 294 deletions
|
|
@ -7,7 +7,8 @@
|
|||
"dev": "next dev --port 3001",
|
||||
"build": "next build",
|
||||
"start": "next start --port 3001",
|
||||
"typecheck": "next typegen && tsc --noEmit"
|
||||
"typecheck": "next typegen && tsc --noEmit",
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@d3ro/api-client": "*",
|
||||
|
|
|
|||
|
|
@ -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 })
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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('')
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
70
apps/admin/src/lib/admin-url-safety.ts
Normal file
70
apps/admin/src/lib/admin-url-safety.ts
Normal 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() }
|
||||
}
|
||||
|
|
@ -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
|
||||
|
|
|
|||
123
apps/admin/tests/admin-security.test.ts
Normal file
123
apps/admin/tests/admin-security.test.ts
Normal file
|
|
@ -0,0 +1,123 @@
|
|||
import { NextRequest } from 'next/server'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
isStaticAssetPath,
|
||||
parseOptionalIsoDate,
|
||||
resolveAdminCallbackOrigin,
|
||||
safeAdminRedirectPath,
|
||||
} from '@/lib/admin-url-safety'
|
||||
|
||||
const mockCreateServerClient = vi.fn()
|
||||
const mockExchangeCodeForSession = vi.fn()
|
||||
|
||||
vi.mock('@supabase/ssr', () => ({
|
||||
createServerClient: (...args: unknown[]) => {
|
||||
mockCreateServerClient(...args)
|
||||
return {
|
||||
auth: {
|
||||
exchangeCodeForSession: (code: string) => mockExchangeCodeForSession(code),
|
||||
},
|
||||
}
|
||||
},
|
||||
}))
|
||||
|
||||
describe('Admin 라우트 가드 및 OAuth 콜백 보안', () => {
|
||||
const originalSupabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL
|
||||
const originalSupabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY
|
||||
const originalAdminOrigin = process.env.ADMIN_PUBLIC_ORIGIN
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks()
|
||||
process.env.NEXT_PUBLIC_SUPABASE_URL = originalSupabaseUrl
|
||||
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY = originalSupabaseAnonKey
|
||||
process.env.ADMIN_PUBLIC_ORIGIN = originalAdminOrigin
|
||||
})
|
||||
|
||||
it('proxy_점포함동적경로나API경로미인증접근_정적으로우회하지않고로그인으로차단한다', async () => {
|
||||
const { proxy } = await import('@/proxy')
|
||||
|
||||
const dottedUserRoute = new NextRequest('https://admin.chanpaca.net/users/john.doe')
|
||||
const userRes = await proxy(dottedUserRoute)
|
||||
expect(userRes.status).toBe(307)
|
||||
expect(userRes.headers.get('location')).toBe(
|
||||
'https://admin.chanpaca.net/login?redirect=%2Fusers%2Fjohn.doe',
|
||||
)
|
||||
|
||||
const dottedApiRoute = new NextRequest('https://admin.chanpaca.net/api/audit.export')
|
||||
const apiRes = await proxy(dottedApiRoute)
|
||||
expect(apiRes.status).toBe(307)
|
||||
expect(apiRes.headers.get('location')).toBe(
|
||||
'https://admin.chanpaca.net/login?redirect=%2Fapi%2Faudit.export',
|
||||
)
|
||||
|
||||
const staticAsset = new NextRequest('https://admin.chanpaca.net/static/logo.png')
|
||||
const staticRes = await proxy(staticAsset)
|
||||
expect(staticRes.status).toBe(200)
|
||||
expect(isStaticAssetPath('/api/logo.png')).toBe(false)
|
||||
expect(isStaticAssetPath('/_next/static/chunk.js')).toBe(true)
|
||||
})
|
||||
|
||||
it('safeAdminRedirectPath_외부URL이나프로토콜상대경로_루트로폴백한다', () => {
|
||||
expect(safeAdminRedirectPath('https://evil.example/phish')).toBe('/')
|
||||
expect(safeAdminRedirectPath('//evil.example/phish')).toBe('/')
|
||||
expect(safeAdminRedirectPath('/\\evil.example')).toBe('/')
|
||||
expect(safeAdminRedirectPath('/users\r\n')).toBe('/')
|
||||
expect(safeAdminRedirectPath('/users/123?tab=billing')).toBe('/users/123?tab=billing')
|
||||
})
|
||||
|
||||
it('parseOptionalIsoDate_유효하지않은날짜입력_예외없이오류를반환한다', () => {
|
||||
expect(parseOptionalIsoDate('')).toEqual({ ok: true, iso: undefined })
|
||||
expect(parseOptionalIsoDate('2026-12-31')).toEqual({
|
||||
ok: true,
|
||||
iso: '2026-12-31T00:00:00.000Z',
|
||||
})
|
||||
expect(parseOptionalIsoDate('invalid-date-value')).toEqual({
|
||||
ok: false,
|
||||
message: '올바른 종료일 형식이 아닙니다.',
|
||||
})
|
||||
})
|
||||
|
||||
it('authCallback_GET_Supabase환경변수누락시_빈문자클라이언트생성없이실패닫힘으로리다이렉트한다', async () => {
|
||||
delete process.env.NEXT_PUBLIC_SUPABASE_URL
|
||||
delete process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY
|
||||
const { GET } = await import('@/app/auth/callback/route')
|
||||
const req = new NextRequest('https://admin.chanpaca.net/auth/callback?code=fake-oauth-code')
|
||||
|
||||
const res = await GET(req)
|
||||
expect(res.status).toBe(307)
|
||||
expect(mockCreateServerClient).not.toHaveBeenCalled()
|
||||
expect(res.headers.get('location')).toBe('https://admin.chanpaca.net/login?error=auth_unavailable')
|
||||
})
|
||||
|
||||
it('authCallback_GET_세션교환실패시_원시에러노출없이고정코드로리다이렉트한다', async () => {
|
||||
process.env.NEXT_PUBLIC_SUPABASE_URL = 'https://example.supabase.co'
|
||||
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY = 'public-anon-example'
|
||||
mockExchangeCodeForSession.mockResolvedValue({
|
||||
error: { message: 'internal error http://10.0.0.5:5432' },
|
||||
})
|
||||
const { GET } = await import('@/app/auth/callback/route')
|
||||
const req = new NextRequest('https://admin.chanpaca.net/auth/callback?code=fake-oauth-code')
|
||||
|
||||
const res = await GET(req)
|
||||
expect(res.status).toBe(307)
|
||||
const location = res.headers.get('location') ?? ''
|
||||
expect(location).toBe('https://admin.chanpaca.net/login?error=oauth_callback_failed')
|
||||
expect(location).not.toContain('10.0.0.5')
|
||||
})
|
||||
|
||||
it('authCallback_GET_공개origin설정과위험한next파라미터_공개도메인루트로만이동한다', async () => {
|
||||
process.env.NEXT_PUBLIC_SUPABASE_URL = 'https://example.supabase.co'
|
||||
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY = 'public-anon-example'
|
||||
process.env.ADMIN_PUBLIC_ORIGIN = 'https://admin.chanpaca.net/ignored-path'
|
||||
mockExchangeCodeForSession.mockResolvedValue({ error: null })
|
||||
const { GET } = await import('@/app/auth/callback/route')
|
||||
const req = new NextRequest('http://127.0.0.1:3001/auth/callback?code=ok-code&next=//evil.example')
|
||||
|
||||
const res = await GET(req)
|
||||
expect(res.status).toBe(307)
|
||||
expect(res.headers.get('location')).toBe('https://admin.chanpaca.net/')
|
||||
expect(
|
||||
resolveAdminCallbackOrigin('http://127.0.0.1:3001/auth/callback', 'javascript:alert(1)'),
|
||||
).toBe('http://127.0.0.1:3001')
|
||||
})
|
||||
})
|
||||
19
apps/admin/vitest.config.ts
Normal file
19
apps/admin/vitest.config.ts
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
import path from 'node:path'
|
||||
import { defineConfig } from 'vitest/config'
|
||||
|
||||
export default defineConfig({
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': path.resolve(__dirname, './src'),
|
||||
},
|
||||
},
|
||||
esbuild: {
|
||||
jsx: 'automatic',
|
||||
},
|
||||
test: {
|
||||
globals: false,
|
||||
environment: 'node',
|
||||
include: ['tests/**/*.test.{ts,tsx}'],
|
||||
testTimeout: 10000,
|
||||
},
|
||||
})
|
||||
507
apps/api-server.Tests/EndpointSecurityAndSttProxyTests.cs
Normal file
507
apps/api-server.Tests/EndpointSecurityAndSttProxyTests.cs
Normal file
|
|
@ -0,0 +1,507 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using D3ROVoice.Api.Controllers;
|
||||
using D3ROVoice.Api.Data;
|
||||
using D3ROVoice.Api.Dtos;
|
||||
using D3ROVoice.Api.Services;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Xunit;
|
||||
|
||||
namespace D3ROVoice.Api.Tests;
|
||||
|
||||
public class EndpointSecurityAndSttProxyTests
|
||||
{
|
||||
private static readonly byte[] SampleWav = BuildTinyWavBytes();
|
||||
|
||||
[Theory]
|
||||
[InlineData("https://169.254.169.254/latest/meta-data", "OpenAI")]
|
||||
[InlineData("https://10.0.0.1/v1/chat/completions", "OpenAI")]
|
||||
[InlineData("https://172.16.0.10/v1/chat/completions", "OpenAI")]
|
||||
[InlineData("https://192.168.1.50/v1/chat/completions", "OpenAI")]
|
||||
[InlineData("https://100.64.0.5/v1/chat/completions", "OpenAI")]
|
||||
[InlineData("https://[::1]/v1/chat/completions", "OpenAI")]
|
||||
[InlineData("https://[fe80::1]/v1/chat/completions", "OpenAI")]
|
||||
[InlineData("https://metadata.google.internal/computeMetadata/v1", "OpenAI")]
|
||||
[InlineData("http://localhost:11434/api/generate", "OpenAI")]
|
||||
public async Task CreateEndpoint_내부SSRF및허용되지않은루프백URL_BadRequest로차단한다(string url, string provider)
|
||||
{
|
||||
await using var harness = await ApiHarness.CreateAsync();
|
||||
|
||||
var result = await harness.AdminController.CreateEndpoint(new CreateModelEndpointDto(
|
||||
ModelId: "test-model",
|
||||
ModelName: "Test Model",
|
||||
Provider: provider,
|
||||
EndpointUrl: url,
|
||||
ApiKey: "sk-test",
|
||||
CostPer1kPromptTokens: 0.001m,
|
||||
CostPer1kCompletionTokens: 0.002m,
|
||||
Memo: "security-audit-test"));
|
||||
|
||||
Assert.IsType<BadRequestObjectResult>(result);
|
||||
Assert.Empty(await harness.Db.ModelEndpoints.ToListAsync());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateEndpoint_URL자격증명포함시_BadRequest로차단한다()
|
||||
{
|
||||
await using var harness = await ApiHarness.CreateAsync();
|
||||
var urlWithUserInfo = new UriBuilder("https", "api.openai.com")
|
||||
{
|
||||
UserName = "user",
|
||||
Password = "pass",
|
||||
Path = "/v1/chat/completions",
|
||||
}.Uri.AbsoluteUri;
|
||||
|
||||
var result = await harness.AdminController.CreateEndpoint(new CreateModelEndpointDto(
|
||||
ModelId: "test-model",
|
||||
ModelName: "Test Model",
|
||||
Provider: "OpenAI",
|
||||
EndpointUrl: urlWithUserInfo,
|
||||
ApiKey: "sk-test",
|
||||
CostPer1kPromptTokens: 0.001m,
|
||||
CostPer1kCompletionTokens: 0.002m,
|
||||
Memo: "security-audit-test"));
|
||||
|
||||
Assert.IsType<BadRequestObjectResult>(result);
|
||||
Assert.Empty(await harness.Db.ModelEndpoints.ToListAsync());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateEndpoint_로컬Ollama와공개HTTPS엔드포인트_정상생성한다()
|
||||
{
|
||||
await using var harness = await ApiHarness.CreateAsync();
|
||||
|
||||
var ollamaResult = await harness.AdminController.CreateEndpoint(new CreateModelEndpointDto(
|
||||
ModelId: "ollama-gemma",
|
||||
ModelName: "Ollama Local",
|
||||
Provider: "Ollama Local",
|
||||
EndpointUrl: "http://localhost:11434/api/generate",
|
||||
ApiKey: "",
|
||||
CostPer1kPromptTokens: 0m,
|
||||
CostPer1kCompletionTokens: 0m,
|
||||
Memo: "security-audit-test"));
|
||||
|
||||
Assert.IsType<OkObjectResult>(ollamaResult);
|
||||
|
||||
harness.SetNewIdempotencyKey();
|
||||
var publicResult = await harness.AdminController.CreateEndpoint(new CreateModelEndpointDto(
|
||||
ModelId: "openai-gpt",
|
||||
ModelName: "GPT",
|
||||
Provider: "OpenAI",
|
||||
EndpointUrl: "https://api.openai.com/v1/chat/completions",
|
||||
ApiKey: "sk-live",
|
||||
CostPer1kPromptTokens: 0.001m,
|
||||
CostPer1kCompletionTokens: 0.002m,
|
||||
Memo: "security-audit-test"));
|
||||
|
||||
Assert.IsType<OkObjectResult>(publicResult);
|
||||
Assert.Equal(2, await harness.Db.ModelEndpoints.CountAsync());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateSttEndpoint_내부SSRF주소와NaN온도및원격루프백_BadRequest로차단한다()
|
||||
{
|
||||
await using var harness = await ApiHarness.CreateAsync();
|
||||
|
||||
var metadataBlocked = await harness.AdminController.CreateSttEndpoint(new CreateSttEndpointDto(
|
||||
Name: "Metadata",
|
||||
ProviderType: "groq",
|
||||
EndpointUrl: "https://169.254.169.254/latest/meta-data",
|
||||
ApiKey: "k",
|
||||
ModelId: "whisper-large-v3",
|
||||
Method: "multipart",
|
||||
Language: "ko",
|
||||
Prompt: null,
|
||||
Temperature: 0.0,
|
||||
CostPerMinute: 0m,
|
||||
CostPerSecond: 0m,
|
||||
IsDefault: false,
|
||||
IsActive: true,
|
||||
FallbackPriority: 1,
|
||||
ExtraHeadersJson: null,
|
||||
Memo: "security-audit-test"));
|
||||
Assert.IsType<BadRequestObjectResult>(metadataBlocked);
|
||||
|
||||
harness.SetNewIdempotencyKey();
|
||||
var remoteLoopbackBlocked = await harness.AdminController.CreateSttEndpoint(new CreateSttEndpointDto(
|
||||
Name: "RemoteLoopback",
|
||||
ProviderType: "groq",
|
||||
EndpointUrl: "http://127.0.0.1:8971/stt/transcribe",
|
||||
ApiKey: "k",
|
||||
ModelId: "whisper-large-v3",
|
||||
Method: "multipart",
|
||||
Language: "ko",
|
||||
Prompt: null,
|
||||
Temperature: 0.0,
|
||||
CostPerMinute: 0m,
|
||||
CostPerSecond: 0m,
|
||||
IsDefault: false,
|
||||
IsActive: true,
|
||||
FallbackPriority: 1,
|
||||
ExtraHeadersJson: null,
|
||||
Memo: "security-audit-test"));
|
||||
Assert.IsType<BadRequestObjectResult>(remoteLoopbackBlocked);
|
||||
|
||||
harness.SetNewIdempotencyKey();
|
||||
var nanTempBlocked = await harness.AdminController.CreateSttEndpoint(new CreateSttEndpointDto(
|
||||
Name: "BadTemp",
|
||||
ProviderType: "groq",
|
||||
EndpointUrl: "https://api.groq.com/openai/v1/audio/transcriptions",
|
||||
ApiKey: "k",
|
||||
ModelId: "whisper-large-v3",
|
||||
Method: "multipart",
|
||||
Language: "ko",
|
||||
Prompt: null,
|
||||
Temperature: double.NaN,
|
||||
CostPerMinute: 0m,
|
||||
CostPerSecond: 0m,
|
||||
IsDefault: false,
|
||||
IsActive: true,
|
||||
FallbackPriority: 1,
|
||||
ExtraHeadersJson: null,
|
||||
Memo: "security-audit-test"));
|
||||
Assert.IsType<BadRequestObjectResult>(nanTempBlocked);
|
||||
|
||||
harness.SetNewIdempotencyKey();
|
||||
var localSidecarOk = await harness.AdminController.CreateSttEndpoint(new CreateSttEndpointDto(
|
||||
Name: "Sidecar",
|
||||
ProviderType: "local-sidecar",
|
||||
EndpointUrl: "http://localhost:8971/stt/transcribe",
|
||||
ApiKey: "",
|
||||
ModelId: "whisper-large-v3-turbo",
|
||||
Method: "multipart",
|
||||
Language: "ko",
|
||||
Prompt: null,
|
||||
Temperature: 0.0,
|
||||
CostPerMinute: 0m,
|
||||
CostPerSecond: 0m,
|
||||
IsDefault: false,
|
||||
IsActive: true,
|
||||
FallbackPriority: 2,
|
||||
ExtraHeadersJson: null,
|
||||
Memo: "security-audit-test"));
|
||||
Assert.IsType<OkObjectResult>(localSidecarOk);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("https://169.254.169.254/latest/meta-data")]
|
||||
[InlineData("http://127.0.0.1:8971/stt/transcribe")]
|
||||
[InlineData("https://10.0.0.5/stt")]
|
||||
public async Task TestSttDirect_내부및루프백URL_요청없이BadRequest로차단한다(string url)
|
||||
{
|
||||
await using var harness = await ApiHarness.CreateAsync();
|
||||
|
||||
var result = await harness.AdminController.TestSttDirect(new DirectSttTestDto(url, "sk-test"));
|
||||
|
||||
Assert.IsType<BadRequestObjectResult>(result);
|
||||
Assert.Empty(harness.CapturedRequests);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TranscribeAsync_악의적언어문자열_쿼리및프롬프트인젝션을차단한다()
|
||||
{
|
||||
await using var harness = await ApiHarness.CreateAsync();
|
||||
harness.Db.SttProviderEndpoints.Add(new SttProviderEndpoint
|
||||
{
|
||||
Name = "Deepgram",
|
||||
ProviderType = "deepgram",
|
||||
EndpointUrl = "https://api.deepgram.com/v1/listen",
|
||||
ApiKey = "dg-secret",
|
||||
ModelId = "nova-3",
|
||||
Method = "binary-stream",
|
||||
Language = "ko",
|
||||
IsDefault = true,
|
||||
IsActive = true,
|
||||
FallbackPriority = 1,
|
||||
});
|
||||
await harness.Db.SaveChangesAsync();
|
||||
|
||||
await Assert.ThrowsAsync<ArgumentException>(() =>
|
||||
harness.SttService.TranscribeAsync(
|
||||
1,
|
||||
"user@d3ro.test",
|
||||
new SttTranscribeRequest(Language: "ko&callback=https://attacker.test/hook"),
|
||||
SampleWav,
|
||||
"audio/wav",
|
||||
"clip.wav",
|
||||
recordUsage: false));
|
||||
|
||||
Assert.Empty(harness.CapturedRequests);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TranscribeAsync_특수문자포함모델ID_Deepgram쿼리를URL인코딩한다()
|
||||
{
|
||||
await using var harness = await ApiHarness.CreateAsync(_ => new HttpResponseMessage(HttpStatusCode.OK)
|
||||
{
|
||||
Content = new StringContent("""{"results":{"channels":[{"alternatives":[{"transcript":"hello","confidence":0.99}]}]},"metadata":{"duration":1.2}}""", Encoding.UTF8, "application/json")
|
||||
});
|
||||
|
||||
harness.Db.SttProviderEndpoints.Add(new SttProviderEndpoint
|
||||
{
|
||||
Name = "Deepgram",
|
||||
ProviderType = "deepgram",
|
||||
EndpointUrl = "https://api.deepgram.com/v1/listen",
|
||||
ApiKey = "dg-secret",
|
||||
ModelId = "nova-3&tier=enterprise",
|
||||
Method = "binary-stream",
|
||||
Language = "ko",
|
||||
IsDefault = true,
|
||||
IsActive = true,
|
||||
FallbackPriority = 1,
|
||||
});
|
||||
await harness.Db.SaveChangesAsync();
|
||||
|
||||
var res = await harness.SttService.TranscribeAsync(
|
||||
1,
|
||||
"user@d3ro.test",
|
||||
new SttTranscribeRequest(Language: "ko-KR"),
|
||||
SampleWav,
|
||||
"audio/wav",
|
||||
"clip.wav",
|
||||
recordUsage: false);
|
||||
|
||||
Assert.Equal("hello", res.Text);
|
||||
var captured = Assert.Single(harness.CapturedRequests);
|
||||
Assert.Contains("model=nova-3%26tier%3Denterprise", captured.RequestUri!.Query, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("&tier=enterprise", captured.RequestUri!.Query, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("openai", "https://api.openai.com/v1/audio/transcriptions", """{"text":"안녕","duration":1.0,"language":"ko"}""")]
|
||||
[InlineData("deepgram", "https://api.deepgram.com/v1/listen", """{"results":{"channels":[{"alternatives":[{"transcript":"안녕","confidence":0.95}]}]},"metadata":{"duration":1.0}}""")]
|
||||
[InlineData("google", "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent", """{"candidates":[{"content":{"parts":[{"text":"안녕"}]}}]}""")]
|
||||
[InlineData("azure", "https://koreacentral.stt.speech.microsoft.com/speech/recognition/conversation/cognitiveservices/v1", """{"DisplayText":"안녕"}""")]
|
||||
public async Task TranscribeAsync_앞뒤공백및개행포함ApiKey_Trim후정상전송한다(string providerType, string url, string jsonBody)
|
||||
{
|
||||
await using var harness = await ApiHarness.CreateAsync(_ => new HttpResponseMessage(HttpStatusCode.OK)
|
||||
{
|
||||
Content = new StringContent(jsonBody, Encoding.UTF8, "application/json")
|
||||
});
|
||||
|
||||
harness.Db.SttProviderEndpoints.Add(new SttProviderEndpoint
|
||||
{
|
||||
Name = providerType,
|
||||
ProviderType = providerType,
|
||||
EndpointUrl = url,
|
||||
ApiKey = " secret-token-with-whitespace \r\n",
|
||||
ModelId = "model-1",
|
||||
Method = "multipart",
|
||||
Language = "ko",
|
||||
IsDefault = true,
|
||||
IsActive = true,
|
||||
FallbackPriority = 1,
|
||||
});
|
||||
await harness.Db.SaveChangesAsync();
|
||||
|
||||
var res = await harness.SttService.TranscribeAsync(
|
||||
1,
|
||||
"user@d3ro.test",
|
||||
new SttTranscribeRequest(Language: "ko"),
|
||||
SampleWav,
|
||||
"audio/wav",
|
||||
"clip.wav",
|
||||
recordUsage: false);
|
||||
|
||||
Assert.Equal("안녕", res.Text);
|
||||
Assert.Single(harness.CapturedRequests);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TranscribeAsync_AssemblyAI비정상폴링ID_경로탐색요청없이실패폐쇄한다()
|
||||
{
|
||||
await using var harness = await ApiHarness.CreateAsync(req =>
|
||||
{
|
||||
var path = req.RequestUri!.AbsolutePath;
|
||||
if (path == "/v2/upload")
|
||||
{
|
||||
return new HttpResponseMessage(HttpStatusCode.OK)
|
||||
{
|
||||
Content = new StringContent("""{"upload_url":"https://cdn.assemblyai.com/upload/abc"}""", Encoding.UTF8, "application/json")
|
||||
};
|
||||
}
|
||||
if (path == "/v2/transcript")
|
||||
{
|
||||
return new HttpResponseMessage(HttpStatusCode.OK)
|
||||
{
|
||||
Content = new StringContent("""{"id":"../../secret/leak?x=1"}""", Encoding.UTF8, "application/json")
|
||||
};
|
||||
}
|
||||
return new HttpResponseMessage(HttpStatusCode.OK)
|
||||
{
|
||||
Content = new StringContent("""{"status":"completed","text":"bad"}""", Encoding.UTF8, "application/json")
|
||||
};
|
||||
});
|
||||
|
||||
harness.Db.SttProviderEndpoints.Add(new SttProviderEndpoint
|
||||
{
|
||||
Name = "AssemblyAI",
|
||||
ProviderType = "assemblyai",
|
||||
EndpointUrl = "https://api.assemblyai.com/v2/transcript",
|
||||
ApiKey = "aai-secret",
|
||||
ModelId = "best",
|
||||
Method = "async-poll",
|
||||
Language = "ko",
|
||||
IsDefault = true,
|
||||
IsActive = true,
|
||||
FallbackPriority = 1,
|
||||
});
|
||||
await harness.Db.SaveChangesAsync();
|
||||
|
||||
await Assert.ThrowsAsync<SttProviderUnavailableException>(() =>
|
||||
harness.SttService.TranscribeAsync(
|
||||
1,
|
||||
"user@d3ro.test",
|
||||
new SttTranscribeRequest(Language: "ko"),
|
||||
SampleWav,
|
||||
"audio/wav",
|
||||
"clip.wav",
|
||||
recordUsage: false));
|
||||
|
||||
Assert.DoesNotContain(harness.CapturedRequests, r => r.RequestUri!.AbsoluteUri.Contains("secret", StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task LlmProxyService_DB내부SSRF엔드포인트_네트워크요청없이안전폴백으로실패폐쇄한다()
|
||||
{
|
||||
await using var harness = await ApiHarness.CreateAsync();
|
||||
harness.Db.ModelEndpoints.Add(new ServiceModelEndpoint
|
||||
{
|
||||
ModelId = "ssrf-llm",
|
||||
ModelName = "Evil",
|
||||
Provider = "OpenAI",
|
||||
EndpointUrl = "https://169.254.169.254/latest/meta-data",
|
||||
ApiKey = "sk-should-not-leak",
|
||||
CostPer1kPromptTokens = 0.001m,
|
||||
CostPer1kCompletionTokens = 0.002m,
|
||||
IsActive = true,
|
||||
});
|
||||
await harness.Db.SaveChangesAsync();
|
||||
|
||||
var res = await harness.LlmService.GenerateAsync(
|
||||
1,
|
||||
"user@d3ro.test",
|
||||
new LlmGenerateRequest("Hello", Model: "ssrf-llm"));
|
||||
|
||||
Assert.Empty(harness.CapturedRequests);
|
||||
Assert.Contains("Fallback", res.Text, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
private static byte[] BuildTinyWavBytes()
|
||||
{
|
||||
var wav = new byte[64];
|
||||
Encoding.ASCII.GetBytes("RIFF").CopyTo(wav, 0);
|
||||
Encoding.ASCII.GetBytes("WAVE").CopyTo(wav, 8);
|
||||
return wav;
|
||||
}
|
||||
|
||||
private sealed class ApiHarness : IAsyncDisposable
|
||||
{
|
||||
private readonly SqliteConnection _connection;
|
||||
|
||||
public AppDbContext Db { get; }
|
||||
public AdminController AdminController { get; }
|
||||
public SttProxyService SttService { get; }
|
||||
public LlmProxyService LlmService { get; }
|
||||
public List<HttpRequestMessage> CapturedRequests { get; }
|
||||
|
||||
private ApiHarness(
|
||||
SqliteConnection connection,
|
||||
AppDbContext db,
|
||||
AdminController adminController,
|
||||
SttProxyService sttService,
|
||||
LlmProxyService llmService,
|
||||
List<HttpRequestMessage> capturedRequests)
|
||||
{
|
||||
_connection = connection;
|
||||
Db = db;
|
||||
AdminController = adminController;
|
||||
SttService = sttService;
|
||||
LlmService = llmService;
|
||||
CapturedRequests = capturedRequests;
|
||||
}
|
||||
|
||||
public void SetNewIdempotencyKey()
|
||||
{
|
||||
AdminController.ControllerContext.HttpContext.Request.Headers["Idempotency-Key"] = Guid.NewGuid().ToString("D");
|
||||
}
|
||||
|
||||
public static async Task<ApiHarness> CreateAsync(Func<HttpRequestMessage, HttpResponseMessage>? responder = null)
|
||||
{
|
||||
var connection = new SqliteConnection("DataSource=:memory:");
|
||||
await connection.OpenAsync();
|
||||
var options = new DbContextOptionsBuilder<AppDbContext>()
|
||||
.UseSqlite(connection)
|
||||
.Options;
|
||||
var db = new AppDbContext(options);
|
||||
await db.Database.EnsureCreatedAsync();
|
||||
|
||||
var captured = new List<HttpRequestMessage>();
|
||||
var handler = new CaptureHandler(captured, responder);
|
||||
var httpFactory = new FixedHttpClientFactory(handler);
|
||||
|
||||
var sttService = new SttProxyService(db, httpFactory, NullLogger<SttProxyService>.Instance);
|
||||
var llmService = new LlmProxyService(db, httpFactory, NullLogger<LlmProxyService>.Instance);
|
||||
var adminOps = new AdminOperationService(db);
|
||||
var controller = new AdminController(db, sttService, adminOps);
|
||||
|
||||
var httpContext = new DefaultHttpContext
|
||||
{
|
||||
User = new ClaimsPrincipal(new ClaimsIdentity(new[]
|
||||
{
|
||||
new Claim(ClaimTypes.Email, "admin@d3ro.test"),
|
||||
new Claim(ClaimTypes.Role, "SuperAdmin"),
|
||||
}, "TestAuth")),
|
||||
};
|
||||
httpContext.Request.Headers["Idempotency-Key"] = Guid.NewGuid().ToString("D");
|
||||
controller.ControllerContext = new ControllerContext { HttpContext = httpContext };
|
||||
|
||||
return new ApiHarness(connection, db, controller, sttService, llmService, captured);
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
await Db.DisposeAsync();
|
||||
await _connection.DisposeAsync();
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class FixedHttpClientFactory : IHttpClientFactory
|
||||
{
|
||||
private readonly HttpMessageHandler _handler;
|
||||
public FixedHttpClientFactory(HttpMessageHandler handler) => _handler = handler;
|
||||
public HttpClient CreateClient(string name) => new(_handler, disposeHandler: false);
|
||||
}
|
||||
|
||||
private sealed class CaptureHandler : HttpMessageHandler
|
||||
{
|
||||
private readonly List<HttpRequestMessage> _captured;
|
||||
private readonly Func<HttpRequestMessage, HttpResponseMessage>? _responder;
|
||||
|
||||
public CaptureHandler(List<HttpRequestMessage> captured, Func<HttpRequestMessage, HttpResponseMessage>? responder)
|
||||
{
|
||||
_captured = captured;
|
||||
_responder = responder;
|
||||
}
|
||||
|
||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
_captured.Add(request);
|
||||
var resp = _responder?.Invoke(request) ?? new HttpResponseMessage(HttpStatusCode.OK)
|
||||
{
|
||||
Content = new StringContent("{}", Encoding.UTF8, "application/json")
|
||||
};
|
||||
return Task.FromResult(resp);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -105,7 +105,8 @@ public class AdminController : ControllerBase
|
|||
public async Task<IActionResult> CreateEndpoint([FromBody] CreateModelEndpointDto dto)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(dto.ModelId) || string.IsNullOrWhiteSpace(dto.ModelName)
|
||||
|| string.IsNullOrWhiteSpace(dto.Provider) || !IsValidEndpointUrl(dto.EndpointUrl)
|
||||
|| string.IsNullOrWhiteSpace(dto.Provider)
|
||||
|| !EndpointUrlPolicy.IsValidEndpointUrl(dto.EndpointUrl, EndpointUrlPolicy.AllowsLoopbackForLlmProvider(dto.Provider))
|
||||
|| dto.CostPer1kPromptTokens < 0 || dto.CostPer1kCompletionTokens < 0)
|
||||
{
|
||||
return BadRequest(new { message = "모델 식별자, 공급자, 유효한 HTTP(S) URL과 0 이상의 비용이 필요합니다." });
|
||||
|
|
@ -145,7 +146,8 @@ public class AdminController : ControllerBase
|
|||
public async Task<IActionResult> UpdateEndpoint(int id, [FromBody] UpdateModelEndpointDto dto)
|
||||
{
|
||||
if (id <= 0 || string.IsNullOrWhiteSpace(dto.ModelName) || string.IsNullOrWhiteSpace(dto.Provider)
|
||||
|| !IsValidEndpointUrl(dto.EndpointUrl) || dto.CostPer1kPromptTokens < 0 || dto.CostPer1kCompletionTokens < 0)
|
||||
|| !EndpointUrlPolicy.IsValidEndpointUrl(dto.EndpointUrl, EndpointUrlPolicy.AllowsLoopbackForLlmProvider(dto.Provider))
|
||||
|| dto.CostPer1kPromptTokens < 0 || dto.CostPer1kCompletionTokens < 0)
|
||||
return BadRequest(new { message = "유효한 모델 엔드포인트 값이 필요합니다." });
|
||||
|
||||
return await ExecuteAdminMutationAsync(
|
||||
|
|
@ -219,7 +221,10 @@ public class AdminController : ControllerBase
|
|||
[Authorize(Policy = "AdminOrAbove")]
|
||||
public async Task<IActionResult> CreateSttEndpoint([FromBody] CreateSttEndpointDto dto)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(dto.Name) || !IsValidEndpointUrl(dto.EndpointUrl)
|
||||
if (string.IsNullOrWhiteSpace(dto.Name)
|
||||
|| !EndpointUrlPolicy.IsValidEndpointUrl(dto.EndpointUrl, EndpointUrlPolicy.AllowsLoopbackForSttProvider(dto.ProviderType))
|
||||
|| !EndpointUrlPolicy.IsValidFiniteDouble(dto.Temperature, 0.0, 2.0)
|
||||
|| !EndpointUrlPolicy.TryValidateLanguageCode(dto.Language)
|
||||
|| dto.CostPerMinute < 0 || dto.CostPerSecond < 0 || dto.FallbackPriority < 1)
|
||||
{
|
||||
return BadRequest(new { message = "유효한 STT 이름, HTTP(S) URL, 비용, 우선순위가 필요합니다." });
|
||||
|
|
@ -239,7 +244,10 @@ public class AdminController : ControllerBase
|
|||
[Authorize(Policy = "AdminOrAbove")]
|
||||
public async Task<IActionResult> UpdateSttEndpoint(int id, [FromBody] UpdateSttEndpointDto dto)
|
||||
{
|
||||
if (id <= 0 || string.IsNullOrWhiteSpace(dto.Name) || !IsValidEndpointUrl(dto.EndpointUrl)
|
||||
if (id <= 0 || string.IsNullOrWhiteSpace(dto.Name)
|
||||
|| !EndpointUrlPolicy.IsValidEndpointUrl(dto.EndpointUrl, EndpointUrlPolicy.AllowsLoopbackForSttProvider(dto.ProviderType))
|
||||
|| !EndpointUrlPolicy.IsValidFiniteDouble(dto.Temperature, 0.0, 2.0)
|
||||
|| !EndpointUrlPolicy.TryValidateLanguageCode(dto.Language)
|
||||
|| dto.CostPerMinute < 0 || dto.CostPerSecond < 0 || dto.FallbackPriority < 1)
|
||||
return BadRequest(new { message = "유효한 STT 엔드포인트 값이 필요합니다." });
|
||||
|
||||
|
|
@ -311,7 +319,8 @@ public class AdminController : ControllerBase
|
|||
[Authorize(Policy = "AdminOrAbove")]
|
||||
public async Task<IActionResult> TestSttDirect([FromBody] DirectSttTestDto dto)
|
||||
{
|
||||
if (!IsValidEndpointUrl(dto.EndpointUrl) || !Uri.TryCreate(dto.EndpointUrl, UriKind.Absolute, out var endpointUri))
|
||||
if (!EndpointUrlPolicy.IsValidEndpointUrl(dto.EndpointUrl, allowLoopback: false)
|
||||
|| !Uri.TryCreate(dto.EndpointUrl, UriKind.Absolute, out var endpointUri))
|
||||
{
|
||||
return BadRequest(new { message = "유효한 HTTP(S) Endpoint URL이 필요합니다." });
|
||||
}
|
||||
|
|
@ -432,13 +441,6 @@ public class AdminController : ControllerBase
|
|||
endpoint.CreatedAt
|
||||
};
|
||||
|
||||
private static bool IsValidEndpointUrl(string? value)
|
||||
{
|
||||
if (!Uri.TryCreate(value, UriKind.Absolute, out var uri) || !string.IsNullOrEmpty(uri.UserInfo)) return false;
|
||||
if (uri.Scheme == Uri.UriSchemeHttp) return uri.IsLoopback;
|
||||
return uri.Scheme == Uri.UriSchemeHttps;
|
||||
}
|
||||
|
||||
private async Task<IActionResult> ExecuteAdminMutationAsync(
|
||||
string operation,
|
||||
object request,
|
||||
|
|
|
|||
|
|
@ -101,9 +101,9 @@ public class SttController : ControllerBase
|
|||
{
|
||||
return StatusCode(StatusCodes.Status503ServiceUnavailable, new { error = "stt_provider_unavailable" });
|
||||
}
|
||||
catch (ArgumentException)
|
||||
catch (ArgumentException ex)
|
||||
{
|
||||
return BadRequest(new { error = "invalid_audio" });
|
||||
return BadRequest(new { error = ex.ParamName == "language" ? "invalid_language" : "invalid_audio" });
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
|
|
|||
|
|
@ -16,6 +16,11 @@ var releaseVersion = System.Reflection.Assembly.GetEntryAssembly()?.GetName().Ve
|
|||
// Add Services to Container
|
||||
builder.Services.AddControllers();
|
||||
builder.Services.AddHttpClient();
|
||||
builder.Services.AddHttpClient("UpstreamNoRedirect")
|
||||
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
|
||||
{
|
||||
AllowAutoRedirect = false
|
||||
});
|
||||
builder.Services.AddEndpointsApiExplorer();
|
||||
builder.Services.AddRateLimiter(options =>
|
||||
{
|
||||
|
|
|
|||
174
apps/api-server/Services/EndpointUrlPolicy.cs
Normal file
174
apps/api-server/Services/EndpointUrlPolicy.cs
Normal file
|
|
@ -0,0 +1,174 @@
|
|||
using System;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace D3ROVoice.Api.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Central validation rules for upstream model/STT endpoint URLs, language parameters,
|
||||
/// numeric bounds, and provider identifiers to prevent SSRF, query/prompt injection, and NaN leaks.
|
||||
/// </summary>
|
||||
public static partial class EndpointUrlPolicy
|
||||
{
|
||||
private static readonly string[] BlockedHostSuffixes =
|
||||
[
|
||||
".localhost",
|
||||
".local",
|
||||
".internal",
|
||||
".localdomain",
|
||||
".home.arpa"
|
||||
];
|
||||
|
||||
[GeneratedRegex("^(?:auto|[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8}){0,2})$", RegexOptions.CultureInvariant)]
|
||||
private static partial Regex LanguageTagRegex();
|
||||
|
||||
[GeneratedRegex("^[A-Za-z0-9_-]{1,128}$", RegexOptions.CultureInvariant)]
|
||||
private static partial Regex AssemblyAiIdRegex();
|
||||
|
||||
public static bool AllowsLoopbackForLlmProvider(string? provider)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(provider)) return false;
|
||||
var trimmed = provider.Trim();
|
||||
return trimmed.Contains("ollama", StringComparison.OrdinalIgnoreCase)
|
||||
|| trimmed.Equals("local", StringComparison.OrdinalIgnoreCase)
|
||||
|| trimmed.Equals("local-sidecar", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
public static bool AllowsLoopbackForSttProvider(string? providerType)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(providerType)) return false;
|
||||
return providerType.Trim().Equals("local-sidecar", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
public static bool IsValidEndpointUrl(string? value, bool allowLoopback = false)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(value)) return false;
|
||||
if (!Uri.TryCreate(value.Trim(), UriKind.Absolute, out var uri)) return false;
|
||||
if (!string.IsNullOrEmpty(uri.UserInfo)) return false;
|
||||
|
||||
var isHttp = uri.Scheme == Uri.UriSchemeHttp;
|
||||
var isHttps = uri.Scheme == Uri.UriSchemeHttps;
|
||||
if (!isHttp && !isHttps) return false;
|
||||
|
||||
var host = uri.IdnHost.Trim().TrimEnd('.');
|
||||
if (string.IsNullOrWhiteSpace(host)) return false;
|
||||
|
||||
if (IPAddress.TryParse(host, out var ip))
|
||||
{
|
||||
if (ip.IsIPv4MappedToIPv6) ip = ip.MapToIPv4();
|
||||
if (IPAddress.IsLoopback(ip))
|
||||
{
|
||||
return allowLoopback;
|
||||
}
|
||||
if (!isHttps || IsNonPublicIp(ip))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
if (isHttp && !IsLoopbackHostname(host))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (IsLoopbackHostname(host))
|
||||
{
|
||||
return allowLoopback;
|
||||
}
|
||||
|
||||
foreach (var suffix in BlockedHostSuffixes)
|
||||
{
|
||||
if (host.EndsWith(suffix, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Reject single-label internal service names (e.g., "redis", "metadata") and raw integer aliases.
|
||||
if (!host.Contains('.', StringComparison.Ordinal))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return isHttps;
|
||||
}
|
||||
|
||||
public static string ValidateLanguageCode(string? rawLanguage, string fallback = "ko")
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(rawLanguage))
|
||||
{
|
||||
return fallback;
|
||||
}
|
||||
|
||||
var trimmed = rawLanguage.Trim();
|
||||
if (trimmed.Length > 32 || !LanguageTagRegex().IsMatch(trimmed))
|
||||
{
|
||||
throw new ArgumentException("Invalid language code format.", "language");
|
||||
}
|
||||
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
public static bool TryValidateLanguageCode(string? rawLanguage)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(rawLanguage)) return true;
|
||||
var trimmed = rawLanguage.Trim();
|
||||
return trimmed.Length <= 32 && LanguageTagRegex().IsMatch(trimmed);
|
||||
}
|
||||
|
||||
public static bool IsValidFiniteDouble(double value, double min, double max) =>
|
||||
double.IsFinite(value) && value >= min && value <= max;
|
||||
|
||||
public static bool IsValidAssemblyAiTranscriptId(string? id) =>
|
||||
!string.IsNullOrWhiteSpace(id) && AssemblyAiIdRegex().IsMatch(id.Trim());
|
||||
|
||||
private static bool IsLoopbackHostname(string host) =>
|
||||
host.Equals("localhost", StringComparison.OrdinalIgnoreCase)
|
||||
|| host.EndsWith(".localhost", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
private static bool IsNonPublicIp(IPAddress ip)
|
||||
{
|
||||
if (ip.AddressFamily == AddressFamily.InterNetwork)
|
||||
{
|
||||
var bytes = ip.GetAddressBytes();
|
||||
return bytes[0] switch
|
||||
{
|
||||
0 => true, // 0.0.0.0/8 unspecified
|
||||
10 => true, // 10.0.0.0/8 RFC1918
|
||||
100 when bytes[1] is >= 64 and <= 127 => true, // 100.64.0.0/10 CGNAT
|
||||
127 => true, // 127.0.0.0/8 loopback
|
||||
169 when bytes[1] == 254 => true, // 169.254.0.0/16 link-local & cloud metadata
|
||||
172 when bytes[1] is >= 16 and <= 31 => true, // 172.16.0.0/12 RFC1918
|
||||
192 when bytes[1] == 0 && bytes[2] == 0 => true, // 192.0.0.0/24 IETF protocol assignments
|
||||
192 when bytes[1] == 0 && bytes[2] == 2 => true, // TEST-NET-1
|
||||
192 when bytes[1] == 168 => true, // 192.168.0.0/16 RFC1918
|
||||
198 when bytes[1] is 18 or 19 => true, // 198.18.0.0/15 benchmark
|
||||
>= 224 => true, // multicast / reserved / broadcast
|
||||
_ => false,
|
||||
};
|
||||
}
|
||||
|
||||
if (ip.AddressFamily == AddressFamily.InterNetworkV6)
|
||||
{
|
||||
if (ip.Equals(IPAddress.IPv6Any) || ip.Equals(IPAddress.IPv6None) || ip.Equals(IPAddress.IPv6Loopback))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
if (ip.IsIPv6LinkLocal || ip.IsIPv6Multicast || ip.IsIPv6SiteLocal)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
var bytes = ip.GetAddressBytes();
|
||||
// fc00::/7 Unique Local Addresses (ULA)
|
||||
if ((bytes[0] & 0xfe) == 0xfc)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
|
@ -73,7 +73,14 @@ public class LlmProxyService : ILlmProxyService
|
|||
{
|
||||
try
|
||||
{
|
||||
using var client = _httpClientFactory.CreateClient();
|
||||
if (!EndpointUrlPolicy.IsValidEndpointUrl(
|
||||
endpoint.EndpointUrl,
|
||||
EndpointUrlPolicy.AllowsLoopbackForLlmProvider(endpoint.Provider)))
|
||||
{
|
||||
throw new InvalidOperationException("Configured model endpoint URL is not permitted.");
|
||||
}
|
||||
|
||||
using var client = _httpClientFactory.CreateClient("UpstreamNoRedirect");
|
||||
client.Timeout = TimeSpan.FromSeconds(60);
|
||||
|
||||
var payload = new
|
||||
|
|
@ -93,9 +100,10 @@ public class LlmProxyService : ILlmProxyService
|
|||
Content = new StringContent(JsonSerializer.Serialize(payload), Encoding.UTF8, "application/json")
|
||||
};
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(endpoint.ApiKey))
|
||||
var trimmedKey = endpoint.ApiKey?.Trim();
|
||||
if (!string.IsNullOrWhiteSpace(trimmedKey))
|
||||
{
|
||||
httpRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", endpoint.ApiKey);
|
||||
httpRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", trimmedKey);
|
||||
}
|
||||
|
||||
using var httpResponse = await client.SendAsync(httpRequest, cancellationToken);
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
|
|
@ -82,6 +83,15 @@ public class SttProxyService : ISttProxyService
|
|||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(request.Language))
|
||||
{
|
||||
EndpointUrlPolicy.ValidateLanguageCode(request.Language);
|
||||
}
|
||||
if (request.Temperature is { } requestedTemp && !EndpointUrlPolicy.IsValidFiniteDouble(requestedTemp, 0.0, 2.0))
|
||||
{
|
||||
throw new ArgumentException("Temperature must be finite and between 0.0 and 2.0.", "temperature");
|
||||
}
|
||||
|
||||
// 1. Resolve Audio Bytes
|
||||
byte[] finalAudioBytes;
|
||||
if (audioBytes != null && audioBytes.Length > 0)
|
||||
|
|
@ -296,11 +306,18 @@ public class SttProxyService : ISttProxyService
|
|||
CancellationToken cancellationToken
|
||||
)
|
||||
{
|
||||
using var client = _httpClientFactory.CreateClient();
|
||||
var providerType = endpoint.ProviderType.ToLowerInvariant();
|
||||
if (!EndpointUrlPolicy.IsValidEndpointUrl(
|
||||
endpoint.EndpointUrl,
|
||||
EndpointUrlPolicy.AllowsLoopbackForSttProvider(providerType)))
|
||||
{
|
||||
throw new InvalidOperationException("STT provider endpoint URL is not permitted.");
|
||||
}
|
||||
|
||||
using var client = _httpClientFactory.CreateClient("UpstreamNoRedirect");
|
||||
client.Timeout = TimeSpan.FromSeconds(90);
|
||||
|
||||
var providerType = endpoint.ProviderType.ToLowerInvariant();
|
||||
var apiKey = endpoint.ApiKey?.Trim() ?? "";
|
||||
var apiKey = GetTrimmedApiKey(endpoint);
|
||||
|
||||
if (RequiresApiKey(providerType) && string.IsNullOrWhiteSpace(apiKey))
|
||||
{
|
||||
|
|
@ -360,8 +377,8 @@ public class SttProxyService : ISttProxyService
|
|||
|
||||
form.Add(new StringContent(endpoint.ModelId), "model");
|
||||
|
||||
var language = request.Language ?? endpoint.Language ?? "ko";
|
||||
if (!string.IsNullOrWhiteSpace(language) && language != "auto")
|
||||
var language = ResolveValidatedLanguage(request.Language, endpoint.Language, "ko");
|
||||
if (language != "auto")
|
||||
{
|
||||
form.Add(new StringContent(language), "language");
|
||||
}
|
||||
|
|
@ -373,7 +390,8 @@ public class SttProxyService : ISttProxyService
|
|||
}
|
||||
|
||||
var temp = request.Temperature ?? endpoint.Temperature;
|
||||
form.Add(new StringContent(temp.ToString("0.0")), "temperature");
|
||||
if (!EndpointUrlPolicy.IsValidFiniteDouble(temp, 0.0, 2.0)) temp = 0.0;
|
||||
form.Add(new StringContent(temp.ToString("0.0", CultureInfo.InvariantCulture)), "temperature");
|
||||
form.Add(new StringContent("verbose_json"), "response_format");
|
||||
|
||||
using var httpRequest = new HttpRequestMessage(HttpMethod.Post, endpoint.EndpointUrl)
|
||||
|
|
@ -381,9 +399,10 @@ public class SttProxyService : ISttProxyService
|
|||
Content = form
|
||||
};
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(endpoint.ApiKey))
|
||||
var apiKey = GetTrimmedApiKey(endpoint);
|
||||
if (!string.IsNullOrWhiteSpace(apiKey))
|
||||
{
|
||||
httpRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", endpoint.ApiKey);
|
||||
httpRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
|
||||
}
|
||||
|
||||
ApplyExtraHeaders(httpRequest, endpoint.ExtraHeadersJson);
|
||||
|
|
@ -423,12 +442,11 @@ public class SttProxyService : ISttProxyService
|
|||
CancellationToken cancellationToken
|
||||
)
|
||||
{
|
||||
var lang = request.Language ?? endpoint.Language ?? "ko";
|
||||
var model = endpoint.ModelId ?? "nova-3";
|
||||
var lang = ResolveValidatedLanguage(request.Language, endpoint.Language, "ko");
|
||||
var model = string.IsNullOrWhiteSpace(endpoint.ModelId) ? "nova-3" : endpoint.ModelId.Trim();
|
||||
var baseUrl = endpoint.EndpointUrl.TrimEnd('/');
|
||||
var url = baseUrl.Contains("?")
|
||||
? $"{baseUrl}&model={model}&language={lang}&smart_format=true&punctuate=true"
|
||||
: $"{baseUrl}?model={model}&language={lang}&smart_format=true&punctuate=true";
|
||||
var separator = baseUrl.Contains('?', StringComparison.Ordinal) ? "&" : "?";
|
||||
var url = $"{baseUrl}{separator}model={Uri.EscapeDataString(model)}&language={Uri.EscapeDataString(lang)}&smart_format=true&punctuate=true";
|
||||
|
||||
using var httpRequest = new HttpRequestMessage(HttpMethod.Post, url)
|
||||
{
|
||||
|
|
@ -436,9 +454,10 @@ public class SttProxyService : ISttProxyService
|
|||
};
|
||||
httpRequest.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(endpoint.ApiKey))
|
||||
var apiKey = GetTrimmedApiKey(endpoint);
|
||||
if (!string.IsNullOrWhiteSpace(apiKey))
|
||||
{
|
||||
httpRequest.Headers.Add("Authorization", $"Token {endpoint.ApiKey}");
|
||||
httpRequest.Headers.Add("Authorization", $"Token {apiKey}");
|
||||
}
|
||||
|
||||
ApplyExtraHeaders(httpRequest, endpoint.ExtraHeadersJson);
|
||||
|
|
@ -484,13 +503,12 @@ public class SttProxyService : ISttProxyService
|
|||
)
|
||||
{
|
||||
var base64Audio = Convert.ToBase64String(audioBytes);
|
||||
var lang = request.Language ?? endpoint.Language ?? "ko";
|
||||
var lang = ResolveValidatedLanguage(request.Language, endpoint.Language, "ko");
|
||||
var apiKey = GetTrimmedApiKey(endpoint);
|
||||
|
||||
// If endpoint is Gemini Flash Multimodal API
|
||||
if (endpoint.EndpointUrl.Contains("generativelanguage.googleapis.com") || endpoint.ModelId.Contains("gemini"))
|
||||
{
|
||||
var apiKey = endpoint.ApiKey;
|
||||
|
||||
var geminiPayload = new
|
||||
{
|
||||
contents = new[]
|
||||
|
|
@ -543,8 +561,6 @@ public class SttProxyService : ISttProxyService
|
|||
else
|
||||
{
|
||||
// Google Cloud Speech-to-Text v1
|
||||
var apiKey = endpoint.ApiKey;
|
||||
|
||||
var gcpPayload = new
|
||||
{
|
||||
config = new
|
||||
|
|
@ -606,20 +622,25 @@ public class SttProxyService : ISttProxyService
|
|||
CancellationToken cancellationToken
|
||||
)
|
||||
{
|
||||
var apiKey = GetTrimmedApiKey(endpoint);
|
||||
// 1. Upload audio
|
||||
using var uploadRequest = new HttpRequestMessage(HttpMethod.Post, "https://api.assemblyai.com/v2/upload")
|
||||
{
|
||||
Content = new ByteArrayContent(audioBytes)
|
||||
};
|
||||
uploadRequest.Headers.Add("Authorization", endpoint.ApiKey);
|
||||
uploadRequest.Headers.Add("Authorization", apiKey);
|
||||
|
||||
var uploadBody = await SendForStringAsync(client, uploadRequest, cancellationToken);
|
||||
|
||||
using var uploadDoc = JsonDocument.Parse(uploadBody);
|
||||
var uploadUrl = uploadDoc.RootElement.GetProperty("upload_url").GetString()!;
|
||||
var uploadUrl = uploadDoc.RootElement.GetProperty("upload_url").GetString();
|
||||
if (!EndpointUrlPolicy.IsValidEndpointUrl(uploadUrl, allowLoopback: false))
|
||||
{
|
||||
throw new JsonException("AssemblyAI returned an invalid upload URL.");
|
||||
}
|
||||
|
||||
// 2. Submit transcript job
|
||||
var lang = request.Language ?? endpoint.Language ?? "ko";
|
||||
var lang = ResolveValidatedLanguage(request.Language, endpoint.Language, "ko");
|
||||
var transcriptPayload = new
|
||||
{
|
||||
audio_url = uploadUrl,
|
||||
|
|
@ -632,19 +653,24 @@ public class SttProxyService : ISttProxyService
|
|||
{
|
||||
Content = new StringContent(JsonSerializer.Serialize(transcriptPayload), Encoding.UTF8, "application/json")
|
||||
};
|
||||
transRequest.Headers.Add("Authorization", endpoint.ApiKey);
|
||||
transRequest.Headers.Add("Authorization", apiKey);
|
||||
|
||||
var transBody = await SendForStringAsync(client, transRequest, cancellationToken);
|
||||
|
||||
using var transDoc = JsonDocument.Parse(transBody);
|
||||
var id = transDoc.RootElement.GetProperty("id").GetString()!;
|
||||
var id = transDoc.RootElement.GetProperty("id").GetString();
|
||||
if (!EndpointUrlPolicy.IsValidAssemblyAiTranscriptId(id))
|
||||
{
|
||||
throw new JsonException("AssemblyAI returned an invalid transcript identifier.");
|
||||
}
|
||||
var safeId = Uri.EscapeDataString(id!.Trim());
|
||||
|
||||
// 3. Poll for result (up to 20 seconds)
|
||||
for (int i = 0; i < 20; i++)
|
||||
{
|
||||
await Task.Delay(1000, cancellationToken);
|
||||
using var pollReq = new HttpRequestMessage(HttpMethod.Get, $"https://api.assemblyai.com/v2/transcript/{id}");
|
||||
pollReq.Headers.Add("Authorization", endpoint.ApiKey);
|
||||
using var pollReq = new HttpRequestMessage(HttpMethod.Get, $"https://api.assemblyai.com/v2/transcript/{safeId}");
|
||||
pollReq.Headers.Add("Authorization", apiKey);
|
||||
|
||||
var pollBody = await SendForStringAsync(client, pollReq, cancellationToken);
|
||||
|
||||
|
|
@ -683,12 +709,11 @@ public class SttProxyService : ISttProxyService
|
|||
CancellationToken cancellationToken
|
||||
)
|
||||
{
|
||||
var lang = request.Language ?? endpoint.Language ?? "ko-KR";
|
||||
var lang = ResolveValidatedLanguage(request.Language, endpoint.Language, "ko-KR");
|
||||
if (lang == "ko") lang = "ko-KR";
|
||||
|
||||
var url = endpoint.EndpointUrl.Contains("?")
|
||||
? $"{endpoint.EndpointUrl}&language={lang}&format=detailed"
|
||||
: $"{endpoint.EndpointUrl}?language={lang}&format=detailed";
|
||||
var separator = endpoint.EndpointUrl.Contains('?', StringComparison.Ordinal) ? "&" : "?";
|
||||
var url = $"{endpoint.EndpointUrl}{separator}language={Uri.EscapeDataString(lang)}&format=detailed";
|
||||
|
||||
using var httpRequest = new HttpRequestMessage(HttpMethod.Post, url)
|
||||
{
|
||||
|
|
@ -696,9 +721,10 @@ public class SttProxyService : ISttProxyService
|
|||
};
|
||||
httpRequest.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType.Contains("wav") ? "audio/wav" : "audio/webm");
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(endpoint.ApiKey))
|
||||
var apiKey = GetTrimmedApiKey(endpoint);
|
||||
if (!string.IsNullOrWhiteSpace(apiKey))
|
||||
{
|
||||
httpRequest.Headers.Add("Ocp-Apim-Subscription-Key", endpoint.ApiKey);
|
||||
httpRequest.Headers.Add("Ocp-Apim-Subscription-Key", apiKey);
|
||||
}
|
||||
|
||||
var responseBody = await SendForStringAsync(client, httpRequest, cancellationToken);
|
||||
|
|
@ -746,16 +772,17 @@ public class SttProxyService : ISttProxyService
|
|||
form.Add(audioContent, "file", fileName);
|
||||
|
||||
form.Add(new StringContent(endpoint.ModelId), "model");
|
||||
form.Add(new StringContent(request.Language ?? endpoint.Language ?? "ko"), "language");
|
||||
form.Add(new StringContent(ResolveValidatedLanguage(request.Language, endpoint.Language, "ko")), "language");
|
||||
|
||||
using var httpRequest = new HttpRequestMessage(HttpMethod.Post, endpoint.EndpointUrl)
|
||||
{
|
||||
Content = form
|
||||
};
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(endpoint.ApiKey))
|
||||
var apiKey = GetTrimmedApiKey(endpoint);
|
||||
if (!string.IsNullOrWhiteSpace(apiKey))
|
||||
{
|
||||
httpRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", endpoint.ApiKey);
|
||||
httpRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
|
||||
}
|
||||
|
||||
var responseBody = await SendForStringAsync(client, httpRequest, cancellationToken);
|
||||
|
|
@ -1061,6 +1088,17 @@ public class SttProxyService : ISttProxyService
|
|||
};
|
||||
}
|
||||
|
||||
private static string GetTrimmedApiKey(SttProviderEndpoint endpoint) =>
|
||||
endpoint.ApiKey?.Trim() ?? string.Empty;
|
||||
|
||||
private static string ResolveValidatedLanguage(string? requested, string? endpointDefault, string fallback)
|
||||
{
|
||||
var candidate = !string.IsNullOrWhiteSpace(requested)
|
||||
? requested
|
||||
: (!string.IsNullOrWhiteSpace(endpointDefault) ? endpointDefault : fallback);
|
||||
return EndpointUrlPolicy.ValidateLanguageCode(candidate, fallback);
|
||||
}
|
||||
|
||||
private static void ApplyExtraHeaders(HttpRequestMessage req, string? extraHeadersJson)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(extraHeadersJson)) return;
|
||||
|
|
|
|||
|
|
@ -5,17 +5,42 @@ const DEFAULT_TITLE = 'D3RO Voice'
|
|||
const DEFAULT_BODY = '새 알림이 도착했습니다.'
|
||||
const DEFAULT_TARGET_URL = '/app/dashboard'
|
||||
|
||||
function hasUnsafeUrlChars(value) {
|
||||
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
|
||||
}
|
||||
|
||||
function sanitizeTargetUrl(rawUrl) {
|
||||
if (typeof rawUrl !== 'string' || !rawUrl.trim()) {
|
||||
if (typeof rawUrl !== 'string' || hasUnsafeUrlChars(rawUrl)) {
|
||||
return DEFAULT_TARGET_URL
|
||||
}
|
||||
const trimmed = rawUrl.trim()
|
||||
if (!trimmed.startsWith('/') || trimmed.startsWith('//') || trimmed.startsWith('/\\')) {
|
||||
if (!trimmed || !trimmed.startsWith('/') || trimmed.startsWith('//')) {
|
||||
return DEFAULT_TARGET_URL
|
||||
}
|
||||
return trimmed.startsWith('/app/') || trimmed === '/app'
|
||||
const candidate = trimmed.startsWith('/app/') || trimmed === '/app'
|
||||
? trimmed
|
||||
: `/app${trimmed}`
|
||||
if (candidate === '/app') {
|
||||
return DEFAULT_TARGET_URL
|
||||
}
|
||||
if (candidate.startsWith('/app//')) {
|
||||
return DEFAULT_TARGET_URL
|
||||
}
|
||||
try {
|
||||
const parsed = new URL(candidate, 'https://d3ro.local')
|
||||
if (parsed.origin !== 'https://d3ro.local' || !parsed.pathname.startsWith('/app/') || parsed.pathname.includes('//')) {
|
||||
return DEFAULT_TARGET_URL
|
||||
}
|
||||
} catch {
|
||||
return DEFAULT_TARGET_URL
|
||||
}
|
||||
return candidate
|
||||
}
|
||||
|
||||
function parsePushPayload(event) {
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
|
||||
import Link from 'next/link'
|
||||
import { useParams, useRouter } from 'next/navigation'
|
||||
import React, { useCallback, useEffect, useState } from 'react'
|
||||
import React, { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import {
|
||||
Alert,
|
||||
Box,
|
||||
|
|
@ -19,6 +19,7 @@ import type { D3roSupabaseClient, HistoryEntry } from '@d3ro/api-client'
|
|||
import { formatDurationClockFromSeconds } from '@d3ro/core/format'
|
||||
import { MetalCard, PhosphorText } from '@d3ro/ui/components/ds'
|
||||
import { d3roFontMono, d3roPalette } from '@d3ro/ui/theme'
|
||||
import { clearTrackedTimeout, scheduleTrackedTimeout } from '@/lib/edge-fetch'
|
||||
import { getSupabaseBrowserClient } from '@/lib/supabase-browser'
|
||||
import {
|
||||
deleteHistoryEntryRevisionSafe,
|
||||
|
|
@ -63,6 +64,18 @@ export default function HistoryDetailPage(): React.ReactElement {
|
|||
const [title, setTitle] = useState('')
|
||||
const [originalText, setOriginalText] = useState('')
|
||||
const [polishedText, setPolishedText] = useState('')
|
||||
const mountedRef = useRef(true)
|
||||
const loadGenerationRef = useRef(0)
|
||||
const copyTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
mountedRef.current = true
|
||||
return () => {
|
||||
mountedRef.current = false
|
||||
loadGenerationRef.current += 1
|
||||
clearTrackedTimeout(copyTimerRef)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const applyEntry = (next: HistoryEntry): void => {
|
||||
setEntry(next)
|
||||
|
|
@ -72,17 +85,23 @@ export default function HistoryDetailPage(): React.ReactElement {
|
|||
}
|
||||
|
||||
const loadEntry = useCallback(async (): Promise<void> => {
|
||||
const generation = ++loadGenerationRef.current
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
try {
|
||||
const client = asApiClient()
|
||||
const userId = await requireCurrentUser(client)
|
||||
applyEntry(await getHistoryEntry(client, userId, entryId))
|
||||
const loaded = await getHistoryEntry(client, userId, entryId)
|
||||
if (!mountedRef.current || generation !== loadGenerationRef.current) return
|
||||
applyEntry(loaded)
|
||||
} catch (requestError) {
|
||||
if (!mountedRef.current || generation !== loadGenerationRef.current) return
|
||||
setEntry(null)
|
||||
setError(historyMessage(requestError))
|
||||
} finally {
|
||||
setLoading(false)
|
||||
if (mountedRef.current && generation === loadGenerationRef.current) {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
}, [entryId])
|
||||
|
||||
|
|
@ -178,10 +197,15 @@ export default function HistoryDetailPage(): React.ReactElement {
|
|||
if (!entry) return
|
||||
try {
|
||||
await navigator.clipboard.writeText(entry.polished_text ?? entry.original_text)
|
||||
if (!mountedRef.current) return
|
||||
setCopied(true)
|
||||
window.setTimeout(() => setCopied(false), 2000)
|
||||
scheduleTrackedTimeout(copyTimerRef, () => {
|
||||
if (mountedRef.current) setCopied(false)
|
||||
}, 2000)
|
||||
} catch {
|
||||
setError('클립보드에 복사하지 못했습니다. 브라우저 권한을 확인해 주세요.')
|
||||
if (mountedRef.current) {
|
||||
setError('클립보드에 복사하지 못했습니다. 브라우저 권한을 확인해 주세요.')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -28,6 +28,7 @@ import {
|
|||
import type { D3roSupabaseClient, HistoryEntry } from '@d3ro/api-client'
|
||||
import { MetalCard, PhosphorText, TactileBadge } from '@d3ro/ui/components/ds'
|
||||
import { d3roFontMono, d3roPalette } from '@d3ro/ui/theme'
|
||||
import { clearTrackedTimeout, scheduleTrackedTimeout } from '@/lib/edge-fetch'
|
||||
import { getSupabaseBrowserClient } from '@/lib/supabase-browser'
|
||||
import {
|
||||
deleteHistoryEntryRevisionSafe,
|
||||
|
|
@ -81,6 +82,16 @@ export default function HistoryPage(): React.ReactElement {
|
|||
const [copiedId, setCopiedId] = useState<string | null>(null)
|
||||
const [mutatingIds, setMutatingIds] = useState<Set<string>>(() => new Set())
|
||||
const requestGeneration = useRef(0)
|
||||
const mountedRef = useRef(true)
|
||||
const copyTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
mountedRef.current = true
|
||||
return () => {
|
||||
mountedRef.current = false
|
||||
clearTrackedTimeout(copyTimerRef)
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
const timer = window.setTimeout(() => setSearch(searchInput), SEARCH_DELAY_MS)
|
||||
|
|
@ -232,10 +243,17 @@ export default function HistoryPage(): React.ReactElement {
|
|||
const copyText = async (entry: HistoryEntry): Promise<void> => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(entry.polished_text ?? entry.original_text)
|
||||
if (!mountedRef.current) return
|
||||
setCopiedId(entry.id)
|
||||
window.setTimeout(() => setCopiedId((current) => current === entry.id ? null : current), 2000)
|
||||
scheduleTrackedTimeout(copyTimerRef, () => {
|
||||
if (mountedRef.current) {
|
||||
setCopiedId((current) => (current === entry.id ? null : current))
|
||||
}
|
||||
}, 2000)
|
||||
} catch {
|
||||
setError('클립보드에 복사하지 못했습니다. 브라우저 권한을 확인해 주세요.')
|
||||
if (mountedRef.current) {
|
||||
setError('클립보드에 복사하지 못했습니다. 브라우저 권한을 확인해 주세요.')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -33,7 +33,7 @@ export async function GET(request: NextRequest): Promise<NextResponse> {
|
|||
const { error } = await supabase.auth.exchangeCodeForSession(code)
|
||||
|
||||
if (error) {
|
||||
return NextResponse.redirect(appUrlFor(origin, `/login?error=${encodeURIComponent(error.message)}`))
|
||||
return NextResponse.redirect(appUrlFor(origin, '/login?error=oauth_callback_failed'))
|
||||
}
|
||||
|
||||
return NextResponse.redirect(appUrlFor(origin, next))
|
||||
|
|
|
|||
|
|
@ -4,11 +4,12 @@
|
|||
// 텍스트 명령 → LLM 파싱 (function-like JSON) → 동작 시뮬레이션.
|
||||
// V1 VoiceActionService의 간이 web 포트.
|
||||
|
||||
import { useState } from 'react'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { Box, Button, TextField, Stack, Alert, CircularProgress, Chip } from '@mui/material'
|
||||
import PlayArrowIcon from '@mui/icons-material/PlayArrow'
|
||||
import { MetalCard, PhosphorText } from '@d3ro/ui/components/ds'
|
||||
import { d3roPalette, typoSx } from '@d3ro/ui/theme'
|
||||
import { createTimedAbortSignal, resolveSupabaseFunctionUrl } from '@/lib/edge-fetch'
|
||||
import { getSupabaseBrowserClient } from '@/lib/supabase-browser'
|
||||
|
||||
type ActionType =
|
||||
|
|
@ -52,6 +53,17 @@ export function ActionRunner(): React.ReactElement {
|
|||
const [error, setError] = useState<string | null>(null)
|
||||
const [result, setResult] = useState<ActionResult | null>(null)
|
||||
const [executed, setExecuted] = useState<string | null>(null)
|
||||
const mountedRef = useRef(true)
|
||||
const abortRef = useRef<AbortController | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
mountedRef.current = true
|
||||
return () => {
|
||||
mountedRef.current = false
|
||||
abortRef.current?.abort()
|
||||
abortRef.current = null
|
||||
}
|
||||
}, [])
|
||||
|
||||
async function handleParse(): Promise<void> {
|
||||
if (!input.trim()) return
|
||||
|
|
@ -59,24 +71,27 @@ export function ActionRunner(): React.ReactElement {
|
|||
setResult(null)
|
||||
setExecuted(null)
|
||||
setBusy(true)
|
||||
const timedAbort = createTimedAbortSignal(30_000, abortRef)
|
||||
|
||||
try {
|
||||
const supabase = getSupabaseBrowserClient()
|
||||
const {
|
||||
data: { session }
|
||||
} = await supabase.auth.getSession()
|
||||
if (!mountedRef.current || timedAbort.controller.signal.aborted) return
|
||||
if (!session) {
|
||||
throw new Error('로그인이 필요합니다')
|
||||
}
|
||||
|
||||
const resp = await fetch(
|
||||
`${process.env.NEXT_PUBLIC_SUPABASE_URL}/functions/v1/llm-proxy`,
|
||||
resolveSupabaseFunctionUrl('llm-proxy'),
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${session.access_token}`,
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
signal: timedAbort.controller.signal,
|
||||
body: JSON.stringify({
|
||||
messages: [{ role: 'user', content: input.trim() }],
|
||||
system: SYSTEM_PROMPT,
|
||||
|
|
@ -99,11 +114,22 @@ export function ActionRunner(): React.ReactElement {
|
|||
}
|
||||
|
||||
const parsed = JSON.parse(jsonMatch[0]) as ActionResult
|
||||
setResult(parsed)
|
||||
if (mountedRef.current) {
|
||||
setResult(parsed)
|
||||
}
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Unknown error')
|
||||
if (mountedRef.current) {
|
||||
setError(timedAbort.didTimeout()
|
||||
? '명령 파싱 시간이 초과되었습니다.'
|
||||
: e instanceof Error
|
||||
? e.message
|
||||
: 'Unknown error')
|
||||
}
|
||||
} finally {
|
||||
setBusy(false)
|
||||
timedAbort.dispose()
|
||||
if (mountedRef.current) {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -116,6 +142,7 @@ export function ActionRunner(): React.ReactElement {
|
|||
const {
|
||||
data: { user }
|
||||
} = await supabase.auth.getUser()
|
||||
if (!mountedRef.current) return
|
||||
if (!user) {
|
||||
throw new Error('로그인이 필요합니다')
|
||||
}
|
||||
|
|
@ -126,6 +153,7 @@ export function ActionRunner(): React.ReactElement {
|
|||
const { error: err } = await supabase
|
||||
.from('meetings')
|
||||
.insert({ user_id: user.id, title, team_id: null, status: 'completed' })
|
||||
if (!mountedRef.current) return
|
||||
if (err) throw new Error(err.message)
|
||||
setExecuted(`회의 "${title}" 생성됨`)
|
||||
break
|
||||
|
|
@ -147,6 +175,7 @@ export function ActionRunner(): React.ReactElement {
|
|||
content,
|
||||
timestamp_ms: 0
|
||||
})
|
||||
if (!mountedRef.current) return
|
||||
if (err) throw new Error(err.message)
|
||||
setExecuted(`메모 생성됨: "${content}"`)
|
||||
break
|
||||
|
|
@ -158,9 +187,13 @@ export function ActionRunner(): React.ReactElement {
|
|||
setExecuted('알 수 없는 액션 — 실행 불가')
|
||||
}
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Unknown error')
|
||||
if (mountedRef.current) {
|
||||
setError(e instanceof Error ? e.message : 'Unknown error')
|
||||
}
|
||||
} finally {
|
||||
setBusy(false)
|
||||
if (mountedRef.current) {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,8 +1,14 @@
|
|||
'use client'
|
||||
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { Alert, Box, Button, CircularProgress } from '@mui/material'
|
||||
import Script from 'next/script'
|
||||
import {
|
||||
clearTrackedTimeout,
|
||||
createTimedAbortSignal,
|
||||
resolveSupabaseFunctionUrl,
|
||||
scheduleTrackedTimeout,
|
||||
} from '@/lib/edge-fetch'
|
||||
import { getSupabaseBrowserClient } from '@/lib/supabase-browser'
|
||||
import { browserBillingUrl } from '@/lib/web-app-url'
|
||||
import {
|
||||
|
|
@ -39,14 +45,11 @@ function checkoutErrorMessage(error: unknown): string {
|
|||
}
|
||||
|
||||
function checkoutEndpoint(): string {
|
||||
const baseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL?.trim()
|
||||
if (!baseUrl) {
|
||||
throw new PaypleClientError('not_configured', '결제 서버 설정이 완료되지 않았습니다.')
|
||||
}
|
||||
try {
|
||||
return new URL('/functions/v1/payple-checkout', baseUrl).toString()
|
||||
} catch {
|
||||
throw new PaypleClientError('not_configured', '결제 서버 설정이 올바르지 않습니다.')
|
||||
return resolveSupabaseFunctionUrl('payple-checkout')
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : '결제 서버 설정이 올바르지 않습니다.'
|
||||
throw new PaypleClientError('not_configured', message)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -55,11 +58,21 @@ export function PaypleCheckoutButton({ tier, catalogPrice }: PaypleCheckoutButto
|
|||
const [error, setError] = useState<string | null>(null)
|
||||
const [success, setSuccess] = useState(false)
|
||||
const [sdkReady, setSdkReady] = useState(false)
|
||||
const mountedRef = useRef(true)
|
||||
const reloadTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
const abortRef = useRef<AbortController | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
mountedRef.current = true
|
||||
if (PAYPLE_CONFIGURED && typeof window.PaypleCpayAuthCheck === 'function') {
|
||||
setSdkReady(true)
|
||||
}
|
||||
return () => {
|
||||
mountedRef.current = false
|
||||
clearTrackedTimeout(reloadTimerRef)
|
||||
abortRef.current?.abort()
|
||||
abortRef.current = null
|
||||
}
|
||||
}, [])
|
||||
|
||||
const handleCheckout = useCallback(async (): Promise<void> => {
|
||||
|
|
@ -98,24 +111,31 @@ export function PaypleCheckoutButton({ tier, catalogPrice }: PaypleCheckoutButto
|
|||
resultUrl: browserBillingUrl(),
|
||||
openSdk: (request) => window.PaypleCpayAuthCheck(request),
|
||||
chargeBillingKey: async (payerId, result) => {
|
||||
const response = await fetch(checkoutEndpoint(), {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${session.access_token}`,
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
payer_id: payerId,
|
||||
tier,
|
||||
idempotency_key: idempotencyKey,
|
||||
pcd_pay_cardname: typeof result['PCD_PAY_CARDNAME'] === 'string'
|
||||
? result['PCD_PAY_CARDNAME']
|
||||
: undefined,
|
||||
pcd_pay_cardnum: typeof result['PCD_PAY_CARDNUM'] === 'string'
|
||||
? result['PCD_PAY_CARDNUM']
|
||||
: undefined
|
||||
const timedAbort = createTimedAbortSignal(30_000, abortRef)
|
||||
let response: Response
|
||||
try {
|
||||
response = await fetch(checkoutEndpoint(), {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${session.access_token}`,
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
signal: timedAbort.controller.signal,
|
||||
body: JSON.stringify({
|
||||
payer_id: payerId,
|
||||
tier,
|
||||
idempotency_key: idempotencyKey,
|
||||
pcd_pay_cardname: typeof result['PCD_PAY_CARDNAME'] === 'string'
|
||||
? result['PCD_PAY_CARDNAME']
|
||||
: undefined,
|
||||
pcd_pay_cardnum: typeof result['PCD_PAY_CARDNUM'] === 'string'
|
||||
? result['PCD_PAY_CARDNUM']
|
||||
: undefined
|
||||
})
|
||||
})
|
||||
})
|
||||
} finally {
|
||||
timedAbort.dispose()
|
||||
}
|
||||
|
||||
let payload: unknown
|
||||
try {
|
||||
|
|
@ -136,12 +156,17 @@ export function PaypleCheckoutButton({ tier, catalogPrice }: PaypleCheckoutButto
|
|||
}
|
||||
})
|
||||
|
||||
if (!mountedRef.current) return
|
||||
setSuccess(true)
|
||||
window.setTimeout(() => window.location.reload(), 2000)
|
||||
scheduleTrackedTimeout(reloadTimerRef, () => window.location.reload(), 2000)
|
||||
} catch (checkoutError) {
|
||||
setError(checkoutErrorMessage(checkoutError))
|
||||
if (mountedRef.current) {
|
||||
setError(checkoutErrorMessage(checkoutError))
|
||||
}
|
||||
} finally {
|
||||
setBusy(false)
|
||||
if (mountedRef.current) {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
}, [catalogPrice, sdkReady, tier])
|
||||
|
||||
|
|
|
|||
|
|
@ -3,9 +3,15 @@
|
|||
// apps/web/src/components/billing/payple-manage-button.tsx
|
||||
// Payple 구독 관리 — payple-manage Edge Function 호출 (구독 취소)
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { Button, CircularProgress, Alert, Box, Dialog, DialogTitle, DialogContent, DialogContentText, DialogActions } from '@mui/material'
|
||||
import SettingsIcon from '@mui/icons-material/Settings'
|
||||
import {
|
||||
clearTrackedTimeout,
|
||||
createTimedAbortSignal,
|
||||
resolveSupabaseFunctionUrl,
|
||||
scheduleTrackedTimeout,
|
||||
} from '@/lib/edge-fetch'
|
||||
import { getSupabaseBrowserClient } from '@/lib/supabase-browser'
|
||||
|
||||
export function PaypleManageButton(): React.ReactElement {
|
||||
|
|
@ -14,27 +20,38 @@ export function PaypleManageButton(): React.ReactElement {
|
|||
const [confirmOpen, setConfirmOpen] = useState(false)
|
||||
const [success, setSuccess] = useState(false)
|
||||
const [ready, setReady] = useState(false)
|
||||
const mountedRef = useRef(true)
|
||||
const reloadTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
const abortRef = useRef<AbortController | null>(null)
|
||||
|
||||
useEffect(() => setReady(true), [])
|
||||
useEffect(() => {
|
||||
mountedRef.current = true
|
||||
setReady(true)
|
||||
return () => {
|
||||
mountedRef.current = false
|
||||
clearTrackedTimeout(reloadTimerRef)
|
||||
abortRef.current?.abort()
|
||||
abortRef.current = null
|
||||
}
|
||||
}, [])
|
||||
|
||||
async function handleCancel(): Promise<void> {
|
||||
setConfirmOpen(false)
|
||||
setError(null)
|
||||
setBusy(true)
|
||||
const timedAbort = createTimedAbortSignal(30_000, abortRef)
|
||||
try {
|
||||
const supabase = getSupabaseBrowserClient()
|
||||
const { data: { session }, error: sessionError } = await supabase.auth.getSession()
|
||||
if (!mountedRef.current || timedAbort.controller.signal.aborted) return
|
||||
|
||||
if (sessionError || !session) {
|
||||
setError('로그인이 필요합니다')
|
||||
return
|
||||
}
|
||||
|
||||
const baseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL?.trim()
|
||||
if (!baseUrl) throw new Error('결제 서버 설정이 완료되지 않았습니다')
|
||||
|
||||
const response = await fetch(
|
||||
new URL('/functions/v1/payple-manage', baseUrl).toString(),
|
||||
resolveSupabaseFunctionUrl('payple-manage'),
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
|
|
@ -42,6 +59,7 @@ export function PaypleManageButton(): React.ReactElement {
|
|||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ action: 'cancel' }),
|
||||
signal: timedAbort.controller.signal,
|
||||
}
|
||||
)
|
||||
|
||||
|
|
@ -58,12 +76,22 @@ export function PaypleManageButton(): React.ReactElement {
|
|||
) {
|
||||
throw new Error('구독 취소 결과를 확인할 수 없습니다.')
|
||||
}
|
||||
if (!mountedRef.current) return
|
||||
setSuccess(true)
|
||||
window.setTimeout(() => window.location.reload(), 2000)
|
||||
scheduleTrackedTimeout(reloadTimerRef, () => window.location.reload(), 2000)
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : '알 수 없는 오류')
|
||||
if (mountedRef.current) {
|
||||
setError(timedAbort.didTimeout()
|
||||
? '요청 시간이 초과되었습니다. 잠시 후 다시 시도해 주세요.'
|
||||
: e instanceof Error
|
||||
? e.message
|
||||
: '알 수 없는 오류')
|
||||
}
|
||||
} finally {
|
||||
setBusy(false)
|
||||
timedAbort.dispose()
|
||||
if (mountedRef.current) {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ import { useRef, useState, useEffect } from 'react'
|
|||
import { Alert, Box, Typography, IconButton } from '@mui/material'
|
||||
import { Send, Trash2 } from 'lucide-react'
|
||||
import { d3roFontMono } from '@d3ro/ui/theme'
|
||||
import { createTimedAbortSignal, resolveSupabaseFunctionUrl } from '@/lib/edge-fetch'
|
||||
import { getSupabaseBrowserClient, isSupabaseConfigured } from '@/lib/supabase-browser'
|
||||
|
||||
interface Message {
|
||||
|
|
@ -17,6 +18,68 @@ interface Message {
|
|||
timestamp: string
|
||||
}
|
||||
|
||||
/**
|
||||
* SSE 응답 스트림에서 text_delta 토큰을 누적하고, 취소·종료 시 reader를 해제한다.
|
||||
*/
|
||||
export async function consumeChatSseStream(options: {
|
||||
body: ReadableStream<Uint8Array>
|
||||
signal: AbortSignal
|
||||
onAccumulated: (accumulated: string) => void
|
||||
}): Promise<string> {
|
||||
const { body, signal, onAccumulated } = options
|
||||
const reader = body.getReader()
|
||||
const decoder = new TextDecoder()
|
||||
let buffer = ''
|
||||
let accumulated = ''
|
||||
|
||||
const onAbort = (): void => {
|
||||
void reader.cancel().catch(() => {})
|
||||
}
|
||||
if (signal.aborted) {
|
||||
await reader.cancel().catch(() => {})
|
||||
return accumulated
|
||||
}
|
||||
signal.addEventListener('abort', onAbort, { once: true })
|
||||
|
||||
try {
|
||||
while (!signal.aborted) {
|
||||
const { done, value } = await reader.read()
|
||||
if (done || signal.aborted) break
|
||||
|
||||
buffer += decoder.decode(value, { stream: true })
|
||||
const lines = buffer.split('\n')
|
||||
buffer = lines.pop() ?? ''
|
||||
|
||||
for (const line of lines) {
|
||||
const trimmed = line.trim()
|
||||
if (!trimmed.startsWith('data:')) continue
|
||||
const data = trimmed.slice(5).trim()
|
||||
if (data === '[DONE]' || data === '') continue
|
||||
|
||||
try {
|
||||
const event = JSON.parse(data) as {
|
||||
type?: unknown
|
||||
delta?: { type?: unknown; text?: unknown }
|
||||
}
|
||||
if (event.type === 'content_block_delta' && event.delta?.type === 'text_delta') {
|
||||
accumulated += typeof event.delta.text === 'string' ? event.delta.text : ''
|
||||
if (!signal.aborted) {
|
||||
onAccumulated(accumulated)
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Ignore malformed SSE lines
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
signal.removeEventListener('abort', onAbort)
|
||||
await reader.cancel().catch(() => {})
|
||||
}
|
||||
|
||||
return accumulated
|
||||
}
|
||||
|
||||
export function ChatPanel(): React.ReactElement {
|
||||
const [messages, setMessages] = useState<Message[]>([
|
||||
{
|
||||
|
|
@ -30,15 +93,30 @@ export function ChatPanel(): React.ReactElement {
|
|||
const [busy, setBusy] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const scrollRef = useRef<HTMLDivElement>(null)
|
||||
const mountedRef = useRef(true)
|
||||
const rafRef = useRef<number | null>(null)
|
||||
const activeControllerRef = useRef<AbortController | null>(null)
|
||||
|
||||
function scrollToBottom(): void {
|
||||
requestAnimationFrame(() => {
|
||||
if (rafRef.current !== null) cancelAnimationFrame(rafRef.current)
|
||||
rafRef.current = requestAnimationFrame(() => {
|
||||
rafRef.current = null
|
||||
if (scrollRef.current) {
|
||||
scrollRef.current.scrollTop = scrollRef.current.scrollHeight
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
mountedRef.current = true
|
||||
return () => {
|
||||
mountedRef.current = false
|
||||
if (rafRef.current !== null) cancelAnimationFrame(rafRef.current)
|
||||
activeControllerRef.current?.abort()
|
||||
activeControllerRef.current = null
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
scrollToBottom()
|
||||
}, [messages])
|
||||
|
|
@ -54,11 +132,12 @@ export function ChatPanel(): React.ReactElement {
|
|||
timestamp: new Date().toLocaleTimeString('ko-KR', { hour: '2-digit', minute: '2-digit' })
|
||||
}
|
||||
const nextMessages = [...messages, userMsg]
|
||||
const assistantId = 'a_' + Date.now()
|
||||
setMessages(nextMessages)
|
||||
setInput('')
|
||||
setError(null)
|
||||
setBusy(true)
|
||||
let requestTimeout: number | null = null
|
||||
const timedAbort = createTimedAbortSignal(45_000, activeControllerRef)
|
||||
|
||||
try {
|
||||
if (!isSupabaseConfigured()) {
|
||||
|
|
@ -67,6 +146,7 @@ export function ChatPanel(): React.ReactElement {
|
|||
|
||||
const supabase = getSupabaseBrowserClient()
|
||||
const { data: { session } } = await supabase.auth.getSession()
|
||||
if (!mountedRef.current || timedAbort.controller.signal.aborted) return
|
||||
|
||||
if (!session) {
|
||||
throw new Error('로그인 필요')
|
||||
|
|
@ -78,10 +158,8 @@ export function ChatPanel(): React.ReactElement {
|
|||
stream: true
|
||||
}
|
||||
|
||||
const controller = new AbortController()
|
||||
requestTimeout = window.setTimeout(() => controller.abort(), 45_000)
|
||||
const response = await fetch(
|
||||
process.env.NEXT_PUBLIC_SUPABASE_URL + '/functions/v1/llm-proxy',
|
||||
resolveSupabaseFunctionUrl('llm-proxy'),
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
|
|
@ -89,7 +167,7 @@ export function ChatPanel(): React.ReactElement {
|
|||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
signal: controller.signal
|
||||
signal: timedAbort.controller.signal
|
||||
}
|
||||
)
|
||||
|
||||
|
|
@ -101,7 +179,7 @@ export function ChatPanel(): React.ReactElement {
|
|||
|
||||
if (!response.body) throw new Error('empty_response')
|
||||
|
||||
const assistantId = 'a_' + Date.now()
|
||||
if (!mountedRef.current) return
|
||||
setMessages((prev) => [
|
||||
...prev,
|
||||
{
|
||||
|
|
@ -112,47 +190,23 @@ export function ChatPanel(): React.ReactElement {
|
|||
}
|
||||
])
|
||||
|
||||
const reader = response.body.getReader()
|
||||
const decoder = new TextDecoder()
|
||||
let buffer = ''
|
||||
let accumulated = ''
|
||||
let streamDone = false
|
||||
|
||||
while (!streamDone) {
|
||||
const { done, value } = await reader.read()
|
||||
if (done) {
|
||||
streamDone = true
|
||||
break
|
||||
}
|
||||
|
||||
buffer += decoder.decode(value, { stream: true })
|
||||
const lines = buffer.split('\n')
|
||||
buffer = lines.pop() ?? ''
|
||||
|
||||
for (const line of lines) {
|
||||
const trimmed = line.trim()
|
||||
if (!trimmed.startsWith('data:')) continue
|
||||
const data = trimmed.slice(5).trim()
|
||||
if (data === '[DONE]' || data === '') continue
|
||||
|
||||
try {
|
||||
const event = JSON.parse(data)
|
||||
if (event.type === 'content_block_delta' && event.delta?.type === 'text_delta') {
|
||||
accumulated += event.delta.text ?? ''
|
||||
setMessages((prev) =>
|
||||
prev.map((m) => (m.id === assistantId ? { ...m, content: accumulated } : m))
|
||||
)
|
||||
}
|
||||
} catch {
|
||||
// Ignore parse errors
|
||||
}
|
||||
}
|
||||
}
|
||||
const accumulated = await consumeChatSseStream({
|
||||
body: response.body,
|
||||
signal: timedAbort.controller.signal,
|
||||
onAccumulated: (partial) => {
|
||||
if (!mountedRef.current) return
|
||||
setMessages((prev) =>
|
||||
prev.map((m) => (m.id === assistantId ? { ...m, content: partial } : m))
|
||||
)
|
||||
},
|
||||
})
|
||||
if (!mountedRef.current || timedAbort.controller.signal.aborted) return
|
||||
if (!accumulated.trim()) throw new Error('empty_response')
|
||||
} catch (candidate) {
|
||||
setMessages(messages)
|
||||
if (!mountedRef.current) return
|
||||
setMessages((prev) => prev.filter((m) => m.id !== userMsg.id && m.id !== assistantId))
|
||||
setInput(text)
|
||||
const timedOut = candidate instanceof DOMException && candidate.name === 'AbortError'
|
||||
const timedOut = timedAbort.didTimeout() || (candidate instanceof DOMException && candidate.name === 'AbortError')
|
||||
const code = candidate instanceof Error ? candidate.message : 'request_failed'
|
||||
setError(code === 'quota_exceeded'
|
||||
? '오늘 사용할 수 있는 AI 대화 한도를 모두 사용했습니다.'
|
||||
|
|
@ -162,8 +216,10 @@ export function ChatPanel(): React.ReactElement {
|
|||
? 'AI 응답 시간이 초과되었습니다.'
|
||||
: 'AI 요청을 완료하지 못했습니다. 입력을 유지했으니 다시 시도할 수 있습니다.')
|
||||
} finally {
|
||||
if (requestTimeout !== null) window.clearTimeout(requestTimeout)
|
||||
setBusy(false)
|
||||
timedAbort.dispose()
|
||||
if (mountedRef.current) {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@
|
|||
// 회의록 문서 편집 — MarkdownEditor 다이얼로그
|
||||
// 클릭 → 다이얼로그 열림 → textarea 편집 → 저장 시 meeting_documents UPDATE
|
||||
|
||||
import { useState } from 'react'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import dynamic from 'next/dynamic'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import {
|
||||
|
|
@ -52,6 +52,14 @@ export function DocumentEditor({ doc }: DocumentEditorProps): React.ReactElement
|
|||
const [busy, setBusy] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [tab, setTab] = useState<'edit' | 'preview'>('edit')
|
||||
const mountedRef = useRef(true)
|
||||
|
||||
useEffect(() => {
|
||||
mountedRef.current = true
|
||||
return () => {
|
||||
mountedRef.current = false
|
||||
}
|
||||
}, [])
|
||||
|
||||
async function handleSave(): Promise<void> {
|
||||
setError(null)
|
||||
|
|
@ -63,6 +71,7 @@ export function DocumentEditor({ doc }: DocumentEditorProps): React.ReactElement
|
|||
.update({ title, content })
|
||||
.eq('id', doc.id)
|
||||
|
||||
if (!mountedRef.current) return
|
||||
if (updateErr) {
|
||||
setError(updateErr.message)
|
||||
return
|
||||
|
|
@ -70,8 +79,14 @@ export function DocumentEditor({ doc }: DocumentEditorProps): React.ReactElement
|
|||
|
||||
setOpen(false)
|
||||
router.refresh()
|
||||
} catch (err) {
|
||||
if (mountedRef.current) {
|
||||
setError(err instanceof Error ? err.message : '문서 저장에 실패했습니다.')
|
||||
}
|
||||
} finally {
|
||||
setBusy(false)
|
||||
if (mountedRef.current) {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -86,6 +101,7 @@ export function DocumentEditor({ doc }: DocumentEditorProps): React.ReactElement
|
|||
.delete()
|
||||
.eq('id', doc.id)
|
||||
|
||||
if (!mountedRef.current) return
|
||||
if (deleteErr) {
|
||||
setError(deleteErr.message)
|
||||
return
|
||||
|
|
@ -93,8 +109,14 @@ export function DocumentEditor({ doc }: DocumentEditorProps): React.ReactElement
|
|||
|
||||
setOpen(false)
|
||||
router.refresh()
|
||||
} catch (err) {
|
||||
if (mountedRef.current) {
|
||||
setError(err instanceof Error ? err.message : '문서 삭제에 실패했습니다.')
|
||||
}
|
||||
} finally {
|
||||
setBusy(false)
|
||||
if (mountedRef.current) {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@
|
|||
// apps/web/src/components/meetings/generate-document-button.tsx
|
||||
// 회의록에서 AI 문서 생성 — llm-proxy 호출 → meeting_documents INSERT
|
||||
|
||||
import { useState } from 'react'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import {
|
||||
Button,
|
||||
|
|
@ -14,6 +14,7 @@ import {
|
|||
Box
|
||||
} from '@mui/material'
|
||||
import AutoAwesomeIcon from '@mui/icons-material/AutoAwesome'
|
||||
import { createTimedAbortSignal, resolveSupabaseFunctionUrl } from '@/lib/edge-fetch'
|
||||
import { getSupabaseBrowserClient } from '@/lib/supabase-browser'
|
||||
|
||||
type TemplateType = 'minutes' | 'report' | 'idea-note' | 'mindmap'
|
||||
|
|
@ -75,17 +76,30 @@ export function GenerateDocumentButton({
|
|||
const [anchorEl, setAnchorEl] = useState<HTMLElement | null>(null)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const mountedRef = useRef(true)
|
||||
const abortRef = useRef<AbortController | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
mountedRef.current = true
|
||||
return () => {
|
||||
mountedRef.current = false
|
||||
abortRef.current?.abort()
|
||||
abortRef.current = null
|
||||
}
|
||||
}, [])
|
||||
|
||||
async function handleGenerate(tpl: TemplateDef): Promise<void> {
|
||||
setAnchorEl(null)
|
||||
setError(null)
|
||||
setBusy(true)
|
||||
const timedAbort = createTimedAbortSignal(45_000, abortRef)
|
||||
|
||||
try {
|
||||
const supabase = getSupabaseBrowserClient()
|
||||
const {
|
||||
data: { session }
|
||||
} = await supabase.auth.getSession()
|
||||
if (!mountedRef.current || timedAbort.controller.signal.aborted) return
|
||||
if (!session) {
|
||||
setError('로그인이 필요합니다')
|
||||
return
|
||||
|
|
@ -99,13 +113,14 @@ export function GenerateDocumentButton({
|
|||
// llm-proxy 호출
|
||||
const startedAt = Date.now()
|
||||
const llmResp = await fetch(
|
||||
`${process.env.NEXT_PUBLIC_SUPABASE_URL}/functions/v1/llm-proxy`,
|
||||
resolveSupabaseFunctionUrl('llm-proxy'),
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${session.access_token}`,
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
signal: timedAbort.controller.signal,
|
||||
body: JSON.stringify({
|
||||
messages: [{ role: 'user', content: transcript }],
|
||||
system: tpl.systemPrompt,
|
||||
|
|
@ -127,6 +142,7 @@ export function GenerateDocumentButton({
|
|||
const {
|
||||
data: { user }
|
||||
} = await supabase.auth.getUser()
|
||||
if (!mountedRef.current) return
|
||||
if (!user) {
|
||||
setError('로그인이 필요합니다')
|
||||
return
|
||||
|
|
@ -142,6 +158,7 @@ export function GenerateDocumentButton({
|
|||
llm_model: llmData.model,
|
||||
llm_latency_ms: latency
|
||||
})
|
||||
if (!mountedRef.current) return
|
||||
|
||||
if (insertErr) {
|
||||
setError(`문서 저장 실패: ${insertErr.message}`)
|
||||
|
|
@ -150,9 +167,18 @@ export function GenerateDocumentButton({
|
|||
|
||||
router.refresh()
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Unknown error')
|
||||
if (mountedRef.current) {
|
||||
setError(timedAbort.didTimeout()
|
||||
? 'AI 문서 생성 시간이 초과되었습니다.'
|
||||
: e instanceof Error
|
||||
? e.message
|
||||
: 'Unknown error')
|
||||
}
|
||||
} finally {
|
||||
setBusy(false)
|
||||
timedAbort.dispose()
|
||||
if (mountedRef.current) {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -19,31 +19,56 @@ const AuthContext = createContext<AuthContextValue>({
|
|||
loading: true
|
||||
})
|
||||
|
||||
export interface AuthSessionBindingClient {
|
||||
auth: {
|
||||
getSession: () => Promise<{ data: { session: Session | null } }>
|
||||
onAuthStateChange: (
|
||||
callback: (_event: unknown, nextSession: Session | null) => void,
|
||||
) => { data: { subscription: { unsubscribe: () => void } } }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 마운트 해제 이후 상태 갱신과 거부된 getSession 프로미스의 미처리 예외를 차단한다.
|
||||
*/
|
||||
export function bindAuthSession(
|
||||
supabase: AuthSessionBindingClient,
|
||||
onSession: (session: Session | null) => void,
|
||||
onLoadingChange: (loading: boolean) => void,
|
||||
): () => void {
|
||||
let cancelled = false
|
||||
|
||||
supabase.auth
|
||||
.getSession()
|
||||
.then(({ data }) => {
|
||||
if (!cancelled) onSession(data.session)
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) onSession(null)
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) onLoadingChange(false)
|
||||
})
|
||||
|
||||
const {
|
||||
data: { subscription },
|
||||
} = supabase.auth.onAuthStateChange((_event, newSession) => {
|
||||
if (!cancelled) onSession(newSession)
|
||||
})
|
||||
|
||||
return () => {
|
||||
cancelled = true
|
||||
subscription.unsubscribe()
|
||||
}
|
||||
}
|
||||
|
||||
export function AuthProvider({ children }: { children: React.ReactNode }): React.ReactElement {
|
||||
const [session, setSession] = useState<Session | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
|
||||
useEffect(() => {
|
||||
const supabase = getSupabaseBrowserClient()
|
||||
|
||||
supabase.auth
|
||||
.getSession()
|
||||
.then(({ data }) => {
|
||||
setSession(data.session)
|
||||
})
|
||||
.finally(() => {
|
||||
setLoading(false)
|
||||
})
|
||||
|
||||
const {
|
||||
data: { subscription }
|
||||
} = supabase.auth.onAuthStateChange((_event, newSession) => {
|
||||
setSession(newSession)
|
||||
})
|
||||
|
||||
return () => {
|
||||
subscription.unsubscribe()
|
||||
}
|
||||
return bindAuthSession(supabase, setSession, setLoading)
|
||||
}, [])
|
||||
|
||||
return (
|
||||
|
|
|
|||
|
|
@ -13,6 +13,25 @@ import { transcribeWebAudio, WebSttError } from '@/lib/web-stt-client'
|
|||
|
||||
type RecorderState = 'idle' | 'recording' | 'processing' | 'done' | 'error'
|
||||
|
||||
export interface StoppableStream {
|
||||
getTracks: () => ReadonlyArray<{ stop: () => void }>
|
||||
}
|
||||
|
||||
/**
|
||||
* 권한 프롬프트 대기 중 언마운트·재시작되면 획득된 마이크 트랙을 즉시 정지한다.
|
||||
*/
|
||||
export async function acquireGuardedMediaStream<TStream extends StoppableStream>(options: {
|
||||
getUserMedia: () => Promise<TStream>
|
||||
isStillActive: () => boolean
|
||||
}): Promise<TStream | null> {
|
||||
const stream = await options.getUserMedia()
|
||||
if (!options.isStillActive()) {
|
||||
stream.getTracks().forEach((track) => track.stop())
|
||||
return null
|
||||
}
|
||||
return stream
|
||||
}
|
||||
|
||||
export function MicRecorder(): React.ReactElement {
|
||||
const [state, setState] = useState<RecorderState>('idle')
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
|
@ -30,20 +49,11 @@ export function MicRecorder(): React.ReactElement {
|
|||
const chunksRef = useRef<Blob[]>([])
|
||||
const transcriptionAbortRef = useRef<AbortController | null>(null)
|
||||
const transcriptionGenerationRef = useRef(0)
|
||||
const mountedRef = useRef(true)
|
||||
const captureGenerationRef = useRef(0)
|
||||
|
||||
const configured = isSupabaseConfigured()
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
stopStream()
|
||||
if (rafRef.current) cancelAnimationFrame(rafRef.current)
|
||||
if (elapsedTimerRef.current) window.clearInterval(elapsedTimerRef.current)
|
||||
transcriptionGenerationRef.current += 1
|
||||
transcriptionAbortRef.current?.abort()
|
||||
transcriptionAbortRef.current = null
|
||||
}
|
||||
}, [])
|
||||
|
||||
const stopStream = useCallback((): void => {
|
||||
streamRef.current?.getTracks().forEach((track) => track.stop())
|
||||
streamRef.current = null
|
||||
|
|
@ -52,9 +62,36 @@ export function MicRecorder(): React.ReactElement {
|
|||
analyserRef.current = null
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
mountedRef.current = true
|
||||
return () => {
|
||||
mountedRef.current = false
|
||||
captureGenerationRef.current += 1
|
||||
const recorder = mediaRecorderRef.current
|
||||
if (recorder) {
|
||||
recorder.ondataavailable = null
|
||||
recorder.onstop = null
|
||||
if (recorder.state !== 'inactive') {
|
||||
try {
|
||||
recorder.stop()
|
||||
} catch {
|
||||
// 언마운트 중 이미 종료된 레코더는 무시한다.
|
||||
}
|
||||
}
|
||||
mediaRecorderRef.current = null
|
||||
}
|
||||
stopStream()
|
||||
if (rafRef.current !== null) cancelAnimationFrame(rafRef.current)
|
||||
if (elapsedTimerRef.current !== null) window.clearInterval(elapsedTimerRef.current)
|
||||
transcriptionGenerationRef.current += 1
|
||||
transcriptionAbortRef.current?.abort()
|
||||
transcriptionAbortRef.current = null
|
||||
}
|
||||
}, [stopStream])
|
||||
|
||||
const updateLevel = useCallback((): void => {
|
||||
const analyser = analyserRef.current
|
||||
if (!analyser) return
|
||||
if (!analyser || !mountedRef.current) return
|
||||
|
||||
const buf = new Uint8Array(analyser.frequencyBinCount)
|
||||
analyser.getByteTimeDomainData(buf)
|
||||
|
|
@ -70,19 +107,25 @@ export function MicRecorder(): React.ReactElement {
|
|||
}, [])
|
||||
|
||||
const startRecording = useCallback(async (): Promise<void> => {
|
||||
const captureGen = ++captureGenerationRef.current
|
||||
setError(null)
|
||||
setTranscript('')
|
||||
setElapsed(0)
|
||||
|
||||
try {
|
||||
const stream = await navigator.mediaDevices.getUserMedia({
|
||||
audio: {
|
||||
sampleRate: 16000,
|
||||
channelCount: 1,
|
||||
echoCancellation: true,
|
||||
noiseSuppression: true,
|
||||
}
|
||||
const stream = await acquireGuardedMediaStream({
|
||||
getUserMedia: () =>
|
||||
navigator.mediaDevices.getUserMedia({
|
||||
audio: {
|
||||
sampleRate: 16000,
|
||||
channelCount: 1,
|
||||
echoCancellation: true,
|
||||
noiseSuppression: true,
|
||||
},
|
||||
}),
|
||||
isStillActive: () => mountedRef.current && captureGen === captureGenerationRef.current,
|
||||
})
|
||||
if (!stream) return
|
||||
streamRef.current = stream
|
||||
|
||||
const AudioCtx = window.AudioContext
|
||||
|
|
@ -106,27 +149,35 @@ export function MicRecorder(): React.ReactElement {
|
|||
if (e.data.size > 0) chunksRef.current.push(e.data)
|
||||
}
|
||||
mediaRecorder.onstop = () => {
|
||||
if (!mountedRef.current) {
|
||||
stopStream()
|
||||
return
|
||||
}
|
||||
void handleRecordingComplete()
|
||||
}
|
||||
mediaRecorder.start(250)
|
||||
|
||||
startAtRef.current = Date.now()
|
||||
elapsedTimerRef.current = window.setInterval(() => {
|
||||
setElapsed(Date.now() - startAtRef.current)
|
||||
if (mountedRef.current) {
|
||||
setElapsed(Date.now() - startAtRef.current)
|
||||
}
|
||||
}, 100)
|
||||
|
||||
setState('recording')
|
||||
} catch (e) {
|
||||
stopStream()
|
||||
if (!mountedRef.current) return
|
||||
setError(e instanceof Error ? e.message : '마이크 권한을 확인해주세요.')
|
||||
setState('error')
|
||||
stopStream()
|
||||
}
|
||||
}, [stopStream, updateLevel])
|
||||
|
||||
const handleRecordingComplete = useCallback(async (): Promise<void> => {
|
||||
if (!mountedRef.current) return
|
||||
setState('processing')
|
||||
if (rafRef.current) cancelAnimationFrame(rafRef.current)
|
||||
if (elapsedTimerRef.current) window.clearInterval(elapsedTimerRef.current)
|
||||
if (rafRef.current !== null) cancelAnimationFrame(rafRef.current)
|
||||
if (elapsedTimerRef.current !== null) window.clearInterval(elapsedTimerRef.current)
|
||||
|
||||
const blob = new Blob(chunksRef.current, { type: 'audio/webm' })
|
||||
stopStream()
|
||||
|
|
@ -148,11 +199,11 @@ export function MicRecorder(): React.ReactElement {
|
|||
supabaseUrl,
|
||||
signal: controller.signal,
|
||||
})
|
||||
if (generation !== transcriptionGenerationRef.current) return
|
||||
if (!mountedRef.current || generation !== transcriptionGenerationRef.current) return
|
||||
setTranscript(result.transcript)
|
||||
setState('done')
|
||||
} catch (transcriptionError) {
|
||||
if (generation !== transcriptionGenerationRef.current) return
|
||||
if (!mountedRef.current || generation !== transcriptionGenerationRef.current) return
|
||||
setTranscript('')
|
||||
const code = transcriptionError instanceof WebSttError ? transcriptionError.code : 'network'
|
||||
const messages: Record<string, string> = {
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@
|
|||
// 팀 멤버 초대 — 이메일 기반 (V2-7b).
|
||||
// Edge Function team-invite로 토큰 발급 → 초대 URL 반환 → 클라이언트가 복사/공유.
|
||||
|
||||
import { useState } from 'react'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import {
|
||||
Box,
|
||||
Button,
|
||||
|
|
@ -23,6 +23,12 @@ import {
|
|||
} from '@mui/material'
|
||||
import PersonAddIcon from '@mui/icons-material/PersonAdd'
|
||||
import ContentCopyIcon from '@mui/icons-material/ContentCopy'
|
||||
import {
|
||||
clearTrackedTimeout,
|
||||
createTimedAbortSignal,
|
||||
resolveSupabaseFunctionUrl,
|
||||
scheduleTrackedTimeout,
|
||||
} from '@/lib/edge-fetch'
|
||||
import { getSupabaseBrowserClient } from '@/lib/supabase-browser'
|
||||
|
||||
interface InviteMemberFormProps {
|
||||
|
|
@ -43,45 +49,74 @@ export function InviteMemberForm({ teamId }: InviteMemberFormProps): React.React
|
|||
const [busy, setBusy] = useState(false)
|
||||
const [result, setResult] = useState<InviteResult | null>(null)
|
||||
const [copied, setCopied] = useState(false)
|
||||
const mountedRef = useRef(true)
|
||||
const copyTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
const abortRef = useRef<AbortController | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
mountedRef.current = true
|
||||
return () => {
|
||||
mountedRef.current = false
|
||||
clearTrackedTimeout(copyTimerRef)
|
||||
abortRef.current?.abort()
|
||||
abortRef.current = null
|
||||
}
|
||||
}, [])
|
||||
|
||||
async function handleInvite(): Promise<void> {
|
||||
if (!email.trim()) return
|
||||
setError(null)
|
||||
setBusy(true)
|
||||
const timedAbort = createTimedAbortSignal(30_000, abortRef)
|
||||
try {
|
||||
const supabase = getSupabaseBrowserClient()
|
||||
const {
|
||||
data: { session }
|
||||
} = await supabase.auth.getSession()
|
||||
if (!mountedRef.current || timedAbort.controller.signal.aborted) return
|
||||
if (!session) {
|
||||
setError('로그인이 필요합니다')
|
||||
return
|
||||
}
|
||||
|
||||
const response = await fetch(
|
||||
`${process.env.NEXT_PUBLIC_SUPABASE_URL}/functions/v1/team-invite`,
|
||||
resolveSupabaseFunctionUrl('team-invite'),
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${session.access_token}`,
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({ team_id: teamId, email: email.trim(), role })
|
||||
body: JSON.stringify({ team_id: teamId, email: email.trim(), role }),
|
||||
signal: timedAbort.controller.signal,
|
||||
}
|
||||
)
|
||||
|
||||
if (!response.ok) {
|
||||
const errData = (await response.json()) as { error?: string; message?: string }
|
||||
setError(errData.message ?? errData.error ?? `실패: ${response.status}`)
|
||||
const errData = (await response.json().catch(() => ({}))) as { error?: string; message?: string }
|
||||
if (mountedRef.current) {
|
||||
setError(errData.message ?? errData.error ?? `실패: ${response.status}`)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
const data = (await response.json()) as InviteResult
|
||||
setResult(data)
|
||||
if (mountedRef.current) {
|
||||
setResult(data)
|
||||
}
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Unknown error')
|
||||
if (mountedRef.current) {
|
||||
setError(timedAbort.didTimeout()
|
||||
? '초대 요청 시간이 초과되었습니다.'
|
||||
: e instanceof Error
|
||||
? e.message
|
||||
: 'Unknown error')
|
||||
}
|
||||
} finally {
|
||||
setBusy(false)
|
||||
timedAbort.dispose()
|
||||
if (mountedRef.current) {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -89,14 +124,20 @@ export function InviteMemberForm({ teamId }: InviteMemberFormProps): React.React
|
|||
if (!result) return
|
||||
try {
|
||||
await navigator.clipboard.writeText(result.url)
|
||||
if (!mountedRef.current) return
|
||||
setCopied(true)
|
||||
setTimeout(() => setCopied(false), 2000)
|
||||
scheduleTrackedTimeout(copyTimerRef, () => {
|
||||
if (mountedRef.current) setCopied(false)
|
||||
}, 2000)
|
||||
} catch {
|
||||
// clipboard 차단 시 무시
|
||||
}
|
||||
}
|
||||
|
||||
function handleClose(): void {
|
||||
clearTrackedTimeout(copyTimerRef)
|
||||
abortRef.current?.abort()
|
||||
abortRef.current = null
|
||||
setOpen(false)
|
||||
setEmail('')
|
||||
setRole('member')
|
||||
|
|
|
|||
88
apps/web/src/lib/edge-fetch.ts
Normal file
88
apps/web/src/lib/edge-fetch.ts
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
export interface TimerRefHandle {
|
||||
current: ReturnType<typeof setTimeout> | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Supabase Edge Function URL을 검증·생성한다.
|
||||
* HTTPS 또는 로컬 loopback HTTP만 허용하고, credentials 포함 URL을 거부한다.
|
||||
*/
|
||||
export function resolveSupabaseFunctionUrl(
|
||||
functionName: string,
|
||||
rawBaseUrl: string | undefined = process.env.NEXT_PUBLIC_SUPABASE_URL,
|
||||
): string {
|
||||
const baseUrl = rawBaseUrl?.trim()
|
||||
if (!baseUrl) {
|
||||
throw new Error('서버 설정이 완료되지 않았습니다.')
|
||||
}
|
||||
const normalizedName = functionName.trim().replace(/^\/+/, '')
|
||||
if (!normalizedName || normalizedName.includes('/') || normalizedName.includes('..')) {
|
||||
throw new Error('잘못된 함수 경로입니다.')
|
||||
}
|
||||
try {
|
||||
const url = new URL(`/functions/v1/${encodeURIComponent(normalizedName)}`, baseUrl)
|
||||
const isLocalHttp =
|
||||
url.protocol === 'http:' && (url.hostname === 'localhost' || url.hostname === '127.0.0.1')
|
||||
if ((url.protocol !== 'https:' && !isLocalHttp) || url.username || url.password) {
|
||||
throw new Error('invalid_origin')
|
||||
}
|
||||
return url.toString()
|
||||
} catch {
|
||||
throw new Error('서버 주소 설정이 올바르지 않습니다.')
|
||||
}
|
||||
}
|
||||
|
||||
export interface TimedAbortHandle {
|
||||
controller: AbortController
|
||||
didTimeout: () => boolean
|
||||
dispose: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* 타임아웃으로 자동 중단되며, 완료/언마운트 시 타이머와 참조를 정리할 수 있는 AbortController 핸들.
|
||||
*/
|
||||
export function createTimedAbortSignal(
|
||||
timeoutMs: number,
|
||||
activeRef?: { current: AbortController | null },
|
||||
): TimedAbortHandle {
|
||||
const controller = new AbortController()
|
||||
let timedOut = false
|
||||
if (activeRef) {
|
||||
activeRef.current?.abort()
|
||||
activeRef.current = controller
|
||||
}
|
||||
|
||||
const timer = globalThis.setTimeout(() => {
|
||||
timedOut = true
|
||||
controller.abort()
|
||||
}, timeoutMs)
|
||||
|
||||
return {
|
||||
controller,
|
||||
didTimeout: () => timedOut,
|
||||
dispose: () => {
|
||||
globalThis.clearTimeout(timer)
|
||||
if (activeRef && activeRef.current === controller) {
|
||||
activeRef.current = null
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export function clearTrackedTimeout(timerRef: TimerRefHandle): void {
|
||||
if (timerRef.current !== null) {
|
||||
globalThis.clearTimeout(timerRef.current)
|
||||
timerRef.current = null
|
||||
}
|
||||
}
|
||||
|
||||
export function scheduleTrackedTimeout(
|
||||
timerRef: TimerRefHandle,
|
||||
callback: () => void,
|
||||
delayMs: number,
|
||||
): void {
|
||||
clearTrackedTimeout(timerRef)
|
||||
timerRef.current = globalThis.setTimeout(() => {
|
||||
timerRef.current = null
|
||||
callback()
|
||||
}, delayMs)
|
||||
}
|
||||
|
|
@ -11,19 +11,41 @@ export const RETURN_PATH_HEADER = 'x-d3ro-return-path'
|
|||
|
||||
const DEFAULT_RETURN_PATH = '/dashboard'
|
||||
|
||||
function hasUnsafePathChars(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
|
||||
}
|
||||
|
||||
/**
|
||||
* 로그인 뒤 이동할 웹앱 내부 경로(basePath 제외)만 통과시킨다.
|
||||
* `//evil.example`, `/\evil.example` 같은 외부 이동은 기본 경로로 바꾼다.
|
||||
* `//evil.example`, `/app//evil.example`, `/\evil.example`, 제어문자는 기본 경로로 바꾼다.
|
||||
*/
|
||||
export function safeReturnPath(value: string | null | undefined): string {
|
||||
if (!value || !value.startsWith('/') || value.startsWith('//') || value.startsWith('/\\')) {
|
||||
if (!value || !value.startsWith('/') || value.startsWith('//') || hasUnsafePathChars(value)) {
|
||||
return DEFAULT_RETURN_PATH
|
||||
}
|
||||
if (value === WEB_APP_BASE_PATH) return DEFAULT_RETURN_PATH
|
||||
if (value.startsWith(`${WEB_APP_BASE_PATH}/`)) {
|
||||
return value.slice(WEB_APP_BASE_PATH.length)
|
||||
const candidate = value === WEB_APP_BASE_PATH
|
||||
? DEFAULT_RETURN_PATH
|
||||
: value.startsWith(`${WEB_APP_BASE_PATH}/`)
|
||||
? value.slice(WEB_APP_BASE_PATH.length)
|
||||
: value
|
||||
if (!candidate.startsWith('/') || candidate.startsWith('//')) {
|
||||
return DEFAULT_RETURN_PATH
|
||||
}
|
||||
return value
|
||||
try {
|
||||
const parsed = new URL(candidate, 'https://d3ro.local')
|
||||
if (parsed.origin !== 'https://d3ro.local' || parsed.pathname.startsWith('//')) {
|
||||
return DEFAULT_RETURN_PATH
|
||||
}
|
||||
} catch {
|
||||
return DEFAULT_RETURN_PATH
|
||||
}
|
||||
return candidate
|
||||
}
|
||||
|
||||
/** 로그인 페이지 경로(basePath 제외). 돌아갈 곳이 기본값이면 쿼리를 붙이지 않는다. */
|
||||
|
|
|
|||
235
apps/web/tests/security-and-lifecycle.test.ts
Normal file
235
apps/web/tests/security-and-lifecycle.test.ts
Normal file
|
|
@ -0,0 +1,235 @@
|
|||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import vm from 'node:vm'
|
||||
import { NextRequest } from 'next/server'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { consumeChatSseStream } from '@/components/chat/chat-panel'
|
||||
import { bindAuthSession } from '@/components/providers/auth-provider'
|
||||
import { acquireGuardedMediaStream } from '@/components/record/mic-recorder'
|
||||
import {
|
||||
clearTrackedTimeout,
|
||||
createTimedAbortSignal,
|
||||
resolveSupabaseFunctionUrl,
|
||||
scheduleTrackedTimeout,
|
||||
} from '@/lib/edge-fetch'
|
||||
import { safeReturnPath } from '@/lib/web-app-url'
|
||||
|
||||
const mockExchangeCodeForSession = vi.fn()
|
||||
const mockIsSupabaseConfiguredServer = vi.fn(() => true)
|
||||
|
||||
vi.mock('@/lib/supabase-server', () => ({
|
||||
isSupabaseConfiguredServer: () => mockIsSupabaseConfiguredServer(),
|
||||
getSupabaseServerClient: async () => ({
|
||||
auth: {
|
||||
exchangeCodeForSession: (code: string) => mockExchangeCodeForSession(code),
|
||||
},
|
||||
}),
|
||||
}))
|
||||
|
||||
function loadSwSanitizeTargetUrl(): (rawUrl: unknown) => string {
|
||||
const swPath = path.resolve(__dirname, '../public/sw.js')
|
||||
const source = fs.readFileSync(swPath, 'utf8')
|
||||
const sandbox: {
|
||||
URL: typeof URL
|
||||
self: {
|
||||
addEventListener: () => void
|
||||
registration: { showNotification: () => Promise<void> }
|
||||
clients: { matchAll: () => Promise<unknown[]> }
|
||||
}
|
||||
sanitizeTargetUrl?: (rawUrl: unknown) => string
|
||||
} = {
|
||||
URL,
|
||||
self: {
|
||||
addEventListener: () => undefined,
|
||||
registration: { showNotification: async () => undefined },
|
||||
clients: { matchAll: async () => [] },
|
||||
},
|
||||
}
|
||||
vm.createContext(sandbox)
|
||||
vm.runInContext(`${source}\nthis.sanitizeTargetUrl = sanitizeTargetUrl;`, sandbox)
|
||||
if (typeof sandbox.sanitizeTargetUrl !== 'function') {
|
||||
throw new Error('sanitizeTargetUrl helper missing in public/sw.js')
|
||||
}
|
||||
return sandbox.sanitizeTargetUrl
|
||||
}
|
||||
|
||||
describe('Web URL 안전성 및 OAuth 콜백 보안', () => {
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.useRealTimers()
|
||||
mockIsSupabaseConfiguredServer.mockReturnValue(true)
|
||||
})
|
||||
|
||||
it('safeReturnPath_앱접두사이후더블슬래시백슬래시제어문자_기본경로로폴백한다', () => {
|
||||
expect(safeReturnPath('/app//evil.example')).toBe('/dashboard')
|
||||
expect(safeReturnPath('/app/\\evil.example')).toBe('/dashboard')
|
||||
expect(safeReturnPath('/dashboard\\@evil.example')).toBe('/dashboard')
|
||||
expect(safeReturnPath('/dashboard\r\nLocation:https://evil.example')).toBe('/dashboard')
|
||||
expect(safeReturnPath('/app/meetings?tab=notes#top')).toBe('/meetings?tab=notes#top')
|
||||
expect(safeReturnPath('/billing')).toBe('/billing')
|
||||
})
|
||||
|
||||
it('sanitizeTargetUrl_푸시알림오픈리다이렉트우회패턴_기본앱경로로폴백한다', () => {
|
||||
const sanitizeTargetUrl = loadSwSanitizeTargetUrl()
|
||||
expect(sanitizeTargetUrl('/app//evil.example')).toBe('/app/dashboard')
|
||||
expect(sanitizeTargetUrl('/app\\evil.example')).toBe('/app/dashboard')
|
||||
expect(sanitizeTargetUrl('/dashboard\\@evil.example')).toBe('/app/dashboard')
|
||||
expect(sanitizeTargetUrl('/dashboard\t\n')).toBe('/app/dashboard')
|
||||
expect(sanitizeTargetUrl('/meetings/123?tab=summary')).toBe('/app/meetings/123?tab=summary')
|
||||
expect(sanitizeTargetUrl('/app/billing')).toBe('/app/billing')
|
||||
})
|
||||
|
||||
it('authCallback_GET_세션교환실패시원시에러문구노출없이고정코드로리다이렉트한다', async () => {
|
||||
mockExchangeCodeForSession.mockResolvedValue({
|
||||
error: { message: 'internal supabase failure https://db.internal:5432' },
|
||||
})
|
||||
const { GET } = await import('@/app/auth/callback/route')
|
||||
const req = new NextRequest('https://d3ro.chanpaca.net/app/auth/callback?code=fake-oauth-code')
|
||||
|
||||
const res = await GET(req)
|
||||
expect(res.status).toBe(307)
|
||||
const location = res.headers.get('location') ?? ''
|
||||
expect(location).toBe('https://d3ro.chanpaca.net/app/login?error=oauth_callback_failed')
|
||||
expect(location).not.toContain('db.internal')
|
||||
})
|
||||
|
||||
it('bindAuthSession_언마운트와세션조회실패_예외누수나해제후상태갱신을차단한다', async () => {
|
||||
let resolveSession!: (value: { data: { session: null } }) => void
|
||||
const unsubscribe = vi.fn()
|
||||
const sessions: unknown[] = []
|
||||
const loadings: boolean[] = []
|
||||
|
||||
const unbind = bindAuthSession(
|
||||
{
|
||||
auth: {
|
||||
getSession: () =>
|
||||
new Promise((resolve) => {
|
||||
resolveSession = resolve
|
||||
}),
|
||||
onAuthStateChange: () => ({ data: { subscription: { unsubscribe } } }),
|
||||
},
|
||||
},
|
||||
(s) => sessions.push(s),
|
||||
(l) => loadings.push(l),
|
||||
)
|
||||
|
||||
unbind()
|
||||
resolveSession({ data: { session: null } })
|
||||
await new Promise((resolve) => setTimeout(resolve, 0))
|
||||
expect(unsubscribe).toHaveBeenCalledTimes(1)
|
||||
expect(sessions).toEqual([])
|
||||
expect(loadings).toEqual([])
|
||||
|
||||
const rejectedSessions: unknown[] = []
|
||||
const rejectedLoadings: boolean[] = []
|
||||
const unbindRejected = bindAuthSession(
|
||||
{
|
||||
auth: {
|
||||
getSession: async () => {
|
||||
throw new Error('session storage corrupted')
|
||||
},
|
||||
onAuthStateChange: () => ({ data: { subscription: { unsubscribe: vi.fn() } } }),
|
||||
},
|
||||
},
|
||||
(s) => rejectedSessions.push(s),
|
||||
(l) => rejectedLoadings.push(l),
|
||||
)
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 0))
|
||||
unbindRejected()
|
||||
expect(rejectedSessions).toEqual([null])
|
||||
expect(rejectedLoadings).toEqual([false])
|
||||
})
|
||||
|
||||
it('acquireGuardedMediaStream_권한대기중언마운트_획득된트랙을즉시중지하고null반환한다', async () => {
|
||||
const stopA = vi.fn()
|
||||
const stopB = vi.fn()
|
||||
let active = true
|
||||
let resolveStream!: (stream: { getTracks: () => Array<{ stop: () => void }> }) => void
|
||||
|
||||
const pending = acquireGuardedMediaStream({
|
||||
getUserMedia: () =>
|
||||
new Promise((resolve) => {
|
||||
resolveStream = resolve
|
||||
}),
|
||||
isStillActive: () => active,
|
||||
})
|
||||
|
||||
active = false
|
||||
resolveStream({ getTracks: () => [{ stop: stopA }, { stop: stopB }] })
|
||||
const result = await pending
|
||||
|
||||
expect(result).toBe(null)
|
||||
expect(stopA).toHaveBeenCalledTimes(1)
|
||||
expect(stopB).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('consumeChatSseStream_중단시그널수신_reader를취소하고잔여토큰을방출하지않는다', async () => {
|
||||
const encoder = new TextEncoder()
|
||||
let cancelled = false
|
||||
let enqueueChunk!: (value: Uint8Array) => void
|
||||
|
||||
const body = new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
enqueueChunk = (chunk) => controller.enqueue(chunk)
|
||||
},
|
||||
cancel() {
|
||||
cancelled = true
|
||||
},
|
||||
})
|
||||
|
||||
const abortController = new AbortController()
|
||||
const emitted: string[] = []
|
||||
const reading = consumeChatSseStream({
|
||||
body,
|
||||
signal: abortController.signal,
|
||||
onAccumulated: (text) => emitted.push(text),
|
||||
})
|
||||
|
||||
enqueueChunk(encoder.encode('data: {"type":"content_block_delta","delta":{"type":"text_delta","text":"안녕"}}\n\n'))
|
||||
await vi.waitFor(() => {
|
||||
expect(emitted).toEqual(['안녕'])
|
||||
})
|
||||
|
||||
abortController.abort()
|
||||
await reading
|
||||
expect(cancelled).toBe(true)
|
||||
expect(emitted).toEqual(['안녕'])
|
||||
})
|
||||
|
||||
it('edgeFetchHelpers_안전하지않은함수URL을차단하고타임아웃및타이머정리를보장한다', () => {
|
||||
expect(resolveSupabaseFunctionUrl('llm-proxy', 'https://proj.supabase.co')).toBe(
|
||||
'https://proj.supabase.co/functions/v1/llm-proxy',
|
||||
)
|
||||
expect(resolveSupabaseFunctionUrl('team-invite', 'http://127.0.0.1:54321')).toBe(
|
||||
'http://127.0.0.1:54321/functions/v1/team-invite',
|
||||
)
|
||||
expect(() => resolveSupabaseFunctionUrl('llm-proxy', 'http://remote.example')).toThrow()
|
||||
expect(() => resolveSupabaseFunctionUrl('llm-proxy', 'https://user:pass@proj.supabase.co')).toThrow()
|
||||
expect(() => resolveSupabaseFunctionUrl('../admin', 'https://proj.supabase.co')).toThrow()
|
||||
|
||||
vi.useFakeTimers()
|
||||
const activeRef: { current: AbortController | null } = { current: null }
|
||||
const handle = createTimedAbortSignal(1000, activeRef)
|
||||
expect(handle.didTimeout()).toBe(false)
|
||||
expect(activeRef.current).toBe(handle.controller)
|
||||
|
||||
vi.advanceTimersByTime(1000)
|
||||
expect(handle.didTimeout()).toBe(true)
|
||||
expect(handle.controller.signal.aborted).toBe(true)
|
||||
handle.dispose()
|
||||
expect(activeRef.current).toBe(null)
|
||||
|
||||
const timerRef: { current: ReturnType<typeof setTimeout> | null } = { current: null }
|
||||
const calls: string[] = []
|
||||
scheduleTrackedTimeout(timerRef, () => calls.push('first'), 500)
|
||||
scheduleTrackedTimeout(timerRef, () => calls.push('second'), 500)
|
||||
vi.advanceTimersByTime(500)
|
||||
expect(calls).toEqual(['second'])
|
||||
|
||||
scheduleTrackedTimeout(timerRef, () => calls.push('unmounted'), 500)
|
||||
clearTrackedTimeout(timerRef)
|
||||
vi.advanceTimersByTime(1000)
|
||||
expect(calls).toEqual(['second'])
|
||||
})
|
||||
})
|
||||
6
server/cloudflare-site-bridge/deno.json
Normal file
6
server/cloudflare-site-bridge/deno.json
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
{
|
||||
"compilerOptions": {
|
||||
"strict": true
|
||||
},
|
||||
"unstable": ["sloppy-imports"]
|
||||
}
|
||||
127
server/cloudflare-site-bridge/src/index.test.ts
Normal file
127
server/cloudflare-site-bridge/src/index.test.ts
Normal file
|
|
@ -0,0 +1,127 @@
|
|||
import { handleBridgeRequest, resolvePagesTargetUrl, servedByOrigin } from './index.ts'
|
||||
|
||||
function assert(condition: boolean, message: string): asserts condition {
|
||||
if (!condition) throw new Error(message)
|
||||
}
|
||||
|
||||
function assertEquals(actual: unknown, expected: unknown, message: string): void {
|
||||
const a = JSON.stringify(actual)
|
||||
const e = JSON.stringify(expected)
|
||||
if (a !== e) throw new Error(`${message}: expected ${e}, got ${a}`)
|
||||
}
|
||||
|
||||
Deno.test('servedByOrigin_웹앱API경로와랜딩경로_라우팅분기를정확히구분한다', () => {
|
||||
assert(servedByOrigin('/app'), '/app goes to origin')
|
||||
assert(servedByOrigin('/app/login'), '/app/login goes to origin')
|
||||
assert(servedByOrigin('/api/health'), '/api/health goes to origin')
|
||||
assert(servedByOrigin('/health'), '/health goes to origin')
|
||||
assert(!servedByOrigin('/'), '/ goes to pages')
|
||||
assert(!servedByOrigin('/ko/'), '/ko/ goes to pages')
|
||||
assert(!servedByOrigin('/app-info'), '/app-info goes to pages')
|
||||
})
|
||||
|
||||
Deno.test('resolvePagesTargetUrl_경로스머글링_null로차단한다', () => {
|
||||
assertEquals(resolvePagesTargetUrl(new URL('https://d3ro.chanpaca.net//evil.com/path')), null, 'double slash blocked')
|
||||
assertEquals(resolvePagesTargetUrl(new URL('https://d3ro.chanpaca.net/\\evil.com')), null, 'backslash blocked')
|
||||
const valid = resolvePagesTargetUrl(new URL('https://d3ro.chanpaca.net/ko/?utm=1'))
|
||||
assertEquals(valid?.toString(), 'https://d3ro.pages.dev/ko/?utm=1', 'valid pages target')
|
||||
})
|
||||
|
||||
Deno.test('handleBridgeRequest_경로스머글링및루프헤더_요청전달없이실패폐쇄한다', async () => {
|
||||
let called = false
|
||||
const neverFetch: typeof fetch = () => {
|
||||
called = true
|
||||
return Promise.resolve(new Response('unexpected', { status: 200 }))
|
||||
}
|
||||
|
||||
const smuggled = await handleBridgeRequest(new Request('https://d3ro.chanpaca.net//evil.com'), neverFetch)
|
||||
assertEquals(called, false, 'smuggled request must not trigger fetch')
|
||||
assertEquals(smuggled.status, 400, 'smuggled path returns 400')
|
||||
|
||||
const looped = await handleBridgeRequest(
|
||||
new Request('https://d3ro.chanpaca.net/ko/', {
|
||||
headers: { 'X-D3RO-Site-Bridge': '1' },
|
||||
}),
|
||||
neverFetch,
|
||||
)
|
||||
assertEquals(called, false, 'looped request must not trigger fetch')
|
||||
assertEquals(looped.status, 508, 'loop header returns 508')
|
||||
})
|
||||
|
||||
Deno.test('handleBridgeRequest_Pages및원본프록시_홉바이홉헤더제거및타임아웃전달한다', async () => {
|
||||
const seen: Array<{ url: string; init?: RequestInit }> = []
|
||||
const fakeFetch: typeof fetch = (input, init) => {
|
||||
const url = input instanceof Request ? input.url : String(input)
|
||||
const rawHeaders = input instanceof Request
|
||||
? input.headers
|
||||
: (init as { headers?: HeadersInit } | undefined)?.headers
|
||||
const headers = new Headers(rawHeaders)
|
||||
seen.push({
|
||||
url,
|
||||
init: {
|
||||
...(init as RequestInit | undefined),
|
||||
headers,
|
||||
},
|
||||
})
|
||||
return Promise.resolve(
|
||||
new Response('<html>ok</html>', {
|
||||
status: 200,
|
||||
headers: {
|
||||
'Content-Type': 'text/html',
|
||||
Connection: 'x-hop-secret',
|
||||
'x-hop-secret': 'drop',
|
||||
},
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
const pagesResp = await handleBridgeRequest(
|
||||
new Request('https://d3ro.chanpaca.net/en/', {
|
||||
headers: {
|
||||
Host: 'd3ro.chanpaca.net',
|
||||
Connection: 'keep-alive',
|
||||
Accept: 'text/html',
|
||||
},
|
||||
}),
|
||||
fakeFetch,
|
||||
)
|
||||
assertEquals(pagesResp.status, 200, 'pages status')
|
||||
assertEquals(pagesResp.headers.has('x-hop-secret'), false, 'response hop-by-hop stripped')
|
||||
assertEquals(seen[0].url, 'https://d3ro.pages.dev/en/', 'proxied to pages target')
|
||||
assertEquals(seen[0].init?.redirect, 'manual', 'manual redirect')
|
||||
assert(seen[0].init?.signal instanceof AbortSignal, 'timeout signal attached')
|
||||
const sentHeaders = new Headers(seen[0].init?.headers)
|
||||
assertEquals(sentHeaders.has('host'), false, 'host header stripped')
|
||||
assertEquals(sentHeaders.has('connection'), false, 'connection header stripped')
|
||||
assertEquals(sentHeaders.get('x-d3ro-site-bridge'), '1', 'bridge marker set')
|
||||
await pagesResp.body?.cancel()
|
||||
|
||||
const originResp = await handleBridgeRequest(new Request('https://d3ro.chanpaca.net/app/login'), fakeFetch)
|
||||
assertEquals(originResp.status, 200, 'origin status')
|
||||
assertEquals(seen[1].url, 'https://d3ro.chanpaca.net/app/login', 'origin passthrough url')
|
||||
assertEquals(seen[1].init?.redirect, 'manual', 'origin request disables auto-redirect')
|
||||
assert(seen[1].init?.signal instanceof AbortSignal, 'origin request has timeout signal')
|
||||
await originResp.body?.cancel()
|
||||
})
|
||||
|
||||
Deno.test('handleBridgeRequest_업스트림네트워크오류와타임아웃_502및504로실패폐쇄하고무본문응답을처리한다', async () => {
|
||||
const errResp = await handleBridgeRequest(
|
||||
new Request('https://d3ro.chanpaca.net/'),
|
||||
() => Promise.reject(new TypeError('connect failed to internal host')),
|
||||
)
|
||||
assertEquals(errResp.status, 502, 'network error maps to 502')
|
||||
const errText = await errResp.text()
|
||||
assert(!errText.includes('internal host'), 'must not leak error message')
|
||||
|
||||
const timeoutResp = await handleBridgeRequest(
|
||||
new Request('https://d3ro.chanpaca.net/'),
|
||||
() => Promise.reject(new DOMException('timed out', 'TimeoutError')),
|
||||
)
|
||||
assertEquals(timeoutResp.status, 504, 'timeout maps to 504')
|
||||
|
||||
const noContent = await handleBridgeRequest(
|
||||
new Request('https://d3ro.chanpaca.net/favicon.ico'),
|
||||
() => Promise.resolve(new Response(null, { status: 304, headers: { ETag: '"1"' } })),
|
||||
)
|
||||
assertEquals(noContent.status, 304, '304 status preserved without null-body error')
|
||||
})
|
||||
|
|
@ -13,34 +13,137 @@
|
|||
import { API_PATH_PREFIXES, WEB_APP_BASE_PATH } from '../../../packages/core/src/web-urls'
|
||||
|
||||
const PAGES_ORIGIN = 'https://d3ro.pages.dev'
|
||||
const UPSTREAM_TIMEOUT_MS = 30_000
|
||||
const BRIDGE_HEADER = 'X-D3RO-Site-Bridge'
|
||||
const NULL_BODY_STATUSES = new Set([204, 205, 304])
|
||||
const ORIGIN_PATH_PREFIXES: readonly string[] = [WEB_APP_BASE_PATH, ...API_PATH_PREFIXES]
|
||||
const HOP_BY_HOP_HEADERS = new Set([
|
||||
'connection',
|
||||
'keep-alive',
|
||||
'proxy-authenticate',
|
||||
'proxy-authorization',
|
||||
'te',
|
||||
'trailer',
|
||||
'transfer-encoding',
|
||||
'upgrade',
|
||||
'host',
|
||||
])
|
||||
|
||||
function servedByOrigin(pathname: string): boolean {
|
||||
return ORIGIN_PATH_PREFIXES.some((prefix) => pathname === prefix || pathname.startsWith(`${prefix}/`))
|
||||
function stripHopByHopHeaders(headers: Headers): void {
|
||||
const connectionValue = headers.get('connection')
|
||||
if (connectionValue) {
|
||||
for (const token of connectionValue.split(',')) {
|
||||
const name = token.trim().toLowerCase()
|
||||
if (name) headers.delete(name)
|
||||
}
|
||||
}
|
||||
for (const name of HOP_BY_HOP_HEADERS) {
|
||||
headers.delete(name)
|
||||
}
|
||||
}
|
||||
|
||||
async function fromPages(request: Request): Promise<Response> {
|
||||
const target = new URL(request.url)
|
||||
target.protocol = 'https:'
|
||||
target.hostname = new URL(PAGES_ORIGIN).hostname
|
||||
target.port = ''
|
||||
|
||||
const headers = new Headers(request.headers)
|
||||
headers.delete('host')
|
||||
|
||||
const hasBody = request.method !== 'GET' && request.method !== 'HEAD'
|
||||
return fetch(target.toString(), {
|
||||
method: request.method,
|
||||
headers,
|
||||
body: hasBody ? request.body : undefined,
|
||||
redirect: 'manual',
|
||||
function bridgeErrorJson(error: string, message: string, status: number): Response {
|
||||
return new Response(JSON.stringify({ error, message }), {
|
||||
status,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Cache-Control': 'no-store',
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function servedByOrigin(pathname: string): boolean {
|
||||
return ORIGIN_PATH_PREFIXES.some((prefix) => pathname === prefix || pathname.startsWith(`${prefix}/`))
|
||||
}
|
||||
|
||||
export function resolvePagesTargetUrl(requestUrl: URL): URL | null {
|
||||
if (requestUrl.pathname.startsWith('//') || requestUrl.pathname.includes('\\')) {
|
||||
return null
|
||||
}
|
||||
const target = new URL(requestUrl.toString())
|
||||
target.protocol = 'https:'
|
||||
target.hostname = new URL(PAGES_ORIGIN).hostname
|
||||
target.port = ''
|
||||
if (target.origin !== PAGES_ORIGIN) {
|
||||
return null
|
||||
}
|
||||
return target
|
||||
}
|
||||
|
||||
function buildForwardHeaders(requestHeaders: Headers): Headers {
|
||||
const headers = new Headers(requestHeaders)
|
||||
stripHopByHopHeaders(headers)
|
||||
headers.set(BRIDGE_HEADER, '1')
|
||||
return headers
|
||||
}
|
||||
|
||||
async function forwardRequest(
|
||||
request: Request,
|
||||
targetUrl: string,
|
||||
fetchImpl: typeof fetch,
|
||||
): Promise<Response> {
|
||||
const headers = buildForwardHeaders(request.headers)
|
||||
const hasBody = request.method !== 'GET' && request.method !== 'HEAD'
|
||||
|
||||
try {
|
||||
const response = await fetchImpl(targetUrl, {
|
||||
method: request.method,
|
||||
headers,
|
||||
body: hasBody ? request.body : undefined,
|
||||
redirect: 'manual',
|
||||
signal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS),
|
||||
})
|
||||
|
||||
const responseHeaders = new Headers(response.headers)
|
||||
stripHopByHopHeaders(responseHeaders)
|
||||
|
||||
let body: ReadableStream<Uint8Array> | null = response.body
|
||||
if (NULL_BODY_STATUSES.has(response.status)) {
|
||||
await response.body?.cancel().catch(() => undefined)
|
||||
body = null
|
||||
}
|
||||
|
||||
return new Response(body, {
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
headers: responseHeaders,
|
||||
})
|
||||
} catch (err: unknown) {
|
||||
const isTimeout = err instanceof DOMException && err.name === 'TimeoutError'
|
||||
return bridgeErrorJson(
|
||||
isTimeout ? 'SiteBridgeTimeout' : 'SiteBridgeError',
|
||||
isTimeout ? 'Upstream request timed out.' : 'Upstream service unavailable.',
|
||||
isTimeout ? 504 : 502,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export async function handleBridgeRequest(
|
||||
request: Request,
|
||||
fetchImpl: typeof fetch = fetch,
|
||||
): Promise<Response> {
|
||||
if (request.headers.get(BRIDGE_HEADER)) {
|
||||
return bridgeErrorJson('SiteBridgeLoopDetected', 'Bridge proxy loop detected.', 508)
|
||||
}
|
||||
|
||||
const url = new URL(request.url)
|
||||
if (url.pathname.startsWith('//') || url.pathname.includes('\\')) {
|
||||
return bridgeErrorJson('InvalidBridgeRequest', 'Invalid request path.', 400)
|
||||
}
|
||||
|
||||
if (servedByOrigin(url.pathname)) {
|
||||
return forwardRequest(request, request.url, fetchImpl)
|
||||
}
|
||||
|
||||
const pagesTarget = resolvePagesTargetUrl(url)
|
||||
if (!pagesTarget) {
|
||||
return bridgeErrorJson('InvalidBridgeRequest', 'Invalid target URL.', 400)
|
||||
}
|
||||
return forwardRequest(request, pagesTarget.toString(), fetchImpl)
|
||||
}
|
||||
|
||||
export default {
|
||||
async fetch(request: Request): Promise<Response> {
|
||||
const { pathname } = new URL(request.url)
|
||||
if (servedByOrigin(pathname)) return fetch(request)
|
||||
return fromPages(request)
|
||||
fetch(request: Request): Promise<Response> {
|
||||
return handleBridgeRequest(request)
|
||||
},
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ function assertEquals(actual: unknown, expected: unknown, message: string): void
|
|||
}
|
||||
|
||||
const TEST_ENV: Env = {
|
||||
BACKEND_ORIGIN: 'http://192.168.0.39:5050',
|
||||
BACKEND_ORIGIN: 'https://api.d3ro.example',
|
||||
SERVICE_NAME: 'D3RO Voice Cloud Gateway',
|
||||
}
|
||||
|
||||
|
|
@ -19,7 +19,7 @@ Deno.test('resolveBackendTargetUrl blocks protocol-relative SSRF and preserves q
|
|||
assertEquals(resolveBackendTargetUrl(new URL('https://edge.test//evil.com/steal'), TEST_ENV.BACKEND_ORIGIN), null, 'protocol-relative path must fail closed')
|
||||
assertEquals(resolveBackendTargetUrl(new URL('https://edge.test/\\evil.com/steal'), TEST_ENV.BACKEND_ORIGIN), null, 'backslash path must fail closed')
|
||||
const valid = resolveBackendTargetUrl(new URL('https://edge.test/api/stt/internal/transcribe?lang=ko'), TEST_ENV.BACKEND_ORIGIN)
|
||||
assertEquals(valid?.toString(), 'http://192.168.0.39:5050/api/stt/internal/transcribe?lang=ko', 'valid upstream url')
|
||||
assertEquals(valid?.toString(), 'https://api.d3ro.example/api/stt/internal/transcribe?lang=ko', 'valid upstream url')
|
||||
})
|
||||
|
||||
Deno.test('worker health check omits internal BACKEND_ORIGIN', async () => {
|
||||
|
|
@ -58,7 +58,7 @@ Deno.test('proxy strips hop-by-hop/host headers, disables auto-redirect, and att
|
|||
fetchImpl,
|
||||
)
|
||||
|
||||
assertEquals(seenUrl, 'http://192.168.0.39:5050/api/health', 'target url')
|
||||
assertEquals(seenUrl, 'https://api.d3ro.example/api/health', 'target url')
|
||||
assertEquals(seenInit?.redirect, 'manual', 'must not follow redirects automatically')
|
||||
assert(seenInit?.signal instanceof AbortSignal, 'must pass timeout AbortSignal')
|
||||
const forwarded = new Headers(seenInit?.headers)
|
||||
|
|
@ -73,10 +73,11 @@ Deno.test('upstream network errors and timeouts fail closed without leaking orig
|
|||
const networkFail = await handleWorkerRequest(
|
||||
new Request('https://edge.test/api/test'),
|
||||
TEST_ENV,
|
||||
() => Promise.reject(new TypeError('connect ECONNREFUSED 192.168.0.39:5050')),
|
||||
() => Promise.reject(new TypeError('connect ECONNREFUSED api.d3ro.example:443')),
|
||||
)
|
||||
assertEquals(networkFail.status, 502, 'network error maps to 502')
|
||||
const networkText = await networkFail.text()
|
||||
assert(!networkText.includes('api.d3ro.example'), 'must not leak upstream hostname')
|
||||
assert(!networkText.includes('192.168.0.39'), 'must not leak internal IP')
|
||||
assert(!networkText.includes('NAS backend'), 'must not leak internal topology wording')
|
||||
assertEquals(JSON.parse(networkText).error, 'EdgeGatewayError', 'fixed error code')
|
||||
|
|
@ -89,3 +90,84 @@ Deno.test('upstream network errors and timeouts fail closed without leaking orig
|
|||
assertEquals(timeoutFail.status, 504, 'timeout maps to 504')
|
||||
assertEquals((await timeoutFail.json()).error, 'EdgeGatewayTimeout', 'fixed timeout code')
|
||||
})
|
||||
|
||||
Deno.test('resolveBackendTargetUrl_IP리터럴과비HTTPS및루프오리진_차단한다', () => {
|
||||
const invalidOrigins = [
|
||||
'http://192.168.0.39:5050',
|
||||
'https://192.168.0.39:5050',
|
||||
'https://127.0.0.1:5050',
|
||||
'https://169.254.169.254',
|
||||
'https://[::1]:5050',
|
||||
'https://2130706433',
|
||||
'http://d3ro.chanpaca.net',
|
||||
'https://localhost:5050',
|
||||
'https://api.internal',
|
||||
'https://api.local',
|
||||
'https://api.d3ro.example/prefix',
|
||||
'https://api.d3ro.example?leak=1',
|
||||
'https://user:pass@api.d3ro.example',
|
||||
]
|
||||
for (const origin of invalidOrigins) {
|
||||
assertEquals(
|
||||
resolveBackendTargetUrl(new URL('https://edge.test/health'), origin),
|
||||
null,
|
||||
`invalid origin must fail closed: ${origin}`,
|
||||
)
|
||||
}
|
||||
assertEquals(
|
||||
resolveBackendTargetUrl(new URL('https://api.d3ro.example/health'), 'https://api.d3ro.example'),
|
||||
null,
|
||||
'self-proxy origin loop must fail closed',
|
||||
)
|
||||
})
|
||||
|
||||
Deno.test('handleWorkerRequest_오리진미설정IP및프록시루프_요청전송없이실패폐쇄한다', async () => {
|
||||
let fetched = false
|
||||
const neverFetch: typeof fetch = () => {
|
||||
fetched = true
|
||||
return Promise.resolve(new Response('unexpected', { status: 200 }))
|
||||
}
|
||||
|
||||
const badOriginResp = await handleWorkerRequest(
|
||||
new Request('https://d3ro-voice-api.yunchan8804.workers.dev/health'),
|
||||
{ BACKEND_ORIGIN: 'http://192.168.0.39:5050', SERVICE_NAME: 'test' },
|
||||
neverFetch,
|
||||
)
|
||||
assertEquals(fetched, false, 'must not call fetch when BACKEND_ORIGIN is an IP literal')
|
||||
assertEquals(badOriginResp.status, 503, 'misconfigured backend origin maps to 503')
|
||||
const badOriginText = await badOriginResp.text()
|
||||
assert(!badOriginText.includes('192.168.0.39'), 'must not echo configured IP')
|
||||
assertEquals(JSON.parse(badOriginText).error, 'EdgeGatewayMisconfigured', 'fixed misconfiguration code')
|
||||
|
||||
const loopResp = await handleWorkerRequest(
|
||||
new Request('https://edge.test/health', {
|
||||
headers: { 'X-D3RO-Edge-Proxy': 'Cloudflare-Worker' },
|
||||
}),
|
||||
TEST_ENV,
|
||||
neverFetch,
|
||||
)
|
||||
assertEquals(fetched, false, 'must not proxy when edge loop header is already set')
|
||||
assertEquals(loopResp.status, 508, 'loop header maps to 508 Loop Detected')
|
||||
assertEquals((await loopResp.json()).error, 'EdgeGatewayLoopDetected', 'fixed loop error code')
|
||||
})
|
||||
|
||||
Deno.test('handleWorkerRequest_204와304무본문응답_예외없이전달한다', async () => {
|
||||
for (const status of [204, 304]) {
|
||||
const resp = await handleWorkerRequest(
|
||||
new Request('https://edge.test/api/ping'),
|
||||
TEST_ENV,
|
||||
() => Promise.resolve(new Response(null, { status, headers: { 'X-Trace': 'ok' } })),
|
||||
)
|
||||
assertEquals(resp.status, status, `status ${status} preserved`)
|
||||
assertEquals(resp.headers.get('Access-Control-Allow-Origin'), '*', 'CORS header attached')
|
||||
assertEquals(resp.headers.get('X-Trace'), 'ok', 'upstream header preserved')
|
||||
}
|
||||
})
|
||||
|
||||
Deno.test('wranglerConfig_BACKENDORIGIN_IP리터럴이아닌공개HTTPS호스트다', async () => {
|
||||
const tomlText = await Deno.readTextFile(new URL('../wrangler.toml', import.meta.url))
|
||||
const match = tomlText.match(/^\s*BACKEND_ORIGIN\s*=\s*"([^"]+)"/m)
|
||||
assert(match !== null, 'BACKEND_ORIGIN must be configured in wrangler.toml')
|
||||
const resolved = resolveBackendTargetUrl(new URL('https://d3ro-voice-api.yunchan8804.workers.dev/health'), match[1])
|
||||
assertEquals(resolved?.toString(), 'https://d3ro.chanpaca.net/health', 'wrangler BACKEND_ORIGIN must resolve cleanly')
|
||||
})
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
// server/cloudflare-worker/src/index.ts
|
||||
// D3RO Voice — Global Cloudflare Edge Gateway & Proxy Worker
|
||||
|
||||
import { hasSmuggledRequestPath, parsePublicHttpsOrigin } from './origin-policy.ts'
|
||||
import { drainPushDispatches } from './push-drain.ts'
|
||||
|
||||
export interface Env {
|
||||
|
|
@ -60,17 +61,14 @@ function workerJson(body: Record<string, unknown>, status = 200, noStore = false
|
|||
return new Response(JSON.stringify(body), { status, headers })
|
||||
}
|
||||
|
||||
const NULL_BODY_STATUSES = new Set([204, 205, 304])
|
||||
|
||||
export function resolveBackendTargetUrl(requestUrl: URL, rawOrigin: string): URL | null {
|
||||
if (requestUrl.pathname.startsWith('//') || requestUrl.pathname.includes('\\')) {
|
||||
if (hasSmuggledRequestPath(requestUrl.pathname)) {
|
||||
return null
|
||||
}
|
||||
let originUrl: URL
|
||||
try {
|
||||
originUrl = new URL(rawOrigin)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
if ((originUrl.protocol !== 'http:' && originUrl.protocol !== 'https:') || originUrl.username || originUrl.password) {
|
||||
const originUrl = parsePublicHttpsOrigin(rawOrigin)
|
||||
if (!originUrl || originUrl.origin === requestUrl.origin) {
|
||||
return null
|
||||
}
|
||||
const targetUrl = new URL(originUrl.origin)
|
||||
|
|
@ -107,14 +105,36 @@ export async function handleWorkerRequest(
|
|||
})
|
||||
}
|
||||
|
||||
// 3. Construct Target Backend URL (fail closed on path/origin smuggling)
|
||||
// 3. Reject proxy loops and verify backend origin configuration (prevents CF 1003 direct-IP errors)
|
||||
if (request.headers.get('X-D3RO-Edge-Proxy')) {
|
||||
return workerJson(
|
||||
{
|
||||
error: 'EdgeGatewayLoopDetected',
|
||||
message: 'Proxy loop detected.',
|
||||
},
|
||||
508,
|
||||
true,
|
||||
)
|
||||
}
|
||||
|
||||
const rawOrigin = (env.BACKEND_ORIGIN || 'https://d3ro.chanpaca.net').trim()
|
||||
if (!parsePublicHttpsOrigin(rawOrigin)) {
|
||||
return workerJson(
|
||||
{
|
||||
error: 'EdgeGatewayMisconfigured',
|
||||
message: 'Upstream gateway origin is invalid or not configured.',
|
||||
},
|
||||
503,
|
||||
true,
|
||||
)
|
||||
}
|
||||
|
||||
const targetUrl = resolveBackendTargetUrl(url, rawOrigin)
|
||||
if (!targetUrl) {
|
||||
return workerJson(
|
||||
{
|
||||
error: 'InvalidGatewayRequest',
|
||||
message: 'Invalid request path or backend origin configuration.',
|
||||
message: 'Invalid request path or proxy target.',
|
||||
},
|
||||
400,
|
||||
true,
|
||||
|
|
@ -144,7 +164,13 @@ export async function handleWorkerRequest(
|
|||
newHeaders.set(key, value)
|
||||
}
|
||||
|
||||
return new Response(response.body, {
|
||||
let responseBody: ReadableStream<Uint8Array> | null = response.body
|
||||
if (NULL_BODY_STATUSES.has(response.status)) {
|
||||
await response.body?.cancel().catch(() => undefined)
|
||||
responseBody = null
|
||||
}
|
||||
|
||||
return new Response(responseBody, {
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
headers: newHeaders,
|
||||
|
|
|
|||
45
server/cloudflare-worker/src/origin-policy.ts
Normal file
45
server/cloudflare-worker/src/origin-policy.ts
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
// server/cloudflare-worker/src/origin-policy.ts
|
||||
// Shared upstream origin validation helpers for the Cloudflare Edge Worker.
|
||||
|
||||
const IPV4_PATTERN = /^\d{1,3}(?:\.\d{1,3}){3}$/
|
||||
const INTEGER_OR_HEX_HOST_PATTERN = /^(?:0x[\da-f]+|\d+)$/i
|
||||
const BLOCKED_HOST_SUFFIXES = ['.localhost', '.local', '.internal', '.home.arpa', '.localdomain']
|
||||
|
||||
export function hasSmuggledRequestPath(pathname: string): boolean {
|
||||
return pathname.startsWith('//') || pathname.includes('\\')
|
||||
}
|
||||
|
||||
export function isDisallowedPublicHost(rawHostname: string): boolean {
|
||||
const trimmed = rawHostname.trim().toLowerCase()
|
||||
if (!trimmed || trimmed.endsWith('.')) return true
|
||||
if (trimmed === 'localhost') return true
|
||||
if (BLOCKED_HOST_SUFFIXES.some((suffix) => trimmed.endsWith(suffix))) return true
|
||||
if (trimmed.startsWith('[') || trimmed.includes(':')) return true
|
||||
if (IPV4_PATTERN.test(trimmed) || INTEGER_OR_HEX_HOST_PATTERN.test(trimmed)) return true
|
||||
if (!trimmed.includes('.')) return true
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates that a configured upstream origin is strictly a clean `https://` public hostname
|
||||
* with no credentials, path prefix, query string, fragment, or IP/internal literal.
|
||||
* Prevents Cloudflare Error 1003 ("Direct IP access not allowed") and internal SSRF.
|
||||
*/
|
||||
export function parsePublicHttpsOrigin(rawOrigin: string): URL | null {
|
||||
let originUrl: URL
|
||||
try {
|
||||
originUrl = new URL(rawOrigin.trim())
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
if (originUrl.protocol !== 'https:' || originUrl.username || originUrl.password) {
|
||||
return null
|
||||
}
|
||||
if (originUrl.pathname !== '/' || originUrl.search !== '' || originUrl.hash !== '') {
|
||||
return null
|
||||
}
|
||||
if (isDisallowedPublicHost(originUrl.hostname)) {
|
||||
return null
|
||||
}
|
||||
return originUrl
|
||||
}
|
||||
|
|
@ -67,3 +67,39 @@ Deno.test('drain tolerates a malformed success body', async () => {
|
|||
assert(result.ok === true, 'ok')
|
||||
assert(result.claimed === undefined, 'summary left undefined')
|
||||
})
|
||||
|
||||
Deno.test('drainPushDispatches_잘못된SupabaseURL또는내부호스트_요청전송없이실패폐쇄한다', async () => {
|
||||
let called = false
|
||||
const neverFetch = (() => {
|
||||
called = true
|
||||
return Promise.resolve(jsonResponse(200, {}))
|
||||
}) as unknown as typeof fetch
|
||||
|
||||
for (const badUrl of [
|
||||
'http://example.supabase.co',
|
||||
'https://127.0.0.1',
|
||||
'https://192.168.0.1',
|
||||
'https://[::1]',
|
||||
'https://localhost',
|
||||
'https://supabase.internal',
|
||||
'https://user:pass@example.supabase.co',
|
||||
'https://example.supabase.co/unexpected-path',
|
||||
]) {
|
||||
const res = await drainPushDispatches({ ...env, SUPABASE_URL: badUrl }, neverFetch)
|
||||
assert(called === false, `fetch must not run for invalid SUPABASE_URL: ${badUrl}`)
|
||||
assert(res.ok === false && res.status === 503, `expected fail-closed 503 for ${badUrl}`)
|
||||
}
|
||||
})
|
||||
|
||||
Deno.test('drainPushDispatches_안전한요청옵션_리다이렉트차단과타임아웃시그널을전달한다', async () => {
|
||||
let seenInit: RequestInit | undefined
|
||||
const fetchImpl = ((_input: string | URL | Request, init?: RequestInit) => {
|
||||
seenInit = init
|
||||
return Promise.resolve(jsonResponse(200, { claimed: 0, completed: 0, pending: 0 }))
|
||||
}) as unknown as typeof fetch
|
||||
|
||||
const res = await drainPushDispatches(env, fetchImpl)
|
||||
assert(res.ok === true, 'ok')
|
||||
assert(seenInit?.redirect === 'manual', 'redirect must be manual')
|
||||
assert(seenInit?.signal instanceof AbortSignal, 'timeout AbortSignal must be attached')
|
||||
})
|
||||
|
|
|
|||
|
|
@ -6,6 +6,8 @@
|
|||
// (team invites, transcription completion, billing) never left the queue. This
|
||||
// worker drains them on a cron schedule.
|
||||
|
||||
import { parsePublicHttpsOrigin } from './origin-policy.ts'
|
||||
|
||||
export interface PushDrainEnv {
|
||||
SUPABASE_URL?: string
|
||||
SUPABASE_SERVICE_ROLE_KEY?: string
|
||||
|
|
@ -35,17 +37,21 @@ export async function drainPushDispatches(
|
|||
env: PushDrainEnv,
|
||||
fetchImpl: typeof fetch = fetch,
|
||||
): Promise<PushDrainResult> {
|
||||
const baseUrl = env.SUPABASE_URL?.trim().replace(/\/+$/, '') ?? ''
|
||||
const rawUrl = env.SUPABASE_URL?.trim().replace(/\/+$/, '') ?? ''
|
||||
const serviceRoleKey = env.SUPABASE_SERVICE_ROLE_KEY?.trim() ?? ''
|
||||
if (!baseUrl || serviceRoleKey.length < 20) {
|
||||
if (!rawUrl || serviceRoleKey.length < 20) {
|
||||
return { ok: false, status: 503, error: 'push_drain_not_configured' }
|
||||
}
|
||||
const parsedBaseUrl = parsePublicHttpsOrigin(rawUrl)
|
||||
if (!parsedBaseUrl) {
|
||||
return { ok: false, status: 503, error: 'push_drain_invalid_config' }
|
||||
}
|
||||
|
||||
const limit = resolveBatchLimit(env.PUSH_DRAIN_BATCH_LIMIT)
|
||||
let response: Response
|
||||
try {
|
||||
response = await fetchImpl(
|
||||
`${baseUrl}/functions/v1/send-push?mode=drain&limit=${limit}`,
|
||||
`${parsedBaseUrl.origin}/functions/v1/send-push?mode=drain&limit=${limit}`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
|
|
@ -53,6 +59,7 @@ export async function drainPushDispatches(
|
|||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: '{}',
|
||||
redirect: 'manual',
|
||||
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
||||
},
|
||||
)
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ main = "src/index.ts"
|
|||
compatibility_date = "2024-04-01"
|
||||
|
||||
[vars]
|
||||
BACKEND_ORIGIN = "http://192.168.0.39:5050"
|
||||
BACKEND_ORIGIN = "https://d3ro.chanpaca.net"
|
||||
SERVICE_NAME = "D3RO Voice Cloud Gateway"
|
||||
# Supabase project base URL for the scheduled push-outbox drain.
|
||||
# SUPABASE_URL = "https://<project-ref>.supabase.co"
|
||||
|
|
|
|||
|
|
@ -9,11 +9,13 @@ function assert(condition: boolean, message: string): asserts condition {
|
|||
type Row = Record<string, unknown>
|
||||
type ServiceClient = ReturnType<typeof createClient>
|
||||
|
||||
type QueryError = { message: string; code?: string } | null
|
||||
|
||||
/** Minimal in-memory stand-in for the supabase-js query builder used by quota.ts. */
|
||||
class FakeQuery implements PromiseLike<{ data: unknown; error: null }> {
|
||||
class FakeQuery implements PromiseLike<{ data: unknown; error: QueryError }> {
|
||||
private filters: Array<(row: Row) => boolean> = []
|
||||
private singleRow = false
|
||||
constructor(private rows: Row[]) {}
|
||||
constructor(private rows: Row[], private error: QueryError = null) {}
|
||||
select(_columns: string): this {
|
||||
return this
|
||||
}
|
||||
|
|
@ -33,10 +35,13 @@ class FakeQuery implements PromiseLike<{ data: unknown; error: null }> {
|
|||
this.singleRow = true
|
||||
return this
|
||||
}
|
||||
then<T1 = { data: unknown; error: null }, T2 = never>(
|
||||
onfulfilled?: ((value: { data: unknown; error: null }) => T1 | PromiseLike<T1>) | null,
|
||||
then<T1 = { data: unknown; error: QueryError }, T2 = never>(
|
||||
onfulfilled?: ((value: { data: unknown; error: QueryError }) => T1 | PromiseLike<T1>) | null,
|
||||
onrejected?: ((reason: unknown) => T2 | PromiseLike<T2>) | null,
|
||||
): PromiseLike<T1 | T2> {
|
||||
if (this.error) {
|
||||
return Promise.resolve({ data: null, error: this.error }).then(onfulfilled, onrejected)
|
||||
}
|
||||
const matched = this.rows.filter((row) => this.filters.every((f) => f(row)))
|
||||
const data = this.singleRow ? (matched[0] ?? null) : matched
|
||||
return Promise.resolve({ data, error: null }).then(onfulfilled, onrejected)
|
||||
|
|
@ -45,6 +50,7 @@ class FakeQuery implements PromiseLike<{ data: unknown; error: null }> {
|
|||
|
||||
class FakeQuotaClient {
|
||||
tables: Record<string, Row[]> = { subscriptions: [], daily_usage: [] }
|
||||
tableErrors: Partial<Record<'subscriptions' | 'daily_usage', QueryError>> = {}
|
||||
rpcCalls: Array<{ name: string; args: Record<string, unknown> }> = []
|
||||
rpcResult: unknown = {
|
||||
allowed: true,
|
||||
|
|
@ -54,7 +60,10 @@ class FakeQuotaClient {
|
|||
consumed_from: 'overage',
|
||||
}
|
||||
from(table: string): FakeQuery {
|
||||
return new FakeQuery(this.tables[table] ?? [])
|
||||
const error = table === 'subscriptions' || table === 'daily_usage'
|
||||
? (this.tableErrors[table] ?? null)
|
||||
: null
|
||||
return new FakeQuery(this.tables[table] ?? [], error)
|
||||
}
|
||||
rpc(name: string, args: Record<string, unknown>): Promise<{ data: unknown; error: null }> {
|
||||
this.rpcCalls.push({ name, args })
|
||||
|
|
@ -149,3 +158,30 @@ Deno.test('RPC response parser rejects malformed payloads', () => {
|
|||
assert(threw, `accepted ${JSON.stringify(bad)}`)
|
||||
}
|
||||
})
|
||||
|
||||
Deno.test('checkQuota_사용량및구독DB오류_0으로허용하지않고예외로실패폐쇄한다', async () => {
|
||||
const usageFailClient = freeUserWithUsage([])
|
||||
usageFailClient.tableErrors.daily_usage = { message: 'connection refused', code: '08006' }
|
||||
let usageThrew = false
|
||||
try {
|
||||
await checkQuota(USER, 'llm_haiku', usageFailClient.asClient(), NOW)
|
||||
} catch {
|
||||
usageThrew = true
|
||||
}
|
||||
assert(usageThrew, 'daily_usage DB error must throw instead of silently returning usage=0')
|
||||
|
||||
const subFailClient = new FakeQuotaClient()
|
||||
subFailClient.tableErrors.subscriptions = { message: 'timeout', code: '57014' }
|
||||
let subThrew = false
|
||||
try {
|
||||
await checkQuota(USER, 'llm_haiku', subFailClient.asClient(), NOW)
|
||||
} catch {
|
||||
subThrew = true
|
||||
}
|
||||
assert(subThrew, 'subscriptions DB error must throw instead of silently falling back')
|
||||
|
||||
const notFoundClient = new FakeQuotaClient()
|
||||
notFoundClient.tableErrors.subscriptions = { message: 'no rows', code: 'PGRST116' }
|
||||
const missingRowCheck = await checkQuota(USER, 'llm_haiku', notFoundClient.asClient(), NOW)
|
||||
assert(missingRowCheck.tier === 'free' && missingRowCheck.overageCredits === 0, 'PGRST116 falls back cleanly to free tier')
|
||||
})
|
||||
|
|
|
|||
|
|
@ -209,11 +209,14 @@ async function readSubscriptionQuotaState(
|
|||
userId: string,
|
||||
serviceRoleClient: ReturnType<typeof createClient>,
|
||||
): Promise<SubscriptionQuotaState> {
|
||||
const { data: sub } = await serviceRoleClient
|
||||
const { data: sub, error } = await serviceRoleClient
|
||||
.from('subscriptions')
|
||||
.select('tier, overage_credits')
|
||||
.eq('user_id', userId)
|
||||
.single()
|
||||
if (error && error.code !== 'PGRST116') {
|
||||
throw new Error(`Failed to read subscription quota state: ${error.message ?? error.code ?? 'unknown'}`)
|
||||
}
|
||||
return {
|
||||
tier: (sub?.tier as Tier) ?? 'free',
|
||||
overageCredits: (sub?.overage_credits as number) ?? 0,
|
||||
|
|
@ -236,13 +239,16 @@ async function readWindowUsage(
|
|||
serviceRoleClient: ReturnType<typeof createClient>,
|
||||
now: Date,
|
||||
): Promise<number> {
|
||||
const { data: rows } = await serviceRoleClient
|
||||
const { data: rows, error } = await serviceRoleClient
|
||||
.from('daily_usage')
|
||||
.select('count')
|
||||
.eq('user_id', userId)
|
||||
.eq('feature', feature)
|
||||
.gte('date', quotaWindowStart(period, now))
|
||||
.lte('date', quotaUsageDate(now))
|
||||
if (error) {
|
||||
throw new Error(`Failed to read quota usage window: ${error.message ?? error.code ?? 'unknown'}`)
|
||||
}
|
||||
const usageRows = (rows ?? []) as Array<{ count: number | null }>
|
||||
return usageRows.reduce((sum, row) => sum + (row.count ?? 0), 0)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -164,3 +164,41 @@ Deno.test('another user\'s document stays hidden', async () => {
|
|||
const response = await call()
|
||||
assert(response.status === 404 && provider.calls === 0, 'foreign document was embedded')
|
||||
})
|
||||
|
||||
Deno.test('embedChunks_공급자200오응답또는저장실패_청구된유닛은환불하지않는다', async () => {
|
||||
const invalidProvider: EmbeddingProvider = {
|
||||
embed: () => Promise.resolve({ ok: false as const, reason: 'invalid' as const }),
|
||||
}
|
||||
const usageInvalid = new MemoryUsageStore('pro', TODAY)
|
||||
const storeInvalid = new FakeKnowledgeStore(chunks(2))
|
||||
const handlerInvalid = createEmbedChunksHandler({
|
||||
authenticate: () => Promise.resolve({ id: USER }),
|
||||
embeddingProvider: () => invalidProvider,
|
||||
knowledgeStore: () => storeInvalid,
|
||||
usageStore: () => usageInvalid,
|
||||
now: () => NOW,
|
||||
})
|
||||
const invalidResp = await handlerInvalid(new Request('https://edge/embed-chunks', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ document_id: DOC }),
|
||||
}))
|
||||
assert(invalidResp.status === 502, `expected 502, got ${invalidResp.status}`)
|
||||
assert(usageInvalid.rows.get(TODAY) === 2, `invalid 200 response must keep units charged, got ${usageInvalid.rows.get(TODAY)}`)
|
||||
|
||||
const usageDbFail = new MemoryUsageStore('pro', TODAY)
|
||||
const storeDbFail = new FakeKnowledgeStore(chunks(2))
|
||||
storeDbFail.saveEmbedding = () => Promise.resolve(false)
|
||||
const handlerDbFail = createEmbedChunksHandler({
|
||||
authenticate: () => Promise.resolve({ id: USER }),
|
||||
embeddingProvider: () => new FakeProvider(false),
|
||||
knowledgeStore: () => storeDbFail,
|
||||
usageStore: () => usageDbFail,
|
||||
now: () => NOW,
|
||||
})
|
||||
const dbFailResp = await handlerDbFail(new Request('https://edge/embed-chunks', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ document_id: DOC }),
|
||||
}))
|
||||
assert(dbFailResp.status === 502, `expected 502, got ${dbFailResp.status}`)
|
||||
assert(usageDbFail.rows.get(TODAY) === 2, `local DB save failure must not refund billed units, got ${usageDbFail.rows.get(TODAY)}`)
|
||||
})
|
||||
|
|
|
|||
|
|
@ -57,14 +57,24 @@ export interface EmbedChunksDeps {
|
|||
now?(): Date
|
||||
}
|
||||
|
||||
interface EmbedBatchOutcome {
|
||||
saved: number
|
||||
refund: boolean
|
||||
}
|
||||
|
||||
async function embedBatch(
|
||||
provider: EmbeddingProvider,
|
||||
store: KnowledgeIndexStore,
|
||||
documentId: string,
|
||||
batch: KnowledgeChunkRow[],
|
||||
): Promise<number> {
|
||||
): Promise<EmbedBatchOutcome> {
|
||||
const outcome = await provider.embed(batch.map((chunk) => chunk.content))
|
||||
if (!outcome.ok || outcome.data.length !== batch.length) return 0
|
||||
if (!outcome.ok) {
|
||||
return { saved: 0, refund: outcome.reason === 'upstream' }
|
||||
}
|
||||
if (outcome.data.length !== batch.length) {
|
||||
return { saved: 0, refund: false }
|
||||
}
|
||||
|
||||
const received = new Set<number>()
|
||||
let saved = 0
|
||||
|
|
@ -82,7 +92,7 @@ async function embedBatch(
|
|||
received.add(item.index)
|
||||
if (await store.saveEmbedding(documentId, batch[item.index].id, item.embedding)) saved += 1
|
||||
}
|
||||
return saved
|
||||
return { saved, refund: false }
|
||||
}
|
||||
|
||||
export function createEmbedChunksHandler(deps: EmbedChunksDeps): (req: Request) => Promise<Response> {
|
||||
|
|
@ -155,15 +165,15 @@ export function createEmbedChunksHandler(deps: EmbedChunksDeps): (req: Request)
|
|||
let failed = 0
|
||||
let unspentUnits = 0
|
||||
for (const batch of planEmbeddingBatches(chunks)) {
|
||||
let saved = 0
|
||||
let outcome: EmbedBatchOutcome = { saved: 0, refund: false }
|
||||
try {
|
||||
saved = await embedBatch(provider, store, documentId, batch)
|
||||
outcome = await embedBatch(provider, store, documentId, batch)
|
||||
} catch {
|
||||
saved = 0
|
||||
outcome = { saved: 0, refund: false }
|
||||
}
|
||||
embedded += saved
|
||||
failed += batch.length - saved
|
||||
if (saved === 0) unspentUnits += embeddingUnits(batch.map((chunk) => chunk.content))
|
||||
embedded += outcome.saved
|
||||
failed += batch.length - outcome.saved
|
||||
if (outcome.refund) unspentUnits += embeddingUnits(batch.map((chunk) => chunk.content))
|
||||
}
|
||||
await refundEmbeddingUnits(usage, user.id, reservation, unspentUnits, now())
|
||||
|
||||
|
|
|
|||
|
|
@ -259,3 +259,30 @@ Deno.test('non-multipart body fails closed with 400 instead of 500', async () =>
|
|||
assertEquals(await response.json(), { error: 'invalid_multipart_body' }, 'body')
|
||||
assertEquals(h.events, [], 'no quota or provider work')
|
||||
})
|
||||
|
||||
Deno.test('sttProxy_초과ContentLength헤더_본문파싱전에413으로차단한다', async () => {
|
||||
const h = harness([fakeProvider('groq', OK)])
|
||||
let bodyRead = false
|
||||
const req = new Request('http://localhost/stt-proxy', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'multipart/form-data; boundary=x',
|
||||
'Content-Length': String(30 * 1024 * 1024),
|
||||
},
|
||||
body: new ReadableStream(
|
||||
{
|
||||
pull() {
|
||||
bodyRead = true
|
||||
return Promise.reject(new Error('body must not be read when Content-Length exceeds cap'))
|
||||
},
|
||||
},
|
||||
new CountQueuingStrategy({ highWaterMark: 0 }),
|
||||
),
|
||||
})
|
||||
const response = await h.handler(req)
|
||||
assertEquals(response.status, 413, 'oversized Content-Length returns 413')
|
||||
assertEquals(await response.json(), { error: 'audio_too_large' }, 'fixed size error code')
|
||||
assertEquals(bodyRead, false, 'request stream must not be pulled')
|
||||
assertEquals(req.bodyUsed, false, 'request body must remain unread')
|
||||
assertEquals(h.events, [], 'no quota or provider work')
|
||||
})
|
||||
|
|
|
|||
|
|
@ -18,6 +18,7 @@ import { handleCorsPreflightRequest } from '../_shared/cors.ts'
|
|||
import { createStatusJsonResponder } from '../_shared/json-response.ts'
|
||||
import {
|
||||
type DictionaryHints,
|
||||
MAX_STT_AUDIO_BYTES,
|
||||
type NormalizedSttResult,
|
||||
type SttFailureCode,
|
||||
SttInputError,
|
||||
|
|
@ -118,6 +119,7 @@ export async function runSttChain(
|
|||
}
|
||||
|
||||
const json = createStatusJsonResponder()
|
||||
const MAX_STT_MULTIPART_BYTES = MAX_STT_AUDIO_BYTES + 1024 * 1024
|
||||
|
||||
export function createSttProxyHandler(deps: SttProxyDeps): (req: Request) => Promise<Response> {
|
||||
const { quota, logger } = deps
|
||||
|
|
@ -137,7 +139,15 @@ export function createSttProxyHandler(deps: SttProxyDeps): (req: Request) => Pro
|
|||
if (!auth.ok) return auth.response
|
||||
const user = auth.user
|
||||
|
||||
// 2) input
|
||||
// 2) input (reject oversized Content-Length before buffering multipart body)
|
||||
const rawContentLength = req.headers.get('content-length')
|
||||
if (rawContentLength !== null) {
|
||||
const declaredBytes = Number(rawContentLength.trim())
|
||||
if (Number.isFinite(declaredBytes) && declaredBytes > MAX_STT_MULTIPART_BYTES) {
|
||||
return json(413, { error: 'audio_too_large' })
|
||||
}
|
||||
}
|
||||
|
||||
let formData: FormData
|
||||
try {
|
||||
formData = await req.formData()
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue