보안 리뷰 반영: 봇 중계 유저별 서버 · 채널 권한, 인증서 검증 우회 차단

봇 중계 권한 (앱 유저의 디스코드 아이디 기준)
- 서버 목록 · 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:
EJClaw
2026-10-15 11:19:13 +09:00
parent b90a895501
commit 6721db23ac
14 changed files with 372 additions and 68 deletions

View File

@@ -29,6 +29,8 @@
## 통신 · 데이터 보안 (v1.2.2~)
- 앱 ↔ 사이트 서버(로그인 토큰 · 기기 키 · 기록 중계 · 봇 중계)는 **https/wss 만** 쓴다. 사이트 서버 주소를 http 로 바꾸면 거절하고 아무것도 보내지 않는다 (이 PC 안 127.0.0.1 · localhost 만 예외, 개발용). `app/src/core/util/secure-url.ts`
- 사이트 서버 인증서는 앱에 들어 있는 Mozilla 루트 인증서로만 검증하고 검증을 끌 수 없다. `NODE_TLS_REJECT_UNAUTHORIZED=0`, Windows 인증서 저장소에 깐 가짜 루트 인증서(감시 · 프록시 프로그램)로는 통신을 엿볼 수 없다. 검증 끄기 변수는 시작할 때 지워서 사이트 밖 통신도 검증한다. `app/src/core/util/secure-http.ts`
- 겜녹이 봇 중계 권한: 앱 유저가 가입한 디스코드 서버, 그 유저가 볼 수 있는 채널만 보이고, 그 유저가 들어갈 수 있는 음성채널에만 봇을 부를 수 있다.
- 게임 연동(Riot 로컬 API)의 자체 서명 인증서 예외는 이 PC 안 주소에만 쓴다. Riot 원격 API 등 바깥 주소는 항상 인증서를 검증한다.
- exe(Electron) 잠금: `NODE_OPTIONS` · `NODE_EXTRA_CA_CERTS`(가짜 인증서를 끼워 통신을 엿보는 데 쓰임) · `ELECTRON_RUN_AS_NODE` · `--inspect` 를 무시하고 `app.asar` 만 읽는다 (Electron fuses). 설정 창은 앱 화면만 띄우고 바깥 주소는 브라우저로 연다. 권한 요청(마이크 · 카메라 등)은 거절한다.
- 사이트 서버: 보안 정책(CSP)으로 이 사이트 스크립트와 이 사이트로의 접속만 허용, 실시간 WebSocket 은 이 사이트에서 온 연결만, 로그인 세션 · 앱 토큰 · 기기 키는 해시로만 저장, 로그에서 로그인 code · state · 검색어를 지운다. 등록 코드 대입 · 로그인 요청 폭주는 IP 별로 막는다. HSTS · http→https 이동 · TLS 1.2 미만 차단은 앞단 프록시(NPMplus)가 한다.

View File

@@ -17,7 +17,8 @@ const BOT = process.env.GVR_E2E_BOT_TOKEN;
if (!BOT) throw new Error('GVR_E2E_BOT_TOKEN 이 필요합니다');
const shots = process.argv[2];
const SUPER = '293719842274541579';
const FRIEND = '111111111111111111';
// 친구 = 테스트봇 계정 (F&L 서버 멤버). 봇 중계는 앱 유저가 가입한 서버만 보여 주므로 실제 멤버여야 한다
const FRIEND = '1538122882528321536';
const PORT = 18931;
const base = `http://127.0.0.1:${PORT}`;
const work = fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-login-e2e-'));

View File

@@ -7,6 +7,7 @@ import { EventEmitter } from 'node:events';
import type { AppLoginBegin, AppLoginPoll, AppMe, AppRole, AppUserInfo, AppUserRow } from '@gvr/shared';
import type { SettingsStore } from './settings.js';
import { logger } from './util/log.js';
import { secureFetch } from './util/secure-http.js';
import { secureServerUrl } from './util/secure-url.js';
const log = logger('auth');
@@ -70,7 +71,7 @@ export class AppAuth extends EventEmitter {
}
private async call<T>(method: string, path: string, body?: unknown, token = this.settings.getSecret('appToken')): Promise<T> {
const r = await fetch(this.server + path, {
const r = await secureFetch(this.server + path, {
method,
headers: {
...(body !== undefined ? { 'content-type': 'application/json' } : {}),
@@ -78,7 +79,7 @@ export class AppAuth extends EventEmitter {
'x-gvr-version': this.opts.version,
},
body: body !== undefined ? JSON.stringify(body) : undefined,
signal: AbortSignal.timeout(15000),
timeoutMs: 15000,
});
const text = await r.text();
let json: any = null;

View File

@@ -8,6 +8,7 @@ import { ChannelType, Client, Events, GatewayIntentBits, MessageFlags, type Guil
import { EventEmitter } from 'node:events';
import WebSocket from 'ws';
import { logger } from '../util/log.js';
import { TLS_TRUST } from '../util/secure-http.js';
import { wsUrl } from '../util/secure-url.js';
const log = logger('gateway');
@@ -264,7 +265,7 @@ export class RemoteGateway extends EventEmitter implements BotGateway {
log.error(e.message);
return;
}
const ws = new WebSocket(url, { headers: { authorization: `Bearer ${token}`, 'x-gvr-version': this.opts.version }, handshakeTimeout: 10000, maxPayload: 8 * 1024 * 1024 });
const ws = new WebSocket(url, { headers: { authorization: `Bearer ${token}`, 'x-gvr-version': this.opts.version }, handshakeTimeout: 10000, maxPayload: 8 * 1024 * 1024, ...TLS_TRUST });
this.ws = ws;
let unauthorized = false;
let alive = Date.now();
@@ -346,6 +347,13 @@ export class RemoteGateway extends EventEmitter implements BotGateway {
this.wait?.resolve(m.guild);
this.wait = null;
return;
case 'watch_denied':
// 이 유저가 가입하지 않은 서버
if (this.watched?.id !== m.guildId) return;
log.warn('이 디스코드 서버에 가입되어 있지 않아 녹음할 수 없습니다');
this.wait?.resolve(null);
this.wait = null;
return;
case 'voiceState':
if (this.watched?.id !== m.guildId) return;
this.remember(m.member);

View File

@@ -18,6 +18,7 @@ import { WorkerClient, type WorkerCommand } from './stt/worker.js';
import { Timeline } from './timeline.js';
import { Bus } from './util/events.js';
import { initLogFile, logger } from './util/log.js';
import { hardenTlsEnv } from './util/secure-http.js';
const log = logger('core');
@@ -39,6 +40,7 @@ export type Core = Awaited<ReturnType<typeof startCore>>;
/** 코어 조립 (Electron 메인 프로세스와 헤드리스 CLI 가 같이 쓴다) */
export async function startCore(opts: CoreOptions) {
hardenTlsEnv(); // 헤드리스 CLI 도 (Electron 은 main.ts 에서 먼저)
fs.mkdirSync(opts.dataDir, { recursive: true });
const settings = opts.settings ?? new SettingsStore(opts.dataDir, opts.codec);
const S = () => settings.get();

View File

@@ -3,6 +3,7 @@ import WebSocket from 'ws';
import type { LiveEvent, RelayFromDevice, RelayToDevice } from '@gvr/shared';
import type { Bus } from '../util/events.js';
import { logger } from '../util/log.js';
import { secureFetch, TLS_TRUST } from '../util/secure-http.js';
import { secureServerUrl, wsUrl } from '../util/secure-url.js';
const log = logger('relay');
@@ -70,7 +71,7 @@ export class RelayClient {
return;
}
this.status = { ...this.status, state: 'connecting', serverUrl: c.serverUrl };
const ws = new WebSocket(url, { headers: { authorization: `Device ${c.deviceId}.${c.deviceKey}` }, handshakeTimeout: 10000, maxPayload: 8 * 1024 * 1024 });
const ws = new WebSocket(url, { headers: { authorization: `Device ${c.deviceId}.${c.deviceKey}` }, handshakeTimeout: 10000, maxPayload: 8 * 1024 * 1024, ...TLS_TRUST });
this.ws = ws;
ws.on('open', () => {
this.retries = 0;
@@ -157,12 +158,17 @@ export class RelayClient {
/** 1회용 등록 코드로 이 PC 를 사이트 서버에 등록한다 */
export async function registerDevice(serverUrl: string, code: string, name: string): Promise<{ deviceId: string; deviceKey: string }> {
const r = await fetch(secureServerUrl(serverUrl) + '/device/register', {
const r = await secureFetch(secureServerUrl(serverUrl) + '/device/register', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ code: code.trim(), name }),
});
const data: any = await r.json().catch(() => ({}));
let data: any = {};
try {
data = JSON.parse(await r.text());
} catch {
/* JSON 아님 */
}
if (!r.ok) throw new Error(data.message || (r.status === 400 || r.status === 404 ? '등록 코드가 올바르지 않거나 만료되었습니다' : `서버 오류 ${r.status}`));
return { deviceId: data.deviceId, deviceKey: data.deviceKey };
}

View File

@@ -0,0 +1,45 @@
// 사이트 서버와의 https/wss 통신에 쓰는 인증서 신뢰 설정.
// Node 에 들어 있는 Mozilla 루트 인증서만 믿고, 검증은 항상 켠다. 그래서 아래 방법으로는 통신을 엿볼 수 없다
// - NODE_TLS_REJECT_UNAUTHORIZED=0 (검증 끄기), NODE_EXTRA_CA_CERTS · NODE_USE_SYSTEM_CA (가짜 루트 인증서 끼우기)
// - Windows 인증서 저장소에 가짜 루트 인증서 설치 (프록시 · 감시 프로그램)
import https from 'node:https';
import tls from 'node:tls';
export const TLS_TRUST: { ca: string[]; rejectUnauthorized: true } = { ca: [...tls.rootCertificates], rejectUnauthorized: true };
const agent = new https.Agent({ ...TLS_TRUST, keepAlive: true });
export interface SecureResponse {
status: number;
ok: boolean;
text(): Promise<string>;
}
/** fetch 와 비슷한 작은 요청 함수. https 는 위 신뢰 설정으로, http 는 이 PC 안 주소(개발 · 테스트, secureServerUrl 이 거른다)만 */
export function secureFetch(url: string, init: { method?: string; headers?: Record<string, string>; body?: string; timeoutMs?: number } = {}): Promise<SecureResponse> {
const u = new URL(url);
if (u.protocol === 'http:') {
return fetch(url, { method: init.method, headers: init.headers, body: init.body, signal: AbortSignal.timeout(init.timeoutMs ?? 15000) });
}
if (u.protocol !== 'https:') return Promise.reject(new Error(`지원하지 않는 주소: ${u.protocol}`));
return new Promise((resolve, reject) => {
const req = https.request(u, { method: init.method || 'GET', headers: init.headers, agent, ...TLS_TRUST, timeout: init.timeoutMs ?? 15000 }, (res) => {
const chunks: Buffer[] = [];
res.on('data', (c: Buffer) => chunks.push(c));
res.on('error', reject);
res.on('end', () => {
const status = res.statusCode || 0;
const body = Buffer.concat(chunks).toString('utf8');
resolve({ status, ok: status >= 200 && status < 300, text: async () => body });
});
});
req.on('timeout', () => req.destroy(new Error('timeout')));
req.on('error', reject);
if (init.body) req.write(init.body);
req.end();
});
}
/** 검증을 끄는 환경변수는 시작할 때 지운다 (사이트 밖 통신: 다른 봇 모드의 디스코드 연결 · Riot 원격 API 등도 검증하게) */
export function hardenTlsEnv(): void {
delete process.env.NODE_TLS_REJECT_UNAUTHORIZED;
}

View File

@@ -7,11 +7,14 @@ import { AppAuth } from '../core/auth.js';
import { startCore, type Core } from '../core/index.js';
import { plainCodec, SettingsStore, type SecretCodec } from '../core/settings.js';
import { logger } from '../core/util/log.js';
import { hardenTlsEnv, secureFetch } from '../core/util/secure-http.js';
import { Finetuner } from './finetune.js';
import type { AuthView } from './api-types.js';
import { buildState, registerIpc } from './ipc.js';
import { brandDir, rendererDir, resolveDataDir, resourcesDir, workerCommand } from './paths.js';
// 인증서 검증을 끄는 환경변수(NODE_TLS_REJECT_UNAUTHORIZED=0)는 무시한다. fuses 로 막지 못하는 변수라 가장 먼저 지운다
hardenTlsEnv();
const log = logger('app');
const argv = process.argv.slice(1);
const flag = (name: string) => argv.includes(`--${name}`);
@@ -187,13 +190,18 @@ async function smoke(): Promise<void> {
out.bot = { status: c.bot.state.status, error: c.bot.state.error };
const botOk = a.status === 'signed_out' && !st.hasBuiltinBot && c.bot.state.status !== 'ready';
out.gpu = await c.worker.request('gpu_info', {}, 30000).catch((e) => String(e));
// 사이트 서버 https: 앱이 믿는 루트 인증서(Node 내장 Mozilla 목록)만으로 실제 서버 인증서가 검증되는지
out.siteTls = await secureFetch(`${c.settings.get().site.serverUrl}/healthz`, { timeoutMs: 20000 }).then(
(r) => r.ok,
(e) => String(e?.message ?? e),
);
c.settings.setSecret('riotApiKey', 'smoke-test');
out.secretRoundTrip = c.settings.getSecret('riotApiKey') === 'smoke-test';
c.settings.setSecret('riotApiKey', null);
out.dict = c.store.listDict().length;
out.renderer = fs.existsSync(path.join(rendererDir(), 'index.html'));
out.tray = fs.existsSync(path.join(brandDir(), 'tray.png'));
code = ready && botOk && out.secretRoundTrip && out.renderer && out.tray ? 0 : 1;
code = ready && botOk && out.secretRoundTrip && out.renderer && out.tray && out.siteTls === true ? 0 : 1;
await c.stop();
} catch (e: any) {
out.error = e.stack || e.message;

View File

@@ -22,6 +22,11 @@ const OTHER_G = '900000000000000002';
const VC1 = '910000000000000001';
const VC2 = '910000000000000002';
const TEXT = '910000000000000009';
/** 최고 관리자만 볼 수 있는 비공개 음성채널 */
const PRIV = '910000000000000003';
/** 모두 볼 수 있지만 최고 관리자만 들어갈 수 있는 음성채널 */
const LOCKED = '910000000000000004';
const OTHER_VC = '920000000000000001';
const tmp = () => fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-botgw-'));
delete process.env.GVR_BOT_TOKEN;
@@ -36,25 +41,48 @@ class FakeSource extends EventEmitter implements BotSource {
me() {
return ME;
}
guilds(): BotGwGuild[] {
return [
{ id: G, name: 'M&L', icon: null },
{ id: OTHER_G, name: '다른 서버', icon: null },
];
private all: BotGwGuild[] = [
{ id: G, name: 'M&L', icon: null },
{ id: OTHER_G, name: '다른 서버', icon: null },
];
/** 서버별 멤버: 친구는 M&L 에만 가입 */
private memberOf: Record<string, string[]> = { [G]: [SUPER, FRIEND], [OTHER_G]: [SUPER] };
private channels: Record<string, { id: string; name: string; voice: boolean; view: string[]; connect: string[] }[]> = {
[G]: [
{ id: VC1, name: '일반', voice: true, view: [SUPER, FRIEND], connect: [SUPER, FRIEND] },
{ id: VC2, name: '게임', voice: true, view: [SUPER, FRIEND], connect: [SUPER, FRIEND] },
{ id: PRIV, name: '운영진', voice: true, view: [SUPER], connect: [SUPER] },
{ id: LOCKED, name: '방송', voice: true, view: [SUPER, FRIEND], connect: [SUPER] },
{ id: TEXT, name: '채팅', voice: false, view: [SUPER, FRIEND], connect: [] },
],
[OTHER_G]: [{ id: OTHER_VC, name: '다른 음성', voice: true, view: [SUPER], connect: [SUPER] }],
};
/** 지금 음성채널에 있는 사람 */
voice: { member: BotGwMember; channelId: string; guildId: string }[] = [
{ member: m(SUPER, '관리자'), channelId: VC1, guildId: G },
{ member: m('300000000000000001', '운영진'), channelId: PRIV, guildId: G },
];
private ch(g: string, c: string) {
return this.channels[g]?.find((x) => x.id === c);
}
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 }] };
async guildsFor(userId: string) {
return this.all.filter((g) => this.memberOf[g.id]?.includes(userId));
}
isVoiceChannel(guildId: string, channelId: string) {
return guildId === G && (channelId === VC1 || channelId === VC2);
async snapshot(guildId: string, userId: string) {
const g = this.all.find((x) => x.id === guildId);
if (!g || !this.memberOf[guildId]?.includes(userId)) return null;
const channels: BotGwChannel[] = this.channels[guildId]!.filter((c) => c.voice && c.view.includes(userId)).map((c) => ({ id: c.id, name: c.name }));
return { guild: g, channels, voice: this.voice.filter((v) => v.guildId === guildId && channels.some((c) => c.id === v.channelId)).map(({ member, channelId }) => ({ member, channelId })) };
}
async members() {
canView(guildId: string, userId: string, channelId: string) {
return !!this.ch(guildId, channelId)?.view.includes(userId);
}
canConnect(guildId: string, userId: string, channelId: string) {
const c = this.ch(guildId, channelId);
return !!c?.voice && c.view.includes(userId) && c.connect.includes(userId);
}
async members(guildId: string, userId: string) {
if (!this.memberOf[guildId]?.includes(userId)) throw new Error('forbidden');
return [m(SUPER, '관리자'), m(FRIEND, '친구'), m('700000000000000001', '음악봇', true)];
}
async registerCommands(guildId: string) {
@@ -312,3 +340,68 @@ test('봇 중계: 슬래시 명령은 그 서버를 지켜보는 앱으로 가
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);
try {
await b.gw.start();
// 서버 목록: 가입한 M&L 만
assert.deepEqual(b.gw.guilds().map((g) => g.id), [G]);
// 가입하지 않은 서버는 지켜볼 수 없다 (바로 거절)
const t0 = Date.now();
assert.equal(await b.gw.watch(OTHER_G, { commands: true }), null);
assert.ok(Date.now() - t0 < 3000, '거절은 바로 온다');
assert.ok(!s.source.commands.includes(OTHER_G), '가입하지 않은 서버에 명령을 등록하지 않는다');
await assert.rejects(b.gw.members(OTHER_G), /forbidden/);
// M&L: 비공개 채널과 그 안의 사람은 안 보인다
assert.ok(await b.gw.watch(G, { commands: false }));
assert.deepEqual((b.gw as any).channels && [...(b.gw as any).channels.keys()].sort(), [VC1, VC2, LOCKED].sort());
assert.equal(b.gw.voiceChannelOf(G, '300000000000000001'), null);
assert.equal(b.gw.channel(G, PRIV), null);
// 비공개 채널 안의 움직임은 안 오고, 비공개 채널로 옮기면 "나감"으로만 보인다
const evs: any[] = [];
b.gw.on('voiceState', (e) => evs.push(e));
s.source.emit('voiceState', { guildId: G, member: m('300000000000000002', '운영진2'), oldChannelId: null, newChannelId: PRIV, channel: { id: PRIV, name: '운영진' } });
s.source.emit('voiceState', { guildId: G, member: m(SUPER, '관리자'), oldChannelId: VC1, newChannelId: PRIV, channel: { id: PRIV, name: '운영진' } });
await until(() => evs.length === 1);
await new Promise((r) => setTimeout(r, 100));
assert.equal(evs.length, 1);
assert.deepEqual([evs[0].member.id, evs[0].oldChannelId, evs[0].newChannelId, evs[0].channel], [SUPER, VC1, null, null]);
// 음성 참여: 비공개 · 연결 권한 없는 채널 · 다른 서버는 거절, 들어갈 수 있는 채널만
const ad = b.gw.adapterCreator(G)({ onVoiceServerUpdate: () => undefined, onVoiceStateUpdate: () => undefined, destroy: () => undefined });
ad.sendPayload(op4(G, PRIV));
ad.sendPayload(op4(G, LOCKED));
ad.sendPayload(op4(G, OTHER_VC));
ad.sendPayload(op4(G, VC2));
await until(() => s.source.sent.length === 1);
await new Promise((r) => setTimeout(r, 100));
assert.deepEqual(s.source.sent.map((x) => x.payload.d.channel_id), [VC2]);
// 슬래시 명령: 최고 관리자가 비공개 채널에서 /녹음시작 → 그 채널에 못 들어가는 친구 PC 로는 보내지 않는다
const cmds: any[] = [];
b.gw.on('command', (c, respond) => (cmds.push(c), respond('ok')));
const cmd = (name: string) =>
new Promise<string>((resolve) => s.source.emit('command', { name, guildId: G, user: m(SUPER, '관리자'), voiceChannel: { id: PRIV, name: '운영진' } } satisfies BotCommand, resolve));
assert.equal(await cmd('녹음시작'), '이 음성채널에 들어갈 수 있는 겜녹이 앱이 없습니다.');
// /녹음제외 는 친구 PC 기록에도 남기되 비공개 채널 이름은 보내지 않는다
assert.equal(await cmd('녹음제외'), 'ok');
assert.equal(cmds.length, 1);
assert.equal(cmds[0].voiceChannel, null);
// 친구 PC 가 받은 메시지 어디에도 비공개 채널 · 그 안의 사람 정보가 없다
const all = b.seen.join('\n');
// (OTHER_G 는 친구가 직접 보낸 watch 의 거절 응답에만 나온다)
for (const secret of [PRIV, '운영진', '300000000000000001', '300000000000000002', '다른 서버', OTHER_VC]) assert.ok(!all.includes(secret), secret);
} finally {
await a.gw.stop();
await b.gw.stop();
await s.close();
}
});

View File

@@ -46,3 +46,76 @@ test('암호화되지 않은 주소로는 로그인 토큰 · 기기 등록 코
test('게임 연동: 인증서 검증을 끄는 건 이 PC 안 주소뿐 (local 을 잘못 넘겨도 바깥 주소는 거절)', async () => {
await assert.rejects(request('https://pd.ap.a.pvp.net/x', { local: true }), /로컬 API 가 아닌 주소/);
});
test('인증서: NODE_TLS_REJECT_UNAUTHORIZED=0 이어도 믿을 수 없는 인증서의 서버로는 토큰 · 기기 키를 보내지 않는다 (https · wss)', async () => {
const { execFileSync } = await import('node:child_process');
const https = await import('node:https');
const { WebSocketServer } = await import('ws');
const { RelayClient } = await import('../src/core/relay/client.ts');
const { Bus } = await import('../src/core/util/events.ts');
// 가짜 서버 (자체 서명 인증서): 받은 요청의 인증 헤더를 모두 기록한다
const dir = tmp();
execFileSync('openssl', ['req', '-x509', '-newkey', 'rsa:2048', '-nodes', '-subj', '/CN=127.0.0.1', '-addext', 'subjectAltName=IP:127.0.0.1', '-days', '1', '-keyout', path.join(dir, 'k.pem'), '-out', path.join(dir, 'c.pem')], { stdio: 'ignore' });
const got: string[] = [];
const srv = https.createServer({ key: fs.readFileSync(path.join(dir, 'k.pem')), cert: fs.readFileSync(path.join(dir, 'c.pem')) }, (req, res) => {
got.push(`${req.url} ${req.headers.authorization ?? ''}`);
res.setHeader('content-type', 'application/json');
res.end('{"state":"pending","user":{"id":"1","name":"x","avatar":null},"role":"user","serverTime":0}');
});
const wss = new WebSocketServer({ noServer: true });
srv.on('upgrade', (req, socket, head) => {
got.push(`WS ${req.url} ${req.headers.authorization ?? ''}`);
wss.handleUpgrade(req, socket, head, (ws) => ws.close());
});
await new Promise<void>((r) => srv.listen(0, '127.0.0.1', () => r()));
const base = `https://127.0.0.1:${(srv.address() as any).port}`;
const prev = process.env.NODE_TLS_REJECT_UNAUTHORIZED;
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
const origWarn = process.emitWarning;
process.emitWarning = () => undefined;
try {
// 대조군: 기본 fetch 는 이 변수 때문에 실제로 토큰을 보낸다 (테스트가 우회를 잡아낼 수 있는지 확인)
await fetch(`${base}/control`, { headers: { authorization: 'Bearer control' } });
assert.deepEqual(got, ['/control Bearer control']);
got.length = 0;
const st = new SettingsStore(tmp());
st.update({ site: { serverUrl: base, deviceId: 'dev1' } });
st.setSecret('appToken', 'secret-app-token');
st.setSecret('deviceKey', 'secret-device-key');
// 로그인 확인 (https)
const auth = new AppAuth(st, { version: 't', openUrl: () => undefined });
const a = await auth.check();
assert.notEqual(a.status, 'ok');
assert.match(a.error ?? '', /연결할 수 없습니다/);
// 기기 등록 (https)
await assert.rejects(registerDevice(base, 'ABCD-EFGH', 'pc'));
// 겜녹이 봇 중계 (wss)
const gw = new RemoteGateway({ serverUrl: () => base, appToken: () => 'secret-app-token', version: 't' });
const started = gw.start().then(() => 'ready', () => 'failed');
await new Promise((r) => setTimeout(r, 1500));
await gw.stop();
assert.equal(await Promise.race([started, new Promise((r) => setTimeout(() => r('pending'), 100))]) === 'ready', false);
// 사이트 기기 중계 (wss)
const relay = new RelayClient({} as any, new Bus(), () => ({ serverUrl: base, deviceId: 'dev1', deviceKey: 'secret-device-key', name: 'pc', version: 't', guildId: null }));
relay.start();
await new Promise((r) => setTimeout(r, 1500));
assert.notEqual(relay.status.state, 'online');
relay.stop();
assert.deepEqual(got, [], '믿을 수 없는 인증서의 서버에 요청 · 토큰이 가면 안 된다');
// 앱 시작 때 이 변수를 지우면 (main.ts · startCore) 사이트 밖 통신(일반 fetch: 다른 봇 · Riot 원격 API 등)도 다시 검증한다
const { hardenTlsEnv } = await import('../src/core/util/secure-http.ts');
hardenTlsEnv();
assert.equal(process.env.NODE_TLS_REJECT_UNAUTHORIZED, undefined);
await assert.rejects(fetch(`${base}/after-harden`, { headers: { authorization: 'Bearer x' } }));
assert.deepEqual(got, []);
} finally {
if (prev === undefined) delete process.env.NODE_TLS_REJECT_UNAUTHORIZED;
else process.env.NODE_TLS_REJECT_UNAUTHORIZED = prev;
process.emitWarning = origWarn;
srv.closeAllConnections();
srv.close();
}
});

View File

@@ -228,7 +228,9 @@ type TimelineItem =
- 서버 → 앱: `ready{me, guilds}` · `guilds` · `guild{guild, channels, voice}`(watch 응답) · `voiceState`(지켜보는 서버만) · `cmd`(슬래시 명령) ·
`vserver`/`vstate`(봇 자신의 VOICE_SERVER/STATE_UPDATE 원문 = 일회용 음성 접속 정보) · `taken` · `res`
- 앱 → 서버: `watch{guildId, commands}` · `voice{guildId, payload}`(@discordjs/voice 어댑터의 op 4) · `cmd_res{id, content}` · `req{op:'members'}`
- 음성채널 참여: 앱의 @discordjs/voice 가 어댑터로 op 4 를 보내면 서버가 검사(지켜보는 서버 · 음성채널 · op 4 만, 필드를 다시 만들어)한 뒤 대신 보내고,
- 권한 (앱 유저의 디스코드 아이디 기준): 서버 목록 · watch 는 그 유저가 가입한 서버만 (아니면 `watch_denied`), 채널 · 음성 상태는 그 유저가 볼 수 있는(ViewChannel) 채널만
(볼 수 없는 채널로 옮기면 "나감"으로 가린다), 음성 참여는 그 유저가 들어갈 수 있는(ViewChannel + Connect) 음성채널만. 슬래시 명령 /녹음시작 도 그 채널에 들어갈 수 있는 유저의 PC 로만 보낸다
- 음성채널 참여: 앱의 @discordjs/voice 가 어댑터로 op 4 를 보내면 서버가 검사(지켜보는 서버 · 들어갈 수 있는 음성채널 · op 4 만, 필드를 다시 만들어)한 뒤 대신 보내고,
디스코드가 준 session_id · 음성 서버 token · endpoint 를 그 앱에만 넘긴다. 음성(UDP · DAVE)은 앱 ↔ 디스코드 음성 서버로 바로 간다 (Lavalink 와 같은 방식)
- 한 서버에서 봇은 음성채널 하나에만 있을 수 있다: 마지막으로 참여를 요청한 앱이 가져가고 이전 앱은 `taken` 을 받는다. 이전 앱의 늦은 나가기는 무시한다.
음성을 가진 앱이 끊기면 서버가 봇을 음성채널에서 뺀다

View File

@@ -272,6 +272,7 @@ export interface AppUserRow {
}
// 겜녹이 봇 중계 (사이트 서버 WebSocket /app/bot/ws, Authorization: Bearer <앱 토큰>)
// 권한: 앱 유저가 가입한 디스코드 서버만, 그 유저가 볼 수 있는 채널만 보이고, 들어갈 수 있는(보기 + 연결) 음성채널에만 봇을 부를 수 있다
// 봇 토큰은 서버에만 있다. 서버가 디스코드 게이트웨이에 붙어 있고, 앱은 필요한 정보만 받는다.
// 음성채널에 들어갈 때는 앱의 @discordjs/voice 가 보낸 op 4 를 서버가 대신 보내고,
// 디스코드가 준 일회용 음성 접속 정보(VOICE_STATE/SERVER_UPDATE)를 앱에 넘긴다. 음성은 앱 ↔ 디스코드로 바로 간다.
@@ -294,8 +295,10 @@ export interface BotGwChannel {
export type BotGwToApp =
| { t: 'ready'; me: BotGwMember; guilds: BotGwGuild[] }
| { t: 'guilds'; guilds: BotGwGuild[] }
/** watch 응답: 그 서버의 음성채널 · 음성채널에 있는 사람 */
/** watch 응답: 그 서버에서 이 유저가 볼 수 있는 음성채널 · 그 채널에 있는 사람 */
| { t: 'guild'; guild: BotGwGuild; channels: BotGwChannel[]; voice: { member: BotGwMember; channelId: string }[] }
/** watch 거절: 이 유저가 가입하지 않은 서버 */
| { t: 'watch_denied'; guildId: string }
| { t: 'voiceState'; guildId: string; member: BotGwMember; oldChannelId: string | null; newChannelId: string | null; channel: BotGwChannel | null }
| { t: 'cmd'; id: string; name: string; guildId: string; user: BotGwMember; voiceChannel: BotGwChannel | null }
/** 음성 접속 정보 (디스코드 VOICE_SERVER_UPDATE / 봇 자신의 VOICE_STATE_UPDATE 원문) */

View File

@@ -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 ?? '겜녹이 앱이 응답하지 않습니다. 잠시 뒤 다시 시도해 주세요.';

View File

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