// 겜녹이 Electron 메인 프로세스: 트레이 아이콘 + 설정 창 + 첫 실행 마법사. 실제 일은 코어(src/core)가 한다. import { app, BrowserWindow, Menu, nativeImage, safeStorage, session, shell, Tray } from 'electron'; import fs from 'node:fs'; import path from 'node:path'; import { pathToFileURL } from 'node:url'; import { AppAuth } from '../core/auth.js'; import { startCore, type Core } from '../core/index.js'; import { plainCodec, SettingsStore, type SecretCodec } from '../core/settings.js'; import { logger } from '../core/util/log.js'; import { hardenTlsEnv, secureFetch } from '../core/util/secure-http.js'; import { Finetuner } from './finetune.js'; import type { AuthView } from './api-types.js'; import { buildState, registerIpc } from './ipc.js'; import { brandDir, rendererDir, replayToolPath, resolveDataDir, resourcesDir, workerCommand } from './paths.js'; import { TrayShell } from './tray-shell.js'; // 인증서 검증을 끄는 환경변수(NODE_TLS_REJECT_UNAUTHORIZED=0)는 무시한다. fuses 로 막지 못하는 변수라 가장 먼저 지운다 hardenTlsEnv(); const log = logger('app'); const argv = process.argv.slice(1); const flag = (name: string) => argv.includes(`--${name}`); const opt = (name: string) => argv.find((a) => a.startsWith(`--${name}=`))?.split('=').slice(1).join('='); const SMOKE = flag('smoke'); app.setAppUserModelId('kr.tkrmagid.gvr'); // 설정 창은 글자 · 버튼뿐이라 GPU 로 그릴 필요가 없다. 게임 · 브라우저와 GPU 를 나눠 쓰지 않게 끈다 (v1.9.0) app.disableHardwareAcceleration(); if (!SMOKE && !app.requestSingleInstanceLock()) { app.quit(); process.exit(0); } let core: Core | null = null; let ft: Finetuner | null = null; // 로그인: 설정 저장소와 로그인 확인은 코어보다 먼저 연다. 등록된 아이디로 로그인해야 코어(봇 · 녹음 · 사이트 연결)를 띄운다 let settings: SettingsStore | null = null; let auth: AppAuth | null = null; let win: BrowserWindow | null = null; const trayShell = new TrayShell(); let quitting = false; const dataDir = resolveDataDir(opt('data-dir')); // 창 보안: 설정 창(window.gvr 로 로그인 · 관리자 기능을 부를 수 있다)에는 앱에 들어 있는 화면만 띄운다. // 링크를 눌러 바깥 페이지가 이 창에 열리면 그 페이지가 window.gvr 를 쓸 수 있으므로, 바깥 주소는 브라우저로만 연다 app.on('web-contents-created', (_e, wc) => { const own = pathToFileURL(path.join(rendererDir(), 'index.html')).href; const guard = (e: Electron.Event, url: string) => { if (url.split(/[?#]/)[0] === own) return; e.preventDefault(); if (/^https?:\/\//.test(url)) void shell.openExternal(url); }; wc.on('will-navigate', guard); wc.on('will-redirect', guard); wc.on('will-attach-webview', (e) => e.preventDefault()); wc.setWindowOpenHandler(({ url }) => { if (/^https?:\/\//.test(url)) void shell.openExternal(url); return { action: 'deny' }; }); }); function dpapiCodec(): SecretCodec { // Windows: safeStorage = DPAPI (현재 사용자 계정에 묶인 암호화, N-03) if (safeStorage.isEncryptionAvailable()) return { name: process.platform === 'win32' ? 'dpapi' : 'os-keychain', encrypt: (s) => safeStorage.encryptString(s), decrypt: (b) => safeStorage.decryptString(b) }; return plainCodec; } function trayImage(state: 'idle' | 'rec' | 'off'): Electron.NativeImage { const f = path.join(brandDir(), state === 'idle' ? 'tray.png' : `tray-${state}.png`); const img = nativeImage.createFromPath(fs.existsSync(f) ? f : path.join(brandDir(), 'tray.png')); const hi = f.replace('.png', '@2x.png'); if (fs.existsSync(hi)) img.addRepresentation({ scaleFactor: 2, buffer: fs.readFileSync(hi) }); return img; } function openWindow(route?: string): void { if (!settings) return; const first = settings.get().firstRunDone; const r = route ?? (first ? '/settings/discord' : '/wizard'); if (win && !win.isDestroyed()) { win.webContents.executeJavaScript(`location.hash = ${JSON.stringify('#' + r)}`).catch(() => undefined); win.show(); win.focus(); return; } win = new BrowserWindow({ width: 1100, height: 760, minWidth: 960, minHeight: 640, title: first ? '겜녹이 · 설정' : '겜녹이 · 첫 실행 설정', icon: path.join(brandDir(), 'icon.png'), backgroundColor: '#0b141c', autoHideMenuBar: true, show: false, webPreferences: { preload: path.join(__dirname, 'preload.cjs'), contextIsolation: true, sandbox: true, nodeIntegration: false }, }); win.setMenu(null); win.on('page-title-updated', (e) => e.preventDefault()); win.loadFile(path.join(rendererDir(), 'index.html'), { hash: r }); win.once('ready-to-show', () => { win?.show(); closeSplash(); }); // 창을 닫아도 트레이에서 계속 돈다 (녹음·사이트 연결 유지) win.on('close', (e) => { if (!quitting) { e.preventDefault(); win?.hide(); } }); } // ── 시작 창: 포터블 exe 는 풀고 켜는 데 시간이 걸린다. 큰 창이 뜨기 전까지 작은 "켜는 중" 창을 바로 띄운다 ── let splash: BrowserWindow | null = null; function showSplash(): void { const banner = path.join(brandDir(), 'banner.png'); const img = fs.existsSync(banner) ? `data:image/png;base64,${fs.readFileSync(banner).toString('base64')}` : ''; const html = `${img ? `` : '
'}
겜녹이를 켜는 중입니다…
`; splash = new BrowserWindow({ width: 480, height: 232, frame: false, resizable: false, movable: true, center: true, show: false, title: '겜녹이 · 켜는 중', icon: path.join(brandDir(), 'icon.png'), backgroundColor: '#0b141c', webPreferences: { sandbox: true, contextIsolation: true, nodeIntegration: false, javascript: true }, }); splash.once('ready-to-show', () => splash?.show()); splash.on('closed', () => (splash = null)); void splash.loadURL(`data:text/html;charset=utf-8,${encodeURIComponent(html)}`).catch(() => undefined); } function splashText(text: string): void { if (splash && !splash.isDestroyed()) splash.webContents.executeJavaScript(`document.getElementById('t').textContent=${JSON.stringify(text)}`).catch(() => undefined); } function closeSplash(): void { if (splash && !splash.isDestroyed()) splash.destroy(); splash = null; } function updateTray(): void { const tray = trayShell.get(); if (!tray) return; if (!core) { tray.setImage(trayImage('off')); tray.setToolTip(`겜녹이\n${auth?.state.status === 'not_registered' ? '등록되지 않은 아이디' : '로그인이 필요합니다'}`); return; } const st = core.bot.state; const rel = core.relay.status; const rec = st.recording.active; const state = rec ? 'rec' : rel.state === 'online' && st.status === 'ready' ? 'idle' : 'off'; tray.setImage(trayImage(state)); const lines = [ '겜녹이', rec ? `🔴 녹음 중 · ${st.recording.channel} (${st.recording.participants.length}명)` : st.status === 'ready' ? '대기 중' : st.status === 'error' ? `봇 오류: ${st.error}` : '봇 꺼짐', `사이트 ${rel.state === 'online' ? '연결됨' : '연결 안 됨'} · STT 대기 ${core.stt.status.queue}`, ]; tray.setToolTip(lines.join('\n')); } function buildTrayMenu(): void { const tray = trayShell.get(); if (!tray) return; if (!core) { tray.setContextMenu( Menu.buildFromTemplate([ { label: '겜녹이 로그인', click: () => openWindow() }, { type: 'separator' }, { label: '종료', click: () => void quit() }, ]), ); return; } const c = core; tray.setContextMenu( Menu.buildFromTemplate([ { label: '겜녹이 설정 열기', click: () => openWindow() }, { label: '사이트 열기 (gvr.tkrmagid.kr)', click: () => void shell.openExternal(c.settings.get().site.serverUrl) }, { type: 'separator' }, { label: '녹음 종료 (음성채널에서 나가기)', click: () => c.bot.leave('tray'), enabled: c.bot.state.recording.active }, { label: '진단', click: () => openWindow('/settings/diag') }, { label: '데이터 폴더 열기', click: () => void shell.openPath(dataDir) }, { type: 'separator' }, { label: '종료', click: () => void quit() }, ]), ); } async function quit(): Promise { if (quitting) return; quitting = true; try { auth?.cancelLogin(); await stopApp(); } catch (e) { log.error('종료 중 오류', e); } // 트레이 갱신 타이머가 app.exit 사이에 한 번 더 돌면 'Tray is destroyed' 오류 창이 뜬다 trayShell.dispose(); app.exit(0); } async function smoke(): Promise { // 배포 전 확인 (win-ci): 코어 시작 → 워커 hello → DB·설정·암호화 → 결과 JSON → 종료 const out: Record = { version: app.getVersion(), dataDir, resources: resourcesDir() }; let code = 1; try { const st = new SettingsStore(dataDir, dpapiCodec()); // 로그인: 토큰이 없는 새 설치는 로그인 화면(signed_out)이어야 한다. exe 에는 겜녹이 봇 토큰이 없어야 한다 const a = await new AppAuth(st, { version: app.getVersion(), openUrl: () => undefined }).check(); out.auth = a.status; out.builtinBot = st.hasBuiltinBot; const c = await startCore({ dataDir, resourcesDir: resourcesDir(), worker: workerCommand(), version: app.getVersion(), settings: st, replayTool: replayToolPath() }); out.codec = c.settings.codecName; out.botMode = c.settings.get().discord.botMode; const ready = await new Promise((res) => { if (c.worker.ready) return res(true); const t = setTimeout(() => res(false), 120000); c.worker.once('ready', (r) => { clearTimeout(t); res(r); }); }); out.worker = ready; // 봇: 로그인 전이라 봇 토큰이 없으니 봇은 꺼져 있어야 한다 (토큰이 exe 에 들어 있지 않다는 확인) out.bot = { status: c.bot.state.status, error: c.bot.state.error }; const botOk = a.status === 'signed_out' && !st.hasBuiltinBot && c.bot.state.status !== 'ready'; out.gpu = await c.worker.request('gpu_info', {}, 30000).catch((e) => String(e)); // 사이트 서버 https: 앱이 믿는 루트 인증서(Node 내장 Mozilla 목록)만으로 실제 서버 인증서가 검증되는지 out.siteTls = await secureFetch(`${c.settings.get().site.serverUrl}/healthz`, { timeoutMs: 20000 }).then( (r) => r.ok, (e) => String(e?.message ?? e), ); c.settings.setSecret('riotApiKey', 'smoke-test'); out.secretRoundTrip = c.settings.getSecret('riotApiKey') === 'smoke-test'; c.settings.setSecret('riotApiKey', null); out.dict = c.store.listDict().length; out.renderer = fs.existsSync(path.join(rendererDir(), 'index.html')); out.tray = fs.existsSync(path.join(brandDir(), 'tray.png')); // 3D 리플레이 변환기 (v1.5.0): 배포본 안에 있어야 한다. GVR_SMOKE_VRF 가 있으면 실제로 변환해 본다 out.replayTool = fs.existsSync(replayToolPath()); if (process.env.GVR_SMOKE_VRF) { const vrf = process.env.GVR_SMOKE_VRF; const id = path.basename(vrf).replace(/\.vrf$/i, ''); process.env.GVR_REPLAY_DIRS = path.dirname(vrf); const t0 = Date.now(); const r = await c.replays.get(id, 170000); out.replayConvert = r.state === 'ready' ? { ok: true, ms: Date.now() - t0, gz: fs.statSync(r.file).size } : r; } const replayOk = out.replayTool === true && (!process.env.GVR_SMOKE_VRF || (out.replayConvert as any)?.ok === true); code = ready && botOk && out.secretRoundTrip && out.renderer && out.tray && out.siteTls === true && replayOk ? 0 : 1; await c.stop(); } catch (e: any) { out.error = e.stack || e.message; } fs.mkdirSync(dataDir, { recursive: true }); fs.writeFileSync(path.join(dataDir, 'smoke.json'), JSON.stringify(out, null, 2)); app.exit(code); } /** 로그인은 됐는데 코어가 못 뜬 경우의 오류 (로그인 화면에 보여 준다) */ let appError: string | null = null; const authView = (): AuthView => ({ ...auth!.state, appReady: !!core, appError, version: app.getVersion(), serverUrl: settings!.get().site.serverUrl }); const pushAuth = () => { if (win && !win.isDestroyed()) win.webContents.send('gvr:auth', authView()); }; const pushState = () => { if (core && auth && win && !win.isDestroyed() && win.isVisible()) win.webContents.send('gvr:state', buildState(core, { dataDir, portable: app.isPackaged, auth: auth.state })); }; const refreshShell = () => { pushAuth(); buildTrayMenu(); updateTray(); }; let starting: Promise | null = null; /** 표시 이름(실명 숨기기)을 사이트 서버에서 받아 녹음 기록 · 범인 분석에 반영한다 (못 받으면 저장해 둔 것을 그대로 쓴다) */ async function syncNames(): Promise { const c = core; if (!c || !auth?.ok) return; try { const names = await auth.displayNames(); if (core === c) { c.store.setDisplayNames(names); // 녹음 파일 이름에도 표시 이름을 쓴다 c.audioNames.refreshAll(); } } catch (e: any) { log.warn(`표시 이름을 받지 못했습니다: ${e?.message ?? e}`); } } /** 로그인 확인 후 코어 시작 */ function startApp(): Promise { if (core) return Promise.resolve(); starting ??= (async () => { try { // 겜녹이 봇 중계가 로그인 만료 · 등록 해제를 알려 오면 10분을 기다리지 않고 바로 확인해서 잠근다 const c = await startCore({ dataDir, resourcesDir: resourcesDir(), worker: workerCommand(), version: app.getVersion(), settings: settings!, onBotUnauthorized: () => void auth?.check(), replayTool: replayToolPath() }); core = c; void syncNames(); ft = new Finetuner(c, pushState); ft.scheduleNightly(); appError = null; } catch (e: any) { log.error('코어 시작 실패', e); appError = `겜녹이를 시작하지 못했습니다: ${e?.message ?? e}`; } finally { starting = null; refreshShell(); } })(); return starting; } /** 로그아웃 · 등록 해제: 봇 · 녹음 · 사이트 연결을 모두 멈춘다 */ async function stopApp(): Promise { if (starting) await starting; if (!core) return; const c = core; core = null; ft?.dispose(); ft = null; try { await c.stop(); } finally { refreshShell(); } } let authChain: Promise = Promise.resolve(); function onAuthChange(): void { authChain = authChain .then(async () => { if (quitting) return; pushAuth(); const st = auth!.state.status; if (st === 'ok') { if (!core) return startApp(); } else if (st !== 'checking' && st !== 'waiting') { await stopApp(); openWindow(); } }) .catch((e) => log.error('로그인 상태 처리 실패', e)); } app.whenReady().then(async () => { // 마이크 · 카메라 · 위치 · 알림 등 권한 요청은 모두 거절한다 (아이디 복사용 클립보드 쓰기만 허용) session.defaultSession.setPermissionRequestHandler((_wc, perm, cb) => cb(perm === 'clipboard-sanitized-write')); if (SMOKE) return smoke(); if (!flag('hidden')) showSplash(); settings = new SettingsStore(dataDir, dpapiCodec()); auth = new AppAuth(settings, { version: app.getVersion(), openUrl: (u) => shell.openExternal(u) }); const a = auth; registerIpc({ dataDir, portable: app.isPackaged, win: () => (win && !win.isDestroyed() ? win : null), finishWizard: () => win?.setTitle('겜녹이 · 설정'), quit: () => void quit(), auth: a, current: () => (core && ft ? { core, ft } : null), authView, recheck: async () => { await a.check(); await authChain; if (starting) await starting; }, }); const tray = new Tray(trayImage('off')); tray.on('click', () => openWindow()); trayShell.set(tray); refreshShell(); a.on('change', onAuthChange); // 시작할 때 확인 → 10분마다 다시 확인 (등록 해제되면 바로 잠김). 서버에 못 붙어 막힌 상태면 1분마다 다시 시도 let lastCheck = Date.now(); const first = a.check(); trayShell.every(15000, () => { const st = a.state.status; if ((st === 'ok' && Date.now() - lastCheck > 10 * 60000) || (st === 'error' && Date.now() - lastCheck > 60000) || (st === 'ok' && a.state.offline && Date.now() - lastCheck > 60000)) { lastCheck = Date.now(); void a.check().then(syncNames); } }); trayShell.every(1500, () => { updateTray(); buildTrayMenu(); pushState(); }); splashText('로그인 확인 중…'); await first; if (a.ok) splashText('녹음 · 음성 인식 엔진 시작 중…'); await authChain; if (!flag('hidden') || !settings.get().firstRunDone || !a.ok) openWindow(); else closeSplash(); // 창이 끝내 안 뜨는 경우(오류 등)에도 시작 창이 남지 않게 setTimeout(closeSplash, 30000); if (process.env.GVR_CAPTURE_DIR) void captureScreens(process.env.GVR_CAPTURE_DIR); }); /** 개발용: 실제 앱 화면을 차례로 캡처 (GVR_CAPTURE_DIR=폴더) */ async function captureScreens(dir: string): Promise { fs.mkdirSync(dir, { recursive: true }); const routes = (process.env.GVR_CAPTURE_ROUTES || '/wizard,/settings/discord,/settings/stt,/settings/storage,/settings/diag').split(','); await new Promise((r) => setTimeout(r, 6000)); for (const r of routes) { openWindow(r); await new Promise((res) => setTimeout(res, Number(process.env.GVR_CAPTURE_WAIT || 3500))); const img = await win!.webContents.capturePage(); fs.writeFileSync(path.join(dir, `app${r.replace(/\//g, '-')}.png`), img.toPNG()); } await quit(); } app.on('second-instance', () => openWindow()); app.on('window-all-closed', () => { /* 트레이에서 계속 */ }); app.on('before-quit', () => { quitting = true; });