M2: 사이트 서버 · 사이트 v1 - gvr.tkrmagid.kr 배포
- site/server: Discord OAuth2 + 봇 토큰 멤버 확인, 세션, 1회용 등록 코드·기기 키 인증, 게임 PC WebSocket 중계(JSON·음성 바이너리), 15초 무응답 잠금, 게임 이미지 캐시, 관리 CLI - site/web: 타임라인·따라 읽기 재생(단어 강조·이어듣기·현장 모드·재생 게인)·필터·검색·실시간·교정, 발로란트/롤 경기 상세, 잠금 화면(관리자 등록 코드), 모바일, 효과음 - deploy/site: Dockerfile·compose·deploy.sh·make-env.sh (.5, 포트 2972) - 앱 코어: 사이트 필터 묶음(킬·라운드)과 유저 필터 규칙 맞춤, hello 에 서버 ID Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
148
site/server/test/relay.test.ts
Normal file
148
site/server/test/relay.test.ts
Normal file
@@ -0,0 +1,148 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import http from 'node:http';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import WebSocket from 'ws';
|
||||
import { buildServer } from '../src/app.ts';
|
||||
import type { Config } from '../src/config.ts';
|
||||
|
||||
const tmp = () => fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-site-'));
|
||||
|
||||
/** 가짜 디스코드 API: OAuth 토큰 교환, users/@me, 길드 멤버 */
|
||||
async function fakeDiscord(members: Set<string>) {
|
||||
const srv = http.createServer((req, res) => {
|
||||
const u = new URL(req.url!, 'http://x');
|
||||
res.setHeader('content-type', 'application/json');
|
||||
if (u.pathname === '/oauth2/token') return res.end(JSON.stringify({ access_token: 'at-' + 'member1' }));
|
||||
if (u.pathname === '/users/@me') return res.end(JSON.stringify({ id: 'member1', username: 'seunghan', global_name: '승한', avatar: null }));
|
||||
const m = /\/guilds\/(\d+)\/members\/(\w+)/.exec(u.pathname);
|
||||
if (m) {
|
||||
if (members.has(m[2])) return res.end(JSON.stringify({ nick: '승한', avatar: null }));
|
||||
res.statusCode = 404;
|
||||
return res.end('{}');
|
||||
}
|
||||
res.statusCode = 404;
|
||||
res.end('{}');
|
||||
});
|
||||
await new Promise<void>((r) => srv.listen(0, '127.0.0.1', () => r()));
|
||||
return { url: `http://127.0.0.1:${(srv.address() as any).port}`, close: () => srv.close() };
|
||||
}
|
||||
|
||||
test('사이트 서버: 로그인 → 기기 등록·연결 → 중계(JSON·음성) → 실시간 이벤트 → 연결 끊김 잠금', async () => {
|
||||
const members = new Set(['member1']);
|
||||
const dc = await fakeDiscord(members);
|
||||
const cfg: Config = {
|
||||
port: 0,
|
||||
host: '127.0.0.1',
|
||||
publicUrl: 'http://127.0.0.1',
|
||||
clientId: 'cid',
|
||||
clientSecret: 'secret',
|
||||
botToken: 'bot',
|
||||
allowedGuilds: ['111'],
|
||||
owners: ['owner1'],
|
||||
sessionSecret: 'x'.repeat(32),
|
||||
dataDir: tmp(),
|
||||
webDir: '/nonexistent',
|
||||
version: 'test',
|
||||
discordApi: dc.url,
|
||||
assetUpstream: {},
|
||||
};
|
||||
const { app, store } = await buildServer(cfg);
|
||||
await app.listen({ host: '127.0.0.1', port: 0 });
|
||||
const base = `http://127.0.0.1:${(app.server.address() as any).port}`;
|
||||
try {
|
||||
// 로그인 안 하면 401
|
||||
assert.equal((await fetch(base + '/api/status')).status, 401);
|
||||
// OAuth: state 쿠키 → callback
|
||||
const start = await fetch(base + '/auth/discord', { redirect: 'manual' });
|
||||
assert.equal(start.status, 302);
|
||||
const loc = new URL(start.headers.get('location')!);
|
||||
assert.equal(loc.searchParams.get('scope'), 'identify guilds');
|
||||
const stateCookie = start.headers.getSetCookie()[0].split(';')[0];
|
||||
const cb = await fetch(`${base}/auth/discord/callback?code=abc&state=${loc.searchParams.get('state')}`, { headers: { cookie: stateCookie }, redirect: 'manual' });
|
||||
assert.equal(cb.headers.get('location'), '/');
|
||||
const sid = cb.headers.getSetCookie().find((c) => c.startsWith('gvr_sid='))!.split(';')[0];
|
||||
const me = (await (await fetch(base + '/auth/me', { headers: { cookie: sid } })).json()) as any;
|
||||
assert.equal(me.user.name, '승한');
|
||||
// 기기 없음 → 상태 registered:false, /api 는 503
|
||||
let st = (await (await fetch(base + '/api/status', { headers: { cookie: sid } })).json()) as any;
|
||||
assert.equal(st.device.registered, false);
|
||||
assert.equal((await fetch(base + '/api/timeline', { headers: { cookie: sid } })).status, 503);
|
||||
// 등록 코드 → 기기 등록
|
||||
const code = store.createCode('test');
|
||||
assert.equal((await fetch(base + '/device/register', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ code: 'WRONG', name: 'x' }) })).status, 400);
|
||||
const reg = (await (await fetch(base + '/device/register', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ code: code.code, name: 'GAME-PC' }) })).json()) as any;
|
||||
assert.ok(reg.deviceKey);
|
||||
// 코드는 1회용
|
||||
assert.equal((await fetch(base + '/device/register', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ code: code.code, name: 'x' }) })).status, 400);
|
||||
// 잘못된 키는 거절
|
||||
await assert.rejects(
|
||||
new Promise((res, rej) => {
|
||||
const w = new WebSocket(base.replace('http', 'ws') + '/device/ws', { headers: { authorization: `Device ${reg.deviceId}.wrong` } });
|
||||
w.on('open', res);
|
||||
w.on('error', rej);
|
||||
}),
|
||||
);
|
||||
// 브라우저 WS
|
||||
const bws = new WebSocket(base.replace('http', 'ws') + '/ws', { headers: { cookie: sid } });
|
||||
const bmsgs: any[] = [];
|
||||
bws.on('message', (d) => bmsgs.push(JSON.parse(String(d))));
|
||||
await new Promise((r) => bws.on('open', r));
|
||||
// 앱 코어 쪽 (실제 RelayClient + Fastify inject)
|
||||
const { RelayClient } = await import('../../../app/src/core/relay/client.ts');
|
||||
const { Bus } = await import('../../../app/src/core/util/events.ts');
|
||||
const Fastify = (await import('fastify')).default;
|
||||
const local = Fastify();
|
||||
local.get('/api/timeline', async (req) => ({ items: [], next: null, user: req.headers['x-gvr-user'] }));
|
||||
local.get('/api/audio/:id', async (_req, reply) => reply.header('content-type', 'audio/ogg').send(Buffer.from('OggS' + 'x'.repeat(5000))));
|
||||
local.patch('/api/utterances/:id', async (req) => ({ ok: true, body: req.body }));
|
||||
const bus = new Bus();
|
||||
const rc = new RelayClient(local as any, bus, () => ({ serverUrl: base, deviceId: reg.deviceId, deviceKey: reg.deviceKey, name: 'GAME-PC', version: '1.0.0', guildId: '222' }));
|
||||
rc.start();
|
||||
const wait = async (fn: () => boolean, ms = 5000) => {
|
||||
const t = Date.now();
|
||||
while (!fn()) {
|
||||
if (Date.now() - t > ms) throw new Error('timeout');
|
||||
await new Promise((r) => setTimeout(r, 50));
|
||||
}
|
||||
};
|
||||
await wait(() => rc.status.state === 'online');
|
||||
await wait(() => bmsgs.some((m) => m.type === 'status' && m.data.device.online));
|
||||
st = (await (await fetch(base + '/api/status', { headers: { cookie: sid } })).json()) as any;
|
||||
assert.equal(st.device.online, true);
|
||||
// JSON 중계
|
||||
const tl = (await (await fetch(base + '/api/timeline?limit=5', { headers: { cookie: sid } })).json()) as any;
|
||||
assert.deepEqual(tl.items, []);
|
||||
assert.equal(JSON.parse(decodeURIComponent(tl.user)).id, 'member1');
|
||||
// 음성(바이너리) 중계
|
||||
const au = await fetch(base + '/api/audio/abc', { headers: { cookie: sid } });
|
||||
assert.equal(au.headers.get('content-type'), 'audio/ogg');
|
||||
assert.equal((await au.arrayBuffer()).byteLength, 5004);
|
||||
// 쓰기 요청: 다른 사이트 Origin 은 거절
|
||||
assert.equal((await fetch(base + '/api/utterances/a', { method: 'PATCH', headers: { cookie: sid, 'content-type': 'application/json', origin: 'https://evil.example' }, body: '{"text":"x"}' })).status, 403);
|
||||
const pr = (await (await fetch(base + '/api/utterances/a', { method: 'PATCH', headers: { cookie: sid, 'content-type': 'application/json', origin: cfg.publicUrl }, body: '{"text":"고침"}' })).json()) as any;
|
||||
assert.equal(pr.body.text, '고침');
|
||||
// 실시간 이벤트 → 브라우저
|
||||
bus.live({ type: 'recording.state', data: { active: true, channel: '음성', since: 1, participants: [] } });
|
||||
await wait(() => bmsgs.some((m) => m.type === 'recording.state'));
|
||||
// 기기가 알려 준 서버(222) 멤버도 로그인 허용
|
||||
assert.equal(store.device()!.guildId, '222');
|
||||
// 연결 끊김 → 잠금
|
||||
rc.stop();
|
||||
await wait(() => bmsgs.some((m) => m.type === 'status' && m.data.device.registered && !m.data.device.online));
|
||||
assert.equal((await fetch(base + '/api/timeline', { headers: { cookie: sid } })).status, 503);
|
||||
// 서버 멤버가 아니면 로그인 거절
|
||||
members.clear();
|
||||
const s2 = await fetch(base + '/auth/discord', { redirect: 'manual' });
|
||||
const l2 = new URL(s2.headers.get('location')!);
|
||||
const cb2 = await fetch(`${base}/auth/discord/callback?code=abc&state=${l2.searchParams.get('state')}`, { headers: { cookie: s2.headers.getSetCookie()[0].split(';')[0] }, redirect: 'manual' });
|
||||
assert.equal(cb2.headers.get('location'), '/?login=not_member');
|
||||
bws.close();
|
||||
await local.close();
|
||||
} finally {
|
||||
await app.close();
|
||||
dc.close();
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user