// 겜녹이 봇 중계. 봇 토큰은 이 서버에만 있고, 앱(exe)에는 절대 보내지 않는다. // - 서버가 디스코드 게이트웨이에 한 번 붙는다 (BotSource). 앱은 /app/bot/ws 로 붙어 필요한 정보만 받는다 // - 음성채널 참여: 앱의 @discordjs/voice 어댑터가 보낸 op 4 를 검사해서 서버가 대신 보내고, // 디스코드가 돌려준 일회용 음성 접속 정보(VOICE_STATE/SERVER_UPDATE)를 그 앱에만 넘긴다. // 음성 데이터는 앱 ↔ 디스코드 음성 서버로 바로 오간다 (이 서버를 거치지 않음) // - 한 디스코드 서버에서 봇은 음성채널 하나에만 있을 수 있다 → 마지막으로 참여를 요청한 앱이 가져가고, 이전 앱에는 taken import crypto from 'node:crypto'; import { EventEmitter } from 'node:events'; import type { IncomingMessage } from 'node:http'; import { WebSocket, WebSocketServer } from 'ws'; import type { AppRole, BotGwChannel, BotGwFromApp, BotGwGuild, BotGwMember, BotGwToApp } from '@gvr/shared'; export interface BotVoiceEvent { guildId: string; member: BotGwMember; oldChannelId: string | null; newChannelId: string | null; channel: BotGwChannel | null; } export interface BotCommand { name: string; guildId: string; user: BotGwMember; voiceChannel: BotGwChannel | null; } export interface BotSnapshot { guild: BotGwGuild; channels: BotGwChannel[]; voice: { member: BotGwMember; channelId: string }[]; } /** * 디스코드 게이트웨이 쪽 (실서버: discord-source.ts 의 discord.js, 테스트: 가짜). * 이벤트: 'ready', 'guilds', 'voiceState' (BotVoiceEvent), 'command' (BotCommand, respond(content)), * 'access' (guildId: 그 서버의 멤버 탈퇴 · 추방 · 역할 · 채널 권한이 바뀜 → 권한을 다시 확인한다) * 권한은 앱 유저(디스코드 아이디) 기준: 그 유저가 가입한 서버, 그 유저가 볼 수 있는 채널만 */ export interface BotSource extends EventEmitter { /** 이 서버의 슬래시 명령을 받을지 (지켜보는 앱이 없으면 응답하지 않는다: 아직 봇 토큰을 직접 쓰는 v1.1.0 PC 의 응답을 가로채지 않게) */ wants?: (guildId: string) => boolean; me(): BotGwMember | null; /** 봇이 들어가 있고 이 유저도 가입한 서버 */ guildsFor(userId: string): Promise; /** 이 유저가 볼 수 있는 음성채널과 그 채널에 있는 사람. 서버 멤버가 아니면 null */ snapshot(guildId: string, userId: string): Promise; /** 이 유저가 이 채널을 볼 수 있는지 (멤버 · 권한 캐시 기준) */ canView(guildId: string, userId: string, channelId: string): boolean; /** 이 유저가 들어갈 수 있는 음성채널인지 (보기 + 연결 권한) */ canConnect(guildId: string, userId: string, channelId: string): boolean; /** 서버 멤버 목록 (이 유저가 멤버일 때만) */ members(guildId: string, userId: string): Promise; registerCommands(guildId: string): Promise; /** 서버마다 하나. 디스코드가 보낸 봇 자신의 음성 접속 정보를 handlers 로 넘기고, send 로 op 4 를 보낸다 */ voiceAdapter(guildId: string, handlers: { server: (d: any) => void; state: (d: any) => void }): { send: (payload: any) => boolean }; } interface Conn { id: string; ws: WebSocket; token: string; userId: string; guildId: string | null; at: number; } const CMD_TIMEOUT_MS = 25000; const SNOWFLAKE = /^\d{17,20}$/; export class BotBroker { readonly wss = new WebSocketServer({ noServer: true, maxPayload: 256 * 1024 }); private conns = new Set(); /** 서버별로 지금 봇 음성 연결을 가진 앱과 그 앱이 봇을 부른 음성채널 */ private owners = new Map(); private adapters = new Map boolean }>(); private commandsDone = new Set(); private cmds = new Map void>(); private timer: NodeJS.Timeout; constructor( private source: BotSource, /** 앱 토큰 확인 (등록 해제 · 로그아웃이면 null) */ private verify: (token: string) => { userId: string; role: AppRole } | null, private log: { info: (o: any, m?: string) => void; warn: (o: any, m?: string) => void }, /** 권한 · 등록 다시 확인 주기 (이벤트를 놓쳐도 이 안에 막힌다) */ recheckMs = 30000, ) { // 디스코드 서버 탈퇴 · 추방 · 역할 · 채널 권한 변경 → 그 서버의 음성 연결 · 지켜보기 권한을 바로 다시 확인 source.on('access', (guildId: string) => this.recheck(guildId)); source.on('ready', () => { for (const c of this.conns) void this.sendReady(c); }); source.on('guilds', () => { for (const c of this.conns) void this.source.guildsFor(c.userId).then((guilds) => this.send(c, { t: 'guilds', guilds }), () => undefined); }); source.on('voiceState', (e: BotVoiceEvent) => { for (const c of this.conns) { if (c.guildId !== e.guildId) continue; // 이 유저가 볼 수 없는 채널은 "없는 곳"으로 가린다 (비공개 채널에 누가 있는지 새지 않게) const vis = (ch: string | null) => (ch && this.source.canView(e.guildId, c.userId, ch) ? ch : null); const oldChannelId = vis(e.oldChannelId); const newChannelId = vis(e.newChannelId); if (!oldChannelId && !newChannelId) continue; this.send(c, { t: 'voiceState', guildId: e.guildId, member: e.member, oldChannelId, newChannelId, channel: newChannelId ? e.channel : null }); } }); source.wants = (guildId) => [...this.conns].some((c) => c.guildId === guildId); source.on('command', (cmd: BotCommand, respond: (content: string) => void) => void this.onCommand(cmd).then(respond)); // 등록 해제 · 로그아웃된 연결은 30초 안에 끊는다 (해제 · 로그아웃 API 는 kick 으로 바로 끊는다) // 서버 · 채널 권한도 다시 확인한다 (권한 변경 이벤트를 놓친 경우) this.timer = setInterval(() => { for (const c of this.conns) if (!this.verify(c.token)) c.ws.close(4401, 'unauthorized'); for (const c of this.conns) if (c.ws.readyState === WebSocket.OPEN) c.ws.ping(); for (const g of new Set([...this.owners.keys(), ...[...this.conns].map((c) => c.guildId).filter((x): x is string => !!x)])) this.recheck(g); }, recheckMs); } close(): void { clearInterval(this.timer); for (const c of this.conns) c.ws.terminate(); } /** 이 유저(또는 이 토큰)의 연결을 바로 끊는다 */ kick(by: { userId?: string; token?: string }): void { for (const c of this.conns) if ((by.userId && c.userId === by.userId) || (by.token && c.token === by.token)) c.ws.close(4401, 'unauthorized'); } authenticate(req: IncomingMessage): { token: string; userId: string } | null { const token = /^Bearer\s+(\S+)$/i.exec(String(req.headers.authorization || ''))?.[1] ?? ''; const a = token ? this.verify(token) : null; return a ? { token, userId: a.userId } : null; } attach(ws: WebSocket, a: { token: string; userId: string }): void { const c: Conn = { id: crypto.randomBytes(6).toString('hex'), ws, token: a.token, userId: a.userId, guildId: null, at: Date.now() }; this.conns.add(c); this.log.info({ user: a.userId, conn: c.id }, '겜녹이 봇 중계 연결'); void this.sendReady(c); ws.on('message', (data, isBinary) => { if (isBinary || !this.conns.has(c)) return; let m: BotGwFromApp; try { m = JSON.parse(String(data)); } catch { return; } try { this.onMessage(c, m); } catch (e) { this.log.warn(e, '봇 중계 메시지 처리 실패'); } }); const drop = () => this.drop(c); ws.on('close', drop); ws.on('error', drop); } private drop(c: Conn): void { if (!this.conns.delete(c)) return; this.log.info({ user: c.userId, conn: c.id }, '겜녹이 봇 중계 끊김'); // 앱이 꺼지거나 끊기면 봇을 음성채널에서 뺀다 (서버 연결은 계속 살아 있어서 그냥 두면 계속 남는다) for (const [g, o] of this.owners) if (o.conn === c) this.release(g); } /** 봇을 그 서버의 음성채널에서 뺀다 */ private release(guildId: string): void { this.owners.delete(guildId); this.adapters.get(guildId)?.send({ op: 4, d: { guild_id: guildId, channel_id: null, self_mute: false, self_deaf: false } }); } /** 권한을 잃은 앱의 음성 연결을 끊는다: 음성 접속 정보 전달을 멈추고, 봇을 빼고, 앱에는 taken 으로 알려 녹음을 멈추게 한다 */ private revoke(guildId: string, why: string): void { const o = this.owners.get(guildId); if (!o) return; this.log.info({ user: o.conn.userId, guild: guildId, why }, '권한이 없어져 겜녹이 봇 음성 연결을 끊음'); this.release(guildId); this.send(o.conn, { t: 'taken', guildId }); } /** 그 서버의 권한을 다시 확인한다 (음성 연결: 들어갈 수 있는 채널인지, 지켜보기: 아직 멤버인지) */ private recheck(guildId: string): void { const o = this.owners.get(guildId); if (o && !this.source.canConnect(guildId, o.conn.userId, o.channelId)) this.revoke(guildId, 'access-changed'); for (const c of this.conns) { if (c.guildId !== guildId) continue; void this.source.snapshot(guildId, c.userId).then( (snap) => { if (snap || c.guildId !== guildId) return; c.guildId = null; this.send(c, { t: 'watch_denied', guildId }); }, () => undefined, ); } } /** 음성 접속 정보를 넘겨도 되는지 (봇이 있는 채널에 그 앱의 유저가 지금도 들어갈 수 있는지) */ private owned(guildId: string, channelId?: string | null): Conn | null { const o = this.owners.get(guildId); if (!o) return null; if (channelId) o.channelId = String(channelId); // 봇이 다른 채널로 옮겨진 경우 그 채널 기준으로 if (!this.source.canConnect(guildId, o.conn.userId, o.channelId)) { this.revoke(guildId, 'forward-check'); return null; } return o.conn; } private async sendReady(c: Conn): Promise { const me = this.source.me(); if (!me) return; const guilds = await this.source.guildsFor(c.userId).catch(() => []); if (this.conns.has(c)) this.send(c, { t: 'ready', me, guilds }); } private send(c: Conn, m: BotGwToApp): void { if (c.ws.readyState === WebSocket.OPEN) c.ws.send(JSON.stringify(m)); } private adapter(guildId: string) { let a = this.adapters.get(guildId); if (!a) { a = this.source.voiceAdapter(guildId, { // 넘기기 전에 매번 권한을 확인한다 server: (d) => { const o = this.owned(guildId); if (o) this.send(o, { t: 'vserver', guildId, data: d }); }, state: (d) => { const o = this.owned(guildId, d?.channel_id); if (o) this.send(o, { t: 'vstate', guildId, data: d }); }, }); this.adapters.set(guildId, a); } return a; } private onMessage(c: Conn, m: BotGwFromApp): void { switch (m.t) { case 'watch': { void this.watch(c, m); return; } case 'voice': { // 앱이 보낼 수 있는 건 "지켜보는 서버의 음성채널 참여 · 나가기" 뿐이다 const g = c.guildId; const d = m.payload?.d; if (!g || m.guildId !== g || m.payload?.op !== 4 || d?.guild_id !== g) return; const ch = d.channel_id === null ? null : String(d.channel_id); // 이 유저가 직접 들어갈 수 있는 음성채널에만 봇을 부른다 (비공개 채널 · 권한 없는 채널 거절) if (ch !== null && !this.source.canConnect(g, c.userId, ch)) return; const owner = this.owners.get(g)?.conn; if (ch === null) { // 이미 다른 PC 가 가져간 봇을 이전 PC 가 빼지 못하게 if (owner !== c) return; this.owners.delete(g); } else { if (owner && owner !== c) this.send(owner, { t: 'taken', guildId: g }); this.owners.set(g, { conn: c, channelId: ch }); } this.adapter(g).send({ op: 4, d: { guild_id: g, channel_id: ch, self_mute: !!d.self_mute, self_deaf: !!d.self_deaf } }); return; } case 'cmd_res': { // 여러 PC 로 보낸 명령은 첫 응답만 쓴다 this.cmds.get(m.id)?.(String(m.content ?? '').slice(0, 1800)); return; } case 'req': { // 지켜보기 전이어도 받을 수 있다 (가입한 서버인지는 source.members 가 확인한다) if (m.op !== 'members' || !SNOWFLAKE.test(String(m.guildId))) return this.send(c, { t: 'res', id: m.id, ok: false, error: 'forbidden' }); this.source.members(m.guildId, c.userId).then( (data) => this.send(c, { t: 'res', id: m.id, ok: true, data }), (e) => this.send(c, { t: 'res', id: m.id, ok: false, error: String(e?.message ?? e) }), ); return; } } } /** 서버 지켜보기: 이 유저가 가입한 서버만, 이 유저가 볼 수 있는 채널만 보낸다 */ private async watch(c: Conn, m: Extract): Promise { const snap = SNOWFLAKE.test(String(m.guildId)) ? await this.source.snapshot(m.guildId, c.userId).catch(() => null) : null; if (!this.conns.has(c)) return; if (!snap) { this.send(c, { t: 'watch_denied', guildId: String(m.guildId) }); return; } c.guildId = m.guildId; c.at = Date.now(); this.send(c, { t: 'guild', ...snap }); if (m.commands && !this.commandsDone.has(m.guildId)) { this.commandsDone.add(m.guildId); this.source.registerCommands(m.guildId).catch((e) => { this.commandsDone.delete(m.guildId); this.log.warn(e, '슬래시 명령 등록 실패'); }); } } /** 슬래시 명령을 맞는 앱으로 보내고 첫 응답을 돌려준다 */ private async onCommand(cmd: BotCommand): Promise { const here = [...this.conns].filter((c) => c.guildId === cmd.guildId).sort((a, b) => b.at - a.at); if (!here.length) { // 명령한 사람의 앱이 켜져 있는데 다른 서버를 녹음 대상으로 잡아 둔 경우를 알려 준다 const own = [...this.conns].filter((c) => c.userId === cmd.user.id); this.log.info({ guild: cmd.guildId, user: cmd.user.id, cmd: cmd.name, apps: this.conns.size, own: own.map((c) => c.guildId) }, '슬래시 명령: 이 서버를 지켜보는 앱 없음'); if (own.some((c) => c.guildId)) return '내 겜녹이 앱이 다른 디스코드 서버를 녹음 대상으로 정해 두었습니다. 게임 PC 의 겜녹이 설정 → 디스코드 → "녹음할 서버"를 이 서버로 바꿔 주세요.'; if (own.length) return '내 겜녹이 앱이 이 서버에 아직 연결되지 않았습니다. 잠시 뒤 다시 시도하거나, 겜녹이 설정 → 디스코드에서 "녹음할 서버"를 확인해 주세요.'; return '지금 이 서버에서 켜져 있는 겜녹이 앱이 없습니다. 게임 PC 에서 겜녹이를 켜고 로그인해 주세요.'; } const owner = this.owners.get(cmd.guildId)?.conn; const mine = here.find((c) => c.userId === cmd.user.id); let targets: Conn[]; if (cmd.name === '녹음제외' || cmd.name === '녹음참여') targets = here; // 각 PC 기록에 모두 남긴다 else if (cmd.name === '녹음종료') targets = owner && here.includes(owner) ? [owner] : []; else { // 녹음시작: 명령한 사람의 음성채널에 그 PC 의 유저도 들어갈 수 있어야 한다 (비공개 채널에 남의 PC 가 봇을 부르지 않게) const vc = cmd.voiceChannel; const able = vc ? here.filter((c) => this.source.canConnect(cmd.guildId, c.userId, vc.id)) : here; const pick = (c: Conn | undefined) => (c && able.includes(c) ? c : undefined); const t = pick(mine) ?? pick(owner) ?? able[0]; if (!t) return '이 음성채널에 들어갈 수 있는 겜녹이 앱이 없습니다.'; targets = [t]; } if (!targets.length) return '지금은 녹음 중이 아닙니다.'; const id = crypto.randomBytes(8).toString('hex'); const content = await new Promise((resolve) => { const t = setTimeout(() => resolve(null), CMD_TIMEOUT_MS); this.cmds.set(id, (v) => { clearTimeout(t); this.cmds.delete(id); resolve(v); }); // 그 PC 의 유저가 볼 수 없는 채널 이름은 보내지 않는다 for (const c of targets) this.send(c, { t: 'cmd', id, ...cmd, voiceChannel: cmd.voiceChannel && this.source.canView(cmd.guildId, c.userId, cmd.voiceChannel.id) ? cmd.voiceChannel : null }); }); this.cmds.delete(id); return content ?? '겜녹이 앱이 응답하지 않습니다. 잠시 뒤 다시 시도해 주세요.'; } }