fix(sync): bind sync engine to its user DB, scope instructions/templates per account, harden navigation
This commit is contained in:
parent
1b8fe445f3
commit
9aa7302944
30 changed files with 2614 additions and 386 deletions
|
|
@ -4,7 +4,9 @@
|
|||
// 실제 동기화는 services/sync/SyncEngine 이 한다 — 이 서비스는 인증·수명주기·트리거를 맡는다.
|
||||
|
||||
import { EventEmitter } from 'events'
|
||||
import { shell, app, safeStorage } from 'electron'
|
||||
import fs from 'fs'
|
||||
import path from 'path'
|
||||
import { app, safeStorage } from 'electron'
|
||||
import {
|
||||
createClient,
|
||||
type SupabaseClient,
|
||||
|
|
@ -19,10 +21,14 @@ import { openForUser, openLocal, closeCurrent, getCurrentUserId, importLocalMode
|
|||
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 } from './sync/session-token-store'
|
||||
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 type { SyncEntity, SyncRunResult } from './sync/sync-types'
|
||||
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'
|
||||
|
|
@ -38,20 +44,12 @@ const HEARTBEAT_MS = 5 * 60_000
|
|||
/** sync_state 에 저장하는 이 사용자 DB의 등록 기기 id */
|
||||
const DEVICE_STATE_KEY = 'device:id'
|
||||
|
||||
/** Realtime 변경 감시 대상. sync_tombstones = 다른 기기의 삭제 */
|
||||
const REALTIME_TABLES = [
|
||||
'history',
|
||||
'dictionary',
|
||||
'meetings',
|
||||
'meeting_memos',
|
||||
'meeting_documents',
|
||||
'memo_tags',
|
||||
'custom_instructions',
|
||||
'user_templates',
|
||||
'knowledge_documents',
|
||||
'user_settings',
|
||||
'sync_tombstones',
|
||||
] as const
|
||||
/** 로그아웃·계정 전환 때 진행 중인 동기화가 멈추기를 기다리는 최대 시간 */
|
||||
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'
|
||||
|
||||
// ============================================================
|
||||
// 타입
|
||||
|
|
@ -103,9 +101,17 @@ class CloudSyncService extends EventEmitter {
|
|||
private _initialized = false
|
||||
private _realtimeChannel: RealtimeChannel | null = null
|
||||
private _engine: SyncEngine | null = null
|
||||
private _flushTimer: NodeJS.Timeout | null = null
|
||||
private _pullTimer: NodeJS.Timeout | null = null
|
||||
private _heartbeatTimer: NodeJS.Timeout | null = null
|
||||
/** 로그인 시작(startSignIn) 후 콜백을 받아들이는 기한. null이면 진행 중인 로그인이 없다 */
|
||||
private _pendingSignInUntil: number | null = null
|
||||
private _tokenStore: SessionTokenStore | null = null
|
||||
private _unbindAuthEvents: (() => void) | null = null
|
||||
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 클라이언트 생성, 저장된 세션 복원.
|
||||
|
|
@ -129,6 +135,18 @@ class CloudSyncService extends EventEmitter {
|
|||
|
||||
this._lastSyncAt = (configGet('cloudSyncLastAt') as number | undefined) ?? null
|
||||
|
||||
// supabase-js는 메인 프로세스에서 refresh token을 주기적으로 회전시킨다. 회전된 토큰과 access token을
|
||||
// 매번 저장·갱신해야 재시작 복원과 Realtime 재구독이 이미 쓰인/만료된 토큰을 쓰지 않는다.
|
||||
const client = this._client
|
||||
this._unbindAuthEvents = bindAuthEvents<Session>(
|
||||
(callback) => client.auth.onAuthStateChange((event, session) => callback(event, session)).data.subscription,
|
||||
this._tokens(),
|
||||
() => this._session?.user.id ?? null,
|
||||
(session) => {
|
||||
this._session = session
|
||||
}
|
||||
)
|
||||
|
||||
// 언어·테마·자동 다듬기·활성 명령이 바뀌면 모바일 user_settings 로 올린다(원격 반영 중엔 제외).
|
||||
onConfigChanged((event) => {
|
||||
if (isApplyingRemoteSettings()) return
|
||||
|
|
@ -201,9 +219,17 @@ class CloudSyncService extends EventEmitter {
|
|||
session: Session,
|
||||
opts: { reason: 'restore' | 'signin' }
|
||||
): Promise<void> {
|
||||
this._session = session
|
||||
const userId = session.user.id
|
||||
|
||||
// 0) 이전 계정의 동기화를 먼저 멈춘다 — 새 DB가 열린 뒤 이전 엔진이 그 DB에 쓰지 않게.
|
||||
const previous = this._engine
|
||||
this._engine = null
|
||||
if (previous) {
|
||||
previous.dispose()
|
||||
await previous.whenIdle(ENGINE_STOP_TIMEOUT_MS)
|
||||
}
|
||||
this._session = session
|
||||
|
||||
// 1) 사용자별 DB 열기 (Phase 1 — 사용자별 SQLite 격리)
|
||||
try {
|
||||
const { created, dbPath } = openForUser(userId)
|
||||
|
|
@ -245,9 +271,8 @@ class CloudSyncService extends EventEmitter {
|
|||
)
|
||||
}
|
||||
|
||||
// 4) 동기화 엔진 — 사용자 DB가 열린 뒤, 이 사용자 전용으로 만든다.
|
||||
this._engine?.dispose()
|
||||
this._engine = null
|
||||
// 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))
|
||||
|
|
@ -358,7 +383,8 @@ class CloudSyncService extends EventEmitter {
|
|||
// 2) Realtime 구독·주기 작업 종료, 엔진 해제
|
||||
await this.stopRealtime()
|
||||
this._stopHeartbeat()
|
||||
this._engine?.dispose()
|
||||
const engine = this._engine
|
||||
engine?.dispose()
|
||||
this._engine = null
|
||||
|
||||
// 3) 사용자가 직접 로그아웃하면 기기 목록에서도 빠진다(원격 해제로 로그아웃될 때는 이미 해제됨).
|
||||
|
|
@ -392,6 +418,11 @@ class CloudSyncService extends EventEmitter {
|
|||
|
||||
// 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()
|
||||
|
|
@ -587,19 +618,22 @@ class CloudSyncService extends EventEmitter {
|
|||
|
||||
const userId = this._session.user.id
|
||||
|
||||
// persistSession: false 에서는 Supabase realtime 클라이언트가 auth state change를
|
||||
// 자동 추적하지 않는다. access_token을 명시적으로 realtime에 주입해서
|
||||
// postgres_changes 채널이 RLS를 통과하도록 한다. (TIMED_OUT 버그 픽스)
|
||||
// postgres_changes 채널이 RLS를 통과하도록 access token을 realtime에 넣는다(TIMED_OUT 버그 픽스).
|
||||
// 로그인 시점의 토큰은 1시간 뒤 만료되므로, 클라이언트의 현재 세션(필요하면 갱신)에서 꺼낸다 —
|
||||
// 만료된 토큰으로 재구독하면 CHANNEL_ERROR만 반복한다.
|
||||
try {
|
||||
this._client.realtime.setAuth(this._session.access_token)
|
||||
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 REALTIME_TABLES) {
|
||||
for (const table of realtimeTables()) {
|
||||
channel = channel.on(
|
||||
'postgres_changes',
|
||||
{ event: '*', schema: 'public', table, filter: `user_id=eq.${userId}` },
|
||||
|
|
@ -710,8 +744,29 @@ class CloudSyncService extends EventEmitter {
|
|||
)
|
||||
}
|
||||
|
||||
// 이 앱이 요청한 로그인만 받아들인다: 콜백은 이 시각 이후 한 번만 유효하다.
|
||||
this._pendingSignInUntil = Date.now() + SIGN_IN_WINDOW_MS
|
||||
logger.info(`Opening OAuth URL in external browser: ${provider}`)
|
||||
await shell.openExternal(data.url)
|
||||
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')
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -723,6 +778,7 @@ class CloudSyncService extends EventEmitter {
|
|||
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(
|
||||
|
|
@ -754,6 +810,7 @@ class CloudSyncService extends EventEmitter {
|
|||
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,
|
||||
|
|
@ -805,20 +862,12 @@ class CloudSyncService extends EventEmitter {
|
|||
this._scheduleFlush()
|
||||
}
|
||||
|
||||
private _scheduleFlush(delayMs = FLUSH_DEBOUNCE_MS): void {
|
||||
if (this._flushTimer) return
|
||||
this._flushTimer = setTimeout(() => {
|
||||
this._flushTimer = null
|
||||
void this._runEngine('flush').catch(() => undefined)
|
||||
}, delayMs)
|
||||
private _scheduleFlush(): void {
|
||||
this._scheduler.scheduleFlush()
|
||||
}
|
||||
|
||||
private _schedulePull(delayMs = PULL_DEBOUNCE_MS): void {
|
||||
if (this._pullTimer) return
|
||||
this._pullTimer = setTimeout(() => {
|
||||
this._pullTimer = null
|
||||
void this._runEngine('pull').catch(() => undefined)
|
||||
}, delayMs)
|
||||
private _schedulePull(): void {
|
||||
this._scheduler.schedulePull()
|
||||
}
|
||||
|
||||
/** 수동 "업로드": 보관된 실패 항목도 다시 시도한다. */
|
||||
|
|
@ -862,6 +911,11 @@ class CloudSyncService extends EventEmitter {
|
|||
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
|
||||
|
|
@ -905,33 +959,23 @@ class CloudSyncService extends EventEmitter {
|
|||
}
|
||||
|
||||
private _startHeartbeat(): void {
|
||||
this._stopHeartbeat()
|
||||
this._heartbeatTimer = setInterval(() => {
|
||||
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)
|
||||
}, HEARTBEAT_MS)
|
||||
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 {
|
||||
if (this._heartbeatTimer) {
|
||||
clearInterval(this._heartbeatTimer)
|
||||
this._heartbeatTimer = null
|
||||
}
|
||||
if (this._flushTimer) {
|
||||
clearTimeout(this._flushTimer)
|
||||
this._flushTimer = null
|
||||
}
|
||||
if (this._pullTimer) {
|
||||
clearTimeout(this._pullTimer)
|
||||
this._pullTimer = null
|
||||
}
|
||||
this._scheduler.stop()
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -966,48 +1010,44 @@ class CloudSyncService extends EventEmitter {
|
|||
}
|
||||
}
|
||||
|
||||
// ── 토큰 영속화 (electron safeStorage) ─────────────────
|
||||
// ── 토큰 영속화 (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): void {
|
||||
try {
|
||||
if (safeStorage.isEncryptionAvailable()) {
|
||||
const encrypted = safeStorage.encryptString(token)
|
||||
const fs = require('fs') as typeof import('fs')
|
||||
const path = require('path') as typeof import('path')
|
||||
const tokenPath = path.join(app.getPath('userData'), 'cloud-sync.token')
|
||||
fs.writeFileSync(tokenPath, encrypted)
|
||||
}
|
||||
} catch (err) {
|
||||
logger.warn(`Token save failed: ${err instanceof Error ? err.message : String(err)}`)
|
||||
}
|
||||
this._tokens().save(token)
|
||||
}
|
||||
|
||||
private _loadStoredRefreshToken(): string | null {
|
||||
try {
|
||||
const fs = require('fs') as typeof import('fs')
|
||||
const path = require('path') as typeof import('path')
|
||||
const tokenPath = path.join(app.getPath('userData'), 'cloud-sync.token')
|
||||
if (!fs.existsSync(tokenPath)) return null
|
||||
if (!safeStorage.isEncryptionAvailable()) return null
|
||||
const encrypted = fs.readFileSync(tokenPath)
|
||||
return safeStorage.decryptString(encrypted)
|
||||
} catch (err) {
|
||||
logger.warn(`Token load failed: ${err instanceof Error ? err.message : String(err)}`)
|
||||
return null
|
||||
}
|
||||
return this._tokens().load()
|
||||
}
|
||||
|
||||
private _clearStoredRefreshToken(): void {
|
||||
try {
|
||||
const fs = require('fs') as typeof import('fs')
|
||||
const path = require('path') as typeof import('path')
|
||||
const tokenPath = path.join(app.getPath('userData'), 'cloud-sync.token')
|
||||
if (fs.existsSync(tokenPath)) {
|
||||
fs.unlinkSync(tokenPath)
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
this._tokens().clear()
|
||||
}
|
||||
|
||||
/** 테스트 전용: 타이머·auth 구독을 해제한다. */
|
||||
disposeForTests(): void {
|
||||
this._scheduler.stop()
|
||||
this._unbindAuthEvents?.()
|
||||
this._unbindAuthEvents = null
|
||||
void this._client?.auth.stopAutoRefresh().catch(() => undefined)
|
||||
this.removeAllListeners()
|
||||
}
|
||||
|
||||
// ── EventEmitter 타입 오버라이드 ───────────────────────
|
||||
|
|
@ -1029,7 +1069,7 @@ class CloudSyncService extends EventEmitter {
|
|||
let instance: CloudSyncService | null = null
|
||||
|
||||
export function resetCloudSyncServiceForTests(): void {
|
||||
if (instance) instance.removeAllListeners()
|
||||
if (instance) instance.disposeForTests()
|
||||
instance = null
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue