app.js 16 KB

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