Activity replay, HUDFX in the overlay, chat filter, redeem art fix

- Dashboard Recent activity: readable details (reward name, cost, variation,
  rarity, TTS, viewer message; sub tier/months; bits; raids; polls), local
  times, and a Replay button. Each row now stores the overlay message that was
  shown (activity_log.replay_json); older redeem/raid rows are rebuilt from the
  raw Twitch event.
- Fix: redeem alerts lost polaroid/art/emote since 4fda606 (they had ended up
  inside a comment), so sticker art, Power-up emotes and sound-only were gone.
- HUDFX embedded in the overlay with ?ext=hudfx (opt-in per OBS source): its
  page is served from our domain with the camcorder CSS, its settings API is
  forwarded, its Web Worker is started from a same-origin stand-in (the alert
  box needs it; blob: workers break the site CSP), and the box sits in the
  alert corner. The HUDFX URL is a field on the Settings page.
- Blerp cassette CSS kept with it (src/ext/blerp.css, pasted into the Blerp
  OBS source; Blerp itself cannot be embedded: its realtime server only
  accepts its own site).
- On-screen chat: Settings -> Hidden chatters and Hide ! commands.
- Outgoing raids are logged with a line in the server log.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Bashy 2026-11-22 15:29:20 +02:00
parent 5f61b1ebe1
commit 19a0965eb2
16 changed files with 671 additions and 35 deletions

View file

@ -4,16 +4,33 @@ const db = require('../db');
const eventsub = require('../eventsub');
const alerts = require('../alerts');
const streamelements = require('../streamelements');
const activity = require('../activity');
const ws = require('../ws');
router.get('/', (req, res) => {
const logs = db.getActivityLog(50);
const settings = db.getSettings();
res.render('dashboard', { logs, settings, eventsubStatus: eventsub.getStatus(), seStatus: streamelements.getStatus(), testKeys: alerts.TEST_KEYS });
res.render('dashboard', { logs, activity, settings, eventsubStatus: eventsub.getStatus(), seStatus: streamelements.getStatus(), testKeys: alerts.TEST_KEYS });
});
// Activity table only (dashboard Reload button / auto-refresh)
router.get('/activity', (req, res) => {
res.render('_activity', { layout: false, logs: db.getActivityLog(50) });
res.render('_activity', { layout: false, logs: db.getActivityLog(50), activity });
});
// Replay: play a logged event on the overlay again (queued like a real alert; not logged again, no actions fired)
router.post('/activity/:id/replay', async (req, res) => {
const log = db.getActivity(parseInt(req.params.id, 10));
if (!log) return res.status(404).json({ ok: false, error: 'not found' });
try {
const msg = await activity.replayMessage(log);
if (!msg) return res.json({ ok: false, error: 'nothing to replay for this event' });
ws.broadcast(msg);
res.json({ ok: true });
} catch (e) {
console.error('[activity] replay:', e.message);
res.status(500).json({ ok: false, error: e.message });
}
});
module.exports = router;

146
src/routers/ext.js Normal file
View file

@ -0,0 +1,146 @@
// HUDFX and Blerp inside our overlay (one OBS source, one audio fader, our CSS).
//
// Their overlay pages are fetched here and served from our domain with a few things injected:
// <base> their own files and APIs still load from their sites
// page address their apps read the overlay id from location.pathname, so it is set back to theirs
// API redirect HUDFX's settings API refuses other sites (CORS), so those calls go through /hudfx-api here
// volume every <audio>/<video> and Howler (Blerp) plays at ?vol= (0..1)
// CSS src/ext/<name>.css (paper/cassette/camcorder look)
// Blerp's main script refuses to load from other sites (module scripts need CORS), so /blerp-assets serves it.
//
// Config: Settings page → HUDFX overlay URL. Blerp is not embedded: its realtime server only accepts its own site.
// Routes live under the overlay id, like the overlay itself: /ext/<overlay id>/hudfx, /ext/<overlay id>/blerp
const express = require('express');
const fs = require('fs');
const path = require('path');
const db = require('../db');
const router = express.Router();
const EXT = {
hudfx: { css: 'hudfx.css', api: { from: 'https://api.hudfx.io/', to: 'hudfx-api/' } },
// Blerp picks its servers from the hostname (anything else = its developers' localhost); ?env=prod forces the real ones
blerp: { css: 'blerp.css', assets: true, query: { env: 'prod' } },
};
// HUDFX: Settings page (settings.hudfx_overlay_url). Blerp: not embeddable (see above), no setting.
function target(name) {
const raw = name === 'hudfx' ? db.getSettings().hudfx_overlay_url : null;
if (!raw) return null;
try { const u = new URL(raw); return u.protocol === 'https:' ? u : null; } catch { return null; }
}
function configured() { return Object.keys(EXT).filter(target); }
// only for our overlay id
router.use('/:uuid', (req, res, next) => {
if (req.params.uuid !== db.getOverlaySettings().overlay_id) return res.status(404).send('Not found');
next();
});
const esc = s => JSON.stringify(s).replace(/</g, '\\u003c');
router.get('/:uuid/:name(hudfx|blerp)', async (req, res) => {
const name = req.params.name, ext = EXT[name], u = target(name);
if (!u) return res.status(404).send(`${name}: not configured (Settings)`);
try {
const r = await fetch(u, { headers: { 'User-Agent': req.get('User-Agent') || 'Mozilla/5.0', 'Accept': 'text/html' } });
if (!r.ok) return res.status(502).send(`${name}: ${r.status}`);
let html = await r.text();
const ours = `${req.protocol}://${req.get('host')}/ext/${req.params.uuid}/`;
const vol = Math.min(1, Math.max(0, parseFloat(req.query.vol)));
const volume = isFinite(vol) ? vol : 1;
html = html.replace(/<script>\s*\(function\(\)\{function c\(\)[\s\S]*?<\/script>/, ''); // Cloudflare beacon (Blerp)
if (ext.assets) html = html.replace(/(src|href)="\/assets\//g, `$1="${ours}${name}-assets/`);
const addr = new URL(u);
for (const [k, v] of Object.entries(ext.query || {})) addr.searchParams.set(k, v);
const head = `<base href="${u.origin}/">
<script>
(() => {
// their router reads the overlay id from the address: put their path back (same origin, so allowed)
history.replaceState(null, '', location.origin + ${esc(addr.pathname + addr.search)});
${ext.api ? `
const FROM = ${esc(ext.api.from)}, TO = ${esc(ours + ext.api.to)};
const fix = x => (typeof x === 'string' && x.startsWith(FROM)) ? TO + x.slice(FROM.length) : x;
const xo = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function (m, url, ...rest) { return xo.call(this, m, fix(String(url)), ...rest); };
const fo = window.fetch;
window.fetch = (i, o) => fo((typeof i === 'string' || i instanceof URL) ? fix(String(i)) : i, o);` : ''}
// Workers must come from the page's own origin; theirs live on their site (HUDFX's alert box uses a
// chromakey worker, and without it the box never renders). Start them from our /worker.js, which imports
// their script (their files allow cross-site loading; a blob: worker would break our Content-Security-Policy).
const NativeWorker = window.Worker;
window.Worker = function (url, opts) {
const u = new URL(String(url), document.baseURI);
if (u.origin !== location.origin) {
url = ${esc(ours + 'worker.js')} + '?type=' + (opts && opts.type === 'module' ? 'module' : 'classic') + '&src=' + encodeURIComponent(u.href);
}
return new NativeWorker(url, opts);
};
window.Worker.prototype = NativeWorker.prototype;
// one volume for everything this page plays
const VOL = ${volume};
const play = HTMLMediaElement.prototype.play;
HTMLMediaElement.prototype.play = function () { this.volume = VOL; return play.apply(this, arguments); };
addEventListener('load', () => { if (window.Howler) window.Howler.volume(VOL); });
})();
</script>`;
const css = fs.readFileSync(path.join(__dirname, '..', 'ext', ext.css), 'utf8');
html = html.replace(/<head([^>]*)>/i, `<head$1>${head}`).replace(/<\/head>/i, `<style id="heystreamer-css">${css}</style></head>`);
res.set('Cache-Control', 'no-store').type('html').send(html);
} catch (e) {
console.error(`[ext] ${name}:`, e.message);
res.status(502).send(`${name}: ${e.message}`);
}
});
// HUDFX settings API (GET/POST), forwarded as is
router.all('/:uuid/hudfx-api/*', express.raw({ type: '*/*', limit: '1mb' }), async (req, res) => {
if (!['GET', 'POST', 'OPTIONS'].includes(req.method)) return res.sendStatus(405);
if (req.method === 'OPTIONS') return res.sendStatus(204); // same origin: only sent if something adds custom headers
try {
const up = new URL(req.params[0] + (req.url.includes('?') ? req.url.slice(req.url.indexOf('?')) : ''), EXT.hudfx.api.from);
if (up.origin !== new URL(EXT.hudfx.api.from).origin) return res.sendStatus(400);
const headers = {};
for (const h of ['content-type', 'authorization', 'accept']) if (req.get(h)) headers[h] = req.get(h);
const r = await fetch(up, { method: req.method, headers, body: req.method === 'POST' && req.body?.length ? req.body : undefined });
res.status(r.status);
if (r.headers.get('content-type')) res.type(r.headers.get('content-type'));
res.send(Buffer.from(await r.arrayBuffer()));
} catch (e) {
console.error('[ext] hudfx-api:', e.message);
res.sendStatus(502);
}
});
// Same-origin stand-in for their Web Workers (see the Worker patch above): imports their worker script.
// Only scripts from the embedded sites' own origins.
router.get('/:uuid/worker.js', (req, res) => {
let src;
try { src = new URL(String(req.query.src || '')); } catch { return res.sendStatus(400); }
const allowed = Object.keys(EXT).map(target).filter(Boolean).map(u => u.origin);
if (src.protocol !== 'https:' || !allowed.includes(src.origin)) return res.sendStatus(400);
const code = req.query.type === 'module' ? `import ${JSON.stringify(src.href)};` : `importScripts(${JSON.stringify(src.href)});`;
res.set('Cache-Control', 'no-store').type('text/javascript').send(code);
});
// Blerp's /assets/* (main module + its chunks, CSS)
router.get('/:uuid/blerp-assets/*', async (req, res) => {
const u = target('blerp');
if (!u) return res.sendStatus(404);
try {
const up = new URL('/assets/' + req.params[0], u.origin);
if (up.origin !== u.origin || !up.pathname.startsWith('/assets/')) return res.sendStatus(400);
const r = await fetch(up);
if (!r.ok) return res.sendStatus(r.status);
res.set('Cache-Control', 'public, max-age=3600');
if (r.headers.get('content-type')) res.type(r.headers.get('content-type'));
res.send(Buffer.from(await r.arrayBuffer()));
} catch (e) {
console.error('[ext] blerp-assets:', e.message);
res.sendStatus(502);
}
});
module.exports = { router, configured };

View file

@ -2,11 +2,14 @@ const express = require('express');
const router = express.Router();
const db = require('../db');
const ws = require('../ws');
const ext = require('./ext');
// Parts of the overlay. One OBS browser source can show all of them, or the overlay can be split into
// several sources with ?parts=, e.g. chat in its own source (audio "Monitor Only" in OBS, so chat
// sounds never reach the stream) and everything else in another.
const PARTS = ['chat', 'alerts', 'poll', 'hypebar', 'raid']; // 'nowplaying' is off for now (see overlay.ejs)
// ?ext=hudfx also embed HUDFX's own overlay page (src/routers/ext.js; needs HUDFX_OVERLAY_URL in .env).
// Opt-in, so an OBS that still has its own HUDFX source does not play effects twice.
// ?parts=chat,raid only those parts
// ?parts=nochat everything except chat (no<part>, several allowed: nochat,noraid)
// no ?parts / nothing valid: everything
@ -19,6 +22,15 @@ function partsFrom(q) {
return asked.length ? asked : PARTS;
}
// ?hudfxvol=0..1 / ?blerpvol=0..1 volume of everything that page plays (default 1)
// ?blerp=cx,cy,scale where Blerp's card goes: its centre in px of the 1920x1080 page + size
const vol = v => { const n = parseFloat(v); return isFinite(n) ? Math.min(1, Math.max(0, n)) : 1; };
function blerpPlace(q) {
const n = String(q || '').split(',').map(Number);
if (n.length === 3 && n.every(isFinite) && n[2] > 0.1 && n[2] <= 2) return { cx: n[0], cy: n[1], s: n[2] };
return { cx: 1725, cy: 365, s: 0.5 }; // under the HUDFX box, above the camera (Game scene)
}
// ?chat=left,top,width,height chat box in px of the 1920x1080 page (e.g. Intermission panel: 130,640,700,360)
// ?chatflow=up|down up = newest at the bottom (normal chat); down (default) = newest on top, under the camera
function chatBoxFrom(q) {
@ -33,7 +45,8 @@ router.get('/:uuid', (req, res) => {
const settings = db.getOverlaySettings();
if (req.params.uuid !== settings.overlay_id) return res.status(404).send('Overlay not found');
res.render('overlay', { layout: false, settings, parts: partsFrom(req.query.parts),
chatBox: chatBoxFrom(req.query.chat), chatFlow: req.query.chatflow === 'up' ? 'up' : 'down', boot: ws.BOOT_ID });
chatBox: chatBoxFrom(req.query.chat), chatFlow: req.query.chatflow === 'up' ? 'up' : 'down', boot: ws.BOOT_ID,
ext: { on: ext.configured().filter(n => String(req.query.ext || '').split(',').includes(n)), hudfxVol: vol(req.query.hudfxvol), blerpVol: vol(req.query.blerpvol), blerp: blerpPlace(req.query.blerp) } });
});
module.exports = router;

View file

@ -13,6 +13,14 @@ router.get('/', (req, res) => {
res.render('settings', { settings, baseUrl });
});
// only a real HUDFX overlay link (https://overlays.hudfx.io/overlay/<id>), anything else clears it
function hudfxUrl(v) {
try {
const u = new URL(String(v || '').trim());
return u.protocol === 'https:' && u.hostname === 'overlays.hudfx.io' && /^\/overlay\/[\w-]+$/.test(u.pathname) ? u.origin + u.pathname : '';
} catch { return ''; }
}
router.post('/', (req, res) => {
const b = req.body;
db.updateSettings({
@ -28,6 +36,9 @@ router.post('/', (req, res) => {
tts_max_chars: Math.max(20, Math.min(500, int(b.tts_max_chars, 200))),
tts_say_name: b.tts_say_name === 'on' ? 1 : 0,
tts_blocklist: String(b.tts_blocklist || '').slice(0, 20000),
hudfx_overlay_url: hudfxUrl(b.hudfx_overlay_url),
chat_hidden_users: String(b.chat_hidden_users || '').split(/[\s,]+/).map(s => s.replace(/^@/, '').toLowerCase()).filter(Boolean).join(', ').slice(0, 2000),
chat_hide_commands: b.chat_hide_commands === 'on' ? 1 : 0,
custom_css: b.custom_css || '',
custom_js: b.custom_js || '',
});