보안 리뷰 반영: 봇 중계 유저별 서버 · 채널 권한, 인증서 검증 우회 차단
봇 중계 권한 (앱 유저의 디스코드 아이디 기준) - 서버 목록 · watch: 그 유저가 가입한 서버만. 아니면 watch_denied (명령 등록 · 멤버 목록도 거절) - 채널 · 음성 상태: 그 유저가 볼 수 있는(ViewChannel) 채널만. 볼 수 없는 채널로 옮기면 "나감"으로 가린다 - 음성 참여 op 4: 그 유저가 들어갈 수 있는(ViewChannel + Connect) 음성채널만 - /녹음시작 은 그 음성채널에 들어갈 수 있는 유저의 PC 로만, 다른 PC 로 가는 명령에는 볼 수 없는 채널 이름을 넣지 않는다 인증서 - 사이트 서버 https/wss(로그인 · 기기 등록 · 봇 중계 · 기기 중계)는 Node 내장 Mozilla 루트만 믿고 검증을 항상 켠다 (core/util/secure-http.ts) NODE_TLS_REJECT_UNAUTHORIZED=0 · 시스템 인증서 저장소의 가짜 루트로 엿볼 수 없다 - 시작할 때 NODE_TLS_REJECT_UNAUTHORIZED 를 지운다 (Electron main · 헤드리스 코어). fuses 로 막히지 않는 변수 - win smoke: 내장 루트만으로 실서버 https 가 검증되는지 확인 (siteTls) 테스트: 봇 중계 권한 1건(가입하지 않은 서버 · 비공개 채널 · 연결 권한 없는 채널 · 명령), 자체 서명 서버 + 검증 끄기 변수 1건(대조군 포함) login-e2e 친구 계정을 실제 F&L 멤버(테스트봇)로 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -24,19 +24,31 @@ export interface BotCommand {
|
||||
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))
|
||||
* 권한은 앱 유저(디스코드 아이디) 기준: 그 유저가 가입한 서버, 그 유저가 볼 수 있는 채널만
|
||||
*/
|
||||
export interface BotSource extends EventEmitter {
|
||||
/** 이 서버의 슬래시 명령을 받을지 (지켜보는 앱이 없으면 응답하지 않는다: 아직 봇 토큰을 직접 쓰는 v1.1.0 PC 의 응답을 가로채지 않게) */
|
||||
wants?: (guildId: string) => boolean;
|
||||
me(): BotGwMember | null;
|
||||
guilds(): BotGwGuild[];
|
||||
/** 음성채널 목록과 음성채널에 있는 사람 */
|
||||
snapshot(guildId: string): { guild: BotGwGuild; channels: BotGwChannel[]; voice: { member: BotGwMember; channelId: string }[] } | null;
|
||||
isVoiceChannel(guildId: string, channelId: string): boolean;
|
||||
members(guildId: string): Promise<BotGwMember[]>;
|
||||
/** 봇이 들어가 있고 이 유저도 가입한 서버 */
|
||||
guildsFor(userId: string): Promise<BotGwGuild[]>;
|
||||
/** 이 유저가 볼 수 있는 음성채널과 그 채널에 있는 사람. 서버 멤버가 아니면 null */
|
||||
snapshot(guildId: string, userId: string): Promise<BotSnapshot | null>;
|
||||
/** 이 유저가 이 채널을 볼 수 있는지 (멤버 · 권한 캐시 기준) */
|
||||
canView(guildId: string, userId: string, channelId: string): boolean;
|
||||
/** 이 유저가 들어갈 수 있는 음성채널인지 (보기 + 연결 권한) */
|
||||
canConnect(guildId: string, userId: string, channelId: string): boolean;
|
||||
/** 서버 멤버 목록 (이 유저가 멤버일 때만) */
|
||||
members(guildId: string, userId: string): Promise<BotGwMember[]>;
|
||||
registerCommands(guildId: string): Promise<void>;
|
||||
/** 서버마다 하나. 디스코드가 보낸 봇 자신의 음성 접속 정보를 handlers 로 넘기고, send 로 op 4 를 보낸다 */
|
||||
voiceAdapter(guildId: string, handlers: { server: (d: any) => void; state: (d: any) => void }): { send: (payload: any) => boolean };
|
||||
@@ -71,12 +83,21 @@ export class BotBroker {
|
||||
private log: { info: (o: any, m?: string) => void; warn: (o: any, m?: string) => void },
|
||||
) {
|
||||
source.on('ready', () => {
|
||||
const me = source.me();
|
||||
if (me) for (const c of this.conns) this.send(c, { t: 'ready', me, guilds: source.guilds() });
|
||||
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('guilds', () => this.broadcast({ t: 'guilds', guilds: source.guilds() }));
|
||||
source.on('voiceState', (e: BotVoiceEvent) => {
|
||||
for (const c of this.conns) if (c.guildId === e.guildId) this.send(c, { t: 'voiceState', ...e });
|
||||
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));
|
||||
@@ -107,8 +128,7 @@ export class BotBroker {
|
||||
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 }, '겜녹이 봇 중계 연결');
|
||||
const me = this.source.me();
|
||||
if (me) this.send(c, { t: 'ready', me, guilds: this.source.guilds() });
|
||||
void this.sendReady(c);
|
||||
ws.on('message', (data, isBinary) => {
|
||||
if (isBinary || !this.conns.has(c)) return;
|
||||
let m: BotGwFromApp;
|
||||
@@ -139,12 +159,16 @@ export class BotBroker {
|
||||
}
|
||||
}
|
||||
|
||||
private async sendReady(c: Conn): Promise<void> {
|
||||
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 broadcast(m: BotGwToApp): void {
|
||||
for (const c of this.conns) this.send(c, m);
|
||||
}
|
||||
|
||||
private adapter(guildId: string) {
|
||||
let a = this.adapters.get(guildId);
|
||||
@@ -167,18 +191,7 @@ export class BotBroker {
|
||||
private onMessage(c: Conn, m: BotGwFromApp): void {
|
||||
switch (m.t) {
|
||||
case 'watch': {
|
||||
const snap = SNOWFLAKE.test(String(m.guildId)) ? this.source.snapshot(m.guildId) : null;
|
||||
if (!snap) 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, '슬래시 명령 등록 실패');
|
||||
});
|
||||
}
|
||||
void this.watch(c, m);
|
||||
return;
|
||||
}
|
||||
case 'voice': {
|
||||
@@ -187,7 +200,8 @@ export class BotBroker {
|
||||
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.isVoiceChannel(g, ch)) return;
|
||||
// 이 유저가 직접 들어갈 수 있는 음성채널에만 봇을 부른다 (비공개 채널 · 권한 없는 채널 거절)
|
||||
if (ch !== null && !this.source.canConnect(g, c.userId, ch)) return;
|
||||
const owner = this.owners.get(g);
|
||||
if (ch === null) {
|
||||
// 이미 다른 PC 가 가져간 봇을 이전 PC 가 빼지 못하게
|
||||
@@ -207,7 +221,7 @@ export class BotBroker {
|
||||
}
|
||||
case 'req': {
|
||||
if (m.op !== 'members' || m.guildId !== c.guildId) return this.send(c, { t: 'res', id: m.id, ok: false, error: 'forbidden' });
|
||||
this.source.members(m.guildId).then(
|
||||
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) }),
|
||||
);
|
||||
@@ -216,6 +230,26 @@ export class BotBroker {
|
||||
}
|
||||
}
|
||||
|
||||
/** 서버 지켜보기: 이 유저가 가입한 서버만, 이 유저가 볼 수 있는 채널만 보낸다 */
|
||||
private async watch(c: Conn, m: Extract<BotGwFromApp, { t: 'watch' }>): Promise<void> {
|
||||
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<string> {
|
||||
const here = [...this.conns].filter((c) => c.guildId === cmd.guildId).sort((a, b) => b.at - a.at);
|
||||
@@ -225,7 +259,15 @@ export class BotBroker {
|
||||
let targets: Conn[];
|
||||
if (cmd.name === '녹음제외' || cmd.name === '녹음참여') targets = here; // 각 PC 기록에 모두 남긴다
|
||||
else if (cmd.name === '녹음종료') targets = owner && here.includes(owner) ? [owner] : [];
|
||||
else targets = [mine ?? (owner && here.includes(owner) ? owner : here[0])];
|
||||
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<string | null>((resolve) => {
|
||||
@@ -235,7 +277,8 @@ export class BotBroker {
|
||||
this.cmds.delete(id);
|
||||
resolve(v);
|
||||
});
|
||||
for (const c of targets) this.send(c, { t: 'cmd', id, ...cmd });
|
||||
// 그 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 ?? '겜녹이 앱이 응답하지 않습니다. 잠시 뒤 다시 시도해 주세요.';
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// 서버의 겜녹이 봇 디스코드 연결 (discord.js). bot-broker.ts 의 BotSource 구현
|
||||
import { EventEmitter } from 'node:events';
|
||||
import { ChannelType, Client, Events, GatewayIntentBits, MessageFlags, type Guild, type GuildMember, type VoiceBasedChannel } from 'discord.js';
|
||||
import { ChannelType, Client, Events, GatewayIntentBits, MessageFlags, PermissionFlagsBits, type Guild, type GuildMember, type VoiceBasedChannel } from 'discord.js';
|
||||
import type { BotGwChannel, BotGwGuild, BotGwMember } from '@gvr/shared';
|
||||
import type { BotCommand, BotSource, BotVoiceEvent } from './bot-broker.js';
|
||||
|
||||
@@ -70,28 +70,45 @@ export class DiscordSource extends EventEmitter implements BotSource {
|
||||
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(): BotGwGuild[] {
|
||||
return [...this.client.guilds.cache.values()].map(guild);
|
||||
/** 서버 멤버 (캐시에 없으면 디스코드에서 받아 온다). 멤버가 아니면 null */
|
||||
private async memberOf(g: Guild, userId: string): Promise<GuildMember | null> {
|
||||
if (!/^\d{17,20}$/.test(userId)) return null;
|
||||
return g.members.cache.get(userId) ?? (await g.members.fetch(userId).catch(() => null));
|
||||
}
|
||||
snapshot(guildId: string) {
|
||||
private perms(guildId: string, userId: string, channelId: string) {
|
||||
const g = this.client.guilds.cache.get(guildId);
|
||||
if (!g) return null;
|
||||
const m = g?.members.cache.get(userId);
|
||||
const ch = g?.channels.cache.get(channelId);
|
||||
return m && ch && 'permissionsFor' in ch ? { ch, p: ch.permissionsFor(m) } : null;
|
||||
}
|
||||
async guildsFor(userId: string): Promise<BotGwGuild[]> {
|
||||
const out: BotGwGuild[] = [];
|
||||
for (const g of this.client.guilds.cache.values()) if (await this.memberOf(g, userId)) out.push(guild(g));
|
||||
return out;
|
||||
}
|
||||
async snapshot(guildId: string, userId: string) {
|
||||
const g = this.client.guilds.cache.get(guildId);
|
||||
const m = g ? await this.memberOf(g, userId) : null;
|
||||
if (!g || !m) return null;
|
||||
const channels: BotGwChannel[] = [];
|
||||
const voice: { member: BotGwMember; channelId: string }[] = [];
|
||||
for (const ch of g.channels.cache.values()) {
|
||||
if (!isVoice(ch)) continue;
|
||||
if (!isVoice(ch) || !ch.permissionsFor(m).has(PermissionFlagsBits.ViewChannel)) continue;
|
||||
channels.push({ id: ch.id, name: ch.name });
|
||||
for (const m of ch.members.values()) voice.push({ member: member(m), channelId: ch.id });
|
||||
for (const vm of ch.members.values()) voice.push({ member: member(vm), channelId: ch.id });
|
||||
}
|
||||
return { guild: guild(g), channels, voice };
|
||||
}
|
||||
isVoiceChannel(guildId: string, channelId: string): boolean {
|
||||
const ch = this.client.guilds.cache.get(guildId)?.channels.cache.get(channelId);
|
||||
return isVoice(ch);
|
||||
canView(guildId: string, userId: string, channelId: string): boolean {
|
||||
return !!this.perms(guildId, userId, channelId)?.p?.has(PermissionFlagsBits.ViewChannel);
|
||||
}
|
||||
async members(guildId: string): Promise<BotGwMember[]> {
|
||||
canConnect(guildId: string, userId: string, channelId: string): boolean {
|
||||
const r = this.perms(guildId, userId, channelId);
|
||||
return !!r && isVoice(r.ch) && !!r.p?.has([PermissionFlagsBits.ViewChannel, PermissionFlagsBits.Connect]);
|
||||
}
|
||||
async members(guildId: string, userId: string): Promise<BotGwMember[]> {
|
||||
const g = this.client.guilds.cache.get(guildId);
|
||||
if (!g) return [];
|
||||
if (!g || !(await this.memberOf(g, userId))) throw new Error('forbidden');
|
||||
const ms = await g.members.fetch().catch(() => g.members.cache);
|
||||
return [...ms.values()].map(member);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user