diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index 3fe8de5..b6ac01b 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -230,6 +230,8 @@ type TimelineItem = - 앱 → 서버: `watch{guildId, commands}` · `voice{guildId, payload}`(@discordjs/voice 어댑터의 op 4) · `cmd_res{id, content}` · `req{op:'members'}` - 권한 (앱 유저의 디스코드 아이디 기준): 서버 목록 · watch 는 그 유저가 가입한 서버만 (아니면 `watch_denied`), 채널 · 음성 상태는 그 유저가 볼 수 있는(ViewChannel) 채널만 (볼 수 없는 채널로 옮기면 "나감"으로 가린다), 음성 참여는 그 유저가 들어갈 수 있는(ViewChannel + Connect) 음성채널만. 슬래시 명령 /녹음시작 도 그 채널에 들어갈 수 있는 유저의 PC 로만 보낸다 +- 권한 회수: 연결한 뒤에도 탈퇴 · 추방 · 역할 · 채널 권한 변경 이벤트(`access`), 음성 접속 정보를 넘기기 직전, 30초 주기로 다시 확인한다. + 봇이 있는 채널에 그 유저가 더는 들어갈 수 없으면 음성 접속 정보 전달을 멈추고 봇을 빼고(op 4 null) 앱에 `taken` 을 보낸다. 서버 멤버가 아니게 되면 `watch_denied` - 음성채널 참여: 앱의 @discordjs/voice 가 어댑터로 op 4 를 보내면 서버가 검사(지켜보는 서버 · 들어갈 수 있는 음성채널 · op 4 만, 필드를 다시 만들어)한 뒤 대신 보내고, 디스코드가 준 session_id · 음성 서버 token · endpoint 를 그 앱에만 넘긴다. 음성(UDP · DAVE)은 앱 ↔ 디스코드 음성 서버로 바로 간다 (Lavalink 와 같은 방식) - 한 서버에서 봇은 음성채널 하나에만 있을 수 있다: 마지막으로 참여를 요청한 앱이 가져가고 이전 앱은 `taken` 을 받는다. 이전 앱의 늦은 나가기는 무시한다. diff --git a/site/server/src/app.ts b/site/server/src/app.ts index b29c4c1..c44d22c 100644 --- a/site/server/src/app.ts +++ b/site/server/src/app.ts @@ -16,7 +16,7 @@ const SID = 'gvr_sid'; const RECHECK_MS = 10 * 60000; /** botSource: 겜녹이 봇 디스코드 연결 (main.ts 가 discord.js 로 만든다. 없으면 /app/bot/ws 는 503) */ -export async function buildServer(cfg: Config, opts: { botSource?: BotSource } = {}) { +export async function buildServer(cfg: Config, opts: { botSource?: BotSource; botRecheckMs?: number } = {}) { const app = Fastify({ logger: { level: process.env.LOG_LEVEL || 'info', @@ -34,7 +34,7 @@ export async function buildServer(cfg: Config, opts: { botSource?: BotSource } = const secure = cfg.publicUrl.startsWith('https://'); let broker: BotBroker | null = null; const appAuth = registerAppAuth(app, { cfg, store, discord, secure, onRevoke: (by) => broker?.kick(by) }); - if (opts.botSource) broker = new BotBroker(opts.botSource, appAuth.verifyToken, app.log); + if (opts.botSource) broker = new BotBroker(opts.botSource, appAuth.verifyToken, app.log, opts.botRecheckMs); // 보안 헤더. HSTS · X-Frame-Options · Referrer-Policy 는 앞단 프록시(NPMplus)가 붙인다 (http → https 이동도 프록시) // CSP: 이 사이트의 스크립트만 실행, 접속은 이 사이트로만 (XSS 가 생겨도 기록을 바깥으로 보내지 못하게) diff --git a/site/server/src/bot-broker.ts b/site/server/src/bot-broker.ts index 39e10a7..41b9bc5 100644 --- a/site/server/src/bot-broker.ts +++ b/site/server/src/bot-broker.ts @@ -32,7 +32,8 @@ export interface BotSnapshot { /** * 디스코드 게이트웨이 쪽 (실서버: discord-source.ts 의 discord.js, 테스트: 가짜). - * 이벤트: 'ready', 'guilds', 'voiceState' (BotVoiceEvent), 'command' (BotCommand, respond(content)) + * 이벤트: 'ready', 'guilds', 'voiceState' (BotVoiceEvent), 'command' (BotCommand, respond(content)), + * 'access' (guildId: 그 서버의 멤버 탈퇴 · 추방 · 역할 · 채널 권한이 바뀜 → 권한을 다시 확인한다) * 권한은 앱 유저(디스코드 아이디) 기준: 그 유저가 가입한 서버, 그 유저가 볼 수 있는 채널만 */ export interface BotSource extends EventEmitter { @@ -69,8 +70,8 @@ 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 owners = new Map(); private adapters = new Map boolean }>(); private commandsDone = new Set(); private cmds = new Map void>(); @@ -81,7 +82,11 @@ export class BotBroker { /** 앱 토큰 확인 (등록 해제 · 로그아웃이면 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); }); @@ -102,10 +107,12 @@ export class BotBroker { 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(); - }, 30000); + 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 { @@ -152,13 +159,53 @@ export class BotBroker { if (!this.conns.delete(c)) return; this.log.info({ user: c.userId, conn: c.id }, '겜녹이 봇 중계 끊김'); // 앱이 꺼지거나 끊기면 봇을 음성채널에서 뺀다 (서버 연결은 계속 살아 있어서 그냥 두면 계속 남는다) - for (const [g, o] of this.owners) { - if (o !== c) continue; - this.owners.delete(g); - this.adapters.get(g)?.send({ op: 4, d: { guild_id: g, channel_id: null, self_mute: false, self_deaf: false } }); + 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; @@ -174,12 +221,13 @@ export class BotBroker { let a = this.adapters.get(guildId); if (!a) { a = this.source.voiceAdapter(guildId, { + // 넘기기 전에 매번 권한을 확인한다 server: (d) => { - const o = this.owners.get(guildId); + const o = this.owned(guildId); if (o) this.send(o, { t: 'vserver', guildId, data: d }); }, state: (d) => { - const o = this.owners.get(guildId); + const o = this.owned(guildId, d?.channel_id); if (o) this.send(o, { t: 'vstate', guildId, data: d }); }, }); @@ -202,14 +250,14 @@ export class BotBroker { 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); + const owner = this.owners.get(g)?.conn; if (ch === null) { // 이미 다른 PC 가 가져간 봇을 이전 PC 가 빼지 못하게 if (owner !== c) return; this.owners.delete(g); - } else if (owner !== c) { - if (owner) this.send(owner, { t: 'taken', guildId: g }); - this.owners.set(g, c); + } 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; @@ -254,7 +302,7 @@ export class BotBroker { 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) return '지금 이 서버에서 켜져 있는 겜녹이 앱이 없습니다.'; - const owner = this.owners.get(cmd.guildId); + 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 기록에 모두 남긴다 diff --git a/site/server/src/discord-source.ts b/site/server/src/discord-source.ts index 96f540d..889fc81 100644 --- a/site/server/src/discord-source.ts +++ b/site/server/src/discord-source.ts @@ -29,6 +29,15 @@ export class DiscordSource extends EventEmitter implements BotSource { this.emit('ready'); }); c.on(Events.GuildCreate, () => this.emit('guilds')); + // 권한이 바뀔 수 있는 일: 탈퇴 · 추방, 역할 변경, 채널 권한 변경 · 삭제, 역할 권한 변경 · 삭제 → 중계가 다시 확인한다 + const access = (guildId: string | null | undefined) => guildId && this.emit('access', guildId); + c.on(Events.GuildMemberRemove, (m) => access(m.guild.id)); + c.on(Events.GuildMemberUpdate, (_o, n) => access(n.guild.id)); + c.on(Events.ChannelUpdate, (_o, n) => access('guildId' in n ? n.guildId : null)); + c.on(Events.ChannelDelete, (ch) => access('guildId' in ch ? ch.guildId : null)); + c.on(Events.GuildRoleUpdate, (_o, n) => access(n.guild.id)); + c.on(Events.GuildRoleDelete, (r) => access(r.guild.id)); + c.on(Events.GuildDelete, (g) => access(g.id)); c.on(Events.GuildDelete, () => this.emit('guilds')); c.on(Events.Error, (e) => log.error(e, '디스코드 오류')); c.on(Events.VoiceStateUpdate, (o, n) => { diff --git a/site/server/test/bot-broker.test.ts b/site/server/test/bot-broker.test.ts new file mode 100644 index 0000000..ec70fb0 --- /dev/null +++ b/site/server/test/bot-broker.test.ts @@ -0,0 +1,185 @@ +// 겜녹이 봇 중계: 연결한 뒤 권한을 잃으면 (탈퇴 · 채널 권한 제거) 음성 접속 정보 전달을 멈추고 봇을 빼고 앱에 알린다 +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { EventEmitter } from 'node:events'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import WebSocket from 'ws'; +import type { BotGwMember } from '@gvr/shared'; +import { buildServer } from '../src/app.ts'; +import type { BotSource } from '../src/bot-broker.ts'; +import type { Config } from '../src/config.ts'; + +const SUPER = '293719842274541579'; +const USER = '111111111111111111'; +const G = '900000000000000001'; +const VC1 = '910000000000000001'; +const tmp = () => fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-broker-')); +const mem = (id: string): BotGwMember => ({ id, name: id, avatar: null, bot: false }); + +/** 권한을 바꿀 수 있는 가짜 디스코드 (members: 서버 멤버, connect: VC1 에 들어갈 수 있는 사람) */ +class FakeSource extends EventEmitter implements BotSource { + members_ = new Set([SUPER, USER]); + connect = new Set([SUPER, USER]); + sent: any[] = []; + handlers: { server: (d: any) => void; state: (d: any) => void } | null = null; + me() { + return { id: '800000000000000001', name: '겜녹이', avatar: null, bot: true }; + } + async guildsFor(u: string) { + return this.members_.has(u) ? [{ id: G, name: 'M&L', icon: null }] : []; + } + async snapshot(g: string, u: string) { + return g === G && this.members_.has(u) ? { guild: { id: G, name: 'M&L', icon: null }, channels: [{ id: VC1, name: '일반' }], voice: [] } : null; + } + canView(g: string, u: string, ch: string) { + return g === G && ch === VC1 && this.members_.has(u); + } + canConnect(g: string, u: string, ch: string) { + return this.canView(g, u, ch) && this.connect.has(u); + } + async members() { + return [mem(SUPER), mem(USER)]; + } + async registerCommands() {} + voiceAdapter(_g: string, h: { server: (d: any) => void; state: (d: any) => void }) { + this.handlers = h; + return { send: (p: any) => (this.sent.push(p), true) }; + } +} + +async function setup(recheckMs?: number) { + const source = new FakeSource(); + const cfg: Config = { + port: 0, host: '127.0.0.1', publicUrl: 'http://127.0.0.1', clientId: 'c', clientSecret: 's', botToken: 'bot-token', + allowedGuilds: [], owners: [SUPER], superAdmins: [SUPER], sessionSecret: 'x'.repeat(32), dataDir: tmp(), webDir: '/nonexistent', + version: 'test', discordApi: 'http://127.0.0.1:1', assetUpstream: {}, + }; + const { app, store } = await buildServer(cfg, { botSource: source, botRecheckMs: recheckMs }); + await app.listen({ host: '127.0.0.1', port: 0 }); + const url = `ws://127.0.0.1:${(app.server.address() as any).port}/app/bot/ws`; + store.upsertAppUser({ id: USER, name: 'u', avatar: null, role: 'user', addedBy: SUPER }); + /** 일반 유저 앱 하나: 받은 메시지를 모은다 */ + const pc = async () => { + const ws = new WebSocket(url, { headers: { authorization: `Bearer ${store.createAppSession(USER)}` } }); + const got: any[] = []; + ws.on('message', (d) => got.push(JSON.parse(String(d)))); + await new Promise((r) => ws.once('open', r)); + const send = (m: unknown) => ws.send(JSON.stringify(m)); + return { ws, got, send }; + }; + return { source, pc, close: () => app.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 = (ch: string | null) => ({ op: 4, d: { guild_id: G, channel_id: ch, self_mute: false, self_deaf: false } }); + +/** 허용 → 연결: 봇을 VC1 에 부르고 음성 접속 정보를 받는 데까지 */ +async function connected(s: Awaited>) { + const p = await s.pc(); + p.send({ t: 'watch', guildId: G, commands: false }); + await until(() => p.got.some((m) => m.t === 'guild')); + p.send({ t: 'voice', guildId: G, payload: op4(VC1) }); + await until(() => s.source.sent.length === 1); + assert.equal(s.source.sent[0].d.channel_id, VC1); + s.source.handlers!.state({ guild_id: G, channel_id: VC1, session_id: 'sess-1', user_id: '800000000000000001' }); + s.source.handlers!.server({ guild_id: G, token: 'voice-token-1', endpoint: 'x' }); + await until(() => p.got.filter((m) => m.t === 'vstate' || m.t === 'vserver').length === 2); + return p; +} + +/** 권한 회수 뒤: 봇을 빼고(op 4 null), 앱에 taken, 음성 접속 정보는 더 가지 않는다 */ +async function assertRevoked(s: Awaited>, p: Awaited>) { + await until(() => s.source.sent.length === 2); + assert.equal(s.source.sent[1].d.channel_id, null, '봇을 음성채널에서 뺀다'); + await until(() => p.got.some((m) => m.t === 'taken' && m.guildId === G)); + const before = p.got.filter((m) => m.t === 'vstate' || m.t === 'vserver').length; + s.source.handlers!.server({ guild_id: G, token: 'voice-token-2', endpoint: 'x' }); + s.source.handlers!.state({ guild_id: G, channel_id: VC1, session_id: 'sess-2', user_id: '800000000000000001' }); + await new Promise((r) => setTimeout(r, 150)); + assert.equal(p.got.filter((m) => m.t === 'vstate' || m.t === 'vserver').length, before, '권한을 잃은 앱에 음성 접속 정보가 가면 안 된다'); + assert.ok(!JSON.stringify(p.got).includes('voice-token-2')); +} + +test('권한 회수 (디스코드 서버 탈퇴 · 추방): 이벤트가 오면 바로 봇을 빼고 알리고 음성 정보 전달을 멈춘다', async () => { + const s = await setup(); + try { + const p = await connected(s); + s.source.members_.delete(USER); + s.source.connect.delete(USER); + s.source.emit('access', G); + await assertRevoked(s, p); + // 지켜보기도 끊긴다 (탈퇴했으니) + await until(() => p.got.some((m) => m.t === 'watch_denied' && m.guildId === G)); + p.ws.close(); + } finally { + await s.close(); + } +}); + +test('권한 회수 (채널 권한 제거): 이벤트가 오면 바로 봇을 빼고 알리고 음성 정보 전달을 멈춘다', async () => { + const s = await setup(); + try { + const p = await connected(s); + s.source.connect.delete(USER); // 서버 멤버는 그대로, VC1 연결 권한만 빼앗김 + s.source.emit('access', G); + await assertRevoked(s, p); + assert.ok(!p.got.some((m) => m.t === 'watch_denied'), '서버 멤버이므로 지켜보기는 유지'); + p.ws.close(); + } finally { + await s.close(); + } +}); + +test('권한 회수 (이벤트를 놓친 경우): 음성 정보를 넘기기 직전 검사와 주기 검사로 막는다', async () => { + // 넘기기 직전 검사 + const s = await setup(); + try { + const p = await connected(s); + s.source.connect.delete(USER); // 이벤트 없이 권한만 바뀜 + const before = p.got.filter((m) => m.t === 'vserver').length; + s.source.handlers!.server({ guild_id: G, token: 'voice-token-x', endpoint: 'x' }); + await until(() => s.source.sent.length === 2); + assert.equal(s.source.sent[1].d.channel_id, null); + await until(() => p.got.some((m) => m.t === 'taken')); + assert.equal(p.got.filter((m) => m.t === 'vserver').length, before); + p.ws.close(); + } finally { + await s.close(); + } + // 주기 검사 (음성 정보도 이벤트도 없을 때) + const s2 = await setup(200); + try { + const p = await connected(s2); + s2.source.members_.delete(USER); + s2.source.connect.delete(USER); + await assertRevoked(s2, p); + await until(() => p.got.some((m) => m.t === 'watch_denied')); + p.ws.close(); + } finally { + await s2.close(); + } +}); + +test('봇이 권한 없는 채널로 옮겨지면 (다른 사람이 끌어감) 그 채널 기준으로 막는다', async () => { + const s = await setup(); + try { + const p = await connected(s); + const before = p.got.filter((m) => m.t === 'vstate').length; + s.source.handlers!.state({ guild_id: G, channel_id: '910000000000000099', session_id: 'sess-1', user_id: '800000000000000001' }); + await until(() => s.source.sent.length === 2); + assert.equal(s.source.sent[1].d.channel_id, null); + await until(() => p.got.some((m) => m.t === 'taken')); + assert.equal(p.got.filter((m) => m.t === 'vstate').length, before); + p.ws.close(); + } finally { + await s.close(); + } +});