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, executeChatSendTurn, type ChatMessage, } from '@/components/chat/chat-panel' import { bindAuthSession } from '@/components/providers/auth-provider' import { acquireGuardedMediaStream } from '@/components/record/mic-recorder' import { clearTrackedTimeout, createTimedAbortSignal, resolveSupabaseFunctionUrl, scheduleTrackedTimeout, shouldExitAfterAwait, } 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 } clients: { matchAll: () => Promise } } 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({ 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) expect(() => shouldExitAfterAwait(handle, () => true)).toThrow('Request timed out') expect(shouldExitAfterAwait(handle, () => false)).toBe(true) handle.dispose() expect(activeRef.current).toBe(null) const manualHandle = createTimedAbortSignal(1000, activeRef) manualHandle.controller.abort() expect(shouldExitAfterAwait(manualHandle, () => true)).toBe(true) manualHandle.dispose() const timerRef: { current: ReturnType | 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']) }) it('executeChatSendTurn_스트림응답중45초타임아웃_부분메시지롤백과입력복구및시간초과오류를표시한다', async () => { vi.useFakeTimers() const encoder = new TextEncoder() let streamCancelled = false const body = new ReadableStream({ start(controller) { controller.enqueue( encoder.encode('data: {"type":"content_block_delta","delta":{"type":"text_delta","text":"부분응답"}}\n\n'), ) }, cancel() { streamCancelled = true }, }) let currentMessages: ChatMessage[] = [ { id: 'welcome', role: 'assistant', content: '초기 안내', timestamp: '09:00' }, ] let restoredInput = '' let latestError: string | null = null let busyState = false const activeRef: { current: AbortController | null } = { current: null } const pendingTurn = executeChatSendTurn({ text: '회의 요약해줘', messages: currentMessages, activeControllerRef: activeRef, isMounted: () => true, isConfigured: () => true, getAccessToken: async () => 'access-token', endpointUrl: 'https://proj.supabase.co/functions/v1/llm-proxy', fetchImpl: async () => new Response(body, { status: 200, headers: { 'Content-Type': 'text/event-stream' } }), onMessagesUpdate: (updater) => { currentMessages = updater(currentMessages) }, onInputChange: (val) => { restoredInput = val }, onErrorChange: (err) => { latestError = err }, onBusyChange: (busy) => { busyState = busy }, }) await vi.advanceTimersByTimeAsync(100) expect(currentMessages.some((m) => m.role === 'assistant' && m.content === '부분응답')).toBe(true) await vi.advanceTimersByTimeAsync(45_000) await pendingTurn expect(streamCancelled).toBe(true) expect(currentMessages).toEqual([ { id: 'welcome', role: 'assistant', content: '초기 안내', timestamp: '09:00' }, ]) expect(restoredInput).toBe('회의 요약해줘') expect(latestError).toBe('AI 응답 시간이 초과되었습니다.') expect(busyState).toBe(false) }) it('executeChatSendTurn_세션조회중45초타임아웃_조용히종료하지않고입력복구와시간초과오류를표시한다', async () => { vi.useFakeTimers() let currentMessages: ChatMessage[] = [ { id: 'welcome', role: 'assistant', content: '초기 안내', timestamp: '09:00' }, ] let restoredInput = '' let latestError: string | null = null let busyState = false let resolveSession!: (token: string | null) => void const activeRef: { current: AbortController | null } = { current: null } const pendingTurn = executeChatSendTurn({ text: '다시 시도할 질문', messages: currentMessages, activeControllerRef: activeRef, isMounted: () => true, isConfigured: () => true, getAccessToken: () => new Promise((resolve) => { resolveSession = resolve }), endpointUrl: 'https://proj.supabase.co/functions/v1/llm-proxy', fetchImpl: async () => new Response(null, { status: 500 }), onMessagesUpdate: (updater) => { currentMessages = updater(currentMessages) }, onInputChange: (val) => { restoredInput = val }, onErrorChange: (err) => { latestError = err }, onBusyChange: (busy) => { busyState = busy }, }) await vi.advanceTimersByTimeAsync(45_000) resolveSession('late-token') await pendingTurn expect(currentMessages).toEqual([ { id: 'welcome', role: 'assistant', content: '초기 안내', timestamp: '09:00' }, ]) expect(restoredInput).toBe('다시 시도할 질문') expect(latestError).toBe('AI 응답 시간이 초과되었습니다.') expect(busyState).toBe(false) }) it('executeChatSendTurn_스트림중언마운트_reader를취소하고오류나롤백을갱신하지않는다', async () => { const encoder = new TextEncoder() let mounted = true let streamCancelled = false const body = new ReadableStream({ start(controller) { controller.enqueue( encoder.encode('data: {"type":"content_block_delta","delta":{"type":"text_delta","text":"부분"}}\n\n'), ) }, cancel() { streamCancelled = true }, }) let currentMessages: ChatMessage[] = [] let inputCalls = 0 let errorCalls = 0 const activeRef: { current: AbortController | null } = { current: null } const pendingTurn = executeChatSendTurn({ text: '언마운트 테스트', messages: currentMessages, activeControllerRef: activeRef, isMounted: () => mounted, isConfigured: () => true, getAccessToken: async () => 'access-token', endpointUrl: 'https://proj.supabase.co/functions/v1/llm-proxy', fetchImpl: async () => new Response(body, { status: 200, headers: { 'Content-Type': 'text/event-stream' } }), onMessagesUpdate: (updater) => { currentMessages = updater(currentMessages) }, onInputChange: () => { inputCalls += 1 }, onErrorChange: () => { errorCalls += 1 }, onBusyChange: () => undefined, }) await vi.waitFor(() => { expect(currentMessages.some((m) => m.content === '부분')).toBe(true) }) const countBeforeUnmount = currentMessages.length mounted = false activeRef.current?.abort() await pendingTurn expect(streamCancelled).toBe(true) expect(currentMessages.length).toBe(countBeforeUnmount) expect(inputCalls).toBe(1) expect(errorCalls).toBe(1) }) })