Files
tv-discord/test/server.test.js
T
4DBug 7de90b5b7c v2: watch-party Activity
The Activity is now the full bug.tv site plus a small Discord overlay. Whoever
starts the instance hosts and controls everything; everyone else mirrors the
host's page and playback. The server is a relay keyed by activity instance and
checks membership through Discord's activity-instances API, so it works in DM
and group calls. The bot gateway, slash commands and control message are gone.
2026-10-27 10:00:34 -05:00

516 lines
19 KiB
JavaScript

const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('fs');
const os = require('os');
const path = require('path');
const WebSocket = require('ws');
const { createServer } = require('../src/server');
/* ---- fakes ----------------------------------------------------------------- */
const USERS = {
alice: { id: '111', username: 'alice', global_name: 'Alice', avatar: 'abc123' },
bob: { id: '222', username: 'bob', avatar: null },
carol: { id: '333', username: 'carol', avatar: 'c0ffee' },
mallory: { id: '999', username: 'mallory', avatar: null },
};
const PNG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 1, 2, 3]);
function fakeDiscord(instances) {
const calls = [];
const fn = async (url, init = {}) => {
calls.push([url, init]);
const res = (status, body, type = 'application/json') => ({
ok: status < 300,
status,
headers: new Headers({ 'content-type': type }),
json: async () => body,
arrayBuffer: async () => (Buffer.isBuffer(body) ? body : Buffer.from(JSON.stringify(body))),
});
if (url.endsWith('/oauth2/token')) {
const p = new URLSearchParams(init.body);
if (p.get('code') === 'goodcode' && p.get('client_secret') === 'sekrit' && p.get('grant_type') === 'authorization_code') {
return res(200, { access_token: 'alice', token_type: 'Bearer' });
}
return res(400, { error: 'invalid_grant' });
}
if (url.endsWith('/users/@me')) {
const tok = (init.headers.Authorization || '').replace('Bearer ', '');
return USERS[tok] ? res(200, USERS[tok]) : res(401, { message: '401: Unauthorized' });
}
const m = /\/applications\/(\w+)\/activity-instances\/([^/?]+)$/.exec(url);
if (m) {
assert.equal(init.headers.Authorization, 'Bot bot-token');
const users = instances[decodeURIComponent(m[2])];
if (!users) return res(404, { message: 'Unknown' });
if (users === 'boom') return res(500, {});
return res(200, {
application_id: m[1],
instance_id: m[2],
launch_id: '1',
location: { id: 'gc-1', kind: 'gc', channel_id: '42', guild_id: '7' },
users: [...users],
});
}
if (url.startsWith('https://cdn.discordapp.com/')) return res(200, PNG, 'image/png');
return res(404, {});
};
fn.calls = calls;
fn.count = (re) => calls.filter(([u]) => re.test(u)).length;
return fn;
}
/* ---- harness --------------------------------------------------------------- */
const activityDir = fs.mkdtempSync(path.join(os.tmpdir(), 'tvd-act-'));
fs.writeFileSync(path.join(activityDir, 'index.html'), '<!doctype html><title>x</title>');
fs.writeFileSync(path.join(activityDir, 'discord.js'), 'console.log(1)');
async function start(opts = {}) {
const instances = opts.instances || { 'i-1': new Set(['111', '222', '333']) };
const discordFetch = fakeDiscord(instances);
const clock = { t: 1_000_000 };
const cfg = { applicationId: 'app1', clientSecret: 'sekrit', token: 'bot-token', activityDir, dev: !!opts.dev, devApiUrl: opts.devApiUrl };
const server = createServer(cfg, { discordFetch, now: () => clock.t, log: () => {} });
await new Promise((r) => server.listen(0, '127.0.0.1', r));
const base = `http://127.0.0.1:${server.address().port}`;
const sockets = [];
const open = (p = '/ws') => {
const ws = new WebSocket(base.replace('http', 'ws') + p);
sockets.push(ws);
const queue = [];
const waiters = [];
ws.on('message', (d) => {
const m = JSON.parse(d);
const i = waiters.findIndex((w) => w.pred(m));
if (i >= 0) waiters.splice(i, 1)[0].resolve(m);
else queue.push(m);
});
ws.next = (pred = () => true, ms = 2000) => {
if (typeof pred === 'string') {
const t = pred;
pred = (m) => m.t === t;
}
const i = queue.findIndex(pred);
if (i >= 0) return Promise.resolve(queue.splice(i, 1)[0]);
return new Promise((resolve, reject) => {
const w = { pred, resolve };
waiters.push(w);
setTimeout(() => {
const j = waiters.indexOf(w);
if (j < 0) return;
waiters.splice(j, 1);
reject(new Error('timeout waiting for message'));
}, ms).unref();
});
};
ws.none = async (t, ms = 150) => {
await assert.rejects(ws.next(t, ms), /timeout/, `unexpected ${t}`);
};
ws.drain = () => queue.splice(0);
ws.closed = new Promise((r) => ws.on('close', (code) => r(code)));
ws.opened = new Promise((r, j) => {
ws.on('open', r);
ws.on('error', j);
});
ws.json = (m) => ws.send(JSON.stringify(m));
return ws;
};
/** open + hello + welcome */
const joinAs = async (token, instanceId = 'i-1') => {
const ws = open();
await ws.opened;
ws.json({ t: 'hello', token, instanceId, channelId: '42' });
ws.welcome = await ws.next('welcome');
return ws;
};
const devJoin = async (userId, instanceId = 'x') => {
const ws = open();
await ws.opened;
ws.json({ t: 'hello', dev: true, userId, username: `u${userId}`, instanceId });
ws.welcome = await ws.next('welcome');
return ws;
};
const stop = async () => {
for (const ws of sockets) ws.terminate();
const closed = new Promise((r) => server.close(r));
server.closeAllConnections();
await closed;
};
return { server, discordFetch, clock, base, open, joinAs, devJoin, stop };
}
const tick = (ms) => new Promise((r) => setTimeout(r, ms));
const closeAndWait = async (ws) => {
ws.close();
await ws.closed;
await tick(50);
};
/* ---- http ------------------------------------------------------------------ */
test('static files, SPA fallback, config, healthz', async () => {
const h = await start();
try {
let r = await fetch(`${h.base}/`);
assert.equal(r.status, 200);
assert.match(r.headers.get('content-type'), /text\/html/);
assert.equal(r.headers.get('cache-control'), 'no-cache');
r = await fetch(`${h.base}/discord.js`);
assert.match(r.headers.get('content-type'), /javascript/);
assert.match(r.headers.get('cache-control'), /max-age/);
r = await fetch(`${h.base}/.proxy/discord.js`);
assert.equal(r.status, 200);
r = await fetch(`${h.base}/title/tv/1399`);
assert.equal(r.status, 200);
assert.match(await r.text(), /<title>x/);
r = await fetch(`${h.base}/missing.js`);
assert.equal(r.status, 404);
r = await fetch(`${h.base}/..%2f..%2fetc%2fpasswd`);
assert.notEqual(await r.text(), fs.readFileSync('/etc/passwd', 'utf8'));
r = await fetch(`${h.base}/api/config`);
assert.deepEqual(await r.json(), { applicationId: 'app1', dev: false });
r = await fetch(`${h.base}/api/nope`);
assert.equal(r.status, 404);
r = await fetch(`${h.base}/healthz`);
assert.deepEqual(await r.json(), { ok: true });
// no dev proxy unless cfg.dev: /tv/v1 is just an SPA route
r = await fetch(`${h.base}/tv/v1/streams`);
assert.match(await r.text(), /<title>x/);
} finally {
await h.stop();
}
});
test('POST /api/token exchanges the code with Discord', async () => {
const h = await start();
try {
let r = await fetch(`${h.base}/api/token`, { method: 'POST', body: JSON.stringify({ code: 'goodcode' }) });
assert.equal(r.status, 200);
assert.deepEqual(await r.json(), { access_token: 'alice' });
const [url, init] = h.discordFetch.calls[0];
assert.equal(url, 'https://discord.com/api/oauth2/token');
assert.equal(new URLSearchParams(init.body).get('client_id'), 'app1');
r = await fetch(`${h.base}/api/token`, { method: 'POST', body: JSON.stringify({ code: 'bad' }) });
assert.equal(r.status, 502);
r = await fetch(`${h.base}/api/token`, { method: 'POST', body: '{}' });
assert.equal(r.status, 400);
r = await fetch(`${h.base}/api/token`, { method: 'POST', body: 'nope' });
assert.equal(r.status, 400);
r = await fetch(`${h.base}/api/token`);
assert.equal(r.status, 405);
} finally {
await h.stop();
}
});
test('avatar endpoint proxies known users from the CDN and caches', async () => {
const h = await start();
try {
let r = await fetch(`${h.base}/api/avatar/111`);
assert.equal(r.status, 404, 'unknown until the user said hello');
const a = await h.joinAs('alice');
const b = await h.joinAs('bob');
assert.equal(a.welcome.you.avatar, '/api/avatar/111');
r = await fetch(`${h.base}/api/avatar/111`);
assert.equal(r.status, 200);
assert.equal(r.headers.get('content-type'), 'image/png');
assert.deepEqual(Buffer.from(await r.arrayBuffer()), PNG);
await fetch(`${h.base}/api/avatar/111`);
const cdn = h.discordFetch.calls.filter(([u]) => u.startsWith('https://cdn.discordapp.com/')).map(([u]) => u);
assert.deepEqual(cdn, ['https://cdn.discordapp.com/avatars/111/abc123.png?size=64'], 'second request served from cache');
// no avatar hash → default embed avatar
r = await fetch(`${h.base}/api/avatar/222`);
assert.equal(r.status, 200);
assert.match(h.discordFetch.calls.at(-1)[0], /^https:\/\/cdn\.discordapp\.com\/embed\/avatars\/\d\.png$/);
r = await fetch(`${h.base}/api/avatar/abc`);
assert.equal(r.status, 404);
a.close();
b.close();
} finally {
await h.stop();
}
});
/* ---- hello / membership ---------------------------------------------------- */
test('hello: bad token, missing instance, not a member, dev refused → error + 4001', async () => {
const h = await start();
try {
const cases = [
[{ t: 'hello', token: 'nope', instanceId: 'i-1' }, /authentication failed/],
[{ t: 'hello', token: 'alice' }, /instanceId/],
[{ t: 'hello', token: 'mallory', instanceId: 'i-1' }, /not in this activity/],
[{ t: 'hello', token: 'alice', instanceId: 'i-unknown' }, /not in this activity/],
[{ t: 'hello', dev: true, userId: '111', instanceId: 'i-1' }, /dev mode is off/],
];
for (const [hello, re] of cases) {
const ws = h.open();
await ws.opened;
ws.json(hello);
assert.match((await ws.next('error')).message, re);
assert.equal(await ws.closed, 4001);
}
} finally {
await h.stop();
}
});
test('membership: checked with the bot token, cached 10s, one refetch on a miss', async () => {
const instances = { 'i-1': new Set(['111']) };
const h = await start({ instances });
const inst = /activity-instances/;
try {
const a = await h.joinAs('alice');
assert.equal(h.discordFetch.count(inst), 1);
const a2 = await h.joinAs('alice');
assert.equal(h.discordFetch.count(inst), 1, 'cached');
assert.equal(h.discordFetch.count(/users\/@me/), 1, 'users/@me cached');
// bob joined the instance after the cache was filled → miss → one refetch → ok
instances['i-1'].add('222');
const b = await h.joinAs('bob');
assert.equal(h.discordFetch.count(inst), 2);
assert.equal(b.welcome.you.id, '222');
// mallory: cached miss → refetch → still missing → rejected (exactly one refetch)
const m = h.open();
await m.opened;
m.json({ t: 'hello', token: 'mallory', instanceId: 'i-1' });
await m.next('error');
assert.equal(h.discordFetch.count(inst), 3);
// cache expires after 10s
h.clock.t += 10_001;
instances['i-1'].delete('111');
const a3 = h.open();
await a3.opened;
a3.json({ t: 'hello', token: 'alice', instanceId: 'i-1' });
assert.match((await a3.next('error')).message, /not in this activity/);
assert.equal(h.discordFetch.count(inst), 4, 'fresh fetch that misses is not refetched');
// Discord failure → error, not a crash
instances['i-2'] = 'boom';
const e = h.open();
await e.opened;
e.json({ t: 'hello', token: 'alice', instanceId: 'i-2' });
assert.match((await e.next('error')).message, /membership check failed/);
for (const ws of [a, a2, b]) ws.close();
} finally {
await h.stop();
}
});
/* ---- hubs ------------------------------------------------------------------ */
test('first member is host; welcome lists members; joins and leaves broadcast members', async () => {
const h = await start();
try {
const a = await h.joinAs('alice');
assert.equal(a.welcome.host, '111');
assert.deepEqual(a.welcome.you, { id: '111', username: 'Alice', avatar: '/api/avatar/111' });
assert.equal(a.welcome.route, null);
assert.equal(a.welcome.play, null);
assert.equal(typeof a.welcome.now, 'number');
const b = await h.joinAs('bob');
assert.equal(b.welcome.host, '111');
assert.deepEqual(b.welcome.members.map((m) => m.id), ['111', '222']);
assert.deepEqual((await a.next('members')).members.map((m) => m.id), ['111', '222']);
// a second socket for bob counts once
const b2 = await h.joinAs('bob');
assert.equal(b2.welcome.members.length, 2);
await a.none('members');
await closeAndWait(b2);
await a.none('members');
await closeAndWait(b);
assert.deepEqual((await a.next('members')).members.map((m) => m.id), ['111']);
await a.none('host');
} finally {
await h.stop();
}
});
test('host handover to the earliest remaining member, and reclaim within 10 min', async () => {
const h = await start();
try {
const a = await h.joinAs('alice');
const b = await h.joinAs('bob');
const c = await h.joinAs('carol');
await closeAndWait(a);
assert.equal((await b.next('host')).host, '222');
assert.equal((await c.next('host')).host, '222');
assert.deepEqual((await c.next((m) => m.t === 'members' && m.members.length === 2)).members.map((m) => m.id), ['222', '333']);
// alice is back within 10 min → host again
h.clock.t += 5 * 60 * 1000;
const a2 = await h.joinAs('alice');
assert.equal(a2.welcome.host, '111');
assert.equal((await b.next('host')).host, '111');
assert.equal((await c.next('host')).host, '111');
// gone longer than 10 min → no reclaim
await closeAndWait(a2);
assert.equal((await b.next('host')).host, '222');
h.clock.t += 10 * 60 * 1000 + 1;
const a3 = await h.joinAs('alice');
assert.equal(a3.welcome.host, '222');
await b.none('host');
} finally {
await h.stop();
}
});
test('an emptied hub keeps route/play for 10 min, then starts fresh', async () => {
const h = await start({ dev: true });
try {
const a = await h.devJoin('1');
a.json({ t: 'route', path: '/title/movie/550' });
await tick(50);
await closeAndWait(a);
h.clock.t += 9 * 60 * 1000;
const b = await h.devJoin('2');
assert.equal(b.welcome.host, '2', 'nobody left → the joiner is host');
assert.equal(b.welcome.route, '/title/movie/550');
const a2 = await h.devJoin('1');
assert.equal(a2.welcome.host, '1', 'original host reclaims');
assert.equal((await b.next('host')).host, '1');
await closeAndWait(a2);
await closeAndWait(b);
h.clock.t += 10 * 60 * 1000 + 1;
const c = await h.devJoin('3');
assert.equal(c.welcome.host, '3');
assert.equal(c.welcome.route, null);
const a3 = await h.devJoin('1');
assert.equal(a3.welcome.host, '3', 'fresh hub: no reclaim');
} finally {
await h.stop();
}
});
/* ---- relay ----------------------------------------------------------------- */
test('route/play relay from the host only, play stamped with server time; late joiner gets both', async () => {
const h = await start();
try {
const a = await h.joinAs('alice');
const b = await h.joinAs('bob');
a.drain();
a.json({ t: 'route', path: '/watch/movie/550' });
assert.deepEqual(await b.next('route'), { t: 'route', path: '/watch/movie/550' });
await a.none('route');
h.clock.t = 2_000_000;
const snapshot = { path: '/watch/movie/550', media: { type: 'movie', id: 550 }, stream: { id: 's1', playback: { kind: 'hls', url: '/v1/p/x' } }, playing: true, position: 12.5, duration: 8000, at: 5 };
a.json({ t: 'play', snapshot });
const p = await b.next('play');
assert.deepEqual(p.snapshot, { ...snapshot, at: 2_000_000 });
await a.none('play');
// non-host messages are ignored
b.json({ t: 'route', path: '/evil' });
b.json({ t: 'play', snapshot: { ...snapshot, position: 0 } });
await a.none('route');
await a.none('play');
// invalid route from the host is ignored
a.json({ t: 'route', path: 'javascript:alert(1)' });
await b.none('route');
const c = await h.joinAs('carol');
assert.equal(c.welcome.route, '/watch/movie/550');
assert.deepEqual(c.welcome.play, { ...snapshot, at: 2_000_000 });
// navigating elsewhere drops the stale snapshot for late joiners
a.json({ t: 'route', path: '/' });
await b.next('route');
await closeAndWait(c);
const c2 = await h.joinAs('carol');
assert.equal(c2.welcome.route, '/');
assert.equal(c2.welcome.play, null);
// explicit play:null is relayed
a.json({ t: 'play', snapshot: null });
assert.equal((await b.next('play')).snapshot, null);
// after handover the new host relays
await closeAndWait(a);
await c2.next('host');
b.json({ t: 'route', path: '/movies' });
assert.equal((await c2.next('route')).path, '/movies');
} finally {
await h.stop();
}
});
test('large snapshots up to ~256KB are accepted', async () => {
const h = await start({ dev: true });
try {
const a = await h.devJoin('1');
const b = await h.devJoin('2');
a.json({ t: 'play', snapshot: { path: '/watch/movie/1', stream: { blob: 'x'.repeat(200 * 1024) }, playing: false, position: 0 } });
assert.equal((await b.next('play')).snapshot.stream.blob.length, 200 * 1024);
} finally {
await h.stop();
}
});
test('ping → pong with server time; messages are rate limited per socket', async () => {
const h = await start({ dev: true });
try {
const a = h.open();
await a.opened;
a.json({ t: 'ping', at: 123 });
assert.deepEqual(await a.next('pong'), { t: 'pong', at: 123, now: 1_000_000 });
const host = await h.devJoin('1');
const v = await h.devJoin('2');
for (let i = 0; i < 60; i++) host.json({ t: 'route', path: `/p${i}` });
await host.next((m) => m.t === 'error' && /slow/.test(m.message));
await tick(100);
let n = 0;
while (await v.next('route', 50).catch(() => null)) n++;
assert.ok(n >= 25 && n <= 40, `got ${n} routes through`);
} finally {
await h.stop();
}
});
test('dev hello with cfg.dev; unknown ws path is refused', async () => {
const h = await start({ dev: true });
try {
const a = await h.devJoin('5', 'x');
assert.deepEqual(a.welcome.you, { id: '5', username: 'u5', avatar: null });
assert.equal(a.welcome.host, '5');
const r = await fetch(`${h.base}/api/config`);
assert.equal((await r.json()).dev, true);
const b = h.open('/nope');
await assert.rejects(b.opened);
} finally {
await h.stop();
}
});
test('dev mode reverse-proxies /tv/v1 to devApiUrl', async () => {
const http = require('http');
const upstream = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ url: req.url, method: req.method }));
});
await new Promise((r) => upstream.listen(0, '127.0.0.1', r));
const h = await start({ dev: true, devApiUrl: `http://127.0.0.1:${upstream.address().port}` });
try {
let r = await fetch(`${h.base}/tv/v1/streams?type=movie&id=550`);
assert.deepEqual(await r.json(), { url: '/v1/streams?type=movie&id=550', method: 'GET' });
r = await fetch(`${h.base}/tv`);
assert.match(await r.text(), /<title>x/, 'the Series route is not proxied');
} finally {
await h.stop();
upstream.close();
}
});