import crypto from 'node:crypto'; import type { IncomingMessage } from 'node:http'; import { WebSocket, WebSocketServer } from 'ws'; import type { BrowserMessage, DeviceStatus, LiveEvent, RelayFromDevice, RelayToDevice } from '@gvr/shared'; import type { ServerStore } from './store.js'; const OFFLINE_AFTER_MS = 15000; interface Pending { resolve: (r: RelayResponse) => void; reject: (e: Error) => void; timer: NodeJS.Timeout; head?: { status: number; headers: Record }; chunks: Buffer[]; } export interface RelayResponse { status: number; headers: Record; body: Buffer; } /** * 게임 PC 연결 하나와 브라우저 연결 여러 개를 잇는다. * - 게임 PC 가 먼저 연결 (기기 키 인증), 5초마다 ping. 15초 동안 소식이 없으면 오프라인 → 모든 브라우저에 잠금 상태 전송 (Q2) * - 브라우저의 /api 요청을 게임 PC 로 넘기고 응답을 돌려준다 */ export class RelayHub { private device: { ws: WebSocket; id: string; name: string; version: string | null; lastMsg: number } | null = null; private browsers = new Set(); private pending = new Map(); readonly deviceWss = new WebSocketServer({ noServer: true, maxPayload: 16 * 1024 * 1024 }); readonly browserWss = new WebSocketServer({ noServer: true, maxPayload: 64 * 1024 }); private watchdog: NodeJS.Timeout; private lastStatus = ''; constructor(private store: ServerStore) { this.watchdog = setInterval(() => this.checkAlive(), 2000); } close(): void { clearInterval(this.watchdog); this.device?.ws.terminate(); for (const b of this.browsers) b.terminate(); } status(): DeviceStatus { const d = this.store.device(); return { registered: !!d, online: !!this.device && Date.now() - this.device.lastMsg < OFFLINE_AFTER_MS, name: d?.name ?? null, lastSeen: this.device ? this.device.lastMsg : (d?.lastSeen ?? null), version: this.device?.version ?? d?.version ?? null, }; } private broadcastStatus(force = false): void { const st = this.status(); const key = `${st.registered}|${st.online}|${st.name}`; if (!force && key === this.lastStatus) return; this.lastStatus = key; this.broadcast({ type: 'status', data: { device: st } }); } private broadcast(m: BrowserMessage): void { const txt = JSON.stringify(m); for (const b of this.browsers) if (b.readyState === WebSocket.OPEN) b.send(txt); } private checkAlive(): void { if (this.device && Date.now() - this.device.lastMsg > OFFLINE_AFTER_MS) { this.device.ws.terminate(); this.dropDevice(this.device.ws); } this.broadcastStatus(); } // ------------------------------------------------------------------ 게임 PC authenticateDevice(req: IncomingMessage): { id: string } | null { const h = String(req.headers.authorization || ''); const m = /^Device ([0-9a-f]+)\.([\w-]+)$/.exec(h); if (!m) return null; const d = this.store.verifyDevice(m[1], m[2]); return d ? { id: d.id } : null; } attachDevice(ws: WebSocket, id: string): void { if (this.device) { // 같은 기기가 다시 연결 (네트워크 재연결) → 이전 연결을 끊는다 this.device.ws.close(4000, 'replaced'); this.dropDevice(this.device.ws); } const dev = this.store.device(); this.device = { ws, id, name: dev?.name ?? 'GAME-PC', version: null, lastMsg: Date.now() }; this.store.touchDevice(id, { lastSeen: Date.now() }); ws.send(JSON.stringify({ t: 'welcome', deviceId: id } satisfies RelayToDevice)); ws.on('message', (data, isBinary) => { if (!this.device || this.device.ws !== ws) return; this.device.lastMsg = Date.now(); if (isBinary) return this.onBinary(data as Buffer); let m: RelayFromDevice; try { m = JSON.parse(String(data)); } catch { return; } this.onDeviceMessage(m); }); ws.on('close', () => this.dropDevice(ws)); ws.on('error', () => this.dropDevice(ws)); this.broadcastStatus(true); } private dropDevice(ws: WebSocket): void { if (!this.device || this.device.ws !== ws) return; this.store.touchDevice(this.device.id, { lastSeen: this.device.lastMsg }); this.device = null; for (const [id, p] of this.pending) { clearTimeout(p.timer); p.reject(new Error('device_offline')); this.pending.delete(id); } this.broadcastStatus(true); } private onDeviceMessage(m: RelayFromDevice): void { const dev = this.device!; switch (m.t) { case 'hello': dev.name = m.name; dev.version = m.version; this.store.touchDevice(dev.id, { name: m.name, version: m.version, guildId: m.guildId ?? null, lastSeen: Date.now() }); this.broadcastStatus(true); break; case 'ping': dev.ws.send(JSON.stringify({ t: 'pong', ts: m.ts } satisfies RelayToDevice)); this.store.touchDevice(dev.id, { lastSeen: Date.now() }); break; case 'res': { const p = this.pending.get(m.id); if (!p) return; this.pending.delete(m.id); clearTimeout(p.timer); p.resolve({ status: m.status, headers: m.headers, body: Buffer.from(m.body ?? '', 'utf8') }); break; } case 'res_head': { const p = this.pending.get(m.id); if (p) p.head = { status: m.status, headers: m.headers }; break; } case 'res_end': { const p = this.pending.get(m.id); if (!p || !p.head) return; this.pending.delete(m.id); clearTimeout(p.timer); p.resolve({ status: p.head.status, headers: p.head.headers, body: Buffer.concat(p.chunks) }); break; } case 'event': this.broadcast(m.event as LiveEvent); break; } } private onBinary(buf: Buffer): void { if (buf.length < 4) return; const n = buf.readUInt32BE(0); const id = buf.subarray(4, 4 + n).toString('utf8'); const p = this.pending.get(id); if (p) p.chunks.push(buf.subarray(4 + n)); } /** 브라우저 요청 하나를 게임 PC 로 넘긴다 */ request(method: string, path: string, headers: Record, user: { id: string; name: string; avatar: string | null }, body: string | null, timeoutMs = 20000): Promise { const dev = this.device; if (!dev || !this.status().online) return Promise.reject(new Error('device_offline')); const id = crypto.randomBytes(8).toString('hex'); return new Promise((resolve, reject) => { const timer = setTimeout(() => { if (this.pending.delete(id)) reject(new Error('timeout')); }, timeoutMs); this.pending.set(id, { resolve, reject, timer, chunks: [] }); const msg: RelayToDevice = { t: 'req', id, method, path, headers, user, body }; dev.ws.send(JSON.stringify(msg)); }); } // ------------------------------------------------------------------ 브라우저 attachBrowser(ws: WebSocket): void { this.browsers.add(ws); ws.send(JSON.stringify({ type: 'status', data: { device: this.status() } } satisfies BrowserMessage)); const ping = setInterval(() => ws.readyState === WebSocket.OPEN && ws.ping(), 25000); ws.on('close', () => { clearInterval(ping); this.browsers.delete(ws); }); ws.on('message', () => undefined); } /** 로그아웃·세션 만료 시 해당 브라우저 연결 끊기용 */ get browserCount(): number { return this.browsers.size; } }