Files
tv-discord/test/server.test.js
T

379 lines
13 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 { EventEmitter } = require('events');
const WebSocket = require('ws');
const { createServer } = require('../src/server');
/* ---- fakes ----------------------------------------------------------------- */
class FakeRoom extends EventEmitter {
constructor(id) {
super();
this.id = id;
this.calls = [];
this.viewers = new Set();
this.rev = 0;
this.media = { type: 'movie', tmdb: 550, title: 'Fight Club' };
}
join(u) {
this.calls.push(['join', u]);
this.viewers.add(u);
}
leave(u) {
this.calls.push(['leave', u]);
this.viewers.delete(u);
}
command(op, args, u) {
this.calls.push(['command', op, args, u]);
this.rev++;
this.emit('change', {}, op);
}
report(data, u) {
this.calls.push(['report', data, u]);
}
publicState(now = Date.now()) {
return { media: this.media, stream: null, playing: false, position: 0, updatedAt: now, now, viewers: [...this.viewers], leader: null, rev: this.rev, notice: null };
}
}
function fakeRooms({ events = false } = {}) {
const map = new Map();
const rooms = events ? new EventEmitter() : {};
rooms.get = (id) => map.get(id);
rooms.create = ({ id }) => {
const r = new FakeRoom(id);
map.set(id, r);
if (events) rooms.emit('created', r);
return r;
};
rooms.delete = (id) => map.delete(id);
rooms.all = () => [...map.values()];
return rooms;
}
const USERS = { good: { id: '111', username: 'alice' }, bob: { id: '222', username: 'bob' } };
function fakeDiscord() {
const calls = [];
const fn = async (url, init = {}) => {
calls.push([url, init]);
const res = (status, body) => ({ ok: status < 300, status, json: async () => 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: 'good', 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' });
}
return res(404, {});
};
fn.calls = calls;
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.mkdirSync(path.join(activityDir, 'dist'));
fs.writeFileSync(path.join(activityDir, 'dist', 'main.js'), 'console.log(1)');
async function start(opts = {}) {
const rooms = opts.rooms || fakeRooms();
const discordFetch = fakeDiscord();
const voice = opts.voice || { '42': new Set(['111', '222']) };
const cfg = { applicationId: 'app1', clientSecret: 'sekrit', activityDir, dev: !!opts.dev };
const server = createServer(cfg, rooms, {
isInVoice: async (c, u) => !!(voice[c] && voice[c].has(u)),
discordFetch,
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 = 3000) => {
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.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;
};
const stop = async () => {
for (const ws of sockets) ws.terminate();
await new Promise((r) => server.close(r));
};
return { server, rooms, discordFetch, base, open, stop };
}
const tick = (ms) => new Promise((r) => setTimeout(r, ms));
/* ---- 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}/dist/main.js`);
assert.match(r.headers.get('content-type'), /javascript/);
assert.match(r.headers.get('cache-control'), /max-age/);
r = await fetch(`${h.base}/.proxy/dist/main.js`);
assert.equal(r.status, 200);
r = await fetch(`${h.base}/some/route`);
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}/healthz`);
assert.deepEqual(await r.json(), { ok: true });
} 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: 'good' });
const [url, init] = h.discordFetch.calls[0];
assert.equal(url, 'https://discord.com/api/oauth2/token');
const p = new URLSearchParams(init.body);
assert.equal(p.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();
}
});
/* ---- websocket ------------------------------------------------------------- */
test('hello: bad token → error + close; not in voice → error + close', async () => {
const h = await start();
try {
const a = h.open();
await a.opened;
a.json({ t: 'hello', token: 'nope', channelId: '42' });
assert.equal((await a.next((m) => m.t === 'error')).message, 'authentication failed');
assert.equal(await a.closed, 4001);
const b = h.open();
await b.opened;
b.json({ t: 'hello', token: 'good', channelId: '99' });
assert.match((await b.next((m) => m.t === 'error')).message, /voice/);
assert.equal(await b.closed, 4001);
// dev hello is refused unless cfg.dev
const c = h.open();
await c.opened;
c.json({ t: 'hello', dev: true, userId: '111', channelId: '42' });
await c.next((m) => m.t === 'error');
assert.equal(await c.closed, 4001);
} finally {
await h.stop();
}
});
test('hello success joins the room; users/@me is cached; leave on close', async () => {
const h = await start();
const room = h.rooms.create({ id: '42' });
try {
const a = h.open();
await a.opened;
a.json({ t: 'hello', token: 'good', channelId: '42' });
const w = await a.next((m) => m.t === 'welcome');
assert.deepEqual(w.user, { id: '111', username: 'alice' });
assert.equal(w.state.media.title, 'Fight Club');
assert.deepEqual(room.calls, [['join', '111']]);
// second socket for the same user: no second join, cached /users/@me
const a2 = h.open();
await a2.opened;
a2.json({ t: 'hello', token: 'good', channelId: '42' });
await a2.next((m) => m.t === 'welcome');
assert.equal(h.discordFetch.calls.filter(([u]) => u.endsWith('/users/@me')).length, 1);
assert.equal(room.calls.length, 1);
a.close();
await tick(100);
assert.equal(room.calls.length, 1, 'still one socket open for the user');
a2.close();
await tick(100);
assert.deepEqual(room.calls.at(-1), ['leave', '111']);
} finally {
await h.stop();
}
});
test('ping → pong with server time', async () => {
const h = await start();
try {
const a = h.open();
await a.opened;
a.json({ t: 'ping', at: 123 });
const p = await a.next((m) => m.t === 'pong');
assert.equal(p.at, 123);
assert.ok(Math.abs(p.now - Date.now()) < 1000);
} finally {
await h.stop();
}
});
test('cmd and report are forwarded; change broadcasts are coalesced', async () => {
const h = await start();
const room = h.rooms.create({ id: '42' });
try {
const a = h.open();
const b = h.open();
await Promise.all([a.opened, b.opened]);
a.json({ t: 'hello', token: 'good', channelId: '42' });
b.json({ t: 'hello', token: 'bob', channelId: '42' });
await a.next((m) => m.t === 'welcome');
await b.next((m) => m.t === 'welcome');
await tick(100);
// drain anything queued so far
while (await a.next((m) => m.t === 'state', 120).catch(() => null));
while (await b.next((m) => m.t === 'state', 120).catch(() => null));
a.json({ t: 'cmd', op: 'seek', args: { t: 90 } });
a.json({ t: 'cmd', op: 'play', args: {} });
a.json({ t: 'report', duration: 5000 });
const s = await b.next((m) => m.t === 'state');
assert.equal(s.state.rev, 2, 'two changes → one broadcast with the latest state');
await assert.rejects(b.next((m) => m.t === 'state', 200));
assert.deepEqual(
room.calls.filter((c) => c[0] !== 'join'),
[
['command', 'seek', { t: 90 }, '111'],
['command', 'play', {}, '111'],
['report', { duration: 5000 }, '111'],
],
);
} finally {
await h.stop();
}
});
test('cmds are rate limited per socket', async () => {
const h = await start();
const room = h.rooms.create({ id: '42' });
try {
const a = h.open();
await a.opened;
a.json({ t: 'hello', token: 'good', channelId: '42' });
await a.next((m) => m.t === 'welcome');
for (let i = 0; i < 25; i++) a.json({ t: 'cmd', op: 'toggle' });
await a.next((m) => m.t === 'error' && /slow/.test(m.message));
const n = room.calls.filter((c) => c[0] === 'command').length;
assert.ok(n >= 10 && n < 15, `got ${n} commands through`);
} finally {
await h.stop();
}
});
for (const events of [true, false]) {
test(`waiting socket attaches when the room appears (${events ? "rooms 'created' event" : 'poll'})`, async () => {
const h = await start({ rooms: fakeRooms({ events }) });
try {
const a = h.open();
await a.opened;
a.json({ t: 'hello', token: 'good', channelId: '42' });
const w = await a.next((m) => m.t === 'welcome');
assert.equal(w.state.media, null);
const room = h.rooms.create({ id: '42' });
const s = await a.next((m) => m.t === 'state', 4000);
assert.equal(s.state.media.title, 'Fight Club');
assert.deepEqual(room.calls, [['join', '111']]);
a.json({ t: 'cmd', op: 'play' });
await a.next((m) => m.t === 'state');
assert.equal(room.calls.at(-1)[1], 'play');
} finally {
await h.stop();
}
});
}
test("room 'closed' → empty state, then a new room re-attaches", async () => {
const h = await start({ rooms: fakeRooms({ events: true }) });
const room = h.rooms.create({ id: '42' });
try {
const a = h.open();
await a.opened;
a.json({ t: 'hello', token: 'good', channelId: '42' });
await a.next((m) => m.t === 'welcome');
room.emit('closed');
h.rooms.delete('42');
const s = await a.next((m) => m.t === 'state' && m.state.media === null);
assert.equal(s.state.stream, null);
room.emit('change'); // a dead room must not broadcast anymore
await assert.rejects(a.next((m) => m.t === 'state', 200));
const room2 = h.rooms.create({ id: '42' });
await a.next((m) => m.t === 'state' && m.state.media);
assert.deepEqual(room2.calls, [['join', '111']]);
} finally {
await h.stop();
}
});
test('dev hello works with cfg.dev; unknown ws path is refused', async () => {
const h = await start({ dev: true, voice: { '7': new Set(['5']) } });
try {
const a = h.open();
await a.opened;
a.json({ t: 'hello', dev: true, userId: '5', channelId: '7' });
const w = await a.next((m) => m.t === 'welcome');
assert.equal(w.user.id, '5');
const b = h.open('/nope');
await assert.rejects(b.opened);
} finally {
await h.stop();
}
});