From 6a03c67b54fc3aed245d1e135c88901c88c653ac Mon Sep 17 00:00:00 2001 From: EJClaw Date: Thu, 15 Oct 2026 10:30:14 +0900 Subject: [PATCH] =?UTF-8?q?=EC=95=B1=20v1.2.1:=20=EA=B2=9C=EB=85=B9?= =?UTF-8?q?=EC=9D=B4=20=EB=B4=87=20=ED=86=A0=ED=81=B0=EC=9D=84=20=EC=95=B1?= =?UTF-8?q?=EC=97=90=20=EB=B3=B4=EB=82=B4=EC=A7=80=20=EC=95=8A=EA=B3=A0=20?= =?UTF-8?q?=EC=82=AC=EC=9D=B4=ED=8A=B8=20=EC=84=9C=EB=B2=84=EA=B0=80=20?= =?UTF-8?q?=EB=B4=87=EC=9D=84=20=EB=8C=80=EC=8B=A0=20=EC=97=B0=EA=B2=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 사이트 서버: discord.js 로 디스코드 게이트웨이에 한 번 붙고(discord-source.ts), 로그인한 앱에 WS /app/bot/ws 로 중계(bot-broker.ts) · 앱이 보낸 op 4 는 지켜보는 서버의 음성채널 참여 · 나가기만 허용하고 필드를 다시 만들어 보낸다 · 디스코드가 준 일회용 음성 접속 정보(VOICE_STATE/SERVER_UPDATE)는 음성을 가진 앱에만 넘긴다. 음성은 앱 ↔ 디스코드로 바로 · 한 서버의 봇 음성은 마지막으로 요청한 앱이 가져가고 이전 앱은 taken. 이전 앱의 늦은 나가기 무시, 음성 가진 앱이 끊기면 봇을 뺀다 · 슬래시 명령은 서버가 받아 defer 후 그 서버를 지켜보는 앱으로 보낸다 · 등록 해제 · 로그아웃하면 그 유저의 중계 연결을 바로 끊는다 (4401), 30초마다 다시 확인 - /app/me 에서 botToken 제거. 앱은 v1.2.0 이 저장해 둔 봇 토큰을 시작할 때 지운다 - 앱: BotGateway 로 디스코드 연결을 분리 (RemoteGateway = 겜녹이 봇 서버 중계, LocalGateway = 다른 봇 토큰 직접 연결) Bot 은 discord.js 객체 대신 이 인터페이스만 쓴다. 중계가 로그인 만료를 알리면 바로 다시 확인해서 잠근다 - 로그인 확인: 잠그라는 응답(401 · 403)은 겹친 확인 때문에 늦게 와도 같은 토큰이면 따른다 (겹친 두 번째 확인이 401 을 받아 "등록되지 않은 아이디" 대신 "로그인 만료"로 잠기던 문제). 미등록 화면은 다시 확인해도 유지 - 테스트: 봇 중계 4건(토큰 미노출 · 음성 정보 전달 · 다른 PC 인계 · 명령 라우팅 · 해제 시 끊김), 겹친 확인 1건 실제 디스코드: voice-e2e GVR_E2E_RELAY=1 (서버 중계로 따라 들어가 녹음 · STT · 녹음 제외), login-e2e 19/19 Co-Authored-By: Claude Opus 5.5 --- README.md | 6 +- app/package-lock.json | 4 +- app/package.json | 2 +- app/scripts/login-e2e.mts | 31 +- app/scripts/voice-e2e.mts | 77 ++++- app/src/core/auth.ts | 17 +- app/src/core/discord/bot.ts | 238 ++++++++------- app/src/core/discord/gateway.ts | 437 +++++++++++++++++++++++++++ app/src/core/index.ts | 24 +- app/src/core/settings.ts | 12 +- app/src/main/ipc.ts | 18 +- app/src/main/main.ts | 15 +- app/src/renderer/tabs/DiscordTab.tsx | 2 +- app/test/auth.test.ts | 49 ++- app/test/bot-gateway.test.ts | 309 +++++++++++++++++++ app/test/bot-token.test.ts | 22 +- docs/dev/ARCHITECTURE.md | 22 +- packages/shared/src/protocol.ts | 44 ++- site/server/package-lock.json | 231 +++++++++++++- site/server/package.json | 1 + site/server/src/app-auth.ts | 27 +- site/server/src/app.ts | 25 +- site/server/src/bot-broker.ts | 240 +++++++++++++++ site/server/src/discord-source.ts | 114 +++++++ site/server/src/main.ts | 12 +- site/server/test/app-auth.test.ts | 6 +- tools/win-ci/run.sh | 2 +- 27 files changed, 1786 insertions(+), 201 deletions(-) create mode 100644 app/src/core/discord/gateway.ts create mode 100644 app/test/bot-gateway.test.ts create mode 100644 site/server/src/bot-broker.ts create mode 100644 site/server/src/discord-source.ts diff --git a/README.md b/README.md index aad671b..21b8993 100644 --- a/README.md +++ b/README.md @@ -20,9 +20,11 @@ ## 디스코드 봇 -- 기본은 **겜녹이 봇으로 진행**: 로그인하면 사이트 서버가 겜녹이 봇 토큰을 내려주므로(암호화 저장) 토큰을 넣지 않아도 바로 연결된다. +- 기본은 **겜녹이 봇으로 진행**: 토큰을 넣지 않아도 로그인만 하면 바로 연결된다. 봇은 사이트 서버가 디스코드에 연결하고, 앱은 로그인 토큰으로 서버 중계(`/app/bot/ws`)를 받는다. - **다른 봇으로 진행하기**(관리자만)를 고르면 직접 만든 봇 토큰을 넣는다 (암호화 저장). v1.0.0 에서 토큰을 넣어 쓰던 설치는 다른 봇 모드로 그대로 이어진다. -- v1.2.0 부터 **exe 안에 봇 토큰이 없다** (v1.1.0 은 빌드 때 감춰 넣었다). 등록되지 않은 사람은 exe 를 받아도 겜녹이 봇을 쓸 수 없고, 등록이 해제되면 받아 둔 토큰도 지운다. 빌드에 비밀값이 필요 없어 공개 릴리스에 올려도 된다. +- v1.2.1 부터 **겜녹이 봇 토큰은 사이트 서버 밖으로 나가지 않는다** (v1.1.0 은 exe 에 감춰 넣었고, v1.2.0 은 로그인한 유저에게 내려줬다). 등록된 유저의 PC 에도 토큰이 없어서 PC 를 뒤지거나 통신을 가로채도 꺼낼 수 없다. + 음성채널에 들어갈 때 서버가 디스코드에서 받은 일회용 음성 접속 정보만 그 PC 에 넘기고, 음성은 PC ↔ 디스코드로 바로 간다. 사이트 서버가 꺼져 있으면 겜녹이 봇은 쓸 수 없다 (다른 봇 모드는 상관없음). 구조: [`docs/dev/ARCHITECTURE.md` 8장](docs/dev/ARCHITECTURE.md) +- 빌드에 비밀값이 필요 없어 공개 릴리스에 올려도 된다. 등록되지 않은 사람은 exe 를 받아도 겜녹이 봇을 쓸 수 없다. ## 진행 현황 diff --git a/app/package-lock.json b/app/package-lock.json index 3080b3f..ec1e766 100644 --- a/app/package-lock.json +++ b/app/package-lock.json @@ -1,12 +1,12 @@ { "name": "gvr-app", - "version": "1.2.0", + "version": "1.2.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "gvr-app", - "version": "1.2.0", + "version": "1.2.1", "license": "UNLICENSED", "dependencies": { "@discordjs/voice": "^0.19.2", diff --git a/app/package.json b/app/package.json index 9a4ce2d..0aabd76 100644 --- a/app/package.json +++ b/app/package.json @@ -1,7 +1,7 @@ { "name": "gvr-app", "productName": "겜녹이", - "version": "1.2.0", + "version": "1.2.1", "description": "겜녹이 (Game Voice Recorder) - 게임 연동 디스코드 음성 기록", "private": true, "main": "dist/main.cjs", diff --git a/app/scripts/login-e2e.mts b/app/scripts/login-e2e.mts index 0e35cd6..5b46dd1 100644 --- a/app/scripts/login-e2e.mts +++ b/app/scripts/login-e2e.mts @@ -1,5 +1,5 @@ // 로그인 E2E (리눅스 · Xvfb): 실제 Electron 앱 + 이 저장소의 사이트 서버 코드 + 가짜 디스코드 OAuth. -// 겜녹이 봇 토큰은 서버에서만 받으므로, 로그인 후 봇이 실제로 디스코드에 붙는지까지 본다. +// 겜녹이 봇 토큰은 서버에만 있다. 서버가 디스코드에 붙고, 로그인한 앱이 서버 중계(/app/bot/ws)로 봇을 쓰는지까지 본다. // GVR_E2E_BOT_TOKEN=<겜녹이 봇 토큰> node --import tsx scripts/login-e2e.mts [스크린샷 폴더] // (먼저 npm run build) import { spawn } from 'node:child_process'; @@ -9,6 +9,7 @@ import os from 'node:os'; import path from 'node:path'; import WebSocket from 'ws'; import { buildServer } from '../../site/server/src/app.ts'; +import { DiscordSource } from '../../site/server/src/discord-source.ts'; import { AppAuth } from '../src/core/auth.ts'; import { SettingsStore } from '../src/core/settings.ts'; @@ -50,13 +51,18 @@ const dc = http.createServer((req, res) => { await new Promise((r) => dc.listen(0, '127.0.0.1', () => r())); const dcUrl = `http://127.0.0.1:${(dc.address() as any).port}`; -const { app: site } = await buildServer({ - port: PORT, host: '127.0.0.1', publicUrl: base, clientId: 'cid', clientSecret: 's', botToken: BOT, - allowedGuilds: [], owners: [SUPER], superAdmins: [SUPER], sessionSecret: 'x'.repeat(32), dataDir: path.join(work, 'site'), - webDir: '/nonexistent', version: 'e2e', discordApi: dcUrl, assetUpstream: {}, -}); +const source = new DiscordSource({ info: () => undefined, error: (o, m) => console.error(m, o) }); +const { app: site } = await buildServer( + { + port: PORT, host: '127.0.0.1', publicUrl: base, clientId: 'cid', clientSecret: 's', botToken: BOT, + allowedGuilds: [], owners: [SUPER], superAdmins: [SUPER], sessionSecret: 'x'.repeat(32), dataDir: path.join(work, 'site'), + webDir: '/nonexistent', version: 'e2e', discordApi: dcUrl, assetUpstream: {}, + }, + { botSource: source }, +); site.log.level = 'warn'; await site.listen({ host: '127.0.0.1', port: PORT }); +await source.login(BOT); // 브라우저 흉내: PATH 맨 앞에 가짜 xdg-open 을 둔다 (Electron shell.openExternal 이 부른다. 실제 브라우저는 열지 않는다) // 로그인 주소 → 가짜 디스코드 → 콜백. 로그인할 아이디는 파일에서 @@ -161,7 +167,13 @@ try { if (st?.bot.status === 'ready' || st?.bot.status === 'error') break; await sleep(500); } - check('서버에서 받은 겜녹이 봇 토큰으로 봇 로그인', st?.bot.status === 'ready' && st.builtinBot, `${st?.bot.status} ${st?.bot.user?.name ?? ''} 서버 ${st?.bot.guilds.length ?? 0}곳 ${st?.bot.error ?? ''}`); + check('겜녹이 봇이 사이트 서버 중계로 연결', st?.bot.status === 'ready' && st.builtinBot && /사이트 서버 중계/.test(logs.join('\n')), `${st?.bot.status} ${st?.bot.user?.name ?? ''} 서버 ${st?.bot.guilds.length ?? 0}곳 ${st?.bot.error ?? ''}`); + const t = (await gvr('window.gvr.testBotToken()')).v; + check('겜녹이 봇 연결 확인 버튼 (토큰 없이 서버 중계)', t?.ok && t.guilds.length > 0, JSON.stringify(t).slice(0, 120)); + const mem = (await gvr('window.gvr.guildMembers()')).v; + check('따라갈 사람 목록 (서버 중계)', Array.isArray(mem) && mem.length > 0, `${mem?.length}명`); + const stored = fs.readdirSync(data).filter((f) => fs.statSync(path.join(data, f)).isFile() && fs.readFileSync(path.join(data, f)).includes(Buffer.from(BOT))); + check('로그인 후에도 앱 데이터에 봇 토큰 없음', stored.length === 0, stored.join(',')); check('계정 표시', st?.account.user?.id === FRIEND && st.account.role === 'user'); // 일반 유저 권한 @@ -185,8 +197,8 @@ try { a = (await gvr('window.gvr.authRecheck()')).v; check('등록 해제 후 확인 → 등록되지 않은 아이디로 잠김', a.status === 'not_registered' && !a.appReady, a.status); check('잠긴 뒤 코어 요청 막힘', /로그인이 필요합니다/.test((await gvr('window.gvr.getState()')).err ?? '')); - const secrets = fs.existsSync(path.join(data, 'secrets.bin')) ? fs.readFileSync(path.join(data, 'secrets.bin')) : Buffer.alloc(0); - check('잠긴 뒤 받아 둔 봇 토큰 삭제', !secrets.includes(Buffer.from(BOT)) && !secrets.toString('latin1').includes('builtinBotToken')); + const secrets = fs.existsSync(path.join(data, 'secrets.bin')) ? fs.readFileSync(path.join(data, 'secrets.bin')).toString('latin1') : ''; + check('잠긴 뒤 앱 토큰 삭제', !secrets.includes('appToken')); await shot('electron-not-registered'); } finally { ws?.close(); @@ -197,6 +209,7 @@ try { } await sleep(1500); await site.close(); + await source.destroy(); dc.close(); fs.writeFileSync(path.join(work, 'electron.log'), logs.join('\n')); console.log(`작업 폴더 ${work}`); diff --git a/app/scripts/voice-e2e.mts b/app/scripts/voice-e2e.mts index 276039b..e6ab962 100644 --- a/app/scripts/voice-e2e.mts +++ b/app/scripts/voice-e2e.mts @@ -2,6 +2,8 @@ // node --import tsx scripts/voice-e2e.mts // 필요: secrets.json 의 겜녹이·테스트봇 토큰, worker/.venv, tiny 모델(HF 캐시) // M7 실사용 시험: GVR_E2E_SET=demo (시연 대화 28문장, 문장별 CER·지연), GVR_E2E_MODEL=<모델 폴더 경로>, GVR_E2E_DEVICE=cuda +// GVR_E2E_RELAY=1: 겜녹이 봇을 사이트 서버 중계로 쓴다 (이 저장소의 사이트 서버 코드를 띄워 봇 토큰은 서버에만 두고, +// 앱은 로그인 토큰으로 /app/bot/ws 에 붙는다. 디스코드 OAuth 만 가짜). 끝나면 앱 데이터 폴더에 봇 토큰이 없는지도 본다 import { Client, GatewayIntentBits } from 'discord.js'; import { joinVoiceChannel, entersState, VoiceConnectionStatus, createAudioPlayer, createAudioResource, StreamType, AudioPlayerStatus } from '@discordjs/voice'; import fs from 'node:fs'; @@ -32,7 +34,62 @@ fs.writeFileSync( }), ); process.env.GVR_RECORD_BOTS = '1'; -process.env.GVR_BOT_TOKEN = GVR_TOKEN; +const RELAY = process.env.GVR_E2E_RELAY === '1'; +let relayStop: (() => Promise) | null = null; +let settings: any; +if (RELAY) { + delete process.env.GVR_BOT_TOKEN; + const http = await import('node:http'); + const { buildServer } = await import('../../site/server/src/app.ts'); + const { DiscordSource } = await import('../../site/server/src/discord-source.ts'); + const { AppAuth } = await import('../src/core/auth.ts'); + const { SettingsStore } = await import('../src/core/settings.ts'); + const SUPER = '293719842274541579'; + // 가짜 디스코드 OAuth: code = 로그인할 아이디 + const dc = http.createServer((req, res) => { + res.setHeader('content-type', 'application/json'); + if (req.url === '/oauth2/token') return void res.end(JSON.stringify({ access_token: SUPER })); + if (req.url === '/users/@me') return void res.end(JSON.stringify({ id: SUPER, username: 'e2e', global_name: 'e2e', avatar: null })); + res.statusCode = 404; + res.end('{}'); + }); + await new Promise((r) => dc.listen(0, '127.0.0.1', () => r())); + const source = new DiscordSource({ info: (o, m) => console.log('[site]', m ?? '', JSON.stringify(o)), error: (o, m) => console.error('[site]', m ?? '', o) }); + const { app: site } = await buildServer( + { + port: 0, host: '127.0.0.1', publicUrl: 'http://placeholder', clientId: 'cid', clientSecret: 's', botToken: GVR_TOKEN, + allowedGuilds: [], owners: [SUPER], superAdmins: [SUPER], sessionSecret: 'x'.repeat(32), dataDir: path.join(work, 'site'), + webDir: '/nonexistent', version: 'e2e', discordApi: `http://127.0.0.1:${(dc.address() as any).port}`, assetUpstream: {}, + }, + { botSource: source }, + ); + site.log.level = 'warn'; + await site.listen({ host: '127.0.0.1', port: 0 }); + const base = `http://127.0.0.1:${(site.server.address() as any).port}`; + await source.login(GVR_TOKEN); + const appDir = path.join(work, 'app'); + fs.mkdirSync(appDir); + fs.copyFileSync(path.join(work, 'settings.json'), path.join(appDir, 'settings.json')); + settings = new SettingsStore(appDir); + settings.update({ site: { serverUrl: base }, stt: { modelsDir: models } }); + const auth = new AppAuth(settings, { + version: 'e2e', + pollMs: 100, + openUrl: async (url: string) => { + const start = await fetch(url.replace('http://placeholder', base), { redirect: 'manual' }); + const state = new URL(start.headers.get('location')!).searchParams.get('state')!; + await fetch(`${base}/auth/discord/callback?code=${SUPER}&state=${encodeURIComponent(state)}`, { headers: { cookie: start.headers.getSetCookie()[0]!.split(';')[0]! }, redirect: 'manual' }); + }, + }); + const a = await auth.login(); + if (a.status !== 'ok') throw new Error(`앱 로그인 실패: ${a.status} ${a.error}`); + console.log('앱 로그인 (서버 중계 모드):', a.user?.name, a.role); + relayStop = async () => { + await site.close(); + await source.destroy(); + dc.close(); + }; +} else process.env.GVR_BOT_TOKEN = GVR_TOKEN; const DEMO = process.env.GVR_E2E_SET === 'demo'; const demoSrc = fs.readFileSync(path.join(import.meta.dirname, 'demo-stack.mts'), 'utf8'); const SENTENCES = DEMO @@ -47,7 +104,7 @@ for (const [i, s] of SENTENCES.entries()) { clips.push(f); } const { startCore } = await import('../src/core/index.ts'); -const core = await startCore({ dataDir: work, resourcesDir: path.join(root, 'app', 'resources'), worker: { cmd: path.join(root, 'worker/.venv/bin/python'), args: ['-m', 'gvr_worker'], cwd: path.join(root, 'worker') }, version: 'e2e' }); +const core = await startCore({ dataDir: RELAY ? path.join(work, 'app') : work, settings, resourcesDir: path.join(root, 'app', 'resources'), worker: { cmd: path.join(root, 'worker/.venv/bin/python'), args: ['-m', 'gvr_worker'], cwd: path.join(root, 'worker') }, version: 'e2e' }); const wait = async (fn: () => boolean, ms: number, label: string) => { const t = Date.now(); while (!fn()) { @@ -59,6 +116,7 @@ let ok = false; const spk = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildVoiceStates] }); try { await wait(() => core.bot.state.status === 'ready', 30000, 'gvr bot ready'); + if (RELAY) console.log('겜녹이 봇 연결:', core.bot.gateway?.kind, core.bot.state.user?.name); await wait(() => core.stt.status.slots.realtime.state === 'loaded', 120000, 'model'); await spk.login(SPEAKER_TOKEN); await new Promise((r) => spk.once('clientReady', r)); @@ -120,6 +178,20 @@ try { console.log(`녹음 제외 후 새 발화: ${after - before}개 (0 이어야 함)`); const texts = rows.map((r) => r.text || '').join(' '); ok = rows.length >= SENTENCES.length && /레이즈|오퍼|치킨/.test(texts) && after === before && (!DEMO || cerAvg < 0.15); + if (RELAY) { + // 서버 중계 모드: 봇은 서버 연결이어야 하고, 앱 데이터 폴더 어디에도 봇 토큰이 없어야 한다 + const leaked: string[] = []; + const scan = (d: string) => { + for (const f of fs.readdirSync(d, { withFileTypes: true })) { + const p = path.join(d, f.name); + if (f.isDirectory()) scan(p); + else if (f.isFile() && fs.statSync(p).size < 200 * 1024 * 1024 && fs.readFileSync(p).includes(Buffer.from(GVR_TOKEN))) leaked.push(p); + } + }; + scan(path.join(work, 'app')); + console.log(`봇 연결 방식: ${core.bot.gateway?.kind} · 앱 데이터에 봇 토큰: ${leaked.length ? leaked.join(', ') : '없음'}`); + ok &&= core.bot.gateway?.kind === 'remote' && leaked.length === 0; + } conn.destroy(); await wait(() => !core.bot.state.recording.active, 20000, 'gvr leaves after speaker').catch(() => console.log('(겜녹이 퇴장 대기 시간 초과)')); console.log('겜녹이 퇴장:', !core.bot.state.recording.active); @@ -128,6 +200,7 @@ try { } finally { await spk.destroy(); await core.stop(); + await relayStop?.(); console.log(ok ? 'VOICE E2E PASS' : 'VOICE E2E FAIL'); process.exit(ok ? 0 : 1); } diff --git a/app/src/core/auth.ts b/app/src/core/auth.ts index 37aac21..7d6619b 100644 --- a/app/src/core/auth.ts +++ b/app/src/core/auth.ts @@ -1,6 +1,7 @@ // 앱(exe) 디스코드 로그인. 사이트 서버(site/server/src/app-auth.ts)가 유저 명단을 갖고 있다. // - 로그인: 서버에 요청을 만들고 브라우저로 디스코드 로그인 → 결과를 받아 온다 (토큰은 DPAPI 로 암호화 저장) -// - 확인: 시작할 때와 10분마다 /app/me. 등록 해제 · 로그아웃되면 바로 잠그고 받아 둔 겜녹이 봇 토큰도 지운다 +// - 확인: 시작할 때와 10분마다 /app/me. 등록 해제 · 로그아웃되면 바로 잠근다 +// - 겜녹이 봇 토큰은 받지 않는다. 봇은 사이트 서버가 연결하고 앱은 앱 토큰으로 중계받는다 (discord/gateway.ts) // - 서버에 잠깐 못 붙으면 마지막 확인 후 3일까지는 그대로 쓴다 import { EventEmitter } from 'node:events'; import type { AppLoginBegin, AppLoginPoll, AppMe, AppRole, AppUserInfo, AppUserRow } from '@gvr/shared'; @@ -89,10 +90,10 @@ export class AppAuth extends EventEmitter { return json as T; } - /** 로그인 정보 · 겜녹이 봇 토큰을 지운다 (등록 해제 · 로그아웃) */ + /** 로그인 정보를 지운다 (등록 해제 · 로그아웃) */ private forget(): void { this.gen++; - for (const k of ['appToken', 'builtinBotToken', 'auth'] as const) if (this.settings.hasSecret(k)) this.settings.setSecret(k, null); + for (const k of ['appToken', 'auth'] as const) if (this.settings.hasSecret(k)) this.settings.setSecret(k, null); } /** 저장된 토큰으로 서버에 확인 */ @@ -101,6 +102,8 @@ export class AppAuth extends EventEmitter { const token = this.settings.getSecret('appToken'); const gen = ++this.gen; if (!token) { + // 등록 해제로 잠긴 화면은 다시 확인해도 그대로 둔다 (봇 중계가 끊기며 바로 확인한 뒤 또 확인이 와도 "등록되지 않은 아이디" 유지) + if (this.state.status === 'not_registered') return this.state; this.set({ status: 'signed_out', user: null, role: null, offline: false, error: null, verifiedAt: null }); return this.state; } @@ -111,11 +114,13 @@ export class AppAuth extends EventEmitter { if (stale()) return this.state; const cache = { user: me.user, role: me.role, verifiedAt: Date.now() }; this.settings.setSecret('auth', cache); - if (me.botToken !== (this.settings.getSecret('builtinBotToken') ?? null)) this.settings.setSecret('builtinBotToken', me.botToken); this.set({ status: 'ok', user: me.user, role: me.role, offline: false, error: null, loginUrl: null, verifiedAt: cache.verifiedAt }); } catch (e: any) { - if (stale()) return this.state; - if (e instanceof HttpError && (e.status === 401 || e.status === 403)) { + const lock = e instanceof HttpError && (e.status === 401 || e.status === 403); + // 잠그라는 응답(401 · 403)은 늦게 와도 같은 토큰이면 따른다. 두 확인이 겹치면 서버가 첫 403 에서 세션을 지워 + // 뒤 확인은 401 을 받는데, 403 을 버리면 "등록되지 않은 아이디" 대신 "로그인 만료"로 잠긴다. 로그인 진행 중에는 건드리지 않는다 + if (lock ? (this.state.status as AuthStatus) === 'waiting' || this.settings.getSecret('appToken') !== token : stale()) return this.state; + if (lock) { const notReg = e.status === 403 && e.body?.error === 'not_registered'; log.warn(notReg ? '등록이 해제된 아이디라 잠급니다' : '로그인이 만료되어 잠급니다'); const user = notReg ? (e.body?.user ?? this.state.user) : null; diff --git a/app/src/core/discord/bot.ts b/app/src/core/discord/bot.ts index 4027b8e..281d9ed 100644 --- a/app/src/core/discord/bot.ts +++ b/app/src/core/discord/bot.ts @@ -10,36 +10,18 @@ import { type AudioPlayer, type VoiceConnection, } from '@discordjs/voice'; -import { - ChannelType, - Client, - Events, - GatewayIntentBits, - MessageFlags, - type ChatInputCommandInteraction, - type Guild, - type GuildMember, - type VoiceBasedChannel, - type VoiceState, -} from 'discord.js'; import fs from 'node:fs'; import type { Store } from '../db/db.js'; import type { Settings } from '../settings.js'; import type { Bus } from '../util/events.js'; import { newId } from '../util/ids.js'; +import type { BotGateway, GChannel, GCommand, GMember, GVoiceEvent } from './gateway.js'; import { logger } from '../util/log.js'; import type { Recorder } from './recorder.js'; import type { Announcer } from './tts.js'; const log = logger('bot'); -export const COMMANDS = [ - { name: '녹음시작', description: '겜녹이를 내가 있는 음성채널로 불러 녹음을 시작합니다' }, - { name: '녹음종료', description: '겜녹이가 음성채널에서 나가고 녹음을 끝냅니다' }, - { name: '녹음제외', description: '내 목소리를 녹음하지 않습니다 (다음 세션에도 유지)' }, - { name: '녹음참여', description: '녹음 제외를 풀고 다시 녹음에 참여합니다' }, -]; - export interface BotState { status: 'off' | 'connecting' | 'ready' | 'error'; error: string | null; @@ -52,9 +34,10 @@ export interface BotState { /** * 디스코드 봇: 나를 따라 음성채널에 들어가거나(/녹음시작) 명령으로 참여하고, TTS 로 녹음 사실을 알린다 (Q7, Q8). * 채팅 메시지는 보내지 않는다. 명령 응답은 본인에게만 보인다. + * 디스코드 연결은 BotGateway 가 맡는다 (겜녹이 봇 = 사이트 서버 중계, 다른 봇 = 이 PC 가 직접 연결) */ export class Bot { - client: Client | null = null; + gateway: BotGateway | null = null; private connection: VoiceConnection | null = null; private player: AudioPlayer | null = null; private sessionId: string | null = null; @@ -77,134 +60,162 @@ export class Bot { private onGuild?: (guildId: string) => void, ) {} - async start(token: string): Promise { + async start(gw: BotGateway): Promise { await this.stop(); this.state.status = 'connecting'; this.state.error = null; - const client = new Client({ - intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildVoiceStates, GatewayIntentBits.GuildMembers], - }); - this.client = client; - client.on(Events.ClientReady, () => void this.onReady()); - client.on(Events.VoiceStateUpdate, (o, n) => void this.onVoiceState(o, n).catch((e) => log.error('voiceState 처리 오류', e))); - client.on(Events.InteractionCreate, (i) => { - if (i.isChatInputCommand()) void this.onCommand(i).catch((e) => log.error('명령 처리 오류', e)); - }); - client.on(Events.Error, (e) => log.error('discord 오류', e)); - client.on(Events.GuildCreate, () => this.refreshGuilds()); + this.gateway = gw; + const mine = (fn: (...a: any[]) => void) => (...a: any[]) => { + if (this.gateway === gw) fn(...a); + }; + gw.on('ready', mine(() => void this.onReady().catch((e) => log.error('봇 준비 처리 오류', e)))); + gw.on('guilds', mine(() => this.refreshGuilds())); + gw.on('voiceState', mine((e: GVoiceEvent) => void this.onVoiceState(e).catch((err) => log.error('voiceState 처리 오류', err)))); + gw.on('command', mine((c: GCommand, respond: (content: string) => void) => void this.onCommand(c).then(respond, (e) => respond(`처리하지 못했습니다: ${e.message}`)))); + gw.on('taken', mine((guildId: string) => { + if (this.connection && this.state.recording.channelId && this.state.guild?.id === guildId) { + log.warn('다른 PC 가 이 서버에서 겜녹이 봇을 데려가 녹음을 멈춥니다'); + this.leave('taken'); + } + })); + gw.on('down', mine(() => { + this.leave('gateway-down'); + this.state.status = 'connecting'; + this.state.error = '연결이 끊겨 다시 연결하는 중입니다'; + })); + gw.on('unauthorized', mine(() => { + this.state.status = 'error'; + this.state.error = '로그인이 만료되었거나 등록이 해제되었습니다'; + })); try { - await client.login(token); + await gw.start(); } catch (e: any) { + if (this.gateway !== gw) return; this.state.status = 'error'; this.state.error = e?.message?.includes('TOKEN_INVALID') || e?.code === 'TokenInvalid' ? '봇 토큰이 올바르지 않습니다' : e.message; - this.client = null; + // 겜녹이 봇(서버 중계)은 뒤에서 계속 다시 붙는다. 다른 봇은 토큰이 틀렸을 수 있으니 멈춘다 + if (gw.kind === 'local') { + this.gateway = null; + await gw.stop().catch(() => undefined); + } throw e; } } async stop(): Promise { this.leave('stop'); - if (this.client) { - await this.client.destroy(); - this.client = null; + const gw = this.gateway; + this.gateway = null; + if (gw) { + gw.removeAllListeners(); + await gw.stop(); } this.state.status = 'off'; + this.state.user = null; + } + + /** 녹음에서 빼야 하는 다른 봇인지 */ + isBot(userId: string): boolean { + return !!this.gateway?.isBot(userId); } private refreshGuilds(): void { - if (!this.client) return; - this.state.guilds = [...this.client.guilds.cache.values()].map((g) => ({ id: g.id, name: g.name })); + this.state.guilds = (this.gateway?.guilds() ?? []).map((g) => ({ id: g.id, name: g.name })); } - guild(): Guild | null { - if (!this.client) return null; + /** 녹음할 디스코드 서버 아이디 (설정값, 없으면 봇이 들어간 첫 서버) */ + guildId(): string | null { + const gs = this.gateway?.guilds() ?? []; const id = this.settings().discord.guildId; - return (id && this.client.guilds.cache.get(id)) || this.client.guilds.cache.first() || null; + return (id && gs.find((g) => g.id === id)?.id) || gs[0]?.id || null; + } + + members(): Promise { + const gid = this.guildId(); + return gid && this.gateway ? this.gateway.members(gid) : Promise.resolve([]); } private async onReady(): Promise { - const c = this.client!; + const gw = this.gateway!; + const me = gw.me()!; this.state.status = 'ready'; - this.state.user = { id: c.user!.id, name: c.user!.username, avatar: c.user!.displayAvatarURL({ size: 128 }) }; + this.state.error = null; + this.state.user = { id: me.id, name: me.name, avatar: me.avatar }; this.refreshGuilds(); - const g = this.guild(); - log.info(`봇 로그인: ${c.user!.tag}, 서버 ${this.state.guilds.map((x) => x.name).join(', ')}`); - if (!g) return; - this.state.guild = { id: g.id, name: g.name, icon: g.iconURL({ size: 128 }) }; + log.info(`봇 로그인: ${me.name}${gw.kind === 'remote' ? ' (사이트 서버 중계)' : ''}, 서버 ${this.state.guilds.map((x) => x.name).join(', ')}`); + const gid = this.guildId(); + if (!gid) return; + const g = await gw.watch(gid, { commands: this.settings().discord.commandsEnabled }); + if (!g || this.gateway !== gw) return; + this.state.guild = { id: g.id, name: g.name, icon: g.icon }; this.onGuild?.(g.id); - if (this.settings().discord.commandsEnabled) { - try { - await g.commands.set(COMMANDS); - log.info('슬래시 명령 등록 완료'); - } catch (e) { - log.warn('슬래시 명령 등록 실패', e); - } - } // 이미 따라갈 유저가 음성채널에 있으면 바로 들어간다 const follow = this.settings().discord.followUserId; if (follow && this.settings().discord.followEnabled) { - const m = await g.members.fetch(follow).catch(() => null); - if (m?.voice.channel) await this.join(m.voice.channel, 'follow'); + const ch = gw.voiceChannelOf(g.id, follow); + if (ch) await this.join(ch, 'follow').catch((e) => log.warn(`따라가기 실패: ${e.message}`)); } } - private async onVoiceState(o: VoiceState, n: VoiceState): Promise { - const g = this.guild(); - if (!g || n.guild.id !== g.id) return; + private async onVoiceState(e: GVoiceEvent): Promise { + const gid = this.state.guild?.id; + if (!gid || e.guildId !== gid) return; const s = this.settings().discord; - const uid = n.id; - if (uid === this.client?.user?.id) { + const uid = e.member.id; + if (uid === this.state.user?.id) { // 누군가 봇을 끊었으면 세션 종료 - if (o.channelId && !n.channelId) this.leave('kicked'); + if (e.oldChannelId && !e.newChannelId) this.leave('kicked'); return; } // 따라가기 - if (s.followEnabled && s.followUserId === uid && o.channelId !== n.channelId) { - if (n.channel) await this.join(n.channel, 'follow'); + if (s.followEnabled && s.followUserId === uid && e.oldChannelId !== e.newChannelId) { + if (e.channel) await this.join(e.channel, 'follow'); else if (this.state.recording.reason === 'follow') this.leave('follow-left'); } const myCh = this.state.recording.channelId; if (!myCh) return; // 새 사람이 들어오면 안내를 다시 튼다 - if (n.channelId === myCh && o.channelId !== myCh && n.member && (!n.member.user.bot || process.env.GVR_RECORD_BOTS === '1')) { - this.touchUser(n.member); + if (e.newChannelId === myCh && e.oldChannelId !== myCh && (!e.member.bot || process.env.GVR_RECORD_BOTS === '1')) { + this.touchUser(e.member); this.updateParticipants(); if (s.ttsEnabled && s.ttsOnNewMember) void this.announce(); } - if (o.channelId === myCh && n.channelId !== myCh) this.updateParticipants(); + if (e.oldChannelId === myCh && e.newChannelId !== myCh) this.updateParticipants(); } - private touchUser(m: GuildMember): void { - this.store.upsertUser({ id: m.id, name: m.displayName, avatar: m.displayAvatarURL({ size: 128 }) }); + private touchUser(m: GMember): void { + this.store.upsertUser({ id: m.id, name: m.name, avatar: m.avatar }); + } + + private channelMembers(): GMember[] { + const id = this.state.recording.channelId; + const gid = this.state.guild?.id; + return id && gid && this.gateway ? this.gateway.channelMembers(gid, id) : []; } private updateParticipants(): void { - const ch = this.currentChannel(); + const inCh = !!this.state.recording.channelId; // GVR_RECORD_BOTS=1 (테스트봇으로 시험할 때)이면 봇도 사람처럼 센다. 안 그러면 30초 뒤 '빈 방'으로 나가 버린다. - const humans = ch ? [...ch.members.values()].filter((m) => !m.user.bot || (process.env.GVR_RECORD_BOTS === '1' && m.id !== this.client?.user?.id)) : []; + const humans = this.channelMembers().filter((m) => !m.bot || (process.env.GVR_RECORD_BOTS === '1' && m.id !== this.state.user?.id)); this.state.recording.participants = humans.map((m) => m.id); this.emitState(); // 사람이 아무도 없으면 30초 뒤 나간다 if (this.emptyTimer) clearTimeout(this.emptyTimer); this.emptyTimer = null; - if (ch && humans.length === 0) this.emptyTimer = setTimeout(() => this.leave('empty'), 30000); + if (inCh && humans.length === 0) this.emptyTimer = setTimeout(() => this.leave('empty'), 30000); } - private currentChannel(): VoiceBasedChannel | null { - const id = this.state.recording.channelId; - if (!id || !this.client) return null; - const ch = this.client.channels.cache.get(id); - return ch && (ch.type === ChannelType.GuildVoice || ch.type === ChannelType.GuildStageVoice) ? (ch as VoiceBasedChannel) : null; - } - - async join(channel: VoiceBasedChannel, reason: 'follow' | 'command'): Promise { + async join(channel: GChannel, reason: 'follow' | 'command'): Promise { + const gw = this.gateway; + const gid = this.state.guild?.id; + if (!gw || !gid) throw new Error('봇이 준비되지 않았습니다'); if (this.state.recording.channelId === channel.id && this.connection) return; if (this.connection) this.leave('move'); log.info(`음성채널 참여: ${channel.name} (${reason})`); const conn = joinVoiceChannel({ channelId: channel.id, - guildId: channel.guild.id, - adapterCreator: channel.guild.voiceAdapterCreator, + guildId: gid, + adapterCreator: gw.adapterCreator(gid), selfDeaf: false, selfMute: false, daveEncryption: true, @@ -221,20 +232,29 @@ export class Bot { if (this.connection === conn) this.leave('disconnected'); } }); + // 연결 통로가 끊겨 어댑터가 사라진 경우 (서버 중계 끊김 등) + conn.on(VoiceConnectionStatus.Destroyed, () => { + if (this.connection === conn) this.leave('destroyed'); + }); try { await entersState(conn, VoiceConnectionStatus.Ready, 20000); } catch (e) { log.error('음성채널 연결 실패', e); - conn.destroy(); if (this.connection === conn) this.connection = null; + try { + conn.destroy(); + } catch { + /* 이미 끊김 */ + } throw new Error('음성채널 연결 실패'); } + if (this.connection !== conn) throw new Error('음성채널 연결이 끊겼습니다'); const now = Date.now(); this.sessionId = newId(now); - this.store.startSession(this.sessionId, channel.guild.id, channel.id, channel.name, now); - for (const m of channel.members.values()) if (!m.user.bot || process.env.GVR_RECORD_BOTS === '1') this.touchUser(m); - this.bus.live({ type: 'users.updated', data: [] }); + this.store.startSession(this.sessionId, gid, channel.id, channel.name, now); this.state.recording = { active: true, channel: channel.name, channelId: channel.id, since: now, participants: [], reason }; + for (const m of this.channelMembers()) if (!m.bot || process.env.GVR_RECORD_BOTS === '1') this.touchUser(m); + this.bus.live({ type: 'users.updated', data: [] }); this.recorder.attach(conn, this.sessionId); this.player = createAudioPlayer({ behaviors: { noSubscriber: NoSubscriberBehavior.Pause } }); conn.subscribe(this.player); @@ -246,15 +266,16 @@ export class Bot { if (this.emptyTimer) clearTimeout(this.emptyTimer); this.emptyTimer = null; this.recorder.detach(); - if (this.connection) { + const conn = this.connection; + this.connection = null; + if (conn) { log.info(`음성채널 나감 (${why})`); try { - this.connection.destroy(); + conn.destroy(); } catch { /* 이미 끊김 */ } } - this.connection = null; this.player?.stop(true); this.player = null; if (this.sessionId) this.store.endSession(this.sessionId, Date.now()); @@ -284,36 +305,35 @@ export class Bot { this.bus.live({ type: 'recording.state', data: { active: r.active, channel: r.channel, since: r.since, participants: r.participants } }); } - private async onCommand(i: ChatInputCommandInteraction): Promise { - const reply = (content: string) => i.reply({ content, flags: MessageFlags.Ephemeral }); - const member = i.member as GuildMember | null; - switch (i.commandName) { + /** 슬래시 명령 처리. 돌려준 문장이 본인에게만 보이는 응답이 된다 */ + private async onCommand(c: GCommand): Promise { + if (c.guildId !== this.state.guild?.id) return '이 서버는 겜녹이 앱의 녹음 서버로 설정되어 있지 않습니다.'; + switch (c.name) { case '녹음시작': { - const ch = member?.voice?.channel; - if (!ch) return void (await reply('먼저 음성채널에 들어가 주세요.')); - await i.deferReply({ flags: MessageFlags.Ephemeral }); + const ch = c.voiceChannel; + if (!ch) return '먼저 음성채널에 들어가 주세요.'; try { await this.join(ch, 'command'); - await i.editReply(`🎙️ ${ch.name} 채널 녹음을 시작했습니다.`); + return `🎙️ ${ch.name} 채널 녹음을 시작했습니다.`; } catch (e: any) { - await i.editReply(`음성채널에 들어가지 못했습니다: ${e.message}`); + return `음성채널에 들어가지 못했습니다: ${e.message}`; } - return; } case '녹음종료': - if (!this.connection) return void (await reply('지금은 녹음 중이 아닙니다.')); + if (!this.connection) return '지금은 녹음 중이 아닙니다.'; this.leave('command'); - return void (await reply('⏹️ 녹음을 끝냈습니다.')); + return '⏹️ 녹음을 끝냈습니다.'; case '녹음제외': - if (member) this.touchUser(member); - this.store.setExcluded(i.user.id, true); + this.touchUser(c.user); + this.store.setExcluded(c.user.id, true); this.bus.live({ type: 'users.updated', data: [] }); - return void (await reply('🔇 이제부터 내 목소리는 녹음하지 않습니다. 다시 참여하려면 /녹음참여 를 입력하세요.')); + return '🔇 이제부터 내 목소리는 녹음하지 않습니다. 다시 참여하려면 /녹음참여 를 입력하세요.'; case '녹음참여': - if (member) this.touchUser(member); - this.store.setExcluded(i.user.id, false); + this.touchUser(c.user); + this.store.setExcluded(c.user.id, false); this.bus.live({ type: 'users.updated', data: [] }); - return void (await reply('🎙️ 다시 녹음에 참여합니다.')); + return '🎙️ 다시 녹음에 참여합니다.'; } + return '알 수 없는 명령입니다.'; } } diff --git a/app/src/core/discord/gateway.ts b/app/src/core/discord/gateway.ts new file mode 100644 index 0000000..6743c26 --- /dev/null +++ b/app/src/core/discord/gateway.ts @@ -0,0 +1,437 @@ +// 봇이 디스코드와 이야기하는 통로 두 가지 +// - LocalGateway: '다른 봇으로 진행하기' (사용자가 넣은 봇 토큰으로 이 PC 가 직접 연결) +// - RemoteGateway: 겜녹이 봇. 봇 토큰은 사이트 서버에만 있고, 이 PC 는 서버(/app/bot/ws)를 거쳐 정보만 받는다. +// 음성채널에 들어갈 때 서버가 디스코드에서 받은 일회용 음성 접속 정보를 넘겨주고, 음성은 이 PC ↔ 디스코드로 바로 간다 +import type { DiscordGatewayAdapterCreator, DiscordGatewayAdapterLibraryMethods } from '@discordjs/voice'; +import type { BotGwChannel, BotGwFromApp, BotGwGuild, BotGwMember, BotGwToApp } from '@gvr/shared'; +import { ChannelType, Client, Events, GatewayIntentBits, MessageFlags, type Guild, type GuildMember, type VoiceBasedChannel } from 'discord.js'; +import { EventEmitter } from 'node:events'; +import WebSocket from 'ws'; +import { logger } from '../util/log.js'; + +const log = logger('gateway'); + +export type GMember = BotGwMember; +export type GGuild = BotGwGuild; +export type GChannel = BotGwChannel; +export interface GVoiceEvent { + guildId: string; + member: GMember; + oldChannelId: string | null; + newChannelId: string | null; + channel: GChannel | null; +} +export interface GCommand { + name: string; + guildId: string; + user: GMember; + voiceChannel: GChannel | null; +} + +export const COMMANDS = [ + { name: '녹음시작', description: '겜녹이를 내가 있는 음성채널로 불러 녹음을 시작합니다' }, + { name: '녹음종료', description: '겜녹이가 음성채널에서 나가고 녹음을 끝냅니다' }, + { name: '녹음제외', description: '내 목소리를 녹음하지 않습니다 (다음 세션에도 유지)' }, + { name: '녹음참여', description: '녹음 제외를 풀고 다시 녹음에 참여합니다' }, +]; + +/** + * 이벤트: 'ready' · 'guilds' · 'voiceState' (GVoiceEvent) · 'command' (GCommand, respond(content)) · + * 'taken' (guildId: 다른 PC 가 봇을 데려감) · 'down' (연결 끊김) · 'unauthorized' (앱 로그인 만료 · 등록 해제) + */ +export interface BotGateway extends EventEmitter { + readonly kind: 'local' | 'remote'; + me(): GMember | null; + guilds(): GGuild[]; + start(): Promise; + stop(): Promise; + /** 이 서버의 음성 상태를 따라간다 (명령 등록 포함) */ + watch(guildId: string, opts: { commands: boolean }): Promise; + voiceChannelOf(guildId: string, userId: string): GChannel | null; + channel(guildId: string, channelId: string): GChannel | null; + channelMembers(guildId: string, channelId: string): GMember[]; + members(guildId: string): Promise; + isBot(userId: string): boolean; + adapterCreator(guildId: string): DiscordGatewayAdapterCreator; +} + +const gm = (m: GuildMember): GMember => ({ id: m.id, name: m.displayName, avatar: m.displayAvatarURL({ size: 128 }), bot: m.user.bot }); +const gg = (g: Guild): GGuild => ({ id: g.id, name: g.name, icon: g.iconURL({ size: 128 }) }); +const isVoice = (c: { type: ChannelType } | null | undefined): c is VoiceBasedChannel => !!c && (c.type === ChannelType.GuildVoice || c.type === ChannelType.GuildStageVoice); + +// ------------------------------------------------------------------ 다른 봇 (토큰으로 직접 연결) +export class LocalGateway extends EventEmitter implements BotGateway { + readonly kind = 'local'; + private client: Client | null = null; + + constructor(private token: string) { + super(); + } + + async start(): Promise { + const c = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildVoiceStates, GatewayIntentBits.GuildMembers] }); + this.client = c; + c.on(Events.ClientReady, () => this.emit('ready')); + c.on(Events.GuildCreate, () => this.emit('guilds')); + c.on(Events.GuildDelete, () => this.emit('guilds')); + c.on(Events.Error, (e) => log.error('discord 오류', e)); + c.on(Events.VoiceStateUpdate, (o, n) => { + const m = n.member ?? o.member; + if (!m) return; + const ch = n.channel; + this.emit('voiceState', { guildId: n.guild.id, member: gm(m), oldChannelId: o.channelId, newChannelId: n.channelId, channel: ch ? { id: ch.id, name: ch.name } : null } satisfies GVoiceEvent); + }); + c.on(Events.InteractionCreate, async (i) => { + if (!i.isChatInputCommand() || !i.guildId) return; + try { + await i.deferReply({ flags: MessageFlags.Ephemeral }); + } catch (e) { + log.error('명령 응답 실패', e); + return; + } + const m = (i.member as GuildMember | null) ?? null; + const vc = m?.voice?.channel ?? null; + const cmd: GCommand = { + name: i.commandName, + guildId: i.guildId, + user: m ? gm(m) : { id: i.user.id, name: i.user.username, avatar: null, bot: i.user.bot }, + voiceChannel: vc ? { id: vc.id, name: vc.name } : null, + }; + this.emit('command', cmd, (content: string) => void i.editReply(content).catch((e) => log.error('명령 응답 실패', e))); + }); + try { + await c.login(this.token); + } catch (e) { + this.client = null; + throw e; + } + } + + async stop(): Promise { + const c = this.client; + this.client = null; + await c?.destroy(); + } + + me(): GMember | null { + const u = this.client?.isReady() ? this.client.user : null; + return u ? { id: u.id, name: u.username, avatar: u.displayAvatarURL({ size: 128 }), bot: true } : null; + } + guilds(): GGuild[] { + return this.client ? [...this.client.guilds.cache.values()].map(gg) : []; + } + private g(id: string): Guild | null { + return this.client?.guilds.cache.get(id) ?? null; + } + async watch(guildId: string, opts: { commands: boolean }): Promise { + const g = this.g(guildId); + if (!g) return null; + if (opts.commands) { + try { + await g.commands.set(COMMANDS); + log.info('슬래시 명령 등록 완료'); + } catch (e) { + log.warn('슬래시 명령 등록 실패', e); + } + } + return gg(g); + } + voiceChannelOf(guildId: string, userId: string): GChannel | null { + const ch = this.g(guildId)?.voiceStates.cache.get(userId)?.channel; + return ch ? { id: ch.id, name: ch.name } : null; + } + channel(guildId: string, channelId: string): GChannel | null { + const ch = this.g(guildId)?.channels.cache.get(channelId); + return isVoice(ch) ? { id: ch.id, name: ch.name } : null; + } + channelMembers(guildId: string, channelId: string): GMember[] { + const ch = this.g(guildId)?.channels.cache.get(channelId); + return isVoice(ch) ? [...ch.members.values()].map(gm) : []; + } + async members(guildId: string): Promise { + const g = this.g(guildId); + if (!g) return []; + const ms = await g.members.fetch().catch(() => g.members.cache); + return [...ms.values()].map(gm); + } + isBot(userId: string): boolean { + return !!this.client?.users.cache.get(userId)?.bot; + } + adapterCreator(guildId: string): DiscordGatewayAdapterCreator { + const g = this.g(guildId); + if (!g) throw new Error('디스코드 서버를 찾지 못했습니다'); + return g.voiceAdapterCreator; + } +} + +// ------------------------------------------------------------------ 겜녹이 봇 (사이트 서버 중계) +export interface RemoteGatewayOptions { + serverUrl: () => string; + appToken: () => string | null; + version: string; +} + +export class RemoteGateway extends EventEmitter implements BotGateway { + readonly kind = 'remote'; + private ws: WebSocket | null = null; + private stopped = true; + private retries = 0; + private retryTimer: NodeJS.Timeout | null = null; + private _me: GMember | null = null; + private _guilds: GGuild[] = []; + private watched: { id: string; commands: boolean } | null = null; + private wait: { resolve: (g: GGuild | null) => void } | null = null; + private channels = new Map(); + /** userId → 음성채널 */ + private voice = new Map(); + private known = new Map(); + private adapters = new Map(); + private reqs = new Map void; reject: (e: Error) => void }>(); + private seq = 0; + lastError: string | null = null; + + constructor(private opts: RemoteGatewayOptions) { + super(); + } + + /** 서버에 붙어 ready 를 받을 때까지 기다린다 (실패해도 뒤에서 계속 다시 붙는다) */ + start(): Promise { + this.stopped = false; + return new Promise((resolve, reject) => { + const t = setTimeout(() => { + cleanup(); + reject(new Error(this.lastError || '사이트 서버의 겜녹이 봇에 연결하지 못했습니다')); + }, 20000); + const ok = () => { + cleanup(); + resolve(); + }; + const bad = () => { + cleanup(); + reject(new Error(this.lastError || '다시 로그인해 주세요')); + }; + const cleanup = () => { + clearTimeout(t); + this.off('ready', ok); + this.off('unauthorized', bad); + }; + this.once('ready', ok); + this.once('unauthorized', bad); + this.connect(); + }); + } + + async stop(): Promise { + this.stopped = true; + if (this.retryTimer) clearTimeout(this.retryTimer); + this.retryTimer = null; + const ws = this.ws; + this.ws = null; + this.reset(); + ws?.close(1000); + } + + private reset(): void { + this._me = null; + for (const a of this.adapters.values()) a.destroy(); + this.adapters.clear(); + for (const r of this.reqs.values()) r.reject(new Error('사이트 서버 연결이 끊겼습니다')); + this.reqs.clear(); + this.wait?.resolve(null); + this.wait = null; + } + + private connect(): void { + if (this.stopped) return; + const token = this.opts.appToken(); + if (!token) { + this.lastError = '로그인이 필요합니다'; + this.emit('unauthorized'); + return; + } + const url = this.opts.serverUrl().replace(/\/$/, '').replace(/^http/, 'ws') + '/app/bot/ws'; + const ws = new WebSocket(url, { headers: { authorization: `Bearer ${token}`, 'x-gvr-version': this.opts.version }, handshakeTimeout: 10000, maxPayload: 8 * 1024 * 1024 }); + this.ws = ws; + let unauthorized = false; + let alive = Date.now(); + const ping = setInterval(() => { + // 서버가 30초마다 ping 을 보낸다. 75초 동안 아무것도 없으면 끊고 다시 붙는다 + if (Date.now() - alive > 75000) ws.terminate(); + }, 15000); + ws.on('ping', () => (alive = Date.now())); + ws.on('open', () => { + this.retries = 0; + alive = Date.now(); + log.info('사이트 서버 겜녹이 봇 중계 연결됨'); + }); + ws.on('message', (data) => { + alive = Date.now(); + let m: BotGwToApp; + try { + m = JSON.parse(String(data)); + } catch { + return; + } + this.onMessage(m); + }); + ws.on('unexpected-response', (_req, res) => { + unauthorized = res.statusCode === 401; + this.lastError = unauthorized ? '로그인이 만료되었습니다. 다시 로그인해 주세요' : res.statusCode === 503 ? '사이트 서버에 겜녹이 봇이 켜져 있지 않습니다' : `사이트 서버 응답 ${res.statusCode}`; + }); + ws.on('error', (e) => { + this.lastError ||= `사이트 서버에 연결할 수 없습니다 (${e.message})`; + }); + ws.on('close', (code) => { + clearInterval(ping); + if (this.ws !== ws) return; + this.ws = null; + const wasReady = !!this._me; + this.reset(); + if (wasReady) this.emit('down'); + if (unauthorized || code === 4401) { + this.lastError = '로그인이 만료되었거나 등록이 해제되었습니다'; + this.emit('unauthorized'); + } + if (this.stopped) return; + const delay = Math.min(30000, 1000 * 2 ** Math.min(this.retries++, 5)); + this.retryTimer = setTimeout(() => this.connect(), delay); + }); + } + + private send(m: BotGwFromApp): boolean { + if (this.ws?.readyState !== WebSocket.OPEN) return false; + this.ws.send(JSON.stringify(m)); + return true; + } + + private remember(m: GMember): void { + this.known.set(m.id, m); + } + + private onMessage(m: BotGwToApp): void { + switch (m.t) { + case 'ready': + this.lastError = null; + this._me = m.me; + this._guilds = m.guilds; + this.emit('ready'); + return; + case 'guilds': + this._guilds = m.guilds; + this.emit('guilds'); + return; + case 'guild': + if (this.watched?.id !== m.guild.id) return; + this.channels.clear(); + this.voice.clear(); + for (const c of m.channels) this.channels.set(c.id, c); + for (const v of m.voice) { + this.remember(v.member); + this.voice.set(v.member.id, v.channelId); + } + this.wait?.resolve(m.guild); + this.wait = null; + return; + case 'voiceState': + if (this.watched?.id !== m.guildId) return; + this.remember(m.member); + if (m.channel) this.channels.set(m.channel.id, m.channel); + if (m.newChannelId) this.voice.set(m.member.id, m.newChannelId); + else this.voice.delete(m.member.id); + this.emit('voiceState', { guildId: m.guildId, member: m.member, oldChannelId: m.oldChannelId, newChannelId: m.newChannelId, channel: m.channel } satisfies GVoiceEvent); + return; + case 'cmd': { + this.remember(m.user); + const cmd: GCommand = { name: m.name, guildId: m.guildId, user: m.user, voiceChannel: m.voiceChannel }; + this.emit('command', cmd, (content: string) => void this.send({ t: 'cmd_res', id: m.id, content })); + return; + } + case 'vserver': + this.adapters.get(m.guildId)?.onVoiceServerUpdate(m.data); + return; + case 'vstate': + this.adapters.get(m.guildId)?.onVoiceStateUpdate(m.data); + return; + case 'taken': + this.emit('taken', m.guildId); + return; + case 'res': { + const r = this.reqs.get(m.id); + if (!r) return; + this.reqs.delete(m.id); + if (m.ok) r.resolve(m.data); + else r.reject(new Error(m.error || '요청 실패')); + return; + } + } + } + + me(): GMember | null { + return this._me; + } + guilds(): GGuild[] { + return this._me ? this._guilds : []; + } + watch(guildId: string, opts: { commands: boolean }): Promise { + this.watched = { id: guildId, ...opts }; + this.wait?.resolve(null); + return new Promise((resolve) => { + if (!this.send({ t: 'watch', guildId, commands: opts.commands })) return resolve(null); + const t = setTimeout(() => { + if (this.wait?.resolve === done) this.wait = null; + resolve(null); + }, 10000); + const done = (g: GGuild | null) => { + clearTimeout(t); + resolve(g); + }; + this.wait = { resolve: done }; + }); + } + voiceChannelOf(_guildId: string, userId: string): GChannel | null { + const id = this.voice.get(userId); + return id ? (this.channels.get(id) ?? { id, name: id }) : null; + } + channel(_guildId: string, channelId: string): GChannel | null { + return this.channels.get(channelId) ?? null; + } + channelMembers(_guildId: string, channelId: string): GMember[] { + const out: GMember[] = []; + for (const [uid, ch] of this.voice) if (ch === channelId) out.push(this.known.get(uid) ?? { id: uid, name: uid, avatar: null, bot: false }); + return out; + } + members(guildId: string): Promise { + const id = String(++this.seq); + return new Promise((resolve, reject) => { + if (!this.send({ t: 'req', id, op: 'members', guildId })) return reject(new Error('사이트 서버에 연결되어 있지 않습니다')); + const t = setTimeout(() => { + if (this.reqs.delete(id)) reject(new Error('사이트 서버 응답 없음')); + }, 20000); + this.reqs.set(id, { + resolve: (v) => { + clearTimeout(t); + for (const m of v as GMember[]) this.remember(m); + resolve(v); + }, + reject: (e) => { + clearTimeout(t); + reject(e); + }, + }); + }); + } + isBot(userId: string): boolean { + return !!this.known.get(userId)?.bot; + } + adapterCreator(guildId: string): DiscordGatewayAdapterCreator { + return (methods) => { + this.adapters.set(guildId, methods); + return { + sendPayload: (payload) => this.send({ t: 'voice', guildId, payload }), + destroy: () => { + if (this.adapters.get(guildId) === methods) this.adapters.delete(guildId); + }, + }; + }; + } +} diff --git a/app/src/core/index.ts b/app/src/core/index.ts index 790e982..4400556 100644 --- a/app/src/core/index.ts +++ b/app/src/core/index.ts @@ -5,6 +5,7 @@ import { buildApi } from './api/server.js'; import { Store } from './db/db.js'; import { Dictionary } from './dict/dictionary.js'; import { Bot } from './discord/bot.js'; +import { LocalGateway, RemoteGateway } from './discord/gateway.js'; import { Recorder } from './discord/recorder.js'; import { Announcer } from './discord/tts.js'; import { GameAssets } from './games/assets.js'; @@ -30,6 +31,8 @@ export interface CoreOptions { settings?: SettingsStore; /** 로컬 API 를 127.0.0.1 포트로도 연다 (설정 창·디버그용). 0 이면 열지 않음 */ apiPort?: number; + /** 겜녹이 봇 중계에서 로그인 만료 · 등록 해제를 알려 왔을 때 (Electron: 바로 다시 확인해서 잠근다) */ + onBotUnauthorized?: () => void; } export type Core = Awaited>; @@ -65,7 +68,7 @@ export async function startCore(opts: CoreOptions) { const u = store.getUser(uid); if (u?.excluded) return true; // 다른 봇(음악봇 등)은 녹음하지 않는다. 자동 테스트에서만 GVR_RECORD_BOTS=1 로 연다. - return process.env.GVR_RECORD_BOTS !== '1' && !!bot.client?.users.cache.get(uid)?.bot; + return process.env.GVR_RECORD_BOTS !== '1' && bot.isBot(uid); }, matchAt: (ts) => games.liveMatchAt(ts), }); @@ -112,16 +115,27 @@ export async function startCore(opts: CoreOptions) { relay.start(); if (opts.apiPort) await api.listen({ host: '127.0.0.1', port: opts.apiPort }); + // 겜녹이 봇: 봇 토큰은 사이트 서버에만 있다. 앱 로그인 토큰으로 서버 중계에 붙는다. + // 다른 봇: 사용자가 넣은 토큰으로 이 PC 가 직접 연결 (개발용 GVR_BOT_TOKEN 도 여기) const startBot = async () => { const token = settings.activeBotToken(); - if (!token) { - log.warn(S().discord.botMode === 'builtin' ? '이 빌드에는 겜녹이 기본 봇이 없습니다. 설정에서 다른 봇 토큰을 넣어 주세요.' : '봇 토큰이 없습니다. 설정에서 입력해 주세요.'); + let gw; + if (token) gw = new LocalGateway(token); + else if (S().discord.botMode === 'builtin') { + if (!settings.getSecret('appToken')) { + log.warn('로그인하지 않아 겜녹이 봇에 연결하지 않습니다'); + return; + } + gw = new RemoteGateway({ serverUrl: () => S().site.serverUrl, appToken: () => settings.getSecret('appToken') ?? null, version: opts.version }); + gw.on('unauthorized', () => opts.onBotUnauthorized?.()); + } else { + log.warn('봇 토큰이 없습니다. 설정에서 입력해 주세요.'); return; } try { - await bot.start(token); + await bot.start(gw); } catch (e: any) { - log.error(`봇 로그인 실패: ${e.message}`); + log.error(`봇 연결 실패: ${e.message}`); } }; await startBot(); diff --git a/app/src/core/settings.ts b/app/src/core/settings.ts index b4a8c29..c894f3a 100644 --- a/app/src/core/settings.ts +++ b/app/src/core/settings.ts @@ -71,7 +71,7 @@ export interface Secrets { riotApiKey?: string; /** 앱 로그인 토큰 (사이트 서버가 발급) */ appToken?: string; - /** 겜녹이 기본 봇 토큰. exe 에 들어 있지 않고, 로그인한 등록 유저에게 사이트 서버가 내려준다 */ + /** v1.2.0 이 받아 두던 겜녹이 봇 토큰. 이제 쓰지 않고 시작할 때 지운다 */ builtinBotToken?: string; /** 마지막으로 서버에서 확인한 로그인 정보 (서버에 잠깐 못 붙을 때 쓰는 사본) */ auth?: { user: AppUserInfo; role: AppRole; verifiedAt: number }; @@ -180,16 +180,18 @@ export class SettingsStore { if (saved && !saved.discord?.botMode && this.secrets.botToken) this.cur.discord.botMode = 'custom'; // 개발/헤드리스: 환경변수 토큰이 있으면 모드와 상관없이 그것을 쓴다 this.envBotToken = process.env.GVR_BOT_TOKEN || null; + // v1.2.0 은 서버에서 받은 겜녹이 봇 토큰을 저장해 두었다. 이제는 서버가 봇을 대신 연결하므로 남기지 않는다 + if (this.secrets.builtinBotToken) this.setSecret('builtinBotToken', null); } - /** 겜녹이 기본 봇 토큰을 받아 두었는지 (로그인하면 사이트 서버가 내려준다) */ + /** 겜녹이 봇을 쓸 수 있는지 (로그인해 있으면 사이트 서버 중계로 연결한다. 봇 토큰은 이 PC 에 오지 않는다) */ get hasBuiltinBot(): boolean { - return !!this.secrets.builtinBotToken; + return !!this.secrets.appToken; } - /** 지금 모드에서 봇이 로그인할 토큰 (없으면 null) */ + /** 이 PC 가 직접 로그인할 봇 토큰: 다른 봇 모드의 토큰 또는 개발용 GVR_BOT_TOKEN (겜녹이 봇은 null) */ activeBotToken(): string | null { if (this.envBotToken) return this.envBotToken; - return (this.cur.discord.botMode === 'builtin' ? this.secrets.builtinBotToken : this.secrets.botToken) || null; + return this.cur.discord.botMode === 'custom' ? this.secrets.botToken || null : null; } get(): Settings { diff --git a/app/src/main/ipc.ts b/app/src/main/ipc.ts index 60af944..4a4f581 100644 --- a/app/src/main/ipc.ts +++ b/app/src/main/ipc.ts @@ -87,7 +87,17 @@ export function registerIpc(ctx: IpcContext) { testBotToken: async (token?: string) => { const t = token || core.settings.activeBotToken(); - if (!t) return { ok: false, error: core.settings.get().discord.botMode === 'builtin' ? '이 빌드에는 겜녹이 봇이 들어 있지 않습니다. 다른 봇으로 진행해 주세요' : '봇 토큰을 입력해 주세요' }; + // 겜녹이 봇은 토큰이 이 PC 에 없다: 사이트 서버 중계로 붙어 보고 결과를 알려 준다 + if (!t && core.settings.get().discord.botMode === 'builtin') { + const b = core.bot; + if (b.state.status !== 'ready' || b.gateway?.kind !== 'remote') { + await b.stop(); + await core.startBot(); + } + if (b.state.status !== 'ready' || !b.state.user) return { ok: false, error: b.state.error ?? '사이트 서버의 겜녹이 봇에 연결하지 못했습니다' }; + return { ok: true, bot: b.state.user, guilds: b.state.guilds }; + } + if (!t) return { ok: false, error: '봇 토큰을 입력해 주세요' }; const get = (p: string) => fetch(`https://discord.com/api/v10${p}`, { headers: { authorization: `Bot ${t}` } }); try { const me = await get('/users/@me'); @@ -110,10 +120,8 @@ export function registerIpc(ctx: IpcContext) { return core.bot.state.status === 'ready' || core.bot.state.status === 'connecting' ? { ok: true } : { ok: false, error: core.bot.state.error ?? '봇을 시작하지 못했습니다' }; }, guildMembers: async () => { - const g = core.bot.guild(); - if (!g) return []; - const ms = await g.members.fetch().catch(() => g.members.cache); - return [...ms.values()].map((m) => ({ id: m.id, name: m.displayName, avatar: m.displayAvatarURL({ size: 64 }), bot: m.user.bot })).sort((a, b) => a.name.localeCompare(b.name, 'ko')); + const ms = await core.bot.members().catch(() => []); + return ms.map((m) => ({ id: m.id, name: m.name, avatar: m.avatar, bot: m.bot })).sort((a, b) => a.name.localeCompare(b.name, 'ko')); }, previewTts: async (text: string, voice: string) => { try { diff --git a/app/src/main/main.ts b/app/src/main/main.ts index 44e1815..8ae0f73 100644 --- a/app/src/main/main.ts +++ b/app/src/main/main.ts @@ -204,17 +204,15 @@ const refreshShell = () => { }; let starting: Promise | null = null; -/** 서버에서 받은 겜녹이 봇 토큰. 서버에서 바뀌면 봇을 다시 연결한다 */ -let builtinSeen: string | null = null; /** 로그인 확인 후 코어 시작 */ function startApp(): Promise { if (core) return Promise.resolve(); starting ??= (async () => { try { - const c = await startCore({ dataDir, resourcesDir: resourcesDir(), worker: workerCommand(), version: app.getVersion(), settings: settings! }); + // 겜녹이 봇 중계가 로그인 만료 · 등록 해제를 알려 오면 10분을 기다리지 않고 바로 확인해서 잠근다 + const c = await startCore({ dataDir, resourcesDir: resourcesDir(), worker: workerCommand(), version: app.getVersion(), settings: settings!, onBotUnauthorized: () => void auth?.check() }); core = c; - builtinSeen = c.settings.getSecret('builtinBotToken') ?? null; ft = new Finetuner(c, pushState); ft.scheduleNightly(); appError = null; @@ -253,15 +251,6 @@ function onAuthChange(): void { const st = auth!.state.status; if (st === 'ok') { if (!core) return startApp(); - const t = core.settings.getSecret('builtinBotToken') ?? null; - if (t !== builtinSeen) { - builtinSeen = t; - if (core.settings.get().discord.botMode === 'builtin') { - log.info('서버에서 받은 겜녹이 봇 토큰이 바뀌어 봇을 다시 연결합니다'); - await core.bot.stop(); - await core.startBot(); - } - } } else if (st !== 'checking' && st !== 'waiting') { await stopApp(); openWindow(); diff --git a/app/src/renderer/tabs/DiscordTab.tsx b/app/src/renderer/tabs/DiscordTab.tsx index 87f92c5..4ae9e1f 100644 --- a/app/src/renderer/tabs/DiscordTab.tsx +++ b/app/src/renderer/tabs/DiscordTab.tsx @@ -111,7 +111,7 @@ export function BotTokenSection({ wizard, onResult }: { wizard?: boolean; onResu