앱 v1.2.1: 겜녹이 봇 토큰을 앱에 보내지 않고 사이트 서버가 봇을 대신 연결

- 사이트 서버: 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 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-15 10:30:14 +09:00
parent a2487e6241
commit 6a03c67b54
27 changed files with 1786 additions and 201 deletions

4
app/package-lock.json generated
View File

@@ -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",

View File

@@ -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",

View File

@@ -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<void>((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}`);

View File

@@ -2,6 +2,8 @@
// node --import tsx scripts/voice-e2e.mts <guildId> <voiceChannelId>
// 필요: 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<void>) | 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<void>((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);
}

View File

@@ -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;

View File

@@ -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<void> {
async start(gw: BotGateway): Promise<void> {
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<void> {
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<GMember[]> {
const gid = this.guildId();
return gid && this.gateway ? this.gateway.members(gid) : Promise.resolve([]);
}
private async onReady(): Promise<void> {
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<void> {
const g = this.guild();
if (!g || n.guild.id !== g.id) return;
private async onVoiceState(e: GVoiceEvent): Promise<void> {
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<void> {
async join(channel: GChannel, reason: 'follow' | 'command'): Promise<void> {
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<void> {
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<string> {
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 '알 수 없는 명령입니다.';
}
}

View File

@@ -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<void>;
stop(): Promise<void>;
/** 이 서버의 음성 상태를 따라간다 (명령 등록 포함) */
watch(guildId: string, opts: { commands: boolean }): Promise<GGuild | null>;
voiceChannelOf(guildId: string, userId: string): GChannel | null;
channel(guildId: string, channelId: string): GChannel | null;
channelMembers(guildId: string, channelId: string): GMember[];
members(guildId: string): Promise<GMember[]>;
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<void> {
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<void> {
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<GGuild | null> {
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<GMember[]> {
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<string, GChannel>();
/** userId → 음성채널 */
private voice = new Map<string, string>();
private known = new Map<string, GMember>();
private adapters = new Map<string, DiscordGatewayAdapterLibraryMethods>();
private reqs = new Map<string, { resolve: (v: any) => void; reject: (e: Error) => void }>();
private seq = 0;
lastError: string | null = null;
constructor(private opts: RemoteGatewayOptions) {
super();
}
/** 서버에 붙어 ready 를 받을 때까지 기다린다 (실패해도 뒤에서 계속 다시 붙는다) */
start(): Promise<void> {
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<void> {
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<GGuild | null> {
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<GMember[]> {
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);
},
};
};
}
}

View File

@@ -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<ReturnType<typeof startCore>>;
@@ -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();

View File

@@ -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 {

View File

@@ -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 {

View File

@@ -204,17 +204,15 @@ const refreshShell = () => {
};
let starting: Promise<void> | null = null;
/** 서버에서 받은 겜녹이 봇 토큰. 서버에서 바뀌면 봇을 다시 연결한다 */
let builtinSeen: string | null = null;
/** 로그인 확인 후 코어 시작 */
function startApp(): Promise<void> {
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();

View File

@@ -111,7 +111,7 @@ export function BotTokenSection({ wizard, onResult }: { wizard?: boolean; onResu
<div className="radio">
<button type="button" className={!custom ? 'on' : ''} disabled={saver.busy || (!admin && custom)} onClick={() => switchMode('builtin')}>
<b>🤖 겜녹이 봇으로 진행 {!custom && '✓'}</b>
<span className="muted">{state.builtinBot ? '기본값 · 토큰 입력 없이 바로 연결' : '겜녹이 봇 토큰을 아직 받지 못했습니다 (사이트 서버 연결 확인)'}</span>
<span className="muted">{state.builtinBot ? '기본값 · 사이트 서버를 거쳐 바로 연결' : '로그인해야 쓸 수 있습니다'}</span>
</button>
<button type="button" className={custom ? 'on' : ''} disabled={saver.busy || !admin} onClick={() => switchMode('custom')} title={admin ? undefined : '관리자만 바꿀 수 있습니다'}>
<b>🔑 다른 봇으로 진행하기 {custom && '✓'}</b>

View File

@@ -65,7 +65,7 @@ async function stack() {
return { base, browser, settingsFor, close: async () => (await app.close(), dc.close()) };
}
test('앱 로그인: 등록된 아이디만 열리고, 겜녹이 봇 토큰은 로그인 후 서버에서 받는다', async () => {
test('앱 로그인: 등록된 아이디만 열리고, 겜녹이 봇 토큰은 로그인해도 앱에 오지 않는다', async () => {
const s = await stack();
try {
// 로그인 전: 토큰 없음 → 로그인 화면
@@ -81,13 +81,16 @@ test('앱 로그인: 등록된 아이디만 열리고, 겜녹이 봇 토큰은
assert.equal(st.hasSecret('appToken'), false);
assert.equal(st.activeBotToken(), null);
// 최고 관리자 로그인 → 봇 토큰 받음
// 최고 관리자 로그인 → 앱 토큰만 받는다. 봇 토큰은 서버 응답 어디에도 없다
const adminSt = s.settingsFor();
const admin = new AppAuth(adminSt, { version: '1.2.0', openUrl: s.browser(SUPER), pollMs: 20 });
const r2 = await admin.login();
assert.equal(r2.status, 'ok');
assert.equal(r2.role, 'superadmin');
assert.equal(adminSt.activeBotToken(), BOT);
assert.equal(adminSt.hasBuiltinBot, true);
assert.equal(adminSt.activeBotToken(), null);
const me = await (await fetch(`${s.base}/app/me`, { headers: { authorization: `Bearer ${adminSt.getSecret('appToken')}` } })).text();
assert.ok(me.includes(SUPER) && !me.includes(BOT) && !me.includes('botToken'), me);
// 최고 관리자가 친구 등록 (관리자 화면 API)
const list = await admin.adminAddUser(FRIEND, 'user');
@@ -100,26 +103,27 @@ test('앱 로그인: 등록된 아이디만 열리고, 겜녹이 봇 토큰은
const r3 = await fr.login();
assert.equal(r3.status, 'ok');
assert.equal(r3.role, 'user');
assert.equal(frSt.activeBotToken(), BOT);
assert.equal(frSt.activeBotToken(), null);
await assert.rejects(fr.adminAddUser(STRANGER, 'user'), /최고 관리자만/);
await assert.rejects(fr.adminUsers(), /관리자만/);
// 다시 켜도 (새 SettingsStore) 로그인 유지
assert.equal((await new AppAuth(s.settingsFor(dir), { version: '1.2.0', openUrl: () => undefined }).check()).status, 'ok');
// 토큰 · 봇 토큰은 평문 settings.json 에 없다
assert.ok(!fs.readFileSync(path.join(dir, 'settings.json'), 'utf8').includes(BOT));
// 봇 토큰은 이 PC 어디에도 저장되지 않는다 (테스트는 평문 codec 이라 secrets.bin 도 그대로 읽힌다)
for (const f of fs.readdirSync(dir)) assert.ok(!fs.readFileSync(path.join(dir, f), 'utf8').includes(BOT), f);
// 등록 해제 → 다음 확인에서 잠기고 받아 둔 봇 토큰도 지운다
// 등록 해제 → 다음 확인에서 잠기고 앱 토큰을 지운다
await admin.adminRemoveUser(FRIEND);
const r4 = await fr.check();
assert.equal(r4.status, 'not_registered');
assert.equal(r4.user?.id, FRIEND);
assert.equal((await fr.check()).status, 'not_registered', '다시 확인해도 "등록되지 않은 아이디" 화면 유지');
assert.equal(frSt.activeBotToken(), null);
assert.equal(frSt.hasSecret('appToken'), false);
// 로그아웃 → 토큰 · 봇 토큰 삭제, 서버에서도 무효
// 로그아웃 → 토큰 삭제, 서버에서도 무효
await admin.logout();
assert.equal(admin.state.status, 'signed_out');
assert.equal(adminSt.activeBotToken(), null);
assert.equal(adminSt.hasBuiltinBot, false);
} finally {
await s.close();
}
@@ -136,7 +140,7 @@ test('앱 로그인: 서버에 못 붙으면 마지막 확인 후 유예 기간
const r = await auth.check();
assert.equal(r.status, 'ok');
assert.equal(r.offline, true);
assert.equal(st.activeBotToken(), BOT);
assert.equal(st.hasSecret('appToken'), true);
// 유예 기간이 지나면 막힌다 (토큰은 남겨 두어 서버가 돌아오면 다시 확인)
const late = new AppAuth(st, { version: '1.2.0', openUrl: () => undefined, offlineGraceMs: 0 });
const r2 = await late.check();
@@ -197,13 +201,12 @@ test('늦은 확인 응답: 등록 해제로 잠긴 뒤 이전 확인의 200 이
// 그 사이 등록 해제 → B: 403 → 잠김
await admin.adminRemoveUser(FRIEND);
assert.equal((await fr.check()).status, 'not_registered');
assert.equal(st.activeBotToken(), null);
// A 의 늦은 200 도착
release();
await a;
assert.equal(fr.state.status, 'not_registered', '늦은 200 이 잠금을 풀면 안 된다');
assert.equal(st.activeBotToken(), null, '지운 봇 토큰이 되살아나면 안 된다');
assert.equal(st.hasSecret('appToken'), false);
assert.equal(st.hasSecret('appToken'), false, '지운 앱 토큰이 되살아나면 안 된다');
assert.equal(st.hasSecret('auth'), false);
} finally {
h.restore();
await s.close();
@@ -225,10 +228,28 @@ test('늦은 확인 응답: 로그아웃 뒤 이전 확인의 200 이 와도 다
release();
await a;
assert.equal(auth.state.status, 'signed_out', '늦은 200 이 로그아웃을 되돌리면 안 된다');
assert.equal(st.activeBotToken(), null);
assert.equal(st.hasSecret('appToken'), false);
assert.equal(st.hasSecret('auth'), false);
} finally {
h.restore();
await s.close();
}
});
test('겹친 확인: 등록 해제 뒤 확인 두 개가 겹쳐도 "로그인 만료"가 아니라 "등록되지 않은 아이디"로 잠긴다', async () => {
// 봇 중계가 끊기며 바로 확인하는 사이 10분 확인 · 다시 확인 버튼이 겹치는 경우. 서버는 첫 403 에서 세션을 지워 뒤 확인은 401 을 받는다
const s = await stack();
try {
const admin = new AppAuth(s.settingsFor(), { version: 't', openUrl: s.browser(SUPER), pollMs: 20 });
await admin.login();
await admin.adminAddUser(FRIEND, 'user');
const fr = new AppAuth(s.settingsFor(), { version: 't', openUrl: s.browser(FRIEND), pollMs: 20 });
assert.equal((await fr.login()).status, 'ok');
await admin.adminRemoveUser(FRIEND);
await Promise.all([fr.check(), fr.check()]);
assert.equal(fr.state.status, 'not_registered');
assert.equal(fr.state.user?.id, FRIEND);
} finally {
await s.close();
}
});

View File

@@ -0,0 +1,309 @@
// 겜녹이 봇 중계: 앱 RemoteGateway ↔ 실제 사이트 서버 코드(BotBroker). 디스코드 게이트웨이만 가짜(FakeSource).
// 핵심: 봇 토큰은 서버 밖으로 나가지 않고, 앱은 지켜보는 서버의 음성 참여 · 나가기만 요청할 수 있다
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { EventEmitter } from 'node:events';
import fs from 'node:fs';
import http from 'node:http';
import os from 'node:os';
import path from 'node:path';
import type { BotGwChannel, BotGwGuild, BotGwMember } from '@gvr/shared';
import { buildServer } from '../../site/server/src/app.ts';
import type { BotCommand, BotSource } from '../../site/server/src/bot-broker.ts';
import { AppAuth } from '../src/core/auth.ts';
import { RemoteGateway } from '../src/core/discord/gateway.ts';
import { SettingsStore } from '../src/core/settings.ts';
const SUPER = '1352267557213573160';
const FRIEND = '111111111111111111';
const BOT = 'MTExMTExMTExMTExMTExMTEx.FAKE00.server-only-bot-token-xxxxxxxxx';
const G = '900000000000000001';
const OTHER_G = '900000000000000002';
const VC1 = '910000000000000001';
const VC2 = '910000000000000002';
const TEXT = '910000000000000009';
const tmp = () => fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-botgw-'));
delete process.env.GVR_BOT_TOKEN;
const m = (id: string, name: string, bot = false): BotGwMember => ({ id, name, avatar: null, bot });
const ME = m('800000000000000001', '겜녹이', true);
class FakeSource extends EventEmitter implements BotSource {
sent: { guildId: string; payload: any }[] = [];
handlers = new Map<string, { server: (d: any) => void; state: (d: any) => void }>();
commands: string[] = [];
me() {
return ME;
}
guilds(): BotGwGuild[] {
return [
{ id: G, name: 'M&L', icon: null },
{ id: OTHER_G, name: '다른 서버', icon: null },
];
}
snapshot(guildId: string) {
const g = this.guilds().find((x) => x.id === guildId);
if (!g) return null;
const channels: BotGwChannel[] = [
{ id: VC1, name: '일반' },
{ id: VC2, name: '게임' },
];
return { guild: g, channels, voice: [{ member: m(SUPER, '관리자'), channelId: VC1 }] };
}
isVoiceChannel(guildId: string, channelId: string) {
return guildId === G && (channelId === VC1 || channelId === VC2);
}
async members() {
return [m(SUPER, '관리자'), m(FRIEND, '친구'), m('700000000000000001', '음악봇', true)];
}
async registerCommands(guildId: string) {
this.commands.push(guildId);
}
voiceAdapter(guildId: string, handlers: { server: (d: any) => void; state: (d: any) => void }) {
this.handlers.set(guildId, handlers);
return {
send: (payload: any) => {
this.sent.push({ guildId, payload });
return true;
},
};
}
}
async function fakeDiscord() {
const names: Record<string, string> = { [SUPER]: '관리자', [FRIEND]: '친구' };
const srv = http.createServer((req, res) => {
const u = new URL(req.url!, 'http://x');
res.setHeader('content-type', 'application/json');
if (u.pathname === '/oauth2/token') {
let b = '';
req.on('data', (c) => (b += c));
req.on('end', () => res.end(JSON.stringify({ access_token: new URLSearchParams(b).get('code') })));
return;
}
if (u.pathname === '/users/@me') {
const id = String(req.headers.authorization).replace('Bearer ', '');
return res.end(JSON.stringify({ id, username: names[id], global_name: names[id], avatar: null }));
}
const mm = /^\/users\/(\d+)$/.exec(u.pathname);
if (mm && names[mm[1]!]) return res.end(JSON.stringify({ id: mm[1], username: names[mm[1]!], global_name: names[mm[1]!], avatar: null }));
res.statusCode = 404;
res.end('{}');
});
await new Promise<void>((r) => srv.listen(0, '127.0.0.1', () => r()));
return { url: `http://127.0.0.1:${(srv.address() as any).port}`, close: () => srv.close() };
}
async function stack() {
const dc = await fakeDiscord();
const source = new FakeSource();
const { app } = await buildServer(
{
port: 0, host: '127.0.0.1', publicUrl: 'http://placeholder', clientId: 'cid', clientSecret: 's', botToken: BOT,
allowedGuilds: [], owners: [SUPER], superAdmins: [SUPER], sessionSecret: 'x'.repeat(32), dataDir: tmp(), webDir: '/nonexistent',
version: 'test', discordApi: dc.url, assetUpstream: {},
},
{ botSource: source },
);
await app.listen({ host: '127.0.0.1', port: 0 });
const base = `http://127.0.0.1:${(app.server.address() as any).port}`;
const browser = (who: string) => 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')!;
const cookie = start.headers.getSetCookie()[0]!.split(';')[0]!;
await fetch(`${base}/auth/discord/callback?code=${who}&state=${encodeURIComponent(state)}`, { headers: { cookie }, redirect: 'manual' });
};
/** 로그인한 앱 하나 (설정 · 로그인 · 봇 중계) */
const pc = async (who: string) => {
const st = new SettingsStore(tmp());
st.update({ site: { serverUrl: base } });
const auth = new AppAuth(st, { version: 't', openUrl: browser(who), pollMs: 20 });
assert.equal((await auth.login()).status, 'ok');
const gw = new RemoteGateway({ serverUrl: () => base, appToken: () => st.getSecret('appToken') ?? null, version: 't' });
// 서버가 앱에 보낸 모든 메시지 (봇 토큰이 섞여 있지 않은지 본다)
const seen: string[] = [];
const orig = (gw as any).onMessage.bind(gw);
(gw as any).onMessage = (msg: any) => (seen.push(JSON.stringify(msg)), orig(msg));
return { st, auth, gw, seen };
};
return { base, source, pc, close: async () => (await app.close(), dc.close()) };
}
const until = async (cond: () => boolean, ms = 3000) => {
const end = Date.now() + ms;
while (!cond()) {
if (Date.now() > end) throw new Error('시간 초과');
await new Promise((r) => setTimeout(r, 10));
}
};
const op4 = (guildId: string, channelId: string | null) => ({ op: 4, d: { guild_id: guildId, channel_id: channelId, self_mute: false, self_deaf: false } });
test('봇 중계: 로그인 안 한 연결은 막히고, 로그인한 앱은 봇 토큰 없이 서버 정보 · 음성 상태를 받는다', async () => {
const s = await stack();
const a = await s.pc(SUPER);
try {
// 앱 토큰이 틀리면 401 → unauthorized
const bad = new RemoteGateway({ serverUrl: () => s.base, appToken: () => 'wrong-token', version: 't' });
await assert.rejects(bad.start(), /로그인/);
await bad.stop();
await a.gw.start();
assert.deepEqual(a.gw.me(), ME);
assert.deepEqual(a.gw.guilds().map((g) => g.id), [G, OTHER_G]);
const g = await a.gw.watch(G, { commands: true });
assert.equal(g?.name, 'M&L');
await until(() => s.source.commands.includes(G));
assert.deepEqual(a.gw.voiceChannelOf(G, SUPER), { id: VC1, name: '일반' });
assert.deepEqual(a.gw.channelMembers(G, VC1).map((x) => x.id), [SUPER]);
// 음성 상태 변화가 넘어온다
const evs: any[] = [];
a.gw.on('voiceState', (e) => evs.push(e));
s.source.emit('voiceState', { guildId: G, member: m(FRIEND, '친구'), oldChannelId: null, newChannelId: VC2, channel: { id: VC2, name: '게임' } });
s.source.emit('voiceState', { guildId: OTHER_G, member: m(FRIEND, '친구'), oldChannelId: null, newChannelId: '1', channel: null }); // 지켜보지 않는 서버
await until(() => evs.length === 1);
assert.deepEqual(a.gw.voiceChannelOf(G, FRIEND), { id: VC2, name: '게임' });
// 멤버 목록 (봇 판별)
const ms = await a.gw.members(G);
assert.equal(ms.length, 3);
assert.equal(a.gw.isBot('700000000000000001'), true);
assert.equal(a.gw.isBot(FRIEND), false);
assert.ok(a.seen.length > 3);
assert.ok(!a.seen.some((x) => x.includes(BOT)), '봇 토큰이 앱으로 가면 안 된다');
} finally {
await a.gw.stop();
await s.close();
}
});
test('봇 중계: 음성 참여는 서버가 대신 보내고 일회용 음성 접속 정보만 그 앱에 넘긴다', async () => {
const s = await stack();
const a = await s.pc(SUPER);
try {
await a.gw.start();
await a.gw.watch(G, { commands: false });
const got: any[] = [];
const adapter = a.gw.adapterCreator(G)({
onVoiceServerUpdate: (d) => got.push(['server', d]),
onVoiceStateUpdate: (d) => got.push(['state', d]),
destroy: () => got.push(['destroy']),
});
// 지켜보지 않는 서버 · 음성채널이 아닌 곳 · op 4 가 아닌 것은 서버가 버린다
a.gw.adapterCreator(OTHER_G)({ onVoiceServerUpdate: () => undefined, onVoiceStateUpdate: () => undefined, destroy: () => undefined }).sendPayload(op4(OTHER_G, '1'));
adapter.sendPayload(op4(G, TEXT));
adapter.sendPayload({ op: 2, d: { token: 'x' } });
adapter.sendPayload({ op: 4, d: { guild_id: OTHER_G, channel_id: VC1 } });
// 정상 참여
assert.equal(adapter.sendPayload({ op: 4, d: { guild_id: G, channel_id: VC1, self_mute: false, self_deaf: false, extra: 'x' } }), true);
await until(() => s.source.sent.length === 1);
assert.deepEqual(s.source.sent[0], { guildId: G, payload: op4(G, VC1) }, '검사한 필드만 다시 만들어 보낸다');
// 디스코드가 준 음성 접속 정보 → 앱의 @discordjs/voice 로
s.source.handlers.get(G)!.state({ guild_id: G, user_id: ME.id, session_id: 'sess-1', channel_id: VC1 });
s.source.handlers.get(G)!.server({ guild_id: G, token: 'one-time-voice-token', endpoint: 'voice.example:443' });
await until(() => got.length === 2);
assert.equal(got[0][0], 'state');
assert.equal(got[0][1].session_id, 'sess-1');
assert.equal(got[1][1].token, 'one-time-voice-token');
// 나가기
adapter.sendPayload(op4(G, null));
await until(() => s.source.sent.length === 2);
assert.equal(s.source.sent[1]!.payload.d.channel_id, null);
assert.ok(!a.seen.some((x) => x.includes(BOT)));
} finally {
await a.gw.stop();
await s.close();
}
});
test('봇 중계: 다른 PC 가 봇을 데려가면 이전 PC 는 taken 을 받고, 이전 PC 가 봇을 빼거나 음성 정보를 받지 못한다', async () => {
const s = await stack();
const a = await s.pc(SUPER);
const admin = new AppAuth(a.st, { version: 't', openUrl: () => undefined });
await admin.adminAddUser(FRIEND, 'user');
const b = await s.pc(FRIEND);
try {
await a.gw.start();
await b.gw.start();
await a.gw.watch(G, { commands: false });
await b.gw.watch(G, { commands: false });
const aGot: any[] = [];
const bGot: any[] = [];
const aAd = a.gw.adapterCreator(G)({ onVoiceServerUpdate: (d) => aGot.push(d), onVoiceStateUpdate: (d) => aGot.push(d), destroy: () => undefined });
const bAd = b.gw.adapterCreator(G)({ onVoiceServerUpdate: (d) => bGot.push(d), onVoiceStateUpdate: (d) => bGot.push(d), destroy: () => undefined });
const taken: string[] = [];
a.gw.on('taken', (g) => taken.push(g));
aAd.sendPayload(op4(G, VC1));
await until(() => s.source.sent.length === 1);
bAd.sendPayload(op4(G, VC2));
await until(() => taken.length === 1 && s.source.sent.length === 2);
assert.equal(taken[0], G);
// 이제 음성 접속 정보는 B 에게만
s.source.handlers.get(G)!.server({ guild_id: G, token: 'for-b' });
await until(() => bGot.length === 1);
assert.equal(aGot.length, 0);
// A 가 늦게 나가기를 보내도 B 의 봇을 빼지 않는다
aAd.sendPayload(op4(G, null));
await new Promise((r) => setTimeout(r, 100));
assert.equal(s.source.sent.length, 2);
// B 앱이 꺼지면 서버가 봇을 음성채널에서 뺀다
await b.gw.stop();
await until(() => s.source.sent.length === 3);
assert.equal(s.source.sent[2]!.payload.d.channel_id, null);
} finally {
await a.gw.stop();
await b.gw.stop();
await s.close();
}
});
test('봇 중계: 슬래시 명령은 그 서버를 지켜보는 앱으로 가고 앱의 답이 돌아간다. 등록 해제하면 바로 끊긴다', async () => {
const s = await stack();
const a = await s.pc(SUPER);
const admin = new AppAuth(a.st, { version: 't', openUrl: () => undefined });
await admin.adminAddUser(FRIEND, 'user');
const b = await s.pc(FRIEND);
const cmd = (name: string, user: string) =>
new Promise<string>((resolve) => s.source.emit('command', { name, guildId: G, user: m(user, user), voiceChannel: { id: VC1, name: '일반' } } satisfies BotCommand, resolve));
try {
assert.equal(await cmd('녹음시작', SUPER), '지금 이 서버에서 켜져 있는 겜녹이 앱이 없습니다.');
await a.gw.start();
await b.gw.start();
await a.gw.watch(G, { commands: false });
await b.gw.watch(G, { commands: false });
const seenBy: string[] = [];
a.gw.on('command', (c, respond) => (seenBy.push(`a:${c.name}`), respond(`A 가 ${c.name}`)));
b.gw.on('command', (c, respond) => (seenBy.push(`b:${c.name}`), respond(`B 가 ${c.name}`)));
// 명령한 사람의 PC 로
assert.equal(await cmd('녹음시작', FRIEND), 'B 가 녹음시작');
assert.equal(await cmd('녹음시작', SUPER), 'A 가 녹음시작');
// 녹음 중인 PC 가 없으면 종료할 것이 없다
assert.equal(await cmd('녹음종료', SUPER), '지금은 녹음 중이 아닙니다.');
// 녹음제외는 모든 PC 기록에 남긴다
await cmd('녹음제외', FRIEND);
await until(() => seenBy.includes('a:녹음제외') && seenBy.includes('b:녹음제외'));
// 등록 해제 → B 의 중계 연결이 바로 끊기고 unauthorized
let unauth = false;
b.gw.on('unauthorized', () => (unauth = true));
await admin.adminRemoveUser(FRIEND);
await until(() => unauth);
assert.equal(b.gw.me(), null);
// 로그아웃 → A 도 끊긴다
let aUnauth = false;
a.gw.on('unauthorized', () => (aUnauth = true));
await a.auth.logout();
await until(() => aUnauth);
} finally {
await a.gw.stop();
await b.gw.stop();
await s.close();
}
});

View File

@@ -7,13 +7,14 @@ import { SettingsStore } from '../src/core/settings.ts';
const tmp = () => fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-bot-'));
const BUILTIN = 'MTExMTExMTExMTExMTExMTEx.FAKE00.builtin-token-for-tests-only-xxxxxxxx';
const APP = 'app-login-token-for-tests';
const OTHER = 'OTE4MTIzMzQ4NzIxMDA4NzAw.FAKE11.other-bot-token-for-tests-only-yyyy';
delete process.env.GVR_BOT_TOKEN;
/** 로그인해서 서버가 겜녹이 봇 토큰을 내려준 상태 */
/** 로그인한 상태 (앱 토큰만 있다. 겜녹이 봇 토큰은 서버에만 있다) */
const loggedIn = (dir = tmp()) => {
const s = new SettingsStore(dir);
s.setSecret('builtinBotToken', BUILTIN);
s.setSecret('appToken', APP);
return s;
};
@@ -24,10 +25,19 @@ test('로그인 전: 겜녹이 봇 토큰이 없다 (exe 에 들어 있지 않
assert.equal(s.activeBotToken(), null);
});
test('로그인 후: 겜녹이 봇이 기본이고 서버에서 받은 토큰을 쓴다', () => {
test('로그인 후: 겜녹이 봇이 기본이고, 이 PC 가 직접 로그인할 봇 토큰은 없다 (서버 중계)', () => {
const s = loggedIn();
assert.equal(s.hasBuiltinBot, true);
assert.equal(s.activeBotToken(), BUILTIN);
assert.equal(s.activeBotToken(), null);
});
test('v1.2.0 이 받아 둔 겜녹이 봇 토큰은 시작할 때 지운다', () => {
const dir = tmp();
loggedIn(dir).setSecret('builtinBotToken', BUILTIN);
const s = new SettingsStore(dir);
assert.equal(s.hasSecret('builtinBotToken'), false);
assert.ok(!fs.readFileSync(path.join(dir, 'secrets.bin'), 'utf8').includes(BUILTIN));
assert.equal(s.activeBotToken(), null);
});
test('다른 봇으로 진행하기: 넣은 토큰을 쓰고, 다시 겜녹이 봇으로 오가도 각자 유지된다', () => {
@@ -39,7 +49,7 @@ test('다른 봇으로 진행하기: 넣은 토큰을 쓰고, 다시 겜녹이
assert.equal(s.activeBotToken(), OTHER);
s.update({ discord: { botMode: 'builtin' } });
assert.equal(s.activeBotToken(), BUILTIN);
assert.equal(s.activeBotToken(), null);
s.update({ discord: { botMode: 'custom' } });
assert.equal(s.activeBotToken(), OTHER, '저장한 다른 봇 토큰은 지워지지 않는다');
@@ -48,7 +58,7 @@ test('다른 봇으로 진행하기: 넣은 토큰을 쓰고, 다시 겜녹이
assert.equal(again.get().discord.botMode, 'custom');
assert.equal(again.activeBotToken(), OTHER);
// 평문 설정 파일(settings.json)에는 토큰이 들어가지 않는다
assert.ok(!fs.readFileSync(path.join(dir, 'settings.json'), 'utf8').includes(BUILTIN));
assert.ok(!fs.readFileSync(path.join(dir, 'settings.json'), 'utf8').includes(OTHER));
});
test('v1.0.0 에서 직접 토큰을 넣어 쓰던 설치는 다른 봇 모드로 이어진다', () => {