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.
This commit is contained in:
1 parent
4d900c5b56
commit
7de90b5b7c
39 files changed
+1620
-4372
No files matched your search
+362
-225
@@ -3,68 +3,35 @@ 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 };
|
||||
}
|
||||
}
|
||||
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 },
|
||||
};
|
||||
|
||||
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 PNG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 1, 2, 3]);
|
||||
|
||||
const USERS = { good: { id: '111', username: 'alice' }, bob: { id: '222', username: 'bob' } };
|
||||
|
||||
function fakeDiscord() {
|
||||
function fakeDiscord(instances) {
|
||||
const calls = [];
|
||||
const fn = async (url, init = {}) => {
|
||||
calls.push([url, init]);
|
||||
const res = (status, body) => ({ ok: status < 300, status, json: async () => body });
|
||||
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: 'good', token_type: 'Bearer' });
|
||||
return res(200, { access_token: 'alice', token_type: 'Bearer' });
|
||||
}
|
||||
return res(400, { error: 'invalid_grant' });
|
||||
}
|
||||
@@ -72,9 +39,25 @@ function fakeDiscord() {
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -82,19 +65,14 @@ function fakeDiscord() {
|
||||
|
||||
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)');
|
||||
fs.writeFileSync(path.join(activityDir, 'discord.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: () => {},
|
||||
});
|
||||
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 = [];
|
||||
@@ -109,7 +87,11 @@ async function start(opts = {}) {
|
||||
if (i >= 0) waiters.splice(i, 1)[0].resolve(m);
|
||||
else queue.push(m);
|
||||
});
|
||||
ws.next = (pred = () => true, ms = 3000) => {
|
||||
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) => {
|
||||
@@ -123,6 +105,10 @@ async function start(opts = {}) {
|
||||
}, 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);
|
||||
@@ -131,14 +117,36 @@ async function start(opts = {}) {
|
||||
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();
|
||||
await new Promise((r) => server.close(r));
|
||||
const closed = new Promise((r) => server.close(r));
|
||||
server.closeAllConnections();
|
||||
await closed;
|
||||
};
|
||||
return { server, rooms, discordFetch, base, open, stop };
|
||||
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 ------------------------------------------------------------------ */
|
||||
|
||||
@@ -149,12 +157,12 @@ test('static files, SPA fallback, config, healthz', async () => {
|
||||
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`);
|
||||
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/dist/main.js`);
|
||||
r = await fetch(`${h.base}/.proxy/discord.js`);
|
||||
assert.equal(r.status, 200);
|
||||
r = await fetch(`${h.base}/some/route`);
|
||||
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`);
|
||||
@@ -163,8 +171,13 @@ test('static files, SPA fallback, config, healthz', async () => {
|
||||
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();
|
||||
}
|
||||
@@ -175,11 +188,10 @@ test('POST /api/token exchanges the code with Discord', async () => {
|
||||
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' });
|
||||
assert.deepEqual(await r.json(), { access_token: 'alice' });
|
||||
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');
|
||||
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: '{}' });
|
||||
@@ -193,186 +205,311 @@ test('POST /api/token exchanges the code with Discord', async () => {
|
||||
}
|
||||
});
|
||||
|
||||
/* ---- websocket ------------------------------------------------------------- */
|
||||
|
||||
test('hello: bad token → error + close; not in voice → error + close', async () => {
|
||||
test('avatar endpoint proxies known users from the CDN and caches', 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);
|
||||
|
||||
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();
|
||||
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']);
|
||||
b.close();
|
||||
} finally {
|
||||
await h.stop();
|
||||
}
|
||||
});
|
||||
|
||||
test('ping → pong with server time', async () => {
|
||||
/* ---- 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 });
|
||||
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();
|
||||
}
|
||||
});
|
||||
assert.deepEqual(await a.next('pong'), { t: 'pong', at: 123, now: 1_000_000 });
|
||||
|
||||
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');
|
||||
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);
|
||||
// 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'],
|
||||
],
|
||||
);
|
||||
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('cmds are rate limited per socket', async () => {
|
||||
const h = await start();
|
||||
const room = h.rooms.create({ id: '42' });
|
||||
test('dev hello with cfg.dev; unknown ws path is refused', async () => {
|
||||
const h = await start({ dev: true });
|
||||
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 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();
|
||||
}
|
||||
});
|
||||
Reference in new issue
Block a user