앱 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

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 {