보안 리뷰 반영: 봇 중계 유저별 서버 · 채널 권한, 인증서 검증 우회 차단
봇 중계 권한 (앱 유저의 디스코드 아이디 기준) - 서버 목록 · 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:
@@ -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-'));
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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 };
|
||||
}
|
||||
|
||||
45
app/src/core/util/secure-http.ts
Normal file
45
app/src/core/util/secure-http.ts
Normal 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;
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user