// The phone gateway: one HTTP server on a private address that accepts only a WebSocket upgrade to // exactly GET /mobile, then runs the E2EE v2 handshake, token auth and the read-only dispatcher. import { createServer } from 'node:http'; import { randomBytes } from 'node:crypto'; import { WebSocketServer } from 'ws'; import { createHostSession } from './e2ee-v2.mjs'; import { assertBindable } from './network.mjs'; import { createDispatcher } from './rpc.mjs'; const HANDSHAKE_TIMEOUT_MS = 10_000; const MAX_DECRYPT_FAILURES = 5; const MAX_CONNECTIONS = 16; const MAX_FRAME_BYTES = 6 * 1024 * 1024; /** * @param {{ store: ReturnType, bind: string, port?: number, * bundle?: any, projects?: any, fullMethods?: any, log?: (event: string, detail?: object) => void, allowLoopbackOnly?: boolean }} options */ export async function startPhoneHost({ store, bind, port = 8792, bundle = null, projects = null, fullMethods = null, log = () => {} }) { assertBindable(bind); const runtimeId = `ruflo-phone-${randomBytes(8).toString('hex')}`; const dispatcher = createDispatcher({ runtimeId, bundle, projects, fullMethods }); /** @type {Map} */ const sockets = new Map(); const http = createServer((req, res) => { res.writeHead(404).end(); }); const wss = new WebSocketServer({ noServer: true, maxPayload: MAX_FRAME_BYTES, perMessageDeflate: false }); http.on('upgrade', (req, socket, head) => { const ok = req.method === 'GET' && req.url === '/mobile' && sockets.size < MAX_CONNECTIONS; if (!ok) { socket.end('HTTP/1.1 404 Not Found\r\nConnection: close\r\n\r\n'); return; } wss.handleUpgrade(req, socket, head, (ws) => onConnection(ws)); }); function onConnection(ws) { const state = { deviceId: null }; sockets.set(ws, state); let session = null; let phase = 'hello'; let failures = 0; const close = (code, reason) => { try { ws.close(code, reason); } catch {} }; const timer = setTimeout(() => close(4002, 'E2EE handshake timeout'), HANDSHAKE_TIMEOUT_MS); const closers = new Set(); ws.on('close', () => { clearTimeout(timer); sockets.delete(ws); for (const fn of closers) { try { fn(); } catch { /* cleanup is best effort */ } } closers.clear(); }); /** Seals and sends one reply or stream frame; frames for a closed socket are dropped. */ const push = (obj) => { if (session && phase === 'ready' && ws.readyState === ws.OPEN) ws.send(session.sealText(JSON.stringify(obj))); }; const conn = { get deviceId() { return state.deviceId; }, // Re-read from the store per request, so a downgrade or revoke applies without a restart. access: () => (state.deviceId ? store.accessOf(state.deviceId) : null), push, /** Per-connection state for method handlers (stream registries). */ state: new Map(), /** Runs when this phone disconnects, e.g. to stop its terminal streams. */ onClose: (fn) => { closers.add(fn); return () => closers.delete(fn); }, }; ws.on('error', () => {}); // Why the catch: a store error (unreadable devices.json, failed write) must close this socket, // not become an unhandled rejection that takes the whole host down. ws.on('message', (data, isBinary) => { onMessage(data, isBinary).catch(() => { log('host-error'); close(1011, 'Host error'); }); }); async function onMessage(data, isBinary) { if (phase === 'hello') { if (isBinary) return close(4001, 'Invalid handshake message'); let hello; try { hello = JSON.parse(data.toString('utf8')); } catch { return close(4001, 'Invalid handshake message'); } session = createHostSession({ hello, hostSecretKey: store.hostSecretKey }); if (!session) return close(4001, 'E2EE v2 required'); phase = 'auth'; ws.send(JSON.stringify(session.ready)); return; } if (isBinary) return close(4001, 'Binary frames are not supported'); const plaintext = session.openText(data.toString('utf8')); if (plaintext === null) { if (phase === 'auth') return close(4001, 'Unauthorized'); if (++failures >= MAX_DECRYPT_FAILURES) close(4003, 'Too many decryption failures'); return; } failures = 0; if (phase === 'auth') { let auth; try { auth = JSON.parse(plaintext); } catch { auth = null; } const shaped = auth && Object.keys(auth).sort().join(',') === 'deviceToken,transcriptHashB64,type,v' && auth.type === 'e2ee_auth' && auth.v === 2 && auth.transcriptHashB64 === session.transcriptHashB64; const device = shaped ? store.authenticate(auth.deviceToken) : null; if (!device) { ws.send(session.sealText(JSON.stringify({ type: 'e2ee_error', error: { code: 'unauthorized', message: 'Unknown device' } }))); log('auth-refused'); return close(4001, 'Unauthorized'); } clearTimeout(timer); state.deviceId = device.deviceId; phase = 'ready'; ws.send(session.sealText(JSON.stringify({ type: 'e2ee_authenticated', v: 2, transcriptHashB64: session.transcriptHashB64 }))); log('connected', { deviceId: device.deviceId, name: device.name }); return; } // Revocation takes effect on the next request even if the socket is still open. if (!store.isPaired(state.deviceId)) return close(4004, 'Device revoked'); const reply = await dispatcher.handle(plaintext, conn); if (reply === null) { if (++failures >= MAX_DECRYPT_FAILURES) close(4003, 'Too many invalid requests'); return; } if (reply !== undefined) push(reply); } } // A stream can run for hours without a request, so revocation is also checked on a timer. const sweep = setInterval(() => { for (const [ws, s] of sockets) if (s.deviceId && !store.isPaired(s.deviceId)) ws.close(4004, 'Device revoked'); }, 2000); sweep.unref(); await new Promise((resolve, reject) => { http.once('error', reject); http.listen(port, bind, resolve); }); const actualPort = http.address().port; return { runtimeId, endpoint: `ws://${bind}:${actualPort}/mobile`, port: actualPort, /** Closes every live socket of a device (used after revoke). */ disconnect(deviceId) { for (const [ws, s] of sockets) if (s.deviceId === deviceId) ws.close(4004, 'Device revoked'); }, refusedMethods: () => dispatcher.refusedMethods(), connectedDeviceIds: () => [...new Set([...sockets.values()].map((s) => s.deviceId).filter(Boolean))], async close() { clearInterval(sweep); for (const ws of sockets.keys()) ws.terminate(); wss.close(); await new Promise((r) => http.close(() => r())); }, }; }