235 lines
8.7 KiB
TypeScript
235 lines
8.7 KiB
TypeScript
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'])
|
|
})
|
|
})
|