// src/main/services/CloudSyncService.ts // Phase V2-4: Supabase 동기화 — OAuth 로그인, 세션 영속화, 기기 간 양방향 동기화 // Local-first: 데스크톱은 SQLite에서 바로 동작하고, Supabase(모바일·웹의 정본)와 양방향으로 맞춘다. // 실제 동기화는 services/sync/SyncEngine 이 한다 — 이 서비스는 인증·수명주기·트리거를 맡는다. import { EventEmitter } from 'events' import fs from 'fs' import path from 'path' import { app, safeStorage } from 'electron' import { createClient, type SupabaseClient, type Session, type User, type RealtimeChannel } from '@supabase/supabase-js' import { getLogger } from './LoggerService' import { configGet, configSet, onConfigChanged } from './ConfigService' import { SUPABASE_URL, SUPABASE_ANON_KEY } from '@d3ro/core/supabase-config' import { openForUser, openLocal, closeCurrent, getCurrentUserId, importLocalModeData, LOCAL_USER_ID, } from '../db' import { D3ROError, ErrorCode } from '@d3ro/core/errors' import type { LicenseTier } from '@d3ro/core/types' import { SyncEngine, type SyncStatus } from './sync/SyncEngine' import { SyncAbortedError } from './sync/sync-adapters' import { SyncScheduler } from './sync/sync-scheduler' import { EncryptedFileTokenStore, bindAuthEvents, type SessionTokenStore, type StoredSessionRecord, } from './sync/session-token-store' import { classifySessionRestoreFailure, sessionRestoreRetryDelayMs } from './sync/session-restore-policy' import { openExternalSafe } from '../windows/web-contents-hardening' import { SupabaseSyncRemote } from './sync/supabase-sync-remote' import { enqueueChange, getSyncState, setSyncState } from './sync/sync-outbox' import { checkInDesktopDevice, currentDeviceInfo, unregisterDesktopDevice } from './sync/device-registration' import { realtimeTables, type SyncEntity, type SyncRunResult } from './sync/sync-types' import { nodeRealtimeTransport } from './sync/realtime-transport' import { SETTINGS_ROW_ID, SYNCED_CONFIG_KEYS, isApplyingRemoteSettings } from './sync/settings-sync' import { AUDIO_BUCKET, listLocalAudioOwners } from './sync/audio-sync' const logger = getLogger('CloudSyncService') /** 로컬 변경을 모아서 보내는 지연 */ const FLUSH_DEBOUNCE_MS = 1_500 /** Realtime 이벤트가 몰릴 때 한 번만 가져오는 지연 */ const PULL_DEBOUNCE_MS = 1_500 /** 기기 생존 신호 + Realtime 누락 대비 전체 동기화 주기 */ const HEARTBEAT_MS = 5 * 60_000 /** sync_state 에 저장하는 이 사용자 DB의 등록 기기 id */ const DEVICE_STATE_KEY = 'device:id' /** 로그아웃·계정 전환 때 진행 중인 동기화가 멈추기를 기다리는 최대 시간 */ const ENGINE_STOP_TIMEOUT_MS = 5_000 /** 로그인 버튼을 누른 뒤 deep link 콜백을 받아들이는 시간 — 요청하지 않은 콜백(login CSRF)을 거른다 */ const SIGN_IN_WINDOW_MS = 10 * 60_000 /** refresh token 파일 이름(userData 아래) */ const TOKEN_FILE = 'cloud-sync.token' // ============================================================ // 타입 // ============================================================ interface SyncProgress { current: number total: number table: string } interface SyncResult { pushed: number errors: string[] } interface CloudSyncState { authenticated: boolean userEmail: string | null lastSyncAt: number | null syncing: boolean /** 아직 서버에 올라가지 않은 로컬 변경 수 */ pendingChanges: number /** 서버가 거부해 자동 재시도를 멈춘 변경 수 (수동 업로드로 재시도) */ failedChanges: number } interface CloudSyncEvents { 'auth-changed': (payload: { user: User | null }) => void 'sync-progress': (payload: SyncProgress) => void 'sync-complete': (payload: SyncResult) => void 'sync-error': (payload: { error: string }) => void /** 다른 기기의 변경이 로컬에 반영됨 — 화면 새로고침 신호 */ 'data-changed': (payload: { entities: SyncEntity[] }) => void } // ============================================================ // CloudSyncService // ============================================================ class CloudSyncService extends EventEmitter { private _client: SupabaseClient | null = null private _session: Session | null = null private _lastSyncAt: number | null = null private _syncing = false /** Realtime 재구독 지수 백오프 상태 (U1) */ private _realtimeRetryCount = 0 private _realtimeRetryTimer: NodeJS.Timeout | null = null private _initialized = false private _realtimeChannel: RealtimeChannel | null = null /** 진행 중인 startRealtime — 동시 호출을 하나로 합친다 */ private _realtimeStarting: Promise | null = null private _engine: SyncEngine | null = null /** 로그인 시작(startSignIn) 후 콜백을 받아들이는 기한. null이면 진행 중인 로그인이 없다 */ private _pendingSignInUntil: number | null = null private _tokenStore: SessionTokenStore | null = null private _unbindAuthEvents: (() => void) | null = null /** * 로그인된 계정이지만 세션을 아직 복원하지 못한 상태(오프라인으로 시작 등)의 계정 id. * 이 동안 기록은 그 계정 DB 에 쓰이고 outbox 에 쌓였다가, 복원되면 올라간다. 세션이 있으면 null. */ private _offlineUserId: string | null = null private _restoreRetryTimer: NodeJS.Timeout | null = null private _restoreAttempt = 0 /** _onSignOut 진행 중 — 자기 signOut() 이 일으킨 SIGNED_OUT 을 다시 처리하지 않게 */ private _signingOut = false private readonly _scheduler = new SyncScheduler({ flushDelayMs: FLUSH_DEBOUNCE_MS, pullDelayMs: PULL_DEBOUNCE_MS, heartbeatMs: HEARTBEAT_MS, run: (kind) => void this._runEngine(kind).catch(() => undefined), onHeartbeat: () => this._onHeartbeat(), }) /** * 초기화 — Supabase 클라이언트 생성, 저장된 세션 복원. * Supabase URL/KEY가 설정되지 않았으면 disabled 상태로 남는다. */ async init(): Promise { if (this._initialized) return this._initialized = true this._client = this._createClient() this._lastSyncAt = (configGet('cloudSyncLastAt') as number | undefined) ?? null this._bindClientAuthEvents(this._client) // 언어·테마·자동 다듬기·활성 명령이 바뀌면 모바일 user_settings 로 올린다(원격 반영 중엔 제외). onConfigChanged((event) => { if (isApplyingRemoteSettings()) return if ((SYNCED_CONFIG_KEYS as readonly string[]).includes(event.key)) { this.pushOne('user_settings', SETTINGS_ROW_ID) } // 녹음 동기화를 켜면 그동안 올리지 않은 녹음을 올린다. if (event.key === 'cloudSyncAudio' && event.value === true && this._engine) { try { for (const id of listLocalAudioOwners('history')) this.pushOne('history_audio', id) for (const id of listLocalAudioOwners('meeting')) this.pushOne('meeting_audio', id) } catch (err) { logger.warn(`Audio re-queue failed: ${err instanceof Error ? err.message : String(err)}`) } } }) // 저장된 refresh token 복원 const stored = this._loadStoredSession() if (stored) { await this._restoreSession(stored) } else { // 저장된 토큰 없음 → 미인증 상태를 렌더러에 명시 전달 this.emit('auth-changed', { user: null }) } logger.info('CloudSyncService initialized') } private _createClient(): SupabaseClient { return createClient(SUPABASE_URL, SUPABASE_ANON_KEY, { auth: { persistSession: false, // 직접 관리 autoRefreshToken: true, detectSessionInUrl: false }, // Electron 33 메인 프로세스(Node 20)에는 전역 WebSocket이 없다. 주입하지 않으면 Realtime이 // 연결조차 못 하고 TIMED_OUT/CLOSED만 반복한다(2026-09-16 설치본 로그) — 다른 기기의 변경이 // 실시간으로 오지 않던 원인. realtime: { transport: nodeRealtimeTransport } }) } /** * supabase-js는 메인 프로세스에서 refresh token을 주기적으로 회전시킨다. 회전된 토큰과 access token을 * 매번 저장·갱신해야 재시작 복원과 Realtime 재구독이 이미 쓰인/만료된 토큰을 쓰지 않는다. */ private _bindClientAuthEvents(client: SupabaseClient): void { this._unbindAuthEvents?.() this._unbindAuthEvents = bindAuthEvents( (callback) => client.auth.onAuthStateChange((event, session) => callback(event, session)).data.subscription, this._tokens(), () => this._session?.user.id ?? null, (session) => { this._session = session }, () => this._onRemoteSignedOut() ) } /** * 이 기기의 Supabase 세션을 서버 결과와 무관하게 버린다. * auth-js signOut 은 오프라인·5xx 면 { error } 를 돌려주고 _removeSession 을 건너뛰어, 클라이언트가 * 옛 계정 세션을 계속 들고 자동 갱신한다(Cloud STT·realtime-token 이 로그아웃 뒤에도 그 계정으로 돌던 원인). * 공개 API 로는 메모리 세션만 지울 수 없으므로, 실패하면 자동 갱신을 멈추고 클라이언트를 새로 만든다. */ private async _revokeLocalSession(): Promise { const client = this._client if (!client) return let failure: string | null = null try { const { error } = await client.auth.signOut({ scope: 'local' }) if (error) failure = error.message } catch (err) { failure = err instanceof Error ? err.message : String(err) } if (failure === null) return logger.warn(`signOut did not clear the client session (${failure}) — discarding the auth client`) await client.auth.stopAutoRefresh().catch(() => undefined) if (this._client !== client) return const fresh = this._createClient() this._client = fresh this._bindClientAuthEvents(fresh) } /** * 저장된 계정 id (없거나 구버전 토큰 파일이면 null). bootstrap 이 세션 복원을 기다리지 않고 * 그 계정 DB 를 먼저 열어, 복원 중·오프라인 동안의 기록이 익명 DB 로 새지 않게 한다. */ peekStoredAccountUserId(): string | null { try { return this._loadStoredSession()?.userId ?? null } catch { return null } } // ── 세션 복원 (시작 시 + 오프라인 재시도) ───────────────── private async _restoreSession(stored: StoredSessionRecord): Promise { const client = this._client if (!client) return try { const { data, error } = await client.auth.refreshSession({ refresh_token: stored.refreshToken }) if (this._session) return // 기다리는 동안 사용자가 새로 로그인했다 if (error) { this._handleRestoreFailure(error, error.message, stored) return } if (!data.session) { this._handleRestoreFailure(null, 'refreshSession returned no session', stored) return } this._saveRefreshToken(data.session.refresh_token, data.session.user.id) logger.info(`Restored session for user: ${data.session.user.email ?? data.session.user.id}`) // 단일 진입점으로 수렴 — DB open + auth-changed emit + Realtime 시작 await this._onAuthenticated(data.session, { reason: 'restore' }) } catch (err) { if (this._session) return this._handleRestoreFailure(err, err instanceof Error ? err.message : String(err), stored) } } /** * 복원 실패 처리. 서버가 토큰을 확실히 거부했을 때만 토큰을 지우고 로그아웃한다. * 네트워크·서버 일시 오류면 토큰을 보관하고, 저장된 계정 DB 에서 오프라인으로 계속 동작하며 * 백오프로 다시 시도한다(예전엔 어떤 오류든 토큰을 지워, 오프라인 시작만으로 로그아웃되고 * 그 뒤 기록이 익명 DB 에 갇혔다). */ private _handleRestoreFailure(error: unknown, message: string, stored: StoredSessionRecord): void { if (classifySessionRestoreFailure(error) === 'invalid') { // U3: 재인증 필요를 사용자에게 알린다(조용히 토큰만 지우면 "왜 로그아웃됐지?" 상태로 방치된다). logger.error(`세션 복원 실패 — 재로그인 필요: ${message} (토큰 만료 또는 서버 세션 무효화)`) this._cancelRestoreRetry() this._offlineUserId = null this._clearStoredRefreshToken() this._revertToLocalDatabase('restore-invalid') this.emit('sync-error', { error: `Sign-in session expired. Please sign in again. (${message})` }) this.emit('auth-changed', { user: null }) return } logger.warn(`세션 복원 보류(일시 오류) — 토큰 보관, 나중에 다시 시도: ${message}`) const firstFailure = this._restoreAttempt === 0 && this._offlineUserId === null if (stored.userId) this._enterOfflineAccount(stored.userId) this._scheduleRestoreRetry() if (firstFailure) { this.emit('sync-error', { error: `Could not reach the sync server. You are still signed in; sync resumes automatically when the connection is back. (${message})`, }) this.emit('auth-changed', { user: null }) } } /** 세션 없이 저장된 계정 DB 로 동작한다(쓰기는 outbox 에 쌓인다). */ private _enterOfflineAccount(userId: string): void { if (getCurrentUserId() !== userId) { try { openForUser(userId) } catch (err) { logger.warn(`Offline account DB open failed (staying in current DB): ${err instanceof Error ? err.message : String(err)}`) return } } this._offlineUserId = userId } private _scheduleRestoreRetry(): void { if (this._restoreRetryTimer) return const delay = sessionRestoreRetryDelayMs(this._restoreAttempt) this._restoreAttempt++ logger.info(`Session restore retry #${this._restoreAttempt} in ${delay}ms`) this._restoreRetryTimer = setTimeout(() => { this._restoreRetryTimer = null if (this._session) return const stored = this._loadStoredSession() if (!stored) return void this._restoreSession(stored) }, delay) this._restoreRetryTimer.unref?.() } private _cancelRestoreRetry(): void { if (this._restoreRetryTimer) { clearTimeout(this._restoreRetryTimer) this._restoreRetryTimer = null } this._restoreAttempt = 0 } /** 로그인되지 않은 상태로 돌아갈 때 익명 로컬 DB 로 되돌린다(이미 로컬이면 그대로). */ private _revertToLocalDatabase(reason: string): void { if (getCurrentUserId() === LOCAL_USER_ID) return try { const { dbPath } = openLocal() logger.info(`[${reason}] Reverted to local DB: ${dbPath}`) } catch (err) { logger.error(`[${reason}] Local DB reopen failed: ${err instanceof Error ? err.message : String(err)}`) } } /** * auth 클라이언트가 세션을 버렸다(SIGNED_OUT) — 다른 기기의 전역 로그아웃, 토큰 폐기 등. * 예전엔 무시해 엔진·Realtime 이 익명 키로 계속 돌며 푸시가 RLS 에 막히고, 5분 뒤 heartbeat 가 * "다른 기기에서 연결 해제됨"이라는 틀린 사유로 로그아웃시켰다. */ private _onRemoteSignedOut(): void { if (this._signingOut || !this._session) return logger.warn('Auth session ended outside this app (SIGNED_OUT) — signing out locally') void this._onSignOut({ unregister: false }) .then(() => { this.emit('sync-error', { error: 'Your sign-in session has ended (signed out elsewhere or expired). Sign in again to keep syncing.', }) }) .catch((err) => { logger.warn(`Remote sign-out cleanup failed: ${err instanceof Error ? err.message : String(err)}`) }) } // ── 인증 lifecycle 단일 진입점 ───────────────────────── /** * 세션이 인증된 직후 호출되는 단일 진입점. * - 사용자별 DB 오픈 * - auth-changed emit (renderer 게이트 해제) * - Realtime 구독 시작 * init()의 세션 복원과 handleAuthCallback()의 신규 로그인 모두 여기로 수렴한다. */ private async _onAuthenticated( session: Session, opts: { reason: 'restore' | 'signin' } ): Promise { const userId = session.user.id // 로그인(또는 복원) 성공 — 오프라인 재시도는 더 필요 없다. this._cancelRestoreRetry() // 0) 이전 계정의 동기화를 먼저 멈춘다 — 새 DB가 열린 뒤 이전 엔진이 그 DB에 쓰지 않게. const previous = this._engine this._engine = null if (previous) { previous.dispose() await previous.whenIdle(ENGINE_STOP_TIMEOUT_MS) } // 다른 계정 DB 로 바뀌기 전에 진행 중인 받아쓰기·회의를 지금 DB 에 끝낸다. 그대로 두면 정지 시점의 // 저장·업로드가 새 계정 DB·저장소로 들어갔다(오프라인 복원 대기 중 다른 계정으로 로그인한 경우). const openUserId = getCurrentUserId() if (openUserId !== null && openUserId !== userId) { await this._stopActiveCapture(`auth:${opts.reason}`) } this._session = session this._offlineUserId = null // 1) 사용자별 DB 열기 (Phase 1 — 사용자별 SQLite 격리) // 이 시점부터 이 계정 DB 의 쓰기는 엔진이 만들어지기 전에도 outbox 에 기록된다(_recordChange). try { const { created, dbPath } = openForUser(userId) logger.info( `[auth:${opts.reason}] DB opened for ${userId}: ${dbPath} (created=${created})` ) } catch (err) { const message = err instanceof Error ? err.message : String(err) logger.error(`[auth:${opts.reason}] DB open failed for ${userId}: ${message}`) // DB를 열지 못하면 로그인 상태를 유지해서는 안 된다 — 즉시 signOut. // openForUser 는 실패해도 이전 DB 를 닫지 않는다. 그것이 다른 계정의 DB 면 로컬로 되돌린다. this._session = null this._clearStoredRefreshToken() this._revertToLocalDatabase(`auth:${opts.reason}`) this.emit('sync-error', { error: `Database open failed: ${message}` }) this.emit('auth-changed', { user: null }) return } // 2) Supabase `subscriptions` 테이블에서 현재 티어 가져와 LicenseService에 동기화 // (빅뱅 Phase 4 — 티어 enforcement) // 다른 계정으로 바로 바뀌는 경우엔 이전 계정의 캐시 티어를 먼저 버린다 — 조회가 실패하면 // 이전 계정의 Pro 배지·광고 판정이 새 계정에 남고, 저장값이라 재시작 후에도 이어졌다. const switchedAccount = openUserId !== null && openUserId !== userId try { const { getLicenseService } = await import('./LicenseService') if (switchedAccount) getLicenseService().resetToFree() const tier = await this._fetchSubscriptionTier(userId) getLicenseService().syncFromCloud(tier) } catch (err) { logger.warn( `[auth:${opts.reason}] Subscription tier sync failed (falling back to free): ${ err instanceof Error ? err.message : String(err) }` ) } // 3) 로그인 전 익명 로컬 모드에서 쌓인 기록을 이 계정 DB로 가져온다(최초 1회). // 가져온 행은 아래 최초 대조가 서버로 올려 모바일에서도 보인다. try { importLocalModeData() } catch (err) { logger.warn( `[auth:${opts.reason}] Local-mode import failed: ${err instanceof Error ? err.message : String(err)}` ) } // 4) 동기화 엔진 — 사용자 DB가 열린 뒤, 이 사용자 전용으로 만든다(엔진은 이 DB에 묶인다). // 이전 엔진은 0)에서 이미 해제했다. if (this._client) { const engine = new SyncEngine({ remote: new SupabaseSyncRemote(this._client), userId }) engine.on('progress', (payload) => this.emit('sync-progress', payload)) this._engine = engine } // 5) renderer 게이트 해제 — DB가 열리고 티어가 반영된 뒤에 emit this.emit('auth-changed', { user: session.user }) // 6) Realtime 구독 자동 시작 void this.startRealtime().catch((err) => { logger.warn( `Realtime 자동 시작 실패: ${err instanceof Error ? err.message : String(err)}` ) }) // 7) 이 데스크톱을 계정의 기기 목록에 등록(모바일 "연결된 기기"), 주기 점검 시작 void this._checkInDevice(opts.reason) this._startHeartbeat() // 8) 최초 동기화: 대조(1회) → 로컬 변경 push → 원격 변경·삭제 pull. // fire-and-forget — UI는 이미 해제됨. 실패해도 outbox에 남아 다음 트리거에 재시도된다. void this._runEngine('full') .then((result) => { logger.info( `[auth:${opts.reason}] Initial sync done: pushed=${result.pushed} pulled=${result.pulled} deleted=${result.deleted} errors=${result.errors.length}` ) }) .catch((err) => { logger.warn( `[auth:${opts.reason}] Initial sync failed: ${err instanceof Error ? err.message : String(err)}` ) }) } /** * 빅뱅 Phase 4: Supabase `subscriptions` 테이블에서 사용자의 현재 티어를 조회. * - row 없음 → 'free' (auth trigger가 가입 시 자동 생성하므로 거의 발생 안 함) * - tier 값 비정상 → 'free' * - 네트워크 실패 → throw (caller가 warn + 현재 티어 유지) */ private async _fetchSubscriptionTier(userId: string): Promise { if (!this._client) { throw new D3ROError(ErrorCode.LLMServerUnreachable, 'Supabase client not initialized') } const { data, error } = await this._client .from('subscriptions') .select('tier, status') .eq('user_id', userId) .eq('status', 'active') .maybeSingle() if (error) { throw new Error(error.message) } if (!data) return 'free' const tier = data.tier as LicenseTier if (tier === 'pro' || tier === 'pro_plus' || tier === 'team' || tier === 'enterprise' || tier === 'free') { return tier } return 'free' } /** * signOut 전 in-flight 세션/녹음을 안전하게 중단시키는 단일 진입점. * VoiceMode/MeetingMode/Caption 진행 중이면 먼저 멈추고, 그 다음 Realtime stop, * 그 다음 auth-changed(null) emit, 마지막으로 DB close. */ private async _onSignOut(options: { unregister: boolean } = { unregister: true }): Promise { if (this._signingOut) return this._signingOut = true try { await this._runSignOut(options) } finally { this._signingOut = false } } /** 진행 중인 받아쓰기·회의 녹음·자막을 지금 열린 DB 에 끝낸다(DB 를 닫거나 바꾸기 전). */ private async _stopActiveCapture(tag: string): Promise { try { const { getVoiceModeService } = await import('./VoiceModeService') const voiceMode = getVoiceModeService() if (voiceMode.isActive) { voiceMode.cancelSession() logger.info(`[${tag}] VoiceMode active session cancelled`) } } catch (err) { logger.warn( `[${tag}] VoiceMode cancel failed: ${err instanceof Error ? err.message : String(err)}` ) } try { const { getMeetingModeService } = await import('./MeetingModeService') const meetingMode = getMeetingModeService() if (meetingMode.isMeetingModeActive()) { await meetingMode.stopRecording() logger.info(`[${tag}] MeetingMode recording stopped`) } } catch (err) { logger.warn( `[${tag}] MeetingMode stop failed: ${err instanceof Error ? err.message : String(err)}` ) } try { const { getCaptionService } = await import('./CaptionService') const captionService = getCaptionService() await captionService.stop() } catch (err) { logger.warn( `[${tag}] Caption stop failed: ${err instanceof Error ? err.message : String(err)}` ) } } private async _runSignOut(options: { unregister: boolean }): Promise { // 오프라인 복원 대기도 끝낸다 — 로그아웃한 계정의 토큰으로 다시 복원하지 않게. this._cancelRestoreRetry() this._offlineUserId = null // 1) 활성 녹음/세션 강제 종료 (DB close 전에 flush 기회 제공) await this._stopActiveCapture('signOut') // 2) Realtime 구독·주기 작업 종료, 엔진 해제 await this.stopRealtime() this._stopHeartbeat() const engine = this._engine engine?.dispose() this._engine = null // 3) 사용자가 직접 로그아웃하면 기기 목록에서도 빠진다(원격 해제로 로그아웃될 때는 이미 해제됨). if (options.unregister && this._client && this._session) { await unregisterDesktopDevice(this._client).catch(() => undefined) } // 4) Supabase 세션 무효화 — 이 기기의 세션만(scope:'local'). // 기본값 'global' 은 계정의 모든 refresh token 을 폐기해 휴대폰·다른 PC 까지 로그아웃시켰다. // 서버가 실패를 돌려줘도 클라이언트의 세션은 반드시 버린다(_revokeLocalSession). if (this._client && this._session) { await this._revokeLocalSession() } // 4) in-memory 상태 + 저장된 토큰 clear this._session = null this._clearStoredRefreshToken() // 5) LicenseService 티어를 free로 리셋 (빅뱅 Phase 4 — 익명 로컬 모드) // pro/pro_plus 캐시가 남아있으면 premium feature gate가 이상하게 동작 try { const { getLicenseService } = await import('./LicenseService') getLicenseService().resetToFree() } catch (err) { logger.warn( `[signOut] License reset failed: ${err instanceof Error ? err.message : String(err)}` ) } // 6) 사용자 DB 닫고 로컬 모드 DB로 복귀 // — 로그아웃 후에도 앱은 익명 로컬 모드로 계속 동작 (entry point 철학) // 진행 중이던 pull이 끝나기를(최대 ENGINE_STOP_TIMEOUT_MS) 기다린다. 해제된 엔진은 다음 await에서 멈추고, // 시간이 넘어도 사용자 DB 검사가 로컬 모드 DB에 쓰는 것을 막는다. if (engine && !(await engine.whenIdle(ENGINE_STOP_TIMEOUT_MS))) { logger.warn('[signOut] Sync engine did not stop in time — continuing (writes are blocked by user DB guard)') } closeCurrent() try { const { dbPath } = openLocal() logger.info(`[signOut] Reverted to local DB: ${dbPath}`) } catch (err) { logger.error( `[signOut] Local DB reopen failed: ${err instanceof Error ? err.message : String(err)}` ) } // 7) renderer에 auth-changed(null) emit — Settings는 다시 로그인 화면으로, // 메인 UI는 로컬 모드로 계속 동작 this.emit('auth-changed', { user: null }) logger.info('Signed out — continuing in local mode') } // ── 상태 조회 ────────────────────────────────────────── isEnabled(): boolean { return this._client !== null } isAuthenticated(): boolean { return this._session !== null } getUser(): User | null { return this._session?.user ?? null } /** * Phase 3.2: Premium LLM proxy 호출 시 Supabase Edge Function Authorization * 헤더에 사용할 JWT access token 반환. null이면 비로그인 상태. * * 중요: 캐시된 _session이 아닌 Supabase 클라이언트에서 최신 세션을 직접 가져옴. * _session은 로그인 시점에만 설정되지만, Supabase 클라이언트 내부에서 자동 * refresh된 토큰은 _session에 반영되지 않아 stale JWT가 될 수 있음. */ async getAccessToken(): Promise { return this._currentAccessToken() } /** * 자격 증명의 단일 관문 — 이 서비스가 로그아웃 상태(_session=null)면 클라이언트에 무엇이 남아 있든 null. * 기다리는 동안 계정이 바뀌거나 로그아웃되면 그 토큰도 버린다. */ private async _currentAccessToken(): Promise { const client = this._client const session = this._session if (!client || !session) return null const { data } = await client.auth.getSession() if (this._client !== client || this._session?.user.id !== session.user.id) return null const current = data.session if (!current || current.user?.id !== session.user.id) return null return current.access_token ?? null } /** * Phase 3.2: Edge Function 호출을 위한 Supabase 프로젝트 URL. * 없으면 SaaS 미설정 상태. */ getSupabaseUrl(): string | null { const url = configGet('supabaseUrl') as string | undefined return url ?? null } /** * Phase 3.2: Edge Function 호출 시 apikey 헤더에 필요한 anon key. */ getAnonKey(): string | null { const key = configGet('supabaseAnonKey') as string | undefined return key ?? null } /** * Phase 3.2: Supabase Edge Function 호출 — 클라이언트가 auth 헤더를 올바르게 처리. * raw fetch 대신 이걸 사용해야 gateway 레벨 401 방지. */ async invokeFunction( name: string, body: Record | FormData, options?: { signal?: AbortSignal; timeoutMs?: number } ): Promise<{ data: unknown; error: { message: string } | null }> { if (!this._client) { return { data: null, error: { message: 'Supabase client not initialized' } } } // 최신 세션 확보 (auto-refresh 보장) — 로그아웃 상태면 클라이언트에 남은 세션을 쓰지 않는다 const token = await this._currentAccessToken() if (!token || !this._client) { return { data: null, error: { message: 'No active session — 로그인 필요' } } } const { data, error } = await this._client.functions.invoke(name, { body, headers: { Authorization: `Bearer ${token}` }, signal: options?.signal, timeout: options?.timeoutMs }) if (error) { let detail = error.message ?? String(error) try { if ('context' in error && error.context instanceof Response) { const respBody = await (error.context as Response).json() detail = JSON.stringify(respBody) } } catch { // body 파싱 실패 시 기본 메시지 사용 } return { data: null, error: { message: detail } } } return { data, error: null } } /** * Edge Function 스트리밍 호출 — SSE 응답의 ReadableStream 반환. * Supabase JS의 functions.invoke()는 JSON 자동 파싱하므로 SSE에 부적합. * raw fetch + auth 토큰으로 직접 호출. */ async invokeFunctionStream( name: string, body: Record, signal?: AbortSignal, ): Promise<{ stream: ReadableStream | null; error: { message: string } | null }> { if (!this._client) { return { stream: null, error: { message: 'Supabase client not initialized' } } } const token = await this._currentAccessToken() if (!token) { return { stream: null, error: { message: 'No active session — 로그인 필요' } } } const url = configGet('supabaseUrl') as string | undefined const anonKey = configGet('supabaseAnonKey') as string | undefined if (!url || !anonKey) { return { stream: null, error: { message: 'Supabase URL/key not configured' } } } try { const response = await fetch(`${url}/functions/v1/${name}`, { method: 'POST', headers: { Authorization: `Bearer ${token}`, apikey: anonKey, 'Content-Type': 'application/json', }, body: JSON.stringify(body), signal, }) if (!response.ok) { const text = await response.text() return { stream: null, error: { message: `${response.status}: ${text}` } } } if (!response.body) { return { stream: null, error: { message: 'No response body' } } } return { stream: response.body, error: null } } catch (err) { if ((err as Error).name === 'AbortError') { return { stream: null, error: { message: 'Request aborted' } } } return { stream: null, error: { message: err instanceof Error ? err.message : String(err) } } } } /** 세션은 없지만 저장된 계정으로 오프라인 동작 중인지 (복원 재시도 대기) */ isOfflineAccount(): boolean { return this._session === null && this._offlineUserId !== null } getState(): CloudSyncState { const status = this.getSyncStatus() return { authenticated: this.isAuthenticated(), userEmail: this._session?.user?.email ?? null, lastSyncAt: this._lastSyncAt, syncing: this._syncing, pendingChanges: status?.pending ?? 0, failedChanges: status?.parked ?? 0, } } getLastSyncAt(): Date | null { return this._lastSyncAt ? new Date(this._lastSyncAt) : null } // ── Realtime 구독 ────────────────────────────────────── /** * 원격 변경사항을 실시간으로 구독한다. * 동기화 대상 테이블·삭제 기록(sync_tombstones)에 변경이 오면 debounce 후 pull, * devices 변경이 오면 이 기기의 연결 해제 여부를 확인한다. * 중복 호출 방지를 위해 기존 채널이 있으면 먼저 해제. */ startRealtime(): Promise { // heartbeat·재시도 타이머·인증 처리가 동시에 부를 수 있다. 겹치면 realtime-js 가 같은 topic 의 // 기존 채널 객체를 돌려줘 postgres_changes 바인딩이 호출마다 중복으로 쌓였다 — 한 번에 하나만 돈다. if (!this._realtimeStarting) { this._realtimeStarting = this._startRealtime().finally(() => { this._realtimeStarting = null }) } return this._realtimeStarting } private async _startRealtime(): Promise { if (!this._client || !this._session) { logger.warn('Realtime 시작 불가 — 로그인 필요') return } if (this._realtimeChannel) { const previous = this._realtimeChannel this._realtimeChannel = null // unsubscribe 만 하면 클라이언트 레지스트리에 채널이 남아 같은 topic 으로 재사용된다 await this._client.removeChannel(previous) } const userId = this._session.user.id // postgres_changes 채널이 RLS를 통과하도록 access token을 realtime에 넣는다(TIMED_OUT 버그 픽스). // 로그인 시점의 토큰은 1시간 뒤 만료되므로, 클라이언트의 현재 세션(필요하면 갱신)에서 꺼낸다 — // 만료된 토큰으로 재구독하면 CHANNEL_ERROR만 반복한다. try { const { data } = await this._client.auth.getSession() if (!this._session || !this._client) return await this._client.realtime.setAuth(data.session?.access_token ?? this._session.access_token) } catch (err) { logger.warn( `Realtime setAuth 실패 (계속 진행): ${err instanceof Error ? err.message : String(err)}` ) } if (!this._session || !this._client) return let channel = this._client.channel(`cloud-sync:${userId}`) for (const table of realtimeTables()) { channel = channel.on( 'postgres_changes', { event: '*', schema: 'public', table, filter: `user_id=eq.${userId}` }, () => this._schedulePull() ) } // 이 계정의 기기 목록이 바뀌면(다른 기기에서 연결 해제 포함) 등록 상태를 다시 확인한다. channel = channel.on( 'postgres_changes', { event: '*', schema: 'public', table: 'devices', filter: `user_id=eq.${userId}` }, () => void this._checkInDevice('heartbeat') ) const subscribed = channel.subscribe((status) => { // 교체된 이전 채널의 CLOSED 는 무시한다 — 재구독을 다시 예약해 채널이 겹치게 된다 if (this._realtimeChannel !== subscribed) return logger.info(`Realtime 채널 상태: ${status}`) // U1: TIMED_OUT / CHANNEL_ERROR / CLOSED 시 지수 백오프 자동 재구독. // Supabase realtime은 네트워크 jitter로 간헐적 TIMED_OUT이 발생할 수 있고, // 이때 기본 fallback(Phase 3.3 auto push)은 동작하지만 다른 기기 변경은 놓친다. // 1s → 3s → 10s 3회 시도 후 포기. 성공(SUBSCRIBED) 시 카운터 리셋. if (status === 'SUBSCRIBED') { this._realtimeRetryCount = 0 if (this._realtimeRetryTimer) { clearTimeout(this._realtimeRetryTimer) this._realtimeRetryTimer = null } return } if (status === 'TIMED_OUT' || status === 'CHANNEL_ERROR' || status === 'CLOSED') { this._scheduleRealtimeRetry() } }) this._realtimeChannel = subscribed } /** * Realtime 재구독 지수 백오프 스케줄러 (U1). * - 1차: 1s, 2차: 3s, 3차: 10s * - 3회 초과 시 포기 (Auto push fallback만으로 동작) * - 이미 스케줄돼 있으면 no-op (중복 방지) */ private _scheduleRealtimeRetry(): void { if (this._realtimeRetryTimer) return if (!this._client || !this._session) return const MAX_RETRIES = 3 const DELAYS_MS = [1000, 3000, 10000] if (this._realtimeRetryCount >= MAX_RETRIES) { logger.warn( `Realtime 재구독 ${MAX_RETRIES}회 실패 — Auto push fallback으로만 동작. 수동 재시도: cloudSync.startRealtime()` ) return } const delay = DELAYS_MS[this._realtimeRetryCount] this._realtimeRetryCount++ const attempt = this._realtimeRetryCount logger.info(`Realtime 재구독 예약 (${attempt}/${MAX_RETRIES}): ${delay}ms 후`) this._realtimeRetryTimer = setTimeout(() => { this._realtimeRetryTimer = null if (!this._session) return void this.startRealtime().catch((err) => { logger.warn( `Realtime 재구독 실패 (${attempt}/${MAX_RETRIES}): ${err instanceof Error ? err.message : String(err)}` ) }) }, delay) } async stopRealtime(): Promise { if (this._realtimeRetryTimer) { clearTimeout(this._realtimeRetryTimer) this._realtimeRetryTimer = null } this._realtimeRetryCount = 0 if (this._realtimeChannel) { const channel = this._realtimeChannel this._realtimeChannel = null if (this._client) await this._client.removeChannel(channel) else await channel.unsubscribe() logger.info('Realtime 채널 종료') } } // ── OAuth 로그인 ─────────────────────────────────────── /** * OAuth 로그인 시작 — Supabase가 발급한 URL을 외부 브라우저로 열기. * 사용자가 동의 후 d3ro-voice://auth-callback?code=...로 deep link 호출됨. */ async startSignIn(provider: 'google' | 'github'): Promise { if (!this._client) { throw new D3ROError(ErrorCode.LLMServerUnreachable, 'Cloud Sync가 설정되지 않았습니다') } const redirectTo = 'd3ro-voice://auth-callback' const { data, error } = await this._client.auth.signInWithOAuth({ provider, options: { redirectTo, skipBrowserRedirect: true } }) if (error || !data.url) { throw new D3ROError( ErrorCode.LLMProcessingFailed, `OAuth 시작 실패: ${error?.message ?? 'unknown'}` ) } // 이 앱이 요청한 로그인만 받아들인다: 콜백은 이 시각 이후 한 번만 유효하다. this._pendingSignInUntil = Date.now() + SIGN_IN_WINDOW_MS logger.info(`Opening OAuth URL in external browser: ${provider}`) if (!(await openExternalSafe(data.url))) { this._pendingSignInUntil = null throw new D3ROError(ErrorCode.LLMProcessingFailed, 'OAuth URL is not an https URL') } } /** * deep link 로그인 콜백을 받아들일지. 사용자가 방금 로그인을 시작했고(startSignIn) 이미 로그인된 상태가 * 아닐 때만 한 번 허용한다 — 아무 웹페이지나 d3ro-voice://auth-callback#access_token=... 으로 앱을 * 공격자 계정에 로그인시켜 로컬 기록을 그 계정으로 올리게 하는 것(login CSRF)을 막는다. */ private _consumePendingSignIn(): void { const until = this._pendingSignInUntil this._pendingSignInUntil = null if (until === null || Date.now() > until) { throw new D3ROError(ErrorCode.LLMProcessingFailed, 'Ignored sign-in callback: no sign-in was started from this app') } if (this._session) { throw new D3ROError(ErrorCode.LLMProcessingFailed, 'Ignored sign-in callback: already signed in — sign out first') } } /** * Deep link 콜백 처리 — PKCE flow code를 session으로 교환. * 성공 시 _onAuthenticated(단일 진입점)로 수렴. */ async handleAuthCallback(code: string): Promise { if (!this._client) { throw new D3ROError(ErrorCode.LLMServerUnreachable, 'Cloud Sync가 설정되지 않았습니다') } this._consumePendingSignIn() const { data, error } = await this._client.auth.exchangeCodeForSession(code) if (error || !data.session) { throw new D3ROError( ErrorCode.LLMProcessingFailed, `세션 교환 실패: ${error?.message ?? 'unknown'}` ) } this._saveRefreshToken(data.session.refresh_token, data.session.user.id) logger.info(`Signed in: ${data.session.user.email ?? data.session.user.id}`) await this._onAuthenticated(data.session, { reason: 'signin' }) } /** * Deep link 콜백 처리 — Implicit flow로 받은 access/refresh token을 * client.auth.setSession()에 주입하여 세션 복원. * * supabase-js가 `persistSession: false`로 떠 있을 때 PKCE code_verifier 저장이 * 없어서 PKCE가 제대로 동작하지 않는다. Supabase가 implicit flow로 떨어져 * fragment(#access_token=...&refresh_token=...)에 토큰을 담아 보내는데, 이때 * 이 메서드를 사용한다. */ async handleAuthTokens(params: { accessToken: string refreshToken: string }): Promise { if (!this._client) { throw new D3ROError(ErrorCode.LLMServerUnreachable, 'Cloud Sync가 설정되지 않았습니다') } this._consumePendingSignIn() const { data, error } = await this._client.auth.setSession({ access_token: params.accessToken, refresh_token: params.refreshToken, }) if (error || !data.session) { throw new D3ROError( ErrorCode.LLMProcessingFailed, `세션 설정 실패: ${error?.message ?? 'unknown'}` ) } this._saveRefreshToken(data.session.refresh_token, data.session.user.id) logger.info(`Signed in (implicit): ${data.session.user.email ?? data.session.user.id}`) await this._onAuthenticated(data.session, { reason: 'signin' }) } /** * 로그아웃 — 단일 진입점 _onSignOut에서 세션/DB/녹음 모두 안전하게 정리. */ async signOut(): Promise { await this._onSignOut() } // ── 동기화 ───────────────────────────────────────────── /** * 로컬 변경 기록(outbox) + 짧은 지연 뒤 push. * 로그인 상태가 아니면(익명 로컬 모드) 기록하지 않는다 — 로그인 시 최초 대조가 올린다. */ pushOne(entity: SyncEntity, id: string): void { this._recordChange(entity, id, 'upsert') } /** 로컬 삭제를 다른 기기로 전파한다. */ pushDelete(entity: SyncEntity, id: string): void { this._recordChange(entity, id, 'delete') } /** * 변경을 이 계정 DB 의 outbox 에 기록한다. 엔진이 아직 없어도(로그인 직후 티어 조회 중, * 오프라인 복원 대기 중) 기록한다 — 예전엔 버려져 최초 대조가 끝난 계정에서는 영영 올라가지 않았다. * 엔진이 있을 때만 곧바로 flush 를 예약한다(없으면 엔진 생성 후 최초 동기화가 올린다). */ private _recordChange(entity: SyncEntity, id: string, op: 'upsert' | 'delete'): void { const accountUserId = this._session?.user.id ?? this._offlineUserId if (!accountUserId || getCurrentUserId() !== accountUserId) return try { enqueueChange(entity, id, op) } catch (err) { // 로컬 write는 절대 막지 않는다 — 다음 최초 대조가 없는 행을 다시 찾는다. logger.warn(`Sync enqueue ${entity}/${id} failed: ${err instanceof Error ? err.message : String(err)}`) return } if (this._engine && this._session) this._scheduleFlush() } private _scheduleFlush(): void { this._scheduler.scheduleFlush() } private _schedulePull(): void { this._scheduler.schedulePull() } /** 수동 "업로드": 보관된 실패 항목도 다시 시도한다. */ async pushAll(): Promise { const result = await this._runEngine('flush', { releaseParked: true }) return { pushed: result.pushed, errors: result.errors } } /** 수동 "다운로드". */ async pullAll(): Promise { const result = await this._runEngine('pull') return { pushed: result.pulled + result.deleted, errors: result.errors } } private async _runEngine( kind: 'full' | 'flush' | 'pull', options: { releaseParked?: boolean } = {} ): Promise { const engine = this._engine if (!engine || !this._session) { throw new D3ROError(ErrorCode.LLMServerUnreachable, '로그인이 필요합니다') } this._syncing = true try { const result = kind === 'full' ? await engine.runFullSync() : kind === 'flush' ? await engine.flush(options) : await engine.pull() if (engine !== this._engine) return result if (kind !== 'flush') { this._lastSyncAt = Date.now() configSet('cloudSyncLastAt', this._lastSyncAt) } if (result.changed.length > 0) this.emit('data-changed', { entities: result.changed }) this.emit('sync-complete', { pushed: result.pushed + result.pulled + result.deleted, errors: result.errors }) if (result.errors.length > 0) { logger.warn(`Sync ${kind} finished with ${result.errors.length} error(s): ${result.errors.slice(0, 3).join(' | ')}`) } return result } catch (err) { const message = err instanceof Error ? err.message : String(err) if (err instanceof SyncAbortedError || engine !== this._engine) { // 로그아웃·계정 전환으로 멈춘 동기화 — 사용자에게 알릴 오류가 아니다. logger.info(`Sync ${kind} stopped: ${message}`) throw err } logger.error(`Sync ${kind} failed: ${message}`) this.emit('sync-error', { error: message }) throw err } finally { this._syncing = false } } // ── 기기 등록 ────────────────────────────────────────── private async _checkInDevice(reason: 'signin' | 'restore' | 'heartbeat'): Promise { const client = this._client const session = this._session if (!client || !session) return let known: string | null = null try { known = getSyncState(DEVICE_STATE_KEY) } catch { known = null } try { const check = await checkInDesktopDevice( client, session.user.id, reason, currentDeviceInfo(app.getVersion()), reason === 'signin' ? null : known ) if (check.status === 'active') { setSyncState(DEVICE_STATE_KEY, check.deviceId) } else if (check.status === 'revoked' && this._session === session) { logger.warn('This desktop was disconnected from another device — signing out') await this._onSignOut({ unregister: false }) this.emit('sync-error', { error: 'This computer was disconnected from your account on another device. Sign in again to keep syncing.', }) } } catch (err) { logger.warn(`Device check-in (${reason}) failed: ${err instanceof Error ? err.message : String(err)}`) } } private _startHeartbeat(): void { this._scheduler.startHeartbeat() } private _onHeartbeat(): void { if (!this._session) return void this._checkInDevice('heartbeat') // 재구독을 포기한 채널(3회 실패)을 되살린다 — 네트워크가 돌아온 뒤에도 실시간이 끊겨 있지 않게. if (this._realtimeChannel?.state !== 'joined') { this._realtimeRetryCount = 0 void this.startRealtime().catch(() => undefined) } // Realtime 이벤트를 놓쳤을 때의 안전망 void this._runEngine('full').catch(() => undefined) } private _stopHeartbeat(): void { this._scheduler.stop() } /** * 다른 기기(모바일·웹)에서 녹음한 기록의 재생 URL(5분 서명). 로컬 파일이 없을 때만 쓴다. * 로그인 전이거나 서버에 녹음이 없으면 null. */ async createHistoryAudioUrl(historyId: string): Promise { const client = this._client const session = this._session if (!client || !session) return null const { data, error } = await client .from('audio_files') .select('storage_key,upload_status') .eq('user_id', session.user.id) .eq('history_id', historyId) .eq('upload_status', 'uploaded') .order('created_at', { ascending: false }) .limit(1) .maybeSingle() if (error || !data || typeof data.storage_key !== 'string') return null if (!data.storage_key.startsWith(`${session.user.id}/`)) return null const signed = await client.storage.from(AUDIO_BUCKET).createSignedUrl(data.storage_key, 300) return signed.error ? null : signed.data.signedUrl } getSyncStatus(): SyncStatus | null { if (!this._engine) return null try { return this._engine.getStatus() } catch { return null } } // ── 토큰 영속화 (electron safeStorage) — SessionTokenStore 에 위임 ───── private _tokens(): SessionTokenStore { if (!this._tokenStore) { this._tokenStore = new EncryptedFileTokenStore( path.join(app.getPath('userData'), TOKEN_FILE), safeStorage, { existsSync: (p) => fs.existsSync(p), readFileSync: (p) => fs.readFileSync(p), writeFileSync: (p, data) => fs.writeFileSync(p, data), unlinkSync: (p) => fs.unlinkSync(p), }, logger ) } return this._tokenStore } private _saveRefreshToken(token: string, userId: string): void { this._tokens().save(token, userId) } private _loadStoredSession(): StoredSessionRecord | null { return this._tokens().loadRecord() } private _clearStoredRefreshToken(): void { this._tokens().clear() } /** 테스트 전용: 타이머·auth 구독을 해제한다. */ disposeForTests(): void { this._scheduler.stop() this._cancelRestoreRetry() this._unbindAuthEvents?.() this._unbindAuthEvents = null void this._client?.auth.stopAutoRefresh().catch(() => undefined) this.removeAllListeners() } // ── EventEmitter 타입 오버라이드 ─────────────────────── override on(event: K, listener: CloudSyncEvents[K]): this { return super.on(event, listener) } override emit( event: K, ...args: Parameters ): boolean { return super.emit(event, ...args) } } // ── 싱글톤 ───────────────────────────────────────────── let instance: CloudSyncService | null = null export function resetCloudSyncServiceForTests(): void { if (instance) instance.disposeForTests() instance = null } export function getCloudSyncService(): CloudSyncService { if (!instance) { instance = new CloudSyncService() } return instance }