d3ro-voice/apps/desktop/src/renderer/components/CloudSyncSection.tsx
yunchan8804 0785374804 feat(V2-X-b): UI 정리 + pull 동기화 + Stripe 서명 검증 + ui-native 패키지
묶음 A — UI 정리 + i18n 완성:
[A1] desktop SettingsModal에 CloudSyncSection 통합 (탭 6번째)
  - CloudIcon import, settings.tabs.cloud 키 추가
  - 기존 about 탭은 index 5 -> 6

[A2] apps/web Sidebar 공유 layout 리팩터링
  - app/(app)/layout.tsx 신규 (route group)
  - dashboard/meetings/record/teams/billing을 (app)/ 아래로 git mv
  - app/(app)/layout.tsx에 auth 가드 + Sidebar 통합
  - 기존 개별 page.tsx에서 Sidebar/auth 중복 제거
  - app/(app)/dashboard/layout.tsx 제거 (루트 layout이 처리)

[A3] 11개 locale에 V2 새 키 추가 (en/ja/zh/zh-TW/es/fr/de/pt/ru/vi/th)
  - nav.meetings/record/teams/billing/logout
  - login.subtitle/google/github/terms
  - settings.tabs.cloud

묶음 B — V2-4b pull 동기화:
- CloudSyncService.pullAll() 신규
  - history/dictionary 테이블 원격에서 fetch
  - last_sync_at 이후 updated_at만 필터
  - Last-Write-Wins 충돌 해결 (remote.updated_at > local.updated_at)
  - 로컬에 없는 행은 INSERT, 있는 행은 UPDATE (구체적 컬럼 지정)
- IPC CLOUD_SYNC.PULL_ALL 채널 + handler + preload api
- CloudSyncSection에 Pull 버튼 추가 (Push 옆에 위치)

묶음 C — V2-8b Stripe webhook 서명 검증:
- stripe-webhook Edge Function에 Web Crypto API 기반 HMAC-SHA256 검증
  - Stripe-Signature 헤더 파싱 (t=, v1= 엔트리)
  - Replay 방지 (timestamp tolerance 300초)
  - constantTimeEqual로 타이밍 공격 방지
  - crypto.subtle.importKey/sign으로 HMAC 계산
- stripe-portal Edge Function 신규 (Customer Portal)
  - JWT 인증 -> 기존 customer_id 조회 -> billing_portal/sessions 생성
  - return_url 지원
- apps/web/components/billing/portal-button.tsx (구독 관리 버튼)
- billing 페이지에 Free 외 tier 사용자에게 PortalButton 표시
- config.toml에 stripe-portal 함수 등록 (verify_jwt=true)

묶음 D — V2-6b packages/ui-native:
- @d3ro/ui-native 신규 패키지 (React Native 전용 DS)
  - theme.ts: d3roNativePalette/Typo/Radius (MUI 없는 정적 값)
  - components/MetalCard.tsx: View + 섀시 섀도우
  - components/PhosphorText.tsx: Text + 앰버 glow (textShadow)
  - components/Led.tsx: View 원 + glow
  - components/PhysicalButton.tsx: Pressable + 누름 느낌
- React/React-Native는 peerDependencies
- apps/mobile/package.json에 @d3ro/ui-native를 file: 의존성으로 추가
  (mobile은 npm workspace 제외이므로 file path 필요)

검증:
- desktop typecheck OK
- web typecheck OK
- web next build OK (11 라우트, (app) 그룹 반영)
- 회귀 없음
2026-04-09 21:36:38 +09:00

281 lines
8.8 KiB
TypeScript

// src/renderer/components/CloudSyncSection.tsx
// Phase V2-4: Settings에 표시되는 Cloud Sync 섹션
// 로그인 상태 / Sync Now 버튼 / 마지막 동기화 / 환경변수 설정
import { useEffect, useState } from 'react'
import { Box, Button, Stack, TextField, Alert, CircularProgress } from '@mui/material'
import CloudIcon from '@mui/icons-material/Cloud'
import CloudDoneIcon from '@mui/icons-material/CloudDone'
import GoogleIcon from '@mui/icons-material/Google'
import GitHubIcon from '@mui/icons-material/GitHub'
import { d3roPalette, typoSx } from '@d3ro/ui/theme'
import { useI18n } from '@d3ro/i18n'
interface CloudSyncState {
authenticated: boolean
userEmail: string | null
lastSyncAt: number | null
syncing: boolean
}
interface SyncProgress {
current: number
total: number
table: string
}
export function CloudSyncSection(): React.ReactElement {
const { t: _t } = useI18n()
const [state, setState] = useState<CloudSyncState>({
authenticated: false,
userEmail: null,
lastSyncAt: null,
syncing: false
})
const [supabaseUrl, setSupabaseUrl] = useState('')
const [anonKey, setAnonKey] = useState('')
const [progress, setProgress] = useState<SyncProgress | null>(null)
const [error, setError] = useState<string | null>(null)
const [info, setInfo] = useState<string | null>(null)
const [busy, setBusy] = useState(false)
// 초기 상태 로드 + 이벤트 구독
useEffect(() => {
void window.electronAPI.cloudSync.getState().then((r) => {
if (r.success) setState(r.data)
})
// 저장된 supabase 설정 로드
void window.electronAPI.config.get({ key: 'supabaseUrl' as never }).then((r) => {
if (r.success && typeof r.data === 'string') setSupabaseUrl(r.data)
})
void window.electronAPI.config.get({ key: 'supabaseAnonKey' as never }).then((r) => {
if (r.success && typeof r.data === 'string') setAnonKey(r.data)
})
const unsubAuth = window.electronAPI.cloudSync.onAuthChanged((payload) => {
setState((prev) => ({
...prev,
authenticated: payload.user !== null,
userEmail: payload.user?.email ?? null
}))
})
const unsubProgress = window.electronAPI.cloudSync.onSyncProgress((p) => {
setProgress(p)
})
const unsubComplete = window.electronAPI.cloudSync.onSyncComplete((p) => {
setProgress(null)
setInfo(`동기화 완료: ${p.pushed}${p.errors.length > 0 ? ` (오류 ${p.errors.length})` : ''}`)
setBusy(false)
setState((prev) => ({ ...prev, syncing: false, lastSyncAt: Date.now() }))
})
const unsubError = window.electronAPI.cloudSync.onSyncError((p) => {
setProgress(null)
setError(p.error)
setBusy(false)
setState((prev) => ({ ...prev, syncing: false }))
})
return () => {
unsubAuth()
unsubProgress()
unsubComplete()
unsubError()
}
}, [])
async function handleConfigure(): Promise<void> {
setError(null)
setBusy(true)
try {
const r = await window.electronAPI.cloudSync.configure({ url: supabaseUrl, anonKey })
if (!r.success) {
setError(r.error.message)
} else {
setInfo('Supabase 연결 설정 저장됨')
}
} finally {
setBusy(false)
}
}
async function handleSignIn(provider: 'google' | 'github'): Promise<void> {
setError(null)
setBusy(true)
try {
const r = await window.electronAPI.cloudSync.signIn({ provider })
if (!r.success) {
setError(r.error.message)
} else {
setInfo('브라우저에서 로그인을 완료해주세요...')
}
} finally {
setBusy(false)
}
}
async function handleSignOut(): Promise<void> {
setBusy(true)
try {
await window.electronAPI.cloudSync.signOut()
setInfo('로그아웃되었습니다')
} finally {
setBusy(false)
}
}
async function handleSync(): Promise<void> {
setError(null)
setBusy(true)
setState((prev) => ({ ...prev, syncing: true }))
try {
await window.electronAPI.cloudSync.pushAll()
} finally {
// 완료/에러 이벤트로 setBusy(false) 처리됨
}
}
async function handlePull(): Promise<void> {
setError(null)
setBusy(true)
setState((prev) => ({ ...prev, syncing: true }))
try {
await window.electronAPI.cloudSync.pullAll()
} finally {
// 완료/에러 이벤트로 setBusy(false) 처리됨
}
}
const lastSyncText = state.lastSyncAt
? new Date(state.lastSyncAt).toLocaleString('ko-KR')
: '없음'
return (
<Box sx={{ p: 3, bgcolor: d3roPalette.bg.elevated, borderRadius: 2 }}>
<Stack direction="row" alignItems="center" spacing={1.5} sx={{ mb: 2 }}>
{state.authenticated ? (
<CloudDoneIcon sx={{ color: d3roPalette.tag.green }} />
) : (
<CloudIcon sx={{ color: d3roPalette.text.label }} />
)}
<Box sx={{ ...typoSx('heading'), color: d3roPalette.text.primary }}>Cloud Sync</Box>
</Stack>
{!state.authenticated && (
<Stack spacing={2}>
<Box sx={{ ...typoSx('label'), color: d3roPalette.text.label }}>
SUPABASE (env )
</Box>
<TextField
label="Supabase URL"
size="small"
value={supabaseUrl}
onChange={(e) => setSupabaseUrl(e.target.value)}
placeholder="https://your-project.supabase.co"
fullWidth
/>
<TextField
label="Anon Key"
size="small"
value={anonKey}
onChange={(e) => setAnonKey(e.target.value)}
placeholder="eyJ..."
type="password"
fullWidth
/>
<Button variant="outlined" onClick={() => void handleConfigure()} disabled={busy}>
</Button>
<Box sx={{ borderTop: `1px solid ${d3roPalette.border.subtle}`, pt: 2 }}>
<Box sx={{ ...typoSx('label'), color: d3roPalette.text.label, mb: 1 }}>OAuth </Box>
<Stack direction="row" spacing={1}>
<Button
variant="contained"
startIcon={<GoogleIcon />}
onClick={() => void handleSignIn('google')}
disabled={busy || !supabaseUrl || !anonKey}
>
Google
</Button>
<Button
variant="outlined"
startIcon={<GitHubIcon />}
onClick={() => void handleSignIn('github')}
disabled={busy || !supabaseUrl || !anonKey}
>
GitHub
</Button>
</Stack>
</Box>
</Stack>
)}
{state.authenticated && (
<Stack spacing={2}>
<Box sx={{ color: d3roPalette.text.primary, fontSize: 13 }}>
: <strong>{state.userEmail ?? '(이메일 없음)'}</strong>
</Box>
<Box sx={{ color: d3roPalette.text.muted, fontSize: 12 }}>
: {lastSyncText}
</Box>
{progress && (
<Box>
<Box sx={{ color: d3roPalette.text.label, fontSize: 12, mb: 0.5 }}>
{progress.table}: {progress.current}/{progress.total}
</Box>
<Box
sx={{
height: 4,
bgcolor: d3roPalette.bg.inset,
borderRadius: 2,
overflow: 'hidden'
}}
>
<Box
sx={{
height: '100%',
width: `${progress.total > 0 ? (progress.current / progress.total) * 100 : 0}%`,
bgcolor: d3roPalette.accent.amber,
transition: 'width 200ms'
}}
/>
</Box>
</Box>
)}
<Stack direction="row" spacing={1}>
<Button
variant="contained"
onClick={() => void handleSync()}
disabled={busy || state.syncing}
startIcon={state.syncing ? <CircularProgress size={16} /> : null}
>
{state.syncing ? '동기화 중...' : 'Push'}
</Button>
<Button
variant="outlined"
onClick={() => void handlePull()}
disabled={busy || state.syncing}
>
Pull
</Button>
<Button variant="outlined" onClick={() => void handleSignOut()} disabled={busy} color="warning">
</Button>
</Stack>
</Stack>
)}
{error && (
<Alert severity="error" sx={{ mt: 2 }} variant="outlined">
{error}
</Alert>
)}
{info && !error && (
<Alert severity="info" sx={{ mt: 2 }} variant="outlined">
{info}
</Alert>
)}
</Box>
)
}