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

봇 중계 권한 (앱 유저의 디스코드 아이디 기준)
- 서버 목록 · 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

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