d3ro-voice/apps/desktop/src/main/index.ts
Yun Chan ba9ef9741e fix: red-team round 3 hardening across desktop, mobile, core and server
Batch of red-team r3 fixes that were in the working tree before the
2026-09-28 design overhaul, committed as one unit with their tests.

- desktop main: STT timeouts and sidecar, voice recording store, sync
  (credentials, audio, knowledge reindex, push gates), runtime
  provisioner, update policy, AltGr keybindings, voice-command policy,
  dictionary file codec/limits, meeting transcript condensing and a
  local recording ledger so interrupted-session recovery only closes
  meetings this device recorded (a phone's live meeting is left alone).
- mobile: login CSRF via implicit token callbacks rejected, account
  deletion/retention, durable queue retention, knowledge realtime
  without unfiltered DELETE, meeting re-record failure paths, cloud STT
  client, preferences store/resync.
- core: text chunking splits long unbroken transcripts to fit, template
  field policy, dictionary limits, meeting markdown inline handling.
- server: payple webhook policy and cancellation order scope, meeting
  document generation quota, team RPC null-role guard, unified LLM
  quota in-flight accounting, knowledge chunk vector index, meeting
  re-record failure paths (migrations 20260929*).
- ci: portable/runtime feed gates, update-policy schema, Forgejo file
  delete and alias planning.

Four older tests are updated to the new contracts rather than the old
behavior: token-pair auth callbacks are rejected, knowledge realtime no
longer subscribes to DELETE, long transcript lines are split, and
meeting recovery requires the local recording ledger for empty rows.
2026-09-28 20:45:52 +09:00

183 lines
6.5 KiB
TypeScript

// src/main/index.ts — 앱 진입점
import { app } from 'electron'
import electronLog from 'electron-log'
import path from 'path'
import { applyAppIdentity } from './app-identity'
// 앱 식별자 명시 (기본값 'Electron'과 충돌 방지).
// AUMID는 electron-builder appId와 같아야 토스트 알림·작업 표시줄 그룹이 동작한다.
applyAppIdentity(app)
// GPU 하드웨어 가속 충돌(NVIDIA/Razer/Oculus 훅)로 인한 투명/블랭크 윈도우 방지
app.disableHardwareAcceleration()
app.commandLine.appendSwitch('disable-gpu')
import { bootstrap } from './bootstrap'
import { setupLifecycle } from './lifecycle'
import { showMainWindow } from './windows/WindowManager'
import { getLogger } from './services/LoggerService'
const deepLinkLogger = getLogger('deep-link')
// EPIPE 에러 방지: electron-log가 stdout/stderr에 쓸 때 파이프가 끊기면 크래시 방지
process.stdout?.on?.('error', () => { /* ignore EPIPE */ })
process.stderr?.on?.('error', () => { /* ignore EPIPE */ })
process.on('uncaughtException', (err) => {
if (err.message?.includes('EPIPE')) return // EPIPE는 무시
// 기타 예외는 로그만
try { electronLog.error('Uncaught:', err) } catch { /* noop */ }
})
// V2-4: deep link 프로토콜 등록 — d3ro-voice://auth-callback?code=...
const PROTOCOL = 'd3ro-voice'
if (process.defaultApp) {
if (process.argv.length >= 2) {
app.setAsDefaultProtocolClient(PROTOCOL, process.execPath, [path.resolve(process.argv[1])])
}
} else {
app.setAsDefaultProtocolClient(PROTOCOL)
}
/**
* deep link URL을 파싱해서 CloudSyncService로 전달.
*
* Supabase OAuth 응답 방식 (둘 다 지원):
* - **Implicit flow** (현재 기본): `d3ro-voice://auth-callback#access_token=...&refresh_token=...&token_type=bearer`
* - **PKCE flow**: `d3ro-voice://auth-callback?code=...`
* - **에러**: query 또는 fragment에 `error=...&error_description=...`
*
* 우리 supabase-js 클라이언트는 `persistSession: false`로 떠 있어서 PKCE가
* 자동 동작하지 않는다. 따라서 Supabase가 implicit flow로 떨어져 fragment에
* access_token/refresh_token을 직접 박아 보낸다. 그 토큰을 client.auth.setSession()에
* 주입해서 세션 복원.
*/
async function handleDeepLink(url: string): Promise<void> {
// 토큰/코드가 포함될 수 있으므로 URL 전체 대신 host + path만 로그
let parsed: URL
try {
parsed = new URL(url)
} catch (err) {
deepLinkLogger.error(
`Failed to parse deep link URL: ${err instanceof Error ? err.message : String(err)}`
)
return
}
deepLinkLogger.info(
`Deep link received: ${parsed.protocol}//${parsed.host}${parsed.pathname} (query=${parsed.search.length > 0 ? 'yes' : 'no'}, fragment=${parsed.hash.length > 0 ? 'yes' : 'no'})`
)
if (parsed.host !== 'auth-callback') {
deepLinkLogger.warn(`Unknown deep link host: "${parsed.host}" (expected 'auth-callback')`)
return
}
// fragment (#...) 와 query (?...) 양쪽 파싱
const fragment = parsed.hash.startsWith('#') ? parsed.hash.slice(1) : parsed.hash
const fragmentParams = new URLSearchParams(fragment)
const queryParams = parsed.searchParams
// 에러 체크 — query/fragment 둘 다
const error = queryParams.get('error') ?? fragmentParams.get('error')
if (error) {
const desc =
queryParams.get('error_description') ??
fragmentParams.get('error_description') ??
'(no description)'
deepLinkLogger.error(`Supabase OAuth returned error: ${error} — ${desc}`)
return
}
const { getCloudSyncService } = await import('./services/CloudSyncService')
// Implicit flow: fragment에 access_token + refresh_token
const accessToken = fragmentParams.get('access_token')
const refreshToken = fragmentParams.get('refresh_token')
if (accessToken && refreshToken) {
deepLinkLogger.info('Implicit flow tokens detected, calling handleAuthTokens()')
try {
await getCloudSyncService().handleAuthTokens({
accessToken,
refreshToken,
})
deepLinkLogger.info('handleAuthTokens completed successfully')
} catch (err) {
deepLinkLogger.error(
`handleAuthTokens failed: ${err instanceof Error ? err.message : String(err)}`
)
}
return
}
// PKCE flow: query에 code
const code = queryParams.get('code')
if (code) {
deepLinkLogger.info('PKCE flow code detected, calling handleAuthCallback()')
try {
await getCloudSyncService().handleAuthCallback(code)
deepLinkLogger.info('handleAuthCallback completed successfully')
} catch (err) {
deepLinkLogger.error(
`handleAuthCallback failed: ${err instanceof Error ? err.message : String(err)}`
)
}
return
}
deepLinkLogger.warn(
'auth-callback deep link had neither access_token (implicit) nor code (PKCE). Ignoring.'
)
}
// 단일 인스턴스 잠금 (테스트 모드에서는 다중 인스턴스 허용)
const gotTheLock = process.env.NODE_ENV === 'test' ? true : app.requestSingleInstanceLock()
if (!gotTheLock) {
deepLinkLogger.info('Another instance is already running. Existing window focused.')
app.exit(0)
} else {
app.on('second-instance', (_event, argv) => {
// 기존 인스턴스의 메인 윈도우를 최상위로 활성화
// 창이 닫혀 없으면 다시 만든다 — 창 없는 프로세스로 남지 않게.
const mainWindow = showMainWindow()
if (mainWindow) {
mainWindow.setAlwaysOnTop(true)
setTimeout(() => {
try {
mainWindow?.setAlwaysOnTop(false)
} catch {
// ignore
}
}, 500)
}
// Windows: deep link는 두 번째 인스턴스의 argv 마지막 인자로 들어옴
const deepLinkArg = argv.find((a) => a.startsWith(`${PROTOCOL}://`))
if (deepLinkArg) {
void handleDeepLink(deepLinkArg)
}
})
// macOS: open-url 이벤트로 deep link 도착
app.on('open-url', (event, url) => {
event.preventDefault()
void handleDeepLink(url)
})
// macOS: Dock 아이콘 클릭 → 트레이로 숨긴(closeToTray) 또는 닫힌 메인 창을 다시 띄운다.
// 부트스트랩 전(launch 직후 첫 activate)에는 showMainWindow 가 창을 만들지 않는다.
app.on('activate', () => {
showMainWindow()
})
app.whenReady().then(async () => {
await bootstrap()
setupLifecycle()
})
app.on('window-all-closed', () => {
// Windows에서는 모든 윈도우 닫아도 앱 유지 (트레이)
if (process.platform !== 'darwin') {
// closeToTray 설정 확인은 lifecycle에서 처리
}
})
}