feat(commands): multi-select ordered command pipeline with step reordering and single-pass composition (AI-05, AI-07)

This commit is contained in:
Yun Chan 2026-10-31 02:54:54 +09:00
parent f49acf0105
commit 10af20a0ad
157 changed files with 29455 additions and 913 deletions

View file

@ -14,6 +14,11 @@ import {
type BillingCatalog,
type BillingCatalogPrice
} from '@/lib/billing-catalog'
import {
isSupportedWebTier,
resolveWebEntitlement,
resolveWebProvider
} from '@/lib/entitlement'
type BillingProvider = Subscription['provider']
@ -43,17 +48,6 @@ interface Plan {
highlight?: boolean
}
const VALID_TIERS = new Set<SubscriptionTier>(['free', 'pro', 'pro_plus'])
// 'stripe' 는 결제 경로가 제거된 뒤에도 과거 구독 행(provider='stripe')을 읽기 위해 남긴다.
const VALID_PROVIDERS = new Set<BillingProvider>([
'none',
'stripe',
'payple',
'google_play',
'app_store',
'admin'
])
const PLANS: Plan[] = [
{
tier: 'free',
@ -124,12 +118,12 @@ async function loadBillingState(): Promise<BillingState> {
if (error) throw new Error('subscription_lookup_failed')
if (!data) throw new Error('subscription_not_initialized')
if (!VALID_TIERS.has(data.tier)) throw new Error('subscription_tier_invalid')
if (!isSupportedWebTier(data.tier)) throw new Error('subscription_tier_invalid')
const providerCandidate = data.provider === 'none' && data.payment_provider !== 'none'
? data.payment_provider
: data.provider
if (!VALID_PROVIDERS.has(providerCandidate)) throw new Error('subscription_provider_invalid')
const providerCandidate = resolveWebProvider(data.provider, data.payment_provider)
if (!providerCandidate) throw new Error('subscription_provider_invalid')
const resolvedEntitlement = resolveWebEntitlement(data)
const { data: catalogData, error: catalogError } = await supabase.functions.invoke('billing-catalog', {
body: {}
@ -139,12 +133,12 @@ async function loadBillingState(): Promise<BillingState> {
return {
email: userData.user.email ?? '이메일 없음',
subscription: {
tier: data.tier,
status: data.status,
tier: resolvedEntitlement.tier,
status: resolvedEntitlement.status,
provider: providerCandidate,
current_period_end: data.current_period_end,
cancel_at: data.cancel_at,
auto_renewing: data.auto_renewing
current_period_end: resolvedEntitlement.currentPeriodEnd,
cancel_at: resolvedEntitlement.cancelAt,
auto_renewing: resolvedEntitlement.autoRenewing
},
catalog
}

View file

@ -65,7 +65,10 @@ export default async function MeetingDetailPage({ params }: PageProps): Promise<
<PhosphorText variant="heading" sx={{ mb: 2 }}>
AUDIO
</PhosphorText>
<MeetingAudioPlayer storageKey={meeting.audio_storage_key ?? null} />
<MeetingAudioPlayer
storageKey={meeting.audio_storage_key ?? null}
meetingId={id}
/>
</MetalCard>
{/* Transcript — Realtime 구독 or raw_transcript fallback */}
@ -73,23 +76,14 @@ export default async function MeetingDetailPage({ params }: PageProps): Promise<
<PhosphorText variant="heading" sx={{ mb: 2 }}>
TRANSCRIPT {meeting.status === 'recording' ? '(LIVE)' : ''}
</PhosphorText>
{(transcripts ?? []).length > 0 || meeting.status === 'recording' ? (
{(transcripts ?? []).length > 0
|| meeting.status === 'recording'
|| Boolean(meeting.edited_transcript || meeting.raw_transcript) ? (
<LiveTranscriptList
meetingId={id}
initial={(transcripts ?? []) as unknown as TranscriptRow[]}
fallbackTranscript={meeting.edited_transcript ?? meeting.raw_transcript ?? null}
/>
) : meeting.edited_transcript || meeting.raw_transcript ? (
<Box
sx={{
whiteSpace: 'pre-wrap',
color: d3roPalette.text.primary,
fontSize: 13,
lineHeight: 1.6,
fontFamily: 'inherit'
}}
>
{meeting.edited_transcript ?? meeting.raw_transcript}
</Box>
) : (
<Box sx={{ color: d3roPalette.text.muted, fontSize: 13 }}>
전사가 없습니다.

View file

@ -0,0 +1,5 @@
import { redirect } from 'next/navigation'
export default function TeamAliasPage(): never {
redirect('/teams')
}

View file

@ -0,0 +1,237 @@
'use client'
import Link from 'next/link'
import { Suspense, useCallback, useEffect, useRef, useState } from 'react'
import { useRouter, useSearchParams } from 'next/navigation'
import { Alert, Box, CircularProgress, Stack, Typography } from '@mui/material'
import { CheckCircle2, RefreshCw, ShieldAlert, Users } from 'lucide-react'
import { MetalCard, PhysicalButton, TactileBadge } from '@d3ro/ui/components/ds'
import { d3roFontMono, d3roFontSans } from '@d3ro/ui/theme'
import { useAuth } from '@/components/providers/auth-provider'
import { getSupabaseBrowserClient, isSupabaseConfigured } from '@/lib/supabase-browser'
const INVITE_TOKEN_PATTERN =
/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|[A-Za-z0-9_-]{32})$/i
interface TeamAcceptEdgePayload {
data?: {
team_id?: unknown
role?: unknown
}
team_id?: unknown
role?: unknown
error?: {
code?: unknown
message?: unknown
}
}
type InviteAcceptState =
| { status: 'checking'; message: string }
| { status: 'accepting'; message: string }
| { status: 'accepted'; teamId: string | null; role: string }
| { status: 'invalid-token'; message: string }
| { status: 'error'; message: string }
export function validateWebInviteToken(rawToken: string | null | undefined): string | null {
const trimmed = rawToken?.trim() ?? ''
return INVITE_TOKEN_PATTERN.test(trimmed) ? trimmed : null
}
export function buildAcceptInviteLoginRedirect(token: string): string {
const nextPath = `/app/accept-invite?token=${encodeURIComponent(token)}`
return `/login?next=${encodeURIComponent(nextPath)}`
}
function parseTeamAcceptResponse(payload: unknown): { teamId: string | null; role: string } {
if (typeof payload !== 'object' || payload === null) {
return { teamId: null, role: 'member' }
}
const record = payload as TeamAcceptEdgePayload
const inner = record.data ?? record
const teamId = typeof inner.team_id === 'string' && inner.team_id.trim() ? inner.team_id : null
const role = typeof inner.role === 'string' && inner.role.trim() ? inner.role : 'member'
return { teamId, role }
}
function AcceptInviteContent(): React.ReactElement {
const router = useRouter()
const searchParams = useSearchParams()
const { user, loading: authLoading } = useAuth()
const rawToken = searchParams.get('token')
const validToken = validateWebInviteToken(rawToken)
const attemptedTokenRef = useRef<string | null>(null)
const [state, setState] = useState<InviteAcceptState>(() => (
validToken
? { status: 'checking', message: '로그인 세션과 초대 토큰을 확인하고 있습니다.' }
: {
status: 'invalid-token',
message: '초대 링크가 없거나 형식이 올바르지 않습니다. 새 초대 링크를 요청해 주세요.'
}
))
const acceptInvite = useCallback(async (tokenToAccept: string): Promise<void> => {
if (!isSupabaseConfigured()) {
setState({
status: 'error',
message: 'Supabase 연결 설정을 확인할 수 없어 초대를 수락할 수 없습니다.'
})
return
}
setState({
status: 'accepting',
message: '팀 초대 권한을 검증하고 워크스페이스에 참여하는 중입니다.'
})
try {
const supabase = getSupabaseBrowserClient()
const { data, error } = await supabase.functions.invoke('team-accept', {
body: { token: tokenToAccept }
})
if (error) {
setState({
status: 'error',
message: error.message || '팀 초대 수락에 실패했습니다. 만료되었거나 권한이 없는 초대일 수 있습니다.'
})
return
}
const parsed = parseTeamAcceptResponse(data)
setState({
status: 'accepted',
teamId: parsed.teamId,
role: parsed.role
})
router.replace('/team')
} catch (invokeError) {
setState({
status: 'error',
message: invokeError instanceof Error
? invokeError.message
: '팀 초대 수락 요청 중 오류가 발생했습니다.'
})
}
}, [router])
useEffect(() => {
if (!validToken) {
setState({
status: 'invalid-token',
message: '초대 링크가 없거나 형식이 올바르지 않습니다. 새 초대 링크를 요청해 주세요.'
})
return
}
if (authLoading) return
if (!user) {
router.replace(buildAcceptInviteLoginRedirect(validToken))
return
}
if (attemptedTokenRef.current === validToken) return
attemptedTokenRef.current = validToken
void acceptInvite(validToken)
}, [acceptInvite, authLoading, router, user, validToken])
return (
<Box
sx={{
minHeight: '100dvh',
display: 'grid',
placeItems: 'center',
bgcolor: 'var(--d3-bg-app)',
p: { xs: 2.5, md: 4 },
fontFamily: d3roFontSans
}}
>
<MetalCard sx={{ width: '100%', maxWidth: 520, p: { xs: 3, md: 4 } }}>
<Stack spacing={2.5}>
<Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 1.5 }}>
<TactileBadge ledColor="green" tone="accent">TEAM INVITE</TactileBadge>
<Typography sx={{ fontFamily: d3roFontMono, fontSize: 11, color: 'var(--d3-text-label)' }}>
{validToken ? `${validToken.slice(0, 8)}…${validToken.slice(-4)}` : 'NO TOKEN'}
</Typography>
</Box>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5 }}>
<Users size={22} color="var(--d3-accent-main)" />
<Typography component="h1" sx={{ fontSize: 22, fontWeight: 600, color: 'var(--d3-text-primary)' }}>
팀 초대 수락
</Typography>
</Box>
{(state.status === 'checking' || state.status === 'accepting') && (
<Box
role="status"
data-testid="accept-invite-loading"
sx={{ display: 'flex', alignItems: 'center', gap: 2, py: 2 }}
>
<CircularProgress size={24} />
<Typography sx={{ fontSize: 14, color: 'var(--d3-text-secondary)' }}>
{state.message}
</Typography>
</Box>
)}
{state.status === 'accepted' && (
<Alert
severity="success"
icon={<CheckCircle2 size={18} />}
data-testid="accept-invite-success"
>
팀 초대를 수락했습니다 ({state.role}). 팀 워크스페이스로 이동합니다.
</Alert>
)}
{(state.status === 'invalid-token' || state.status === 'error') && (
<Alert
severity="error"
icon={<ShieldAlert size={18} />}
data-testid="accept-invite-error"
>
{state.message}
</Alert>
)}
<Stack direction={{ xs: 'column', sm: 'row' }} spacing={1.5} sx={{ pt: 1 }}>
{state.status === 'error' && validToken && (
<PhysicalButton
tone="accent"
data-testid="accept-invite-retry"
onClick={() => {
attemptedTokenRef.current = validToken
void acceptInvite(validToken)
}}
>
<RefreshCw size={14} /> 다시 시도
</PhysicalButton>
)}
<Link href="/team" style={{ textDecoration: 'none' }}>
<PhysicalButton tone="glass" data-testid="accept-invite-go-teams">
팀 화면으로 이동
</PhysicalButton>
</Link>
</Stack>
</Stack>
</MetalCard>
</Box>
)
}
export default function AcceptInvitePage(): React.ReactElement {
return (
<Suspense
fallback={(
<Box sx={{ minHeight: '100dvh', display: 'grid', placeItems: 'center', bgcolor: 'var(--d3-bg-app)' }}>
<CircularProgress aria-label="초대 정보 확인 중" />
</Box>
)}
>
<AcceptInviteContent />
</Suspense>
)
}

View file

@ -1,12 +1,18 @@
'use client'
// apps/web/src/components/meetings/live-transcript-list.tsx
// 회의 세그먼트 실시간 구독 — Supabase Realtime으로 INSERT 이벤트 수신
// 회의 세그먼트 실시간 구독 + 오디오 타임스탬프 탐색 동기화
import { useEffect, useState } from 'react'
import { useCallback, useEffect, useMemo, useState } from 'react'
import { Box, Stack } from '@mui/material'
import { d3roPalette, typoSx } from '@d3ro/ui/theme'
import { getSupabaseBrowserClient } from '@/lib/supabase-browser'
import { formatTranscriptTimestamp, parseTranscriptLines } from '@d3ro/core/meeting-transcript'
import { d3roFontMono, d3roFocusRing, d3roPalette, typoSx } from '@d3ro/ui/theme'
import { getSupabaseBrowserClient } from '../../lib/supabase-browser'
import {
dispatchMeetingAudioSeek,
MEETING_AUDIO_TIMEUPDATE_EVENT,
type MeetingAudioTimeUpdateDetail
} from './meeting-audio-player'
export interface TranscriptRow {
id: string
@ -20,18 +26,87 @@ export interface TranscriptRow {
interface LiveTranscriptListProps {
meetingId: string
initial: TranscriptRow[]
fallbackTranscript?: string | null
currentPositionMs?: number | null
onSeekTimestamp?: (timestampMs: number) => void
}
export function parseFallbackTranscriptRows(
fallbackTranscript: string | null | undefined
): TranscriptRow[] {
return parseTranscriptLines(fallbackTranscript).map((line, index) => ({
id: `fallback-line-${index}`,
segment_index: index,
timestamp_ms: Math.max(0, line.timestampMs),
text: line.text,
speaker: line.speaker,
edited: false
}))
}
export function findActiveWebTranscriptSegmentId(
segments: readonly Pick<TranscriptRow, 'id' | 'timestamp_ms'>[],
currentPositionMs: number | null | undefined
): string | null {
if (
currentPositionMs === null
|| currentPositionMs === undefined
|| !Number.isFinite(currentPositionMs)
|| currentPositionMs < 0
|| segments.length === 0
) {
return null
}
const ordered = segments
.slice()
.sort((left, right) => left.timestamp_ms - right.timestamp_ms)
let activeId: string | null = null
for (let index = 0; index < ordered.length; index += 1) {
const current = ordered[index]
const next = ordered[index + 1]
if (currentPositionMs < current.timestamp_ms) {
break
}
const endBound = next !== undefined ? next.timestamp_ms : Number.POSITIVE_INFINITY
if (currentPositionMs <= endBound) {
activeId = current.id
}
}
return activeId
}
export function LiveTranscriptList({
meetingId,
initial
initial,
fallbackTranscript = null,
currentPositionMs,
onSeekTimestamp
}: LiveTranscriptListProps): React.ReactElement {
const [segments, setSegments] = useState<TranscriptRow[]>(initial)
const [internalPositionMs, setInternalPositionMs] = useState<number | null>(null)
useEffect(() => {
setSegments(initial)
}, [initial])
useEffect(() => {
if (typeof window === 'undefined') return undefined
const handleTimeUpdate = (event: Event): void => {
const detail = (event as CustomEvent<MeetingAudioTimeUpdateDetail>).detail
if (!detail || !Number.isFinite(detail.positionMs)) return
if (detail.meetingId && detail.meetingId !== meetingId) return
setInternalPositionMs(detail.positionMs)
}
window.addEventListener(MEETING_AUDIO_TIMEUPDATE_EVENT, handleTimeUpdate)
return () => {
window.removeEventListener(MEETING_AUDIO_TIMEUPDATE_EVENT, handleTimeUpdate)
}
}, [meetingId])
useEffect(() => {
const supabase = getSupabaseBrowserClient()
// 회의별 Realtime 채널 구독. V2-2 migration에서
// ALTER PUBLICATION supabase_realtime ADD TABLE public.transcripts; 적용됨.
const channel = supabase
.channel(`transcripts:meeting:${meetingId}`)
.on(
@ -45,7 +120,6 @@ export function LiveTranscriptList({
(payload) => {
const row = payload.new as TranscriptRow
setSegments((prev) => {
// 중복 방지 (segment_index 기준)
if (prev.some((s) => s.segment_index === row.segment_index)) {
return prev
}
@ -73,41 +147,102 @@ export function LiveTranscriptList({
}
}, [meetingId])
if (segments.length === 0) {
const effectiveSegments = useMemo<TranscriptRow[]>(() => {
if (segments.length > 0) return segments
return parseFallbackTranscriptRows(fallbackTranscript)
}, [fallbackTranscript, segments])
const effectivePositionMs = currentPositionMs !== undefined ? currentPositionMs : internalPositionMs
const activeSegmentId = useMemo(
() => findActiveWebTranscriptSegmentId(effectiveSegments, effectivePositionMs),
[effectivePositionMs, effectiveSegments]
)
const handleSeek = useCallback((timestampMs: number): void => {
const normalized = Math.max(0, Math.floor(timestampMs))
setInternalPositionMs(normalized)
onSeekTimestamp?.(normalized)
dispatchMeetingAudioSeek(normalized, meetingId)
}, [meetingId, onSeekTimestamp])
if (effectiveSegments.length === 0) {
return (
<Box sx={{ color: d3roPalette.text.muted, fontSize: 13 }}>전사 세그먼트가 없습니다.</Box>
)
}
return (
<Stack spacing={1.5}>
{segments.map((seg) => (
<Box key={seg.id}>
<Box sx={{ color: d3roPalette.text.label, fontSize: 11, mb: 0.5 }}>
{Math.floor(seg.timestamp_ms / 60000)}:
{String(Math.floor((seg.timestamp_ms / 1000) % 60)).padStart(2, '0')}
{seg.speaker && ` · ${seg.speaker}`}
{seg.edited && (
<Stack spacing={1.25}>
{effectiveSegments.map((seg) => {
const isActive = activeSegmentId === seg.id
const formattedTime = formatTranscriptTimestamp(seg.timestamp_ms)
return (
<Box
key={seg.id}
data-testid={`transcript-segment-${seg.id}`}
data-active={isActive ? 'true' : 'false'}
sx={{
p: 1.25,
borderRadius: 1.5,
borderLeft: isActive
? `3px solid ${d3roPalette.accent.main}`
: '3px solid transparent',
bgcolor: isActive ? d3roPalette.bg.inset : 'transparent',
transition: 'background-color 140ms ease, border-color 140ms ease'
}}
>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1, color: d3roPalette.text.label, fontSize: 11, mb: 0.5 }}>
<Box
component="span"
component="button"
type="button"
data-testid={`transcript-seek-${seg.id}`}
aria-label={`${formattedTime} 위치로 오디오 이동`}
onClick={() => handleSeek(seg.timestamp_ms)}
sx={{
ml: 1,
px: 0.75,
py: 0.25,
borderRadius: 0.5,
bgcolor: d3roPalette.tag.orangeBg,
color: d3roPalette.tag.orange,
py: 0.2,
border: `1px solid ${isActive ? d3roPalette.accent.main : d3roPalette.border.default}`,
borderRadius: 1,
bgcolor: d3roPalette.bg.card,
color: isActive ? d3roPalette.accent.main : d3roPalette.text.secondary,
fontFamily: d3roFontMono,
fontSize: 11,
fontWeight: 500
cursor: 'pointer',
'&:hover': {
borderColor: d3roPalette.accent.main,
color: d3roPalette.accent.main
},
'&:focus-visible': d3roFocusRing
}}
>
EDITED
[{formattedTime}]
</Box>
)}
{seg.speaker && (
<Box component="span" sx={{ color: d3roPalette.text.secondary, fontWeight: 500 }}>
{seg.speaker}
</Box>
)}
{seg.edited && (
<Box
component="span"
sx={{
px: 0.75,
py: 0.25,
borderRadius: 0.5,
bgcolor: d3roPalette.tag.orangeBg,
color: d3roPalette.tag.orange,
fontSize: 11,
fontWeight: 500
}}
>
EDITED
</Box>
)}
</Box>
<Box sx={{ color: d3roPalette.text.primary, ...typoSx('body') }}>{seg.text}</Box>
</Box>
<Box sx={{ color: d3roPalette.text.primary, ...typoSx('body') }}>{seg.text}</Box>
</Box>
))}
)
})}
</Stack>
)
}

View file

@ -1,23 +1,104 @@
'use client'
// apps/web/src/components/meetings/meeting-audio-player.tsx
// 회의 오디오 재생 — storage key → signed URL → <audio> 엘리먼트
// 회의 오디오 재생 — storage key → signed URL → <audio> 엘리먼트 + 타임스탬프 탐색 동기화
import { useEffect, useState } from 'react'
import { useCallback, useEffect, useRef, useState } from 'react'
import { Alert, Box, CircularProgress } from '@mui/material'
import { d3roPalette, typoSx } from '@d3ro/ui/theme'
import { getSupabaseBrowserClient } from '@/lib/supabase-browser'
import { getSupabaseBrowserClient } from '../../lib/supabase-browser'
export const MEETING_AUDIO_SEEK_EVENT = 'd3ro:meeting-audio-seek'
export const MEETING_AUDIO_TIMEUPDATE_EVENT = 'd3ro:meeting-audio-timeupdate'
export interface MeetingAudioSeekDetail {
timestampMs: number
meetingId?: string
}
export interface MeetingAudioTimeUpdateDetail {
positionMs: number
meetingId?: string
}
export function dispatchMeetingAudioSeek(timestampMs: number, meetingId?: string): void {
if (typeof window === 'undefined' || !Number.isFinite(timestampMs)) return
const clamped = Math.max(0, Math.floor(timestampMs))
window.dispatchEvent(
new CustomEvent<MeetingAudioSeekDetail>(MEETING_AUDIO_SEEK_EVENT, {
detail: { timestampMs: clamped, meetingId }
})
)
}
interface MeetingAudioPlayerProps {
storageKey: string | null
meetingId?: string
seekPositionMs?: number | null
onPositionChangeMs?: (positionMs: number) => void
}
const SIGNED_URL_TTL_SECONDS = 3600
export function MeetingAudioPlayer({ storageKey }: MeetingAudioPlayerProps): React.ReactElement {
export function MeetingAudioPlayer({
storageKey,
meetingId,
seekPositionMs,
onPositionChangeMs
}: MeetingAudioPlayerProps): React.ReactElement {
const [signedUrl, setSignedUrl] = useState<string | null>(null)
const [error, setError] = useState<string | null>(null)
const [loading, setLoading] = useState<boolean>(false)
const audioRef = useRef<HTMLAudioElement | null>(null)
const pendingSeekMsRef = useRef<number | null>(null)
const emitPositionChange = useCallback((positionMs: number): void => {
const normalized = Math.max(0, Math.floor(positionMs))
onPositionChangeMs?.(normalized)
if (typeof window !== 'undefined') {
window.dispatchEvent(
new CustomEvent<MeetingAudioTimeUpdateDetail>(MEETING_AUDIO_TIMEUPDATE_EVENT, {
detail: { positionMs: normalized, meetingId }
})
)
}
}, [meetingId, onPositionChangeMs])
const applySeekToElement = useCallback((timestampMs: number, autoPlay = false): void => {
const normalized = Math.max(0, Math.floor(timestampMs))
const audio = audioRef.current
if (!audio) {
pendingSeekMsRef.current = normalized
emitPositionChange(normalized)
return
}
audio.currentTime = normalized / 1000
emitPositionChange(normalized)
if (autoPlay && typeof audio.play === 'function') {
void audio.play().catch(() => undefined)
}
}, [emitPositionChange])
useEffect(() => {
if (seekPositionMs === null || seekPositionMs === undefined || !Number.isFinite(seekPositionMs)) {
return
}
applySeekToElement(seekPositionMs, false)
}, [applySeekToElement, seekPositionMs])
useEffect(() => {
if (typeof window === 'undefined') return undefined
const handleSeekEvent = (event: Event): void => {
const detail = (event as CustomEvent<MeetingAudioSeekDetail>).detail
if (!detail || !Number.isFinite(detail.timestampMs)) return
if (meetingId && detail.meetingId && detail.meetingId !== meetingId) return
applySeekToElement(detail.timestampMs, true)
}
window.addEventListener(MEETING_AUDIO_SEEK_EVENT, handleSeekEvent)
return () => {
window.removeEventListener(MEETING_AUDIO_SEEK_EVENT, handleSeekEvent)
}
}, [applySeekToElement, meetingId])
useEffect(() => {
if (!storageKey) {
@ -87,9 +168,20 @@ export function MeetingAudioPlayer({ storageKey }: MeetingAudioPlayerProps): Rea
return (
<Box sx={{ width: '100%' }}>
<Box
ref={audioRef}
component="audio"
controls
preload="metadata"
data-testid="meeting-audio-element"
onLoadedMetadata={(event: React.SyntheticEvent<HTMLAudioElement>) => {
if (pendingSeekMsRef.current !== null) {
event.currentTarget.currentTime = pendingSeekMsRef.current / 1000
pendingSeekMsRef.current = null
}
}}
onTimeUpdate={(event: React.SyntheticEvent<HTMLAudioElement>) => {
emitPositionChange(Math.floor(event.currentTarget.currentTime * 1000))
}}
sx={{
width: '100%',
'&::-webkit-media-controls-panel': {

View file

@ -1,5 +1,10 @@
import type { D3roSupabaseClient, Subscription } from '@d3ro/api-client'
import type { SupabaseClient } from '@supabase/supabase-js'
import {
isSupportedWebProvider,
isSupportedWebTier,
resolveWebEntitlement
} from './entitlement'
export interface DashboardRecentEntry {
id: string
@ -55,8 +60,6 @@ export class DashboardClientError extends Error {
}
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
const TIERS = new Set(['free', 'pro', 'pro_plus'])
const PROVIDERS = new Set(['none', 'stripe', 'payple', 'google_play', 'app_store', 'admin'])
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
@ -152,11 +155,9 @@ function normalizeSubscription(value: unknown): DashboardSubscription {
const periodEnd = normalizeDate(value.current_period_end, true)
const cancelAt = normalizeDate(value.cancel_at, true)
if (
typeof value.tier !== 'string'
|| !TIERS.has(value.tier)
!isSupportedWebTier(value.tier)
|| (value.status !== null && typeof value.status !== 'string')
|| typeof value.provider !== 'string'
|| !PROVIDERS.has(value.provider)
|| !isSupportedWebProvider(value.provider)
|| overageCredits === null
|| (value.current_period_end !== null && periodEnd === null)
|| (value.cancel_at !== null && cancelAt === null)
@ -164,14 +165,15 @@ function normalizeSubscription(value: unknown): DashboardSubscription {
) {
throw new DashboardClientError('invalid-response', 'Subscription response shape is invalid')
}
const resolved = resolveWebEntitlement(value)
return {
tier: value.tier as Subscription['tier'],
status: value.status,
provider: value.provider as Subscription['provider'],
overageCredits,
currentPeriodEnd: periodEnd,
cancelAt,
autoRenewing: value.auto_renewing
tier: resolved.tier,
status: resolved.status,
provider: resolved.provider,
overageCredits: resolved.overageCredits,
currentPeriodEnd: resolved.currentPeriodEnd,
cancelAt: resolved.cancelAt,
autoRenewing: resolved.autoRenewing
}
}

View file

@ -0,0 +1,119 @@
import type { Subscription, SubscriptionTier } from '@d3ro/api-client'
import {
normalizeAdminRole,
normalizeEntitlementTier,
resolveEntitlement,
type AdminRole,
type EntitlementSnapshot as CoreEntitlementSnapshot,
type EntitlementTier
} from '@d3ro/core/entitlement'
import type { Feature } from '@d3ro/core/types'
export type WebBillingProvider = Subscription['provider']
export interface WebEntitlementSubscriptionRow {
tier?: unknown
status?: unknown
provider?: unknown
payment_provider?: unknown
current_period_end?: unknown
cancel_at?: unknown
auto_renewing?: unknown
overage_credits?: unknown
}
export interface WebResolvedEntitlement {
tier: SubscriptionTier
rawTier: EntitlementTier
status: string | null
provider: WebBillingProvider
currentPeriodEnd: string | null
cancelAt: string | null
autoRenewing: boolean | null
overageCredits: number
adFree: boolean
adminRole: AdminRole
adminCapabilities: CoreEntitlementSnapshot['adminCapabilities']
features: readonly Feature[]
coreSnapshot: CoreEntitlementSnapshot
}
const VALID_TIERS = new Set<SubscriptionTier>(['free', 'pro', 'pro_plus'])
const VALID_PROVIDERS = new Set<WebBillingProvider>([
'none',
'stripe',
'payple',
'google_play',
'app_store',
'admin'
])
const PAID_ACCESS_STATUSES = new Set(['active', 'trialing', 'canceled', 'past_due'])
function normalizeIsoDate(value: unknown): string | null {
if (typeof value !== 'string' || !Number.isFinite(Date.parse(value))) return null
return new Date(value).toISOString()
}
function normalizeNonNegativeInt(value: unknown): number {
const numeric = typeof value === 'number' ? value : Number(value)
return Number.isSafeInteger(numeric) && numeric >= 0 ? numeric : 0
}
export function isSupportedWebTier(value: unknown): value is SubscriptionTier {
return typeof value === 'string' && VALID_TIERS.has(value as SubscriptionTier)
}
export function isSupportedWebProvider(value: unknown): value is WebBillingProvider {
return typeof value === 'string' && VALID_PROVIDERS.has(value as WebBillingProvider)
}
export function resolveWebProvider(
provider: unknown,
paymentProvider?: unknown
): WebBillingProvider | null {
const candidate = provider === 'none' && typeof paymentProvider === 'string' && paymentProvider !== 'none'
? paymentProvider
: provider
return isSupportedWebProvider(candidate) ? candidate : null
}
export function resolveWebEntitlement(
row: WebEntitlementSubscriptionRow | null | undefined,
options: {
supabaseRole?: unknown
dotnetRole?: unknown
now?: Date
} = {}
): WebResolvedEntitlement {
const now = options.now ?? new Date()
const rawTier = normalizeEntitlementTier(row?.tier)
const status = typeof row?.status === 'string' && row.status.trim() ? row.status : null
const statusAllowsPaidAccess = status === null || PAID_ACCESS_STATUSES.has(status)
const currentPeriodEnd = normalizeIsoDate(row?.current_period_end)
const cancelAt = normalizeIsoDate(row?.cancel_at)
const provider = resolveWebProvider(row?.provider, row?.payment_provider) ?? 'none'
const coreSnapshot = resolveEntitlement({
subscriptionTier: statusAllowsPaidAccess ? rawTier : 'free',
supabaseRole: options.supabaseRole,
dotnetRole: options.dotnetRole,
expiresAt: currentPeriodEnd !== null ? Date.parse(currentPeriodEnd) : null,
refreshedAt: now.getTime()
})
return {
tier: coreSnapshot.tier,
rawTier,
status,
provider,
currentPeriodEnd,
cancelAt,
autoRenewing: typeof row?.auto_renewing === 'boolean' ? row.auto_renewing : null,
overageCredits: normalizeNonNegativeInt(row?.overage_credits),
adFree: coreSnapshot.adFree,
adminRole: normalizeAdminRole(options.supabaseRole ?? options.dotnetRole),
adminCapabilities: coreSnapshot.adminCapabilities,
features: coreSnapshot.features,
coreSnapshot
}
}

View file

@ -19,6 +19,10 @@ export function safeReturnPath(value: string | null | undefined): string {
if (!value || !value.startsWith('/') || value.startsWith('//') || value.startsWith('/\\')) {
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)
}
return value
}

View file

@ -0,0 +1,175 @@
// apps/web/src/lib/web-push.ts
// D3RO Voice — Web Push Service Worker Registration & VAPID Subscription
import type { SupabaseClient } from '@supabase/supabase-js'
import { getSupabaseBrowserClient } from './supabase-browser'
export type WebPushProvider = 'webpush'
export type WebPushErrorCode =
| 'auth'
| 'unsupported-browser'
| 'permission-denied'
| 'vapid-key-missing'
| 'invalid-vapid-key'
| 'subscription-failed'
| 'persistence-failed'
export class WebPushError extends Error {
constructor(
public readonly code: WebPushErrorCode,
message: string,
) {
super(message)
this.name = 'WebPushError'
}
}
export interface WebPushSubscriptionRecord {
provider: WebPushProvider
endpoint: string
subscriptionJson: string
registeredAt: string
}
export interface SubscribeWebPushOptions {
userId: string
deviceId?: string
vapidPublicKey?: string
serviceWorkerPath?: string
serviceWorkerScope?: string
client?: SupabaseClient
}
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
const DEFAULT_SW_PATH = '/app/sw.js'
const DEFAULT_SW_SCOPE = '/app/'
export function getVapidPublicKey(overrideKey?: string): string | null {
const candidate = (overrideKey ?? process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY ?? '').trim()
return candidate.length > 0 ? candidate : null
}
export function urlBase64ToUint8Array(base64String: string): Uint8Array {
const trimmed = base64String.trim()
if (!trimmed || !/^[A-Za-z0-9\-_=]+$/.test(trimmed)) {
throw new WebPushError('invalid-vapid-key', 'VAPID public key must be URL-safe base64')
}
const padding = '='.repeat((4 - (trimmed.length % 4)) % 4)
const base64 = (trimmed + padding).replace(/-/g, '+').replace(/_/g, '/')
const rawData = typeof atob === 'function'
? atob(base64)
: Buffer.from(base64, 'base64').toString('binary')
const outputArray = new Uint8Array(rawData.length)
for (let index = 0; index < rawData.length; index += 1) {
outputArray[index] = rawData.charCodeAt(index)
}
return outputArray
}
export async function registerWebPushServiceWorker(
serviceWorkerPath = DEFAULT_SW_PATH,
scope = DEFAULT_SW_SCOPE,
): Promise<ServiceWorkerRegistration> {
if (
typeof window === 'undefined'
|| typeof navigator === 'undefined'
|| !('serviceWorker' in navigator)
|| !('PushManager' in window)
) {
throw new WebPushError('unsupported-browser', 'Web Push is not supported in this browser')
}
return navigator.serviceWorker.register(serviceWorkerPath, { scope })
}
export async function subscribeWebPush(
options: SubscribeWebPushOptions,
): Promise<WebPushSubscriptionRecord> {
if (!UUID_PATTERN.test(options.userId)) {
throw new WebPushError('auth', 'A valid authenticated user ID is required for Web Push')
}
if (options.deviceId !== undefined && !UUID_PATTERN.test(options.deviceId)) {
throw new WebPushError('auth', 'A valid device ID is required when binding Web Push to a device')
}
const vapidPublicKey = getVapidPublicKey(options.vapidPublicKey)
if (!vapidPublicKey) {
throw new WebPushError('vapid-key-missing', 'NEXT_PUBLIC_VAPID_PUBLIC_KEY is not configured')
}
const applicationServerKey = urlBase64ToUint8Array(vapidPublicKey)
if (typeof Notification !== 'undefined' && Notification.permission === 'denied') {
throw new WebPushError('permission-denied', 'Notification permission has been denied')
}
const registration = await registerWebPushServiceWorker(
options.serviceWorkerPath ?? DEFAULT_SW_PATH,
options.serviceWorkerScope ?? DEFAULT_SW_SCOPE,
)
let subscription: PushSubscription
try {
const existing = await registration.pushManager.getSubscription()
subscription = existing ?? await registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: applicationServerKey as BufferSource,
})
} catch (error) {
throw new WebPushError(
'subscription-failed',
error instanceof Error ? error.message : 'Failed to subscribe to Web Push',
)
}
const serialized = JSON.stringify(subscription.toJSON())
const supabase = options.client ?? getSupabaseBrowserClient()
const nowIso = new Date().toISOString()
if (options.deviceId) {
const { data, error } = await supabase.rpc('register_push_registration', {
push_device_id: options.deviceId,
push_provider: 'webpush',
registration_id: serialized,
})
if (error) {
throw new WebPushError('persistence-failed', error.message)
}
const record = typeof data === 'object' && data !== null
? (data as Record<string, unknown>)
: null
const registeredAt = typeof record?.registered_at === 'string'
? record.registered_at
: nowIso
return {
provider: 'webpush',
endpoint: subscription.endpoint,
subscriptionJson: serialized,
registeredAt,
}
}
const { error } = await supabase
.from('push_tokens')
.upsert(
{
user_id: options.userId,
token: serialized,
platform: 'web',
provider: 'webpush',
updated_at: nowIso,
},
{ onConflict: 'user_id,token' },
)
if (error) {
throw new WebPushError('persistence-failed', error.message)
}
return {
provider: 'webpush',
endpoint: subscription.endpoint,
subscriptionJson: serialized,
registeredAt: nowIso,
}
}

View file

@ -13,6 +13,6 @@ export function proxy(request: NextRequest): NextResponse {
}
export const config = {
// basePath 기준 경로. 외부에서 직접 여는 결제 진입점만 대상이다.
matcher: ['/billing']
// basePath 기준 경로. 외부에서 직접 여는 결제·초대 진입점만 대상이다.
matcher: ['/billing', '/accept-invite']
}