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) { 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: 'haneul', 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((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'], superAdmins: [], sessionSecret: 'x'.repeat(32), dataDir: tmp(), webDir: '/nonexistent', version: 'test', discordApi: dc.url, assetUpstream: {}, }; const { app, store } = await buildServer(cfg, { logEcho: false }); 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 })); // 큰 zip (20MB: 한 메시지 한도 16MB 넘음) 내보내기 · 받아오기 const big = Buffer.alloc(20 * 1024 * 1024); for (let i = 0; i < big.length; i += 4096) big[i] = (i / 4096) & 0xff; local.get('/api/bundles/export', async (_req, reply) => reply.header('content-type', 'application/zip').header('content-disposition', 'attachment; filename="gvr-test.zip"').send(big)); local.addContentTypeParser('application/zip', { parseAs: 'buffer', bodyLimit: 300 * 1024 * 1024 }, (_req, body, done) => done(null, body)); local.post('/api/bundles/import', async (req) => ({ size: (req.body as Buffer).length, same: (req.body as Buffer).equals(big) })); 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); // 큰 zip 내보내기: 조각으로 나눠 와서 그대로 붙는다 (content-disposition 도 전달) const ex = await fetch(base + '/api/bundles/export?ids=match-1', { headers: { cookie: sid } }); assert.equal(ex.headers.get('content-disposition'), 'attachment; filename="gvr-test.zip"'); assert.ok(Buffer.from(await ex.arrayBuffer()).equals(big)); // 받아오기 · 지우기는 관리자만 (주소를 %인코딩해 돌아가도 막힌다) for (const u of ['/api/bundles/delete', '/api/%62undles/delete', '/api/BUNDLES/delete', '/api/bundles%2Fdelete']) assert.equal((await fetch(base + u, { method: 'POST', headers: { cookie: sid, 'content-type': 'application/json', origin: cfg.publicUrl }, body: '{"ids":["x"]}' })).status, 403, u); assert.equal((await fetch(base + '/api/bundles/import', { method: 'POST', headers: { cookie: sid, 'content-type': 'application/zip', origin: cfg.publicUrl }, body: big })).status, 403); store.upsertAppUser({ id: 'member1', name: '하늘', avatar: null, role: 'admin', addedBy: 'test' }); const im = (await (await fetch(base + '/api/bundles/import', { method: 'POST', headers: { cookie: sid, 'content-type': 'application/zip', origin: cfg.publicUrl }, body: big })).json()) as any; assert.deepEqual(im, { size: big.length, same: true }); store.setAppUserRole('member1', 'user'); // 쓰기 요청: 다른 사이트 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); // 사이트 로그: 게임 PC 가 끊겨도 관리자는 볼 수 있다. 일반 유저는 못 본다 assert.equal((await fetch(base + '/site/logs', { headers: { cookie: sid } })).status, 403); assert.equal(((await (await fetch(base + '/auth/me', { headers: { cookie: sid } })).json()) as any).canViewLogs, false); assert.equal((await fetch(base + '/site/client-log', { method: 'POST', headers: { cookie: sid, 'content-type': 'application/json' }, body: JSON.stringify({ level: 'error', message: '화면 오류 테스트', page: '/' }) })).status, 204); store.upsertAppUser({ id: 'member1', name: '하늘', avatar: null, role: 'admin', addedBy: 'test' }); assert.equal(((await (await fetch(base + '/auth/me', { headers: { cookie: sid } })).json()) as any).canViewLogs, true); const days = ((await (await fetch(base + '/site/logs', { headers: { cookie: sid } })).json()) as any).days; assert.equal(days.length, 1); const logText = await (await fetch(`${base}/site/logs/${days[0].date}`, { headers: { cookie: sid } })).text(); for (const want of ['[relay] 게임 PC 연결', '[relay] 게임 PC 정보', '[relay] 게임 PC 연결 끊김', 'GET /api/timeline?limit=***', '"status":503', '[web] 화면 오류 테스트']) assert.ok(logText.includes(want), `로그에 "${want}" 없음\n${logText}`); assert.ok(!/GET \/api\/status \{"status":200/.test(logText), '성공한 상태 확인 폴링은 남기지 않는다'); const dl = await fetch(`${base}/site/logs/${days[0].date}?download=1`, { headers: { cookie: sid } }); assert.match(dl.headers.get('content-disposition') ?? '', /gvr-site-\d{4}-\d{2}-\d{2}\.log/); assert.equal((await fetch(`${base}/site/logs/..%2F..%2Fetc`, { headers: { cookie: sid } })).status, 404); // 서버 멤버가 아니면 로그인 거절 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(); } });