app.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  1. import { createServer } from 'node:http';
  2. import { EventEmitter } from 'node:events';
  3. import path from 'node:path';
  4. import { fileURLToPath } from 'node:url';
  5. import express from 'express';
  6. import { Server } from 'socket.io';
  7. import validator from 'validator';
  8. const __dirname = path.dirname(fileURLToPath(import.meta.url));
  9. // ***************************************************************************
  10. // Config
  11. // ***************************************************************************
  12. // Everything comes from the environment. Use `.env` locally (see .env.example);
  13. // `npm run dev` loads it. In production pass real env vars via the service
  14. // manager. This replaces the old config.js / config-dev.js pair, which was
  15. // gitignored and therefore never actually present.
  16. const config = {
  17. port: Number(process.env.PORT ?? 3000),
  18. // '' when served at the domain root, '/radio' when mounted at a subpath.
  19. basePath: normalizeBasePath(process.env.BASE_PATH ?? ''),
  20. mainRoom: process.env.MAIN_ROOM ?? 'Lobby',
  21. // Unset => single process, no Redis. Set => Redis adapter, multi-process safe.
  22. redisUrl: process.env.REDIS_URL ?? '',
  23. // Number of reverse proxies in front of us, or a preset like 'loopback'.
  24. trustProxy: process.env.TRUST_PROXY ?? '',
  25. debug: process.env.DEBUG === 'true',
  26. // NOT authentication. See the /other route below.
  27. roomPassword: process.env.ROOM_PASSWORD ?? 'stillgame',
  28. // Icecast's own JSON status. The old code polled a hand-customized
  29. // status2.xsl over JSONP; Icecast upgrades overwrite those XSL files (it
  30. // 404s today, and has since 2021 per the README), so use the stock endpoint
  31. // and proxy it from here instead.
  32. streamStatusUrl:
  33. process.env.STREAM_STATUS_URL ?? 'https://stream.davidawindham.com/status-json.xsl',
  34. streamMount: process.env.STREAM_MOUNT ?? '/stream',
  35. // Proxied via /api/lastfm so the key stops shipping in the client bundle.
  36. // Unset => the sidebar lists just stay empty.
  37. lastfmKey: process.env.LASTFM_API_KEY ?? '',
  38. lastfmUser: process.env.LASTFM_USER ?? 'windhamdavid',
  39. // Local dev only. See the /embed proxy below.
  40. dawOrigin: process.env.DAW_ORIGIN ?? '',
  41. };
  42. function normalizeBasePath(value) {
  43. const trimmed = value.trim().replace(/\/+$/, '');
  44. if (!trimmed) return '';
  45. return trimmed.startsWith('/') ? trimmed : `/${trimmed}`;
  46. }
  47. const MAX_MESSAGE_LENGTH = 500;
  48. const MAX_ROOM_LENGTH = 25;
  49. const MAX_ROOMS_PER_REQUEST = 10;
  50. const logger = new EventEmitter();
  51. logger.on('newEvent', (event, data) => {
  52. console.log('%s: %s', event, JSON.stringify(data));
  53. });
  54. // ***************************************************************************
  55. // App
  56. // ***************************************************************************
  57. const app = express();
  58. const server = createServer(app);
  59. if (config.trustProxy) {
  60. // Needed for correct client IPs / protocol when nginx fronts us at /radio.
  61. const asNumber = Number(config.trustProxy);
  62. app.set('trust proxy', Number.isNaN(asNumber) ? config.trustProxy : asNumber);
  63. }
  64. app.use(express.json());
  65. app.use(express.urlencoded({ extended: false }));
  66. const router = express.Router();
  67. // Built assets. `npm run build` produces app/ from src/.
  68. router.use(express.static(path.join(__dirname, 'app')));
  69. router.get('/health', (req, res) => {
  70. res.json({ ok: true, rooms: publicRooms().length, sockets: io.engine.clientsCount });
  71. });
  72. // Now-playing / listener counts, proxied from Icecast.
  73. //
  74. // Proxying rather than calling Icecast from the browser buys three things: the
  75. // page can be served over TLS without mixed-content breakage, JSONP goes away,
  76. // and the stream host stops being baked into client JS. Every client polls this
  77. // on a timer, so a short cache keeps one Icecast hit per interval regardless of
  78. // how many listeners are connected.
  79. router.get('/api/status', async (req, res) => {
  80. try {
  81. res.json(await getStreamStatus());
  82. } catch {
  83. res.status(502).json({ online: false, error: 'stream status unavailable' });
  84. }
  85. });
  86. // Last.fm sidebar data, proxied so the API key stays on the server.
  87. //
  88. // The key used to be hardcoded in src/js/radio.js (4x) and shipped in the
  89. // bundle. It's read-only public data, so the exposure was mild, but a
  90. // credential in client JS is a credential you can't rotate quietly.
  91. //
  92. // Strictly allowlisted -- method, period and limit are all constrained, so
  93. // this can't be turned into an open relay for arbitrary Last.fm calls.
  94. const LASTFM_METHODS = new Set([
  95. 'user.gettopartists',
  96. 'user.gettoptracks',
  97. 'user.gettopalbums',
  98. 'user.getrecenttracks',
  99. ]);
  100. const LASTFM_PERIODS = new Set(['overall', '7day', '1month', '3month', '6month', '12month']);
  101. const LASTFM_CACHE_MS = 60000;
  102. const lastfmCache = new Map();
  103. router.get('/api/lastfm', async (req, res) => {
  104. const method = String(req.query.method ?? '');
  105. if (!LASTFM_METHODS.has(method)) {
  106. res.status(400).json({ error: 'unsupported method' });
  107. return;
  108. }
  109. if (!config.lastfmKey) {
  110. res.status(503).json({ error: 'lastfm not configured' });
  111. return;
  112. }
  113. const period = LASTFM_PERIODS.has(String(req.query.period)) ? String(req.query.period) : '12month';
  114. const limit = Math.min(Math.max(Number(req.query.limit) || 50, 1), 200);
  115. const cacheKey = `${method}:${period}:${limit}`;
  116. const hit = lastfmCache.get(cacheKey);
  117. if (hit && Date.now() - hit.at < LASTFM_CACHE_MS) {
  118. res.json(hit.value);
  119. return;
  120. }
  121. const url = new URL('https://ws.audioscrobbler.com/2.0/');
  122. url.searchParams.set('method', method);
  123. url.searchParams.set('user', config.lastfmUser);
  124. url.searchParams.set('api_key', config.lastfmKey);
  125. url.searchParams.set('format', 'json');
  126. url.searchParams.set('limit', String(limit));
  127. // getrecenttracks has no notion of a period.
  128. if (method !== 'user.getrecenttracks') url.searchParams.set('period', period);
  129. try {
  130. const upstream = await fetch(url, { signal: AbortSignal.timeout(8000) });
  131. if (!upstream.ok) throw new Error(`lastfm responded ${upstream.status}`);
  132. const value = await upstream.json();
  133. lastfmCache.set(cacheKey, { at: Date.now(), value });
  134. res.json(value);
  135. } catch {
  136. res.status(502).json({ error: 'lastfm unavailable' });
  137. }
  138. });
  139. // Broadcast a message to every active room.
  140. router.post('/api/broadcast', requireAuthentication, (req, res) => {
  141. const text = typeof req.body?.msg === 'string' ? req.body.msg.trim() : '';
  142. if (!text) {
  143. res.status(400).send('No message provided');
  144. return;
  145. }
  146. sendBroadcast(validator.escape(text.slice(0, MAX_MESSAGE_LENGTH)));
  147. res.status(201).send('Message sent to all rooms');
  148. });
  149. // The front-end's "password" field posts here via bootstrap-validator's
  150. // data-remote. This is a speed bump, not a lock: it gates a modal and nothing
  151. // else. The socket handshake and the Icecast stream remain wide open, so this
  152. // must not be treated as protection. Real auth is a separate piece of work --
  153. // it needs to cover the handshake and the stream too, not just this route.
  154. router.get('/other', (req, res) => {
  155. if (req.query.other === config.roomPassword) res.sendStatus(200);
  156. else res.status(400).send('WRONG!');
  157. });
  158. // Local dev only: serve the shared site chrome (/embed/chrome.js + its fonts)
  159. // by proxying to the main site.
  160. //
  161. // index.html loads /embed/chrome.js root-relative. In production that path is
  162. // served by Apache from the WordPress docroot, alongside /radio -- nginx only
  163. // routes /radio/ here, so this never runs there. Locally there's no Apache in
  164. // front, so without this the chrome would 404 and the page would render bare.
  165. // Unset DAW_ORIGIN => not mounted at all.
  166. if (config.dawOrigin) {
  167. app.use('/embed', async (req, res) => {
  168. try {
  169. const upstream = await fetch(new URL(`/embed${req.url}`, config.dawOrigin), {
  170. signal: AbortSignal.timeout(5000),
  171. });
  172. if (!upstream.ok) {
  173. res.sendStatus(upstream.status);
  174. return;
  175. }
  176. const type = upstream.headers.get('content-type');
  177. if (type) res.type(type);
  178. res.send(Buffer.from(await upstream.arrayBuffer()));
  179. } catch {
  180. res.sendStatus(502);
  181. }
  182. });
  183. logger.emit('newEvent', 'embedProxyEnabled', { origin: config.dawOrigin });
  184. }
  185. // Canonicalize /radio -> /radio/ before the router sees it. Without the
  186. // trailing slash the browser resolves the page's relative asset URLs against
  187. // the parent directory, so every script and stylesheet 404s.
  188. //
  189. // The exact `req.path ===` test matters: Express's default non-strict routing
  190. // treats '/radio' and '/radio/' as the same route, so a plain
  191. // app.get(basePath) would also match the slashed URL and redirect it to
  192. // itself, forever.
  193. if (config.basePath) {
  194. app.use((req, res, next) => {
  195. if (req.path === config.basePath) res.redirect(301, `${config.basePath}/`);
  196. else next();
  197. });
  198. }
  199. app.use(config.basePath || '/', router);
  200. // ***************************************************************************
  201. // Helpers
  202. // ***************************************************************************
  203. // Placeholder, as it has always been. Kept so the broadcast route has an
  204. // obvious place to grow one rather than pretending the gap isn't there.
  205. function requireAuthentication(req, res, next) {
  206. next();
  207. }
  208. // socket.io keeps a private room per socket, keyed by socket id. `sids` lets us
  209. // tell those apart from rooms people actually joined.
  210. function publicRooms() {
  211. const { rooms, sids } = io.of('/').adapter;
  212. const named = [];
  213. for (const key of rooms.keys()) {
  214. if (!sids.has(key)) named.push(key);
  215. }
  216. return named;
  217. }
  218. // Rooms this socket joined, minus its own private room.
  219. function joinedRooms(socket) {
  220. return [...socket.rooms].filter((room) => room !== socket.id);
  221. }
  222. // Room names become DOM ids and jQuery selectors on the client, so keep them to
  223. // a charset that can't break out of either.
  224. function cleanRoomName(value) {
  225. if (typeof value !== 'string') return null;
  226. const cleaned = value.replace(/[^A-Za-z0-9_-]/g, '').slice(0, MAX_ROOM_LENGTH);
  227. return cleaned || null;
  228. }
  229. function cleanNickname(value) {
  230. if (typeof value !== 'string') return null;
  231. const cleaned = value.replace(/[^A-Za-z0-9_-]/g, '').slice(0, 25);
  232. return cleaned.length >= 3 ? cleaned : null;
  233. }
  234. // Icecast reports `source` as an object for one mount, an array for several,
  235. // and omits it entirely when nothing is broadcasting -- which is the off-air
  236. // case the player draws.
  237. function normalizeIcecastStatus(payload, mount) {
  238. const stats = payload?.icestats ?? {};
  239. const sources = stats.source == null ? [] : [].concat(stats.source);
  240. const source =
  241. sources.find((s) => typeof s?.listenurl === 'string' && s.listenurl.endsWith(mount)) ??
  242. sources[0];
  243. if (!source) return { online: false };
  244. // `bitrate` is kbps; `audio_bitrate` is bps. Only one is usually present,
  245. // depending on how the source client connected.
  246. const bitrate =
  247. source.bitrate ?? (source.audio_bitrate ? Math.round(source.audio_bitrate / 1000) : null);
  248. return {
  249. online: true,
  250. title: source.title ?? source.yp_currently_playing ?? null,
  251. listeners: source.listeners ?? 0,
  252. peakListeners: source.listener_peak ?? 0,
  253. bitrate,
  254. };
  255. }
  256. const STATUS_CACHE_MS = 5000;
  257. let statusCache = { at: 0, value: null };
  258. async function getStreamStatus() {
  259. const now = Date.now();
  260. if (statusCache.value && now - statusCache.at < STATUS_CACHE_MS) return statusCache.value;
  261. const upstream = await fetch(config.streamStatusUrl, { signal: AbortSignal.timeout(5000) });
  262. if (!upstream.ok) throw new Error(`icecast responded ${upstream.status}`);
  263. const value = normalizeIcecastStatus(await upstream.json(), config.streamMount);
  264. statusCache = { at: now, value };
  265. return value;
  266. }
  267. function sendBroadcast(text) {
  268. for (const room of publicRooms()) {
  269. io.to(room).emit('newMessage', {
  270. room,
  271. username: 'Radio-Robbot',
  272. msg: text,
  273. date: new Date(),
  274. });
  275. }
  276. logger.emit('newEvent', 'newBroadcastMessage', { msg: text });
  277. }
  278. // ***************************************************************************
  279. // Socket.io
  280. // ***************************************************************************
  281. const io = new Server(server, {
  282. // Must line up with the client and with the proxy's websocket location.
  283. path: `${config.basePath}/socket.io`,
  284. });
  285. io.on('connection', (socket) => {
  286. // Per-socket state lives here instead of Redis. It survives exactly as long
  287. // as the connection does, which is all it ever needed to do, and it works
  288. // unchanged whether or not the Redis adapter is enabled.
  289. socket.data.username = 'anonymous';
  290. socket.data.connectedAt = new Date();
  291. socket.emit('connected', 'Welcome to the chat server');
  292. logger.emit('newEvent', 'userConnected', { socket: socket.id });
  293. socket.join(config.mainRoom);
  294. logger.emit('newEvent', 'userJoinsRoom', { socket: socket.id, room: config.mainRoom });
  295. socket.emit('subscriptionConfirmed', { room: config.mainRoom });
  296. io.to(config.mainRoom).emit('userJoinsRoom', {
  297. room: config.mainRoom,
  298. username: socket.data.username,
  299. msg: '----- Joined -----',
  300. id: socket.id,
  301. });
  302. socket.on('subscribe', (data) => {
  303. const rooms = Array.isArray(data?.rooms) ? data.rooms.slice(0, MAX_ROOMS_PER_REQUEST) : [];
  304. for (const raw of rooms) {
  305. const room = cleanRoomName(raw);
  306. if (!room) continue;
  307. socket.join(room);
  308. logger.emit('newEvent', 'userJoinsRoom', {
  309. socket: socket.id,
  310. username: socket.data.username,
  311. room,
  312. });
  313. socket.emit('subscriptionConfirmed', { room });
  314. io.to(room).emit('userJoinsRoom', {
  315. room,
  316. username: socket.data.username,
  317. msg: '----- Joined the room -----',
  318. id: socket.id,
  319. });
  320. }
  321. });
  322. socket.on('unsubscribe', (data) => {
  323. const rooms = Array.isArray(data?.rooms) ? data.rooms.slice(0, MAX_ROOMS_PER_REQUEST) : [];
  324. for (const raw of rooms) {
  325. const room = cleanRoomName(raw);
  326. if (!room || room === config.mainRoom) continue;
  327. socket.leave(room);
  328. logger.emit('newEvent', 'userLeavesRoom', {
  329. socket: socket.id,
  330. username: socket.data.username,
  331. room,
  332. });
  333. socket.emit('unsubscriptionConfirmed', { room });
  334. io.to(room).emit('userLeavesRoom', {
  335. room,
  336. username: socket.data.username,
  337. msg: '----- Left the room -----',
  338. id: socket.id,
  339. });
  340. }
  341. });
  342. socket.on('getRooms', () => {
  343. socket.emit('roomsReceived', joinedRooms(socket));
  344. logger.emit('newEvent', 'userGetsRooms', { socket: socket.id });
  345. });
  346. socket.on('getUsersInRoom', async (data) => {
  347. const room = cleanRoomName(data?.room);
  348. if (!room) return;
  349. // Works across processes when the Redis adapter is on.
  350. const sockets = await io.in(room).fetchSockets();
  351. socket.emit('usersInRoom', {
  352. users: sockets.map((member) => ({
  353. room,
  354. username: member.data.username,
  355. id: member.id,
  356. })),
  357. });
  358. });
  359. socket.on('setNickname', (data) => {
  360. const nickname = cleanNickname(data?.username);
  361. if (!nickname) return;
  362. const oldUsername = socket.data.username;
  363. socket.data.username = nickname;
  364. logger.emit('newEvent', 'userSetsNickname', {
  365. socket: socket.id,
  366. oldUsername,
  367. newUsername: nickname,
  368. });
  369. for (const room of joinedRooms(socket)) {
  370. io.to(room).emit('userNicknameUpdated', {
  371. room,
  372. oldUsername,
  373. newUsername: nickname,
  374. id: socket.id,
  375. });
  376. }
  377. });
  378. socket.on('newMessage', (data) => {
  379. const room = cleanRoomName(data?.room);
  380. const text = typeof data?.msg === 'string' ? data.msg.trim() : '';
  381. if (!room || !text) return;
  382. // Only relay to rooms this socket actually joined.
  383. if (!socket.rooms.has(room)) return;
  384. const message = {
  385. room,
  386. username: socket.data.username,
  387. msg: text.slice(0, MAX_MESSAGE_LENGTH),
  388. date: new Date(),
  389. };
  390. io.to(room).emit('newMessage', message);
  391. logger.emit('newEvent', 'newMessage', message);
  392. });
  393. // 'disconnecting' fires while socket.rooms is still populated; by the time
  394. // 'disconnect' runs it has been cleared, so departure notices must go out
  395. // from here.
  396. socket.on('disconnecting', () => {
  397. logger.emit('newEvent', 'userDisconnected', {
  398. socket: socket.id,
  399. username: socket.data.username,
  400. });
  401. for (const room of joinedRooms(socket)) {
  402. io.to(room).emit('userLeavesRoom', {
  403. room,
  404. username: socket.data.username,
  405. msg: '----- Left the room -----',
  406. id: socket.id,
  407. });
  408. }
  409. });
  410. });
  411. // ***************************************************************************
  412. // Startup
  413. // ***************************************************************************
  414. async function connectRedisAdapter(url) {
  415. const { createClient } = await import('redis');
  416. const { createAdapter } = await import('@socket.io/redis-adapter');
  417. const pubClient = createClient({ url });
  418. const subClient = pubClient.duplicate();
  419. pubClient.on('error', (err) => logger.emit('newEvent', 'redisError', { msg: err.message }));
  420. subClient.on('error', (err) => logger.emit('newEvent', 'redisError', { msg: err.message }));
  421. await Promise.all([pubClient.connect(), subClient.connect()]);
  422. io.adapter(createAdapter(pubClient, subClient));
  423. return [pubClient, subClient];
  424. }
  425. let redisClients = [];
  426. if (config.redisUrl) {
  427. redisClients = await connectRedisAdapter(config.redisUrl);
  428. logger.emit('newEvent', 'redisAdapterEnabled', {});
  429. } else {
  430. logger.emit('newEvent', 'redisAdapterDisabled', { reason: 'REDIS_URL not set; single process' });
  431. }
  432. if (config.debug) {
  433. setInterval(() => sendBroadcast('Testing rooms'), 60000);
  434. }
  435. server.listen(config.port, () => {
  436. logger.emit('newEvent', 'serverStarted', {
  437. port: config.port,
  438. basePath: config.basePath || '/',
  439. mainRoom: config.mainRoom,
  440. });
  441. });
  442. async function shutdown(signal) {
  443. logger.emit('newEvent', 'shuttingDown', { signal });
  444. await io.close();
  445. await Promise.all(redisClients.map((client) => client.quit().catch(() => {})));
  446. server.close(() => process.exit(0));
  447. }
  448. process.on('SIGTERM', () => shutdown('SIGTERM'));
  449. process.on('SIGINT', () => shutdown('SIGINT'));