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
|
|
@ -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 제외). 돌아갈 곳이 기본값이면 쿼리를 붙이지 않는다. */
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue