/* HTTP + WebSocket watch-party relay (docs/protocol.md, v2). createServer(cfg, { discordFetch?, now?, log? }) → http.Server (not listening) GET / static Activity files from cfg.activityDir, SPA fallback to index.html GET /api/config { applicationId, dev } POST /api/token {code} { access_token } (Discord OAuth2 code exchange) GET /api/avatar/:id the user's Discord avatar (64px PNG), proxied: the Activity CSP blocks cdn.discordapp.com, so avatars come from our own origin GET /healthz { ok: true } GET /ws watch-party WebSocket cfg.dev === true additionally accepts dev hellos and reverse-proxies the paths Discord's URL mappings would handle, so dev and prod use the same URLs: /tv/v1/* → cfg.devApiUrl/v1/* (only /tv/v1: plain /tv is the site's Series route) /tmdb/* → https://api.themoviedb.org/* /img/* → https://image.tmdb.org/* A leading "/.proxy" (Discord's legacy URL-mapping prefix) is stripped from every path. `discordFetch` (default: global fetch) and `now` (default Date.now) are injectable for tests. */ const http = require('http'); const https = require('https'); const fs = require('fs'); const path = require('path'); const { WebSocketServer } = require('ws'); const DISCORD_API = 'https://discord.com/api/v10'; const DISCORD_CDN = 'https://cdn.discordapp.com'; const USER_CACHE_MS = 10 * 60 * 1000; const INSTANCE_CACHE_MS = 10 * 1000; const AVATAR_CACHE_MS = 60 * 60 * 1000; const HUB_TTL_MS = 10 * 60 * 1000; // empty hubs + original-host reclaim window const HELLO_TIMEOUT_MS = 15000; const HEARTBEAT_MS = 30000; const MAX_BODY = 8 * 1024; const MAX_WS_PAYLOAD = 256 * 1024; // play snapshots carry a whole bug-tv Stream object const MSG_RATE = 30; // per second, per socket (burst = rate) const MAX_PATH = 2048; const MIME = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.json': 'application/json; charset=utf-8', '.map': 'application/json; charset=utf-8', '.svg': 'image/svg+xml', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.ico': 'image/x-icon', '.woff2': 'font/woff2', '.txt': 'text/plain; charset=utf-8', '.vtt': 'text/vtt; charset=utf-8', '.webmanifest': 'application/manifest+json', }; function sendJson(res, status, body, headers = {}) { const data = JSON.stringify(body); res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Content-Length': Buffer.byteLength(data), 'Cache-Control': 'no-store', ...headers, }); res.end(data); } function readBody(req) { return new Promise((resolve, reject) => { let size = 0; const chunks = []; req.on('data', (c) => { size += c.length; if (size > MAX_BODY) { reject(Object.assign(new Error('body too large'), { status: 413 })); req.destroy(); return; } chunks.push(c); }); req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8'))); req.on('error', reject); }); } /** Token bucket: `rate` events per second, burst = rate. */ function bucket(rate) { let tokens = rate; let last = Date.now(); return () => { const t = Date.now(); tokens = Math.min(rate, tokens + ((t - last) / 1000) * rate); last = t; if (tokens < 1) return false; tokens -= 1; return true; }; } function stripProxy(pathname) { return pathname === '/.proxy' ? '/' : pathname.startsWith('/.proxy/') ? pathname.slice(7) : pathname; } const ID_RE = /^[\w.:-]{1,128}$/; function createServer(cfg, opts = {}) { const discordFetch = opts.discordFetch || ((...a) => fetch(...a)); const now = opts.now || Date.now; const activityDir = path.resolve(cfg.activityDir || path.join(__dirname, '..', 'site')); const log = opts.log || ((...a) => console.log('tv-discord:', ...a)); const dev = cfg.dev === true; const appId = String(cfg.applicationId || ''); /* ---- Discord HTTP ------------------------------------------------------ */ const userCache = new Map(); // token → { user, exp } const avatarHash = new Map(); // userId → avatar hash | null (Discord users we have seen) async function exchangeCode(code) { const body = new URLSearchParams({ client_id: appId, client_secret: String(cfg.clientSecret || ''), grant_type: 'authorization_code', code, }); const r = await discordFetch('https://discord.com/api/oauth2/token', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: body.toString(), }); const data = await r.json().catch(() => ({})); if (!r.ok || !data.access_token) { throw Object.assign(new Error(data.error_description || data.error || `discord ${r.status}`), { status: 502 }); } return data.access_token; } async function userForToken(token) { const t = now(); const hit = userCache.get(token); if (hit && hit.exp > t) return hit.user; const r = await discordFetch(`${DISCORD_API}/users/@me`, { headers: { Authorization: `Bearer ${token}` } }); if (!r.ok) throw new Error(`invalid token (${r.status})`); const u = await r.json(); if (!u || !u.id) throw new Error('invalid token'); const id = String(u.id); const user = { id, username: String(u.global_name || u.username || id).slice(0, 64), avatar: `/api/avatar/${id}` }; avatarHash.set(id, typeof u.avatar === 'string' && /^\w{1,64}$/.test(u.avatar) ? u.avatar : null); if (userCache.size > 5000) { for (const [k, v] of userCache) if (v.exp <= t) userCache.delete(k); if (userCache.size > 5000) userCache.clear(); } userCache.set(token, { user, exp: t + USER_CACHE_MS }); return user; } // instanceId → { users:Set, exp } ; inflight: instanceId → Promise const instanceCache = new Map(); const instanceInflight = new Map(); function loadInstance(instanceId) { let p = instanceInflight.get(instanceId); if (p) return p; p = (async () => { const r = await discordFetch(`${DISCORD_API}/applications/${appId}/activity-instances/${encodeURIComponent(instanceId)}`, { headers: { Authorization: `Bot ${cfg.token || ''}` }, }); let users = new Set(); if (r.ok) { const data = await r.json().catch(() => ({})); const list = Array.isArray(data && data.users) ? data.users : []; users = new Set(list.map((u) => String(u && typeof u === 'object' ? u.id : u))); } else if (r.status !== 404) { throw new Error(`activity-instances ${r.status}`); } const entry = { users, exp: now() + INSTANCE_CACHE_MS }; if (instanceCache.size > 2000) instanceCache.clear(); instanceCache.set(instanceId, entry); return entry; })().finally(() => instanceInflight.delete(instanceId)); instanceInflight.set(instanceId, p); return p; } /** Is `userId` in the Activity instance? Cached 10s; one refetch when a cached list misses. */ async function isMember(instanceId, userId) { let e = instanceCache.get(instanceId); let fresh = false; if (!e || e.exp <= now()) { e = await loadInstance(instanceId); fresh = true; } if (e.users.has(userId)) return true; if (fresh) return false; e = await loadInstance(instanceId); return e.users.has(userId); } /* ---- avatars ----------------------------------------------------------- */ const avatarCache = new Map(); // userId → { hash, type, body, exp } async function serveAvatar(req, res, userId) { if (!avatarHash.has(userId)) return sendJson(res, 404, { error: 'unknown user' }); const hash = avatarHash.get(userId); let hit = avatarCache.get(userId); if (!hit || hit.hash !== hash || hit.exp <= now()) { let url; if (hash) url = `${DISCORD_CDN}/avatars/${userId}/${hash}.png?size=64`; else { let idx = 0; try { idx = Number((BigInt(userId) >> 22n) % 6n); } catch (e) { /* non-numeric id */ } url = `${DISCORD_CDN}/embed/avatars/${idx}.png`; } const r = await discordFetch(url); if (!r.ok) return sendJson(res, 502, { error: `avatar ${r.status}` }); const body = Buffer.from(await r.arrayBuffer()); const type = (r.headers && r.headers.get && r.headers.get('content-type')) || 'image/png'; hit = { hash, type: /^image\//.test(type) ? type : 'image/png', body, exp: now() + AVATAR_CACHE_MS }; if (avatarCache.size > 1000) avatarCache.clear(); avatarCache.set(userId, hit); } res.writeHead(200, { 'Content-Type': hit.type, 'Content-Length': hit.body.length, 'Cache-Control': 'public, max-age=600', 'X-Content-Type-Options': 'nosniff', }); res.end(req.method === 'HEAD' ? undefined : hit.body); } /* ---- static ------------------------------------------------------------ */ function cacheControl(ext) { if (ext === '.html') return 'no-cache'; if (ext === '.js' || ext === '.mjs' || ext === '.css' || ext === '.map') return 'public, max-age=300'; return 'public, max-age=3600'; } function serveFile(req, res, file, status = 200) { fs.stat(file, (err, st) => { if (err || !st.isFile()) return notFound(req, res); const ext = path.extname(file).toLowerCase(); res.writeHead(status, { 'Content-Type': MIME[ext] || 'application/octet-stream', 'Content-Length': st.size, 'Cache-Control': cacheControl(ext), 'X-Content-Type-Options': 'nosniff', }); if (req.method === 'HEAD') return res.end(); fs.createReadStream(file).on('error', () => res.destroy()).pipe(res); }); } function notFound(req, res) { res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-cache' }); res.end(req.method === 'HEAD' ? undefined : 'not found'); } function serveStatic(req, res, pathname) { let rel; try { rel = decodeURIComponent(pathname); } catch (e) { return notFound(req, res); } if (rel.includes('\0')) return notFound(req, res); let file = path.join(activityDir, path.normalize(rel)); if (file !== activityDir && !file.startsWith(activityDir + path.sep)) return notFound(req, res); if (rel.endsWith('/')) file = path.join(file, 'index.html'); fs.stat(file, (err, st) => { if (!err && st.isFile()) return serveFile(req, res, file); if (!err && st.isDirectory()) return serveFile(req, res, path.join(file, 'index.html')); // SPA fallback only for extension-less routes; a missing asset is a real 404 if (path.extname(rel)) return notFound(req, res); serveFile(req, res, path.join(activityDir, 'index.html')); }); } /* ---- dev reverse proxy (mirrors Discord's URL mappings) --------------- */ function devTarget(p, search) { if (!dev) return null; if (p.startsWith('/tv/v1/') && cfg.devApiUrl) return cfg.devApiUrl + p.slice(3) + search; if (p.startsWith('/tmdb/')) return `https://api.themoviedb.org${p.slice(5)}${search}`; if (p.startsWith('/img/')) return `https://image.tmdb.org${p.slice(4)}${search}`; return null; } function proxy(req, res, target) { const u = new URL(target); const headers = { ...req.headers, host: u.host }; delete headers.origin; delete headers.referer; delete headers.cookie; const mod = u.protocol === 'https:' ? https : http; const up = mod.request(u, { method: req.method, headers }, (ur) => { const h = { ...ur.headers }; delete h['set-cookie']; res.writeHead(ur.statusCode || 502, h); ur.pipe(res); }); up.on('error', (e) => { if (!res.headersSent) sendJson(res, 502, { error: `proxy: ${e.message}` }); else res.destroy(); }); res.on('close', () => !res.writableFinished && up.destroy()); req.pipe(up); } /* ---- http -------------------------------------------------------------- */ async function onRequest(req, res) { let url; try { url = new URL(req.url, 'http://x'); } catch (e) { return sendJson(res, 400, { error: 'bad url' }); } const p = stripProxy(url.pathname); try { const target = devTarget(p, url.search); if (target) return proxy(req, res, target); if (p === '/healthz') return sendJson(res, 200, { ok: true }); if (p === '/api/config') { if (req.method !== 'GET' && req.method !== 'HEAD') return sendJson(res, 405, { error: 'method not allowed' }); return sendJson(res, 200, { applicationId: appId, dev }); } if (p === '/api/token') { if (req.method !== 'POST') return sendJson(res, 405, { error: 'method not allowed' }); let body; try { body = JSON.parse((await readBody(req)) || '{}'); } catch (e) { return sendJson(res, e.status || 400, { error: e.status ? e.message : 'invalid json' }); } const code = body && body.code; if (typeof code !== 'string' || !code || code.length > 512) return sendJson(res, 400, { error: 'missing code' }); const access_token = await exchangeCode(code); return sendJson(res, 200, { access_token }); } const av = /^\/api\/avatar\/(\d{1,25})$/.exec(p); if (av) { if (req.method !== 'GET' && req.method !== 'HEAD') return sendJson(res, 405, { error: 'method not allowed' }); return await serveAvatar(req, res, av[1]); } if (p.startsWith('/api/')) return sendJson(res, 404, { error: 'not found' }); if (req.method !== 'GET' && req.method !== 'HEAD') return sendJson(res, 405, { error: 'method not allowed' }); return serveStatic(req, res, p); } catch (e) { log('http error', p, e.message); if (!res.headersSent) sendJson(res, e.status || 500, { error: e.status ? e.message : 'internal error' }); else res.destroy(); } } const server = http.createServer((req, res) => { onRequest(req, res); }); /* ---- hubs -------------------------------------------------------------- */ // instanceId → { id, members: Map}> (join order), host, owner, // ownerLeftAt, route, play, emptySince } // owner = the first user ever in the hub (the one who started the instance). const hubs = new Map(); function getHub(id) { let hub = hubs.get(id); if (hub && !hub.members.size && now() - hub.emptySince > HUB_TTL_MS) { hubs.delete(id); hub = null; } if (!hub) { hub = { id, members: new Map(), host: null, owner: null, ownerLeftAt: 0, route: null, play: null, emptySince: now() }; hubs.set(id, hub); } return hub; } function send(ws, msg) { if (ws.readyState === 1) ws.send(typeof msg === 'string' ? msg : JSON.stringify(msg)); } function broadcast(hub, msg, exceptUser = null) { const data = JSON.stringify(msg); for (const [uid, m] of hub.members) { if (uid === exceptUser) continue; for (const ws of m.sockets) send(ws, data); } } const membersOf = (hub) => [...hub.members.values()].map((m) => m.user); function join(hub, user, ws) { let m = hub.members.get(user.id); const isNew = !m; if (!m) { m = { user, sockets: new Set() }; hub.members.set(user.id, m); } else m.user = user; m.sockets.add(ws); const before = hub.host; if (!hub.owner) hub.owner = user.id; if (!hub.host || !hub.members.has(hub.host)) hub.host = user.id; else if (user.id === hub.owner && hub.host !== user.id && now() - hub.ownerLeftAt <= HUB_TTL_MS) { hub.host = user.id; // the original host is back within the window: reclaim } send(ws, { t: 'welcome', you: user, host: hub.host, members: membersOf(hub), route: hub.route, play: hub.play, now: now() }); if (isNew) broadcast(hub, { t: 'members', members: membersOf(hub) }, user.id); if (hub.host !== before && before) broadcast(hub, { t: 'host', host: hub.host }, user.id); } function leave(hub, userId, ws) { const m = hub.members.get(userId); if (!m) return; m.sockets.delete(ws); if (m.sockets.size) return; hub.members.delete(userId); if (userId === hub.owner) hub.ownerLeftAt = now(); if (!hub.members.size) { hub.emptySince = now(); // keep host/route/play for the TTL so a rejoin resumes return; } const wasHost = hub.host === userId; if (wasHost) hub.host = hub.members.keys().next().value; // earliest remaining member broadcast(hub, { t: 'members', members: membersOf(hub) }); if (wasHost) broadcast(hub, { t: 'host', host: hub.host }); } function onRoute(hub, msg) { const p = msg.path; if (typeof p !== 'string' || !p.startsWith('/') || p.length > MAX_PATH) return; hub.route = p; // a snapshot for another page is stale for late joiners if (hub.play && typeof hub.play.path === 'string' && hub.play.path !== p) hub.play = null; broadcast(hub, { t: 'route', path: p }, hub.host); } function onPlay(hub, msg) { const s = msg.snapshot; if (s === null) { hub.play = null; return broadcast(hub, { t: 'play', snapshot: null }, hub.host); } if (!s || typeof s !== 'object' || Array.isArray(s)) return; const snapshot = { ...s, at: now() }; hub.play = snapshot; broadcast(hub, { t: 'play', snapshot }, hub.host); } /* ---- websocket --------------------------------------------------------- */ const wss = new WebSocketServer({ noServer: true, maxPayload: MAX_WS_PAYLOAD }); server.on('upgrade', (req, socket, head) => { let p = ''; try { p = stripProxy(new URL(req.url, 'http://x').pathname); } catch (e) { /* bad url */ } if (p !== '/ws') { socket.write('HTTP/1.1 404 Not Found\r\nConnection: close\r\n\r\n'); socket.destroy(); return; } wss.handleUpgrade(req, socket, head, (ws) => wss.emit('connection', ws, req)); }); // half-open sockets (host's network dropped) must close so the host hands over const heartbeat = setInterval(() => { for (const ws of wss.clients) { if (ws.alive === false) { ws.terminate(); continue; } ws.alive = false; try { ws.ping(); } catch (e) { /* closing */ } } }, HEARTBEAT_MS); if (heartbeat.unref) heartbeat.unref(); wss.on('connection', (ws) => { let user = null; let hub = null; let authing = false; const msgOk = bucket(MSG_RATE); ws.alive = true; ws.on('pong', () => (ws.alive = true)); const fatal = (message) => { send(ws, { t: 'error', message }); ws.close(4001, message.slice(0, 100)); }; const helloTimer = setTimeout(() => !user && fatal('hello timeout'), HELLO_TIMEOUT_MS); if (helloTimer.unref) helloTimer.unref(); async function hello(msg) { if (user || authing) return; authing = true; const instanceId = String(msg.instanceId || ''); if (!ID_RE.test(instanceId)) return fatal('missing instanceId'); let u; if (msg.dev) { if (!dev) return fatal('dev mode is off'); const id = String(msg.userId || ''); if (!/^[\w-]{1,32}$/.test(id)) return fatal('missing userId'); u = { id, username: String(msg.username || `dev-${id}`).slice(0, 32), avatar: null }; } else { if (typeof msg.token !== 'string' || !msg.token || msg.token.length > 512) return fatal('missing token'); try { u = await userForToken(msg.token); } catch (e) { return fatal('authentication failed'); } let ok = false; try { ok = await isMember(instanceId, u.id); } catch (e) { log('membership check failed', instanceId, e.message); return fatal('membership check failed'); } if (!ok) return fatal('not in this activity'); } if (ws.readyState !== 1) return; clearTimeout(helloTimer); user = u; hub = getHub(instanceId); join(hub, user, ws); } ws.on('message', (raw, isBinary) => { if (isBinary) return; let msg; try { msg = JSON.parse(raw.toString('utf8')); } catch (e) { return; } if (!msg || typeof msg !== 'object') return; if (!msgOk()) { if (msg.t !== 'ping') send(ws, { t: 'error', message: 'slow down' }); return; } switch (msg.t) { case 'ping': return send(ws, { t: 'pong', at: msg.at, now: now() }); case 'hello': return void hello(msg); case 'route': if (user && hub && hub.host === user.id) onRoute(hub, msg); return; case 'play': if (user && hub && hub.host === user.id) onPlay(hub, msg); return; default: } }); ws.on('close', () => { clearTimeout(helloTimer); if (user && hub) leave(hub, user.id, ws); }); ws.on('error', () => {}); }); // drop long-empty hubs const sweep = setInterval(() => { for (const [id, hub] of hubs) if (!hub.members.size && now() - hub.emptySince > HUB_TTL_MS) hubs.delete(id); }, 60 * 1000); if (sweep.unref) sweep.unref(); server.on('close', () => { clearInterval(heartbeat); clearInterval(sweep); for (const ws of wss.clients) ws.terminate(); wss.close(); }); server.wss = wss; server.hubs = hubs; return server; } module.exports = { createServer };