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'; type Log = { info: (o: any, m?: string) => void; warn: (o: any, m?: string) => void }; const NOLOG: Log = { info: () => undefined, warn: () => undefined }; 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 browserSessions = new Map(); 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 = ''; /** 사이트 로그 (app.ts 가 [relay] 영역 로거를 넣는다) */ log: Log = NOLOG; 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 } }); } /** 서버가 만든 실시간 이벤트 (범인찾기 진행 단계 등) */ publish(ev: LiveEvent): void { this.broadcast(ev); } 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.log.warn({ name: this.device.name, silentMs: Date.now() - this.device.lastMsg }, '게임 PC 응답 없음 (15초) → 연결 끊음'); 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.log.info({ name: this.device.name }, '게임 PC 가 다시 연결해서 이전 연결을 닫음'); 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.log.info({ name: this.device.name }, '게임 PC 연결'); 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', (code, reason) => this.dropDevice(ws, `닫힘 ${code}${reason?.length ? ' ' + String(reason) : ''}`)); ws.on('error', (e) => this.dropDevice(ws, `오류 ${e.message}`)); this.broadcastStatus(true); } private dropDevice(ws: WebSocket, why = '응답 없음'): void { if (!this.device || this.device.ws !== ws) return; this.log.warn({ name: this.device.name, why, pending: this.pending.size }, '게임 PC 연결 끊김 (사이트 잠김)'); 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.log.info({ name: m.name, version: m.version, guild: m.guildId ?? null }, '게임 PC 정보'); 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 | Buffer | 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)) { this.log.warn({ method, path: path.split('?')[0], ms: timeoutMs }, '게임 PC 가 기록 요청에 답하지 않음 (시간 초과)'); reject(new Error('timeout')); } }, timeoutMs); this.pending.set(id, { resolve, reject, timer, chunks: [] }); if (Buffer.isBuffer(body)) { // 바이너리 본문(zip 받아오기): 1MB 조각으로 먼저 보내고 요청을 보낸다 (앱은 한 메시지 8MB 까지). // 보낼 것이 4MB 넘게 쌓이면 기다려서 ping · pong 이 너무 밀리지 않게 한다 const idBuf = Buffer.from(id, 'utf8'); const head = Buffer.alloc(4); head.writeUInt32BE(idBuf.length, 0); const CH = 1024 * 1024; void (async () => { for (let i = 0; i < body.length; i += CH) { while (dev.ws.readyState === WebSocket.OPEN && dev.ws.bufferedAmount > 4 * CH) await new Promise((r) => setTimeout(r, 20)); if (dev.ws.readyState !== WebSocket.OPEN) return; dev.ws.send(Buffer.concat([head, idBuf, body.subarray(i, i + CH)]), { binary: true }); } const msg: RelayToDevice = { t: 'req', id, method, path, headers, user, body: null, bin: true }; dev.ws.send(JSON.stringify(msg)); })(); return; } const msg: RelayToDevice = { t: 'req', id, method, path, headers, user, body }; dev.ws.send(JSON.stringify(msg)); }); } // ------------------------------------------------------------------ 브라우저 /** * sessionId: 로그아웃하면 바로 끊는다 (closeSession). * stillAllowed: 주기적으로(기본 30초) 세션이 살아 있고 봇과 같은 서버 멤버인지 다시 확인해, 아니면 4401 로 끊는다 */ attachBrowser(ws: WebSocket, sessionId?: string, stillAllowed?: () => Promise, recheckMs = 30000): void { this.browsers.add(ws); if (sessionId) this.browserSessions.set(ws, sessionId); ws.send(JSON.stringify({ type: 'status', data: { device: this.status() } } satisfies BrowserMessage)); const ping = setInterval(() => ws.readyState === WebSocket.OPEN && ws.ping(), 25000); const recheck = stillAllowed ? setInterval(() => { void stillAllowed() .catch(() => true) // 확인 자체가 실패하면(디스코드 장애) 유지 .then((ok) => { if (!ok && ws.readyState === WebSocket.OPEN) ws.close(4401, 'unauthorized'); }); }, recheckMs) : null; ws.on('close', () => { clearInterval(ping); if (recheck) clearInterval(recheck); this.browsers.delete(ws); this.browserSessions.delete(ws); }); ws.on('message', () => undefined); } /** 로그아웃: 그 세션의 실시간 연결을 끊는다 */ closeSession(sessionId: string): void { for (const [ws, sid] of this.browserSessions) if (sid === sessionId) ws.close(4401, 'logged_out'); } /** 로그아웃·세션 만료 시 해당 브라우저 연결 끊기용 */ get browserCount(): number { return this.browsers.size; } }