257 lines
18 KiB
JavaScript
257 lines
18 KiB
JavaScript
import assert from "node:assert/strict";
|
|
import { once } from "node:events";
|
|
import { generateKeyPairSync, randomUUID } from "node:crypto";
|
|
import { test } from "node:test";
|
|
import WebSocket from "ws";
|
|
import { CHANNEL_PROTOCOL, ChannelEventDecoder, eventSchema } from "../../src/client/channel/protocol.ts";
|
|
|
|
const endpoint = process.env.CHANNEL_WS_URL ?? "ws://127.0.0.1:8791/prototype/channel";
|
|
const origin = process.env.CHANNEL_UI_ORIGIN ?? "http://127.0.0.1:8790";
|
|
assert(["127.0.0.1", "localhost"].includes(new URL(endpoint).hostname), "Checks only target loopback");
|
|
const ownerKey = process.env.PIIK_CHANNEL_OWNER_KEY;
|
|
assert(ownerKey, "Set PIIK_CHANNEL_OWNER_KEY to the local server's owner bootstrap key");
|
|
// The protocol-only sources explicitly declare the accepted 720p30 ceiling.
|
|
const videoSettings = { ceiling: { resolution: { width: 1280, height: 720 }, maxFramerate: 30, maxBitrate: 3_000_000 }, degradationPreference: 'balanced' };
|
|
const source = { kind: "screen", name: null };
|
|
|
|
async function connect(t, join = {}) {
|
|
const socket = new WebSocket(endpoint, { origin });
|
|
const decoder = new ChannelEventDecoder();
|
|
const inbox = [], waiters = [];
|
|
const recent = [];
|
|
let closeCode;
|
|
socket.on("close", code => { closeCode = code; });
|
|
socket.on("message", bytes => {
|
|
const raw = JSON.parse(bytes.toString());
|
|
if (["welcome", "state"].includes(raw.type))
|
|
assert(raw.state.users.every(user => !Object.hasOwn(user, "avatar")), "live summaries keep avatars in the profile path");
|
|
const event = decoder.decode(raw, bytes.byteLength);
|
|
recent.push({ type: event.type,
|
|
...(event.type === "error" ? { code: event.code } : {}),
|
|
...(event.type === "room_reply" ? { result: event.result.type, code: event.result.code } : {}),
|
|
...(["welcome", "state"].includes(event.type) ? { rooms: event.state.channel.rooms.map(room => ({ id: room.id, available: room.available })) } : {}),
|
|
});
|
|
if (recent.length > 16) recent.shift();
|
|
const index = waiters.findIndex(waiter => waiter.predicate(event));
|
|
if (index < 0) inbox.push(event);
|
|
else {
|
|
const [waiter] = waiters.splice(index, 1);
|
|
clearTimeout(waiter.timer); waiter.resolve(event);
|
|
}
|
|
});
|
|
const wait = (predicate, description) => {
|
|
const index = inbox.findIndex(predicate);
|
|
if (index >= 0) return Promise.resolve(inbox.splice(index, 1)[0]);
|
|
return new Promise((resolve, reject) => {
|
|
const waiter = { predicate, resolve, timer: setTimeout(() => {
|
|
waiters.splice(waiters.indexOf(waiter), 1);
|
|
const queued = {};
|
|
for (const event of inbox) queued[event.type] = (queued[event.type] ?? 0) + 1;
|
|
reject(new Error(`Waiting for ${description}; ${JSON.stringify({ socket: socket.readyState, closeCode, queued, recent })}`));
|
|
}, 5000) };
|
|
waiters.push(waiter);
|
|
});
|
|
};
|
|
t.after(() => { socket.terminate(); for (const waiter of waiters) clearTimeout(waiter.timer); });
|
|
await once(socket, "open");
|
|
const client = { socket, wait,
|
|
async request(command) {
|
|
const requestId = randomUUID();
|
|
const response = wait(event => event.requestId === requestId && ["ack", "error", "room_reply", "profiles", "room_created"].includes(event.type), command.type);
|
|
socket.send(JSON.stringify({ ...command, requestId }));
|
|
const result = await response;
|
|
if (result.type === "error" || result.result?.type === "error") {
|
|
console.error(`Protocol ${command.type}: ${result.code ?? result.result.code}`);
|
|
}
|
|
return result.type === "room_reply" ? { requestId, ...result.result, type: result.result.type === "error" ? "error" : "ack" } : result;
|
|
},
|
|
};
|
|
const signingKey = [...Buffer.from(generateKeyPairSync("ed25519").publicKey.export({ format: "jwk" }).x, "base64url")];
|
|
socket.send(JSON.stringify({ type: "join", protocol: CHANNEL_PROTOCOL, name: "Protocol check", signingKey, ...join }));
|
|
client.welcome = await wait(event => ["welcome", "error"].includes(event.type), "join result");
|
|
return client;
|
|
}
|
|
|
|
test("the frontend accepts real cross-room publications and subscriptions", { timeout: 30_000 }, async t => {
|
|
const clients = [];
|
|
try {
|
|
// The twentieth real participant is the Server hosting these rooms.
|
|
for (let index = 0; index < 19; index++) clients.push(await connect(t, index === 0 ? { ownerKey } : {}));
|
|
for (const client of clients) assert.equal(client.welcome.type, "welcome");
|
|
const reader = clients[0];
|
|
const state = reader.welcome.state.channel.rooms.length === 3 ? reader.welcome.state
|
|
: (await reader.wait(event => event.type === "state" && event.state.channel.rooms.length === 3, "Server rooms registered")).state;
|
|
const rooms = state.channel.rooms;
|
|
assert.equal(rooms.length, 3);
|
|
assert.equal(state.channel.hostingMode, "lightweight");
|
|
assert.equal(state.channel.roomCreationPolicy, "ordinary");
|
|
assert.deepEqual([...state.channel.managedRoomIds].sort(), rooms.map(room => room.id).sort());
|
|
assert.deepEqual(clients[1].welcome.state.channel.managedRoomIds, []);
|
|
for (const room of rooms) for (const client of clients) {
|
|
assert.equal((await client.request({ type: "voice", roomId: room.id, joined: true, muted: false, deafened: false })).type, "ack");
|
|
for (const kind of ["screen", "voice"]) {
|
|
const publicationId = randomUUID();
|
|
assert.equal((await client.request({ type: "publish", publication: { id: publicationId, roomId: room.id, kind,
|
|
...(kind === "screen" ? { videoSettings, source } : {}) } })).type, "ack");
|
|
if (client !== reader && kind === "screen") assert.equal((await reader.request({ type: "subscribe", publicationId, enabled: true })).type, "ack");
|
|
}
|
|
}
|
|
const event = await reader.wait(event => event.type === "state" && event.state.publications.length === clients.length * rooms.length * 2
|
|
&& event.state.subscriptions.length === (clients.length - 1) * rooms.length * 2, "three rooms with independent activity");
|
|
assert.equal(event.state.voice.length, clients.length * rooms.length);
|
|
const parsed = eventSchema.safeParse(event);
|
|
assert(parsed.success, JSON.stringify(parsed.error?.issues));
|
|
const negotiated = eventSchema.safeParse({ type: "signal", pairId: randomUUID(),
|
|
fromSessionId: reader.welcome.sessionId,
|
|
payload: { tracks: event.state.pairs.flatMap(pair => pair.incoming).map(flow => ({ flowId: flow.id, streamId: randomUUID() })) } });
|
|
assert(negotiated.success, JSON.stringify(negotiated.error?.issues));
|
|
} finally {
|
|
// Leave immediately so the following protocol cases have the same endpoint budget.
|
|
for (const client of clients) if (client.socket.readyState === WebSocket.OPEN) await client.request({ type: "leave" });
|
|
}
|
|
});
|
|
|
|
test("authenticated users, signed conversation and selective source ownership", { timeout: 30_000 }, async t => {
|
|
const owner = await connect(t, { ownerKey, name: "Owner check" });
|
|
const friend = await connect(t, { name: "Friend check" });
|
|
const other = await connect(t, { name: "Other check" });
|
|
for (const client of [owner, friend, other]) assert.equal(client.welcome.type, "welcome");
|
|
const state = owner.welcome.state;
|
|
assert(Number.isSafeInteger(state.channel.historyWindow) && state.channel.historyWindow > 0);
|
|
const ownerSession = state.sessions.find(session => session.id === owner.welcome.sessionId);
|
|
assert.equal(ownerSession.userId, state.channel.ownerId);
|
|
assert.notEqual(friend.welcome.sessionId, other.welcome.sessionId);
|
|
const friendUser = friend.welcome.state.sessions.find(session => session.id === friend.welcome.sessionId).userId;
|
|
const avatar = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIHWP4z8DwHwAFgAI/ScLbtAAAAABJRU5ErkJggg==";
|
|
assert.equal((await friend.request({ type: "set_profile", name: "Friend check", avatar })).type, "ack");
|
|
const updated = await other.wait(event => event.type === "state" && event.state.users.some(user => user.id === friendUser
|
|
&& user.version !== friend.welcome.selfProfile.version), "profile version broadcast");
|
|
const profile = (await other.request({ type: "profiles", ids: [friendUser] })).profiles[0];
|
|
assert.equal(profile.avatar, avatar);
|
|
assert.equal(profile.version, updated.state.users.find(user => user.id === friendUser).version);
|
|
const roomId = state.channel.rooms[0].id;
|
|
if (!state.channel.rooms[0].available) await owner.wait(event => event.type === "state"
|
|
&& event.state.channel.rooms.some(room => room.id === roomId && room.available), "Server room host available after cleanup");
|
|
for (const client of [owner, friend, other]) assert.equal((await client.request({ type: "browse", roomId, active: true })).type, "ack");
|
|
const text = `prototype-check-${randomUUID()}`;
|
|
const nonce = randomUUID();
|
|
assert.equal((await friend.request({ type: "chat", roomId, text, nonce })).type, "error",
|
|
"the domain cannot execute a room's conversation");
|
|
const attacker = await connect(t, { name: "Spoof check" });
|
|
const rejected = Promise.race([
|
|
attacker.wait(event => event.type === "error", "spoof rejection"),
|
|
once(attacker.socket, "close"),
|
|
]);
|
|
attacker.socket.send(JSON.stringify({ type: "chat", roomId, text: "forged", nonce: randomUUID(), userId: state.channel.ownerId }));
|
|
await rejected;
|
|
attacker.socket.close();
|
|
|
|
const publicationId = randomUUID();
|
|
assert.equal((await friend.request({ type: "publish", publication: { id: publicationId, roomId, kind: "screen", videoSettings, source } })).type, "ack");
|
|
const initial = await other.wait(event => event.type === "state"
|
|
&& event.state.publications.some(publication => publication.id === publicationId), "new screen publication");
|
|
const screen = initial.state.publications.find(publication => publication.id === publicationId);
|
|
assert.equal(Object.hasOwn(screen, "directLimit"), false);
|
|
assert.equal((await other.request({ type: "set_screen_direct_limit", publicationId, limit: 1 })).type, "error");
|
|
assert.equal((await friend.request({ type: "set_screen_direct_limit", publicationId, limit: 21 })).code, "invalid_relay_capacity");
|
|
assert.equal((await friend.request({ type: "set_screen_direct_limit", publicationId, limit: 1 })).type, "ack");
|
|
await other.wait(event => event.type === "state"
|
|
&& event.state.publications.some(publication => publication.id === publicationId && publication.directLimit === 1),
|
|
"explicit screen source limit");
|
|
assert.equal((await friend.request({ type: "set_screen_direct_limit", publicationId, limit: null })).type, "ack");
|
|
await other.wait(event => event.type === "state"
|
|
&& event.state.publications.some(publication => publication.id === publicationId && !Object.hasOwn(publication, "directLimit")),
|
|
"screen source limit restored to room default");
|
|
assert.equal((await other.request({ type: "unpublish", publicationId })).type, "error");
|
|
assert.equal((await other.request({ type: "subscribe", publicationId, enabled: true })).type, "ack");
|
|
const routed = await other.wait(event => event.type === "state" && event.state.pairs.some(pair => pair.incoming.some(flow => flow.publicationId === publicationId)), "admitted subscription");
|
|
assert.equal(routed.state.users.find(user => user.id === friendUser).version, profile.version);
|
|
assert(routed.state.pairs.every(pair => pair.peerId !== other.welcome.sessionId));
|
|
assert.equal((await owner.request({ type: "signal", pairId: randomUUID(), payload: { resync: true } })).type, "ack",
|
|
"an unknown or retired pair cannot restore its transport lease");
|
|
const sourcePair = routed.state.pairs.find(pair => pair.incoming.some(flow => flow.publicationId === publicationId));
|
|
// A description needs its exchangeId, even on the caller's admitted pair.
|
|
const malformed = await other.request({ type: "signal", pairId: sourcePair.id, payload: { description: { type: "offer", sdp: "invalid" } } });
|
|
assert.equal(malformed.type, "error");
|
|
assert.equal(malformed.code, "invalid_signal");
|
|
assert.equal((await friend.request({ type: "unpublish", publicationId })).type, "ack");
|
|
await other.wait(event => event.type === "state" && !event.state.publications.some(publication => publication.id === publicationId)
|
|
&& event.state.pairs.every(pair => !pair.incoming.some(flow => flow.publicationId === publicationId)), "source retirement");
|
|
|
|
const disconnected = once(friend.socket, "close");
|
|
friend.socket.close();
|
|
await disconnected;
|
|
const resumed = await connect(t, { credential: friend.welcome.credential, sessionId: friend.welcome.sessionId });
|
|
assert.equal(resumed.welcome.type, "welcome");
|
|
assert.equal(resumed.welcome.sessionId, friend.welcome.sessionId, "a transient disconnect resumes the same endpoint");
|
|
|
|
const returning = await connect(t, { credential: friend.welcome.credential, name: "Returning friend" });
|
|
assert.equal(returning.welcome.type, "welcome");
|
|
const returningUser = returning.welcome.state.sessions.find(session => session.id === returning.welcome.sessionId).userId;
|
|
assert.equal(returningUser, friendUser);
|
|
assert.notEqual(returning.welcome.sessionId, friend.welcome.sessionId, "another page is another endpoint");
|
|
assert.equal((await returning.request({ type: "browse", roomId, active: true })).type, "ack");
|
|
assert.equal((await returning.request({ type: "history", roomId })).type, "error",
|
|
"history requires a signed conversation addressed to the actual room host");
|
|
|
|
const stolen = await connect(t, { credential: other.welcome.credential, sessionId: friend.welcome.sessionId });
|
|
if (stolen.welcome.type === "welcome") {
|
|
assert.notEqual(stolen.welcome.sessionId, friend.welcome.sessionId, "another user cannot resume the victim's session");
|
|
} else assert.equal(stolen.welcome.type, "error");
|
|
|
|
const ordinary = await connect(t);
|
|
assert.equal(ordinary.welcome.type, "welcome", "opening the site needs no domain invitation");
|
|
});
|
|
|
|
|
|
test("Server-owned private invitations admit new users, conceal content and revoke room grants", { timeout: 30_000 }, async t => {
|
|
const creator = await connect(t, { ownerKey });
|
|
const outsider = await connect(t);
|
|
const roomId = "studio";
|
|
if (!creator.welcome.state.channel.rooms.some(room => room.id === roomId && room.available)) await creator.wait(event => event.type === "state"
|
|
&& event.state.channel.rooms.some(room => room.id === roomId && room.available), "Server room host available for management");
|
|
assert.equal((await creator.request({ type: "update_room", roomId, name: "Private check", icon: "couch", access: "private", hidden: true, password: "test-room-password" })).type, "ack");
|
|
const concealed = await outsider.wait(event => event.type === "state" && !event.state.channel.rooms.some(room => room.id === roomId), "hidden room excluded");
|
|
assert(!concealed.state.publications.some(p => p.roomId === roomId));
|
|
assert.equal((await outsider.request({ type: "browse", roomId, active: true })).type, "error");
|
|
assert.equal((await outsider.request({ type: "enter_room", roomId, password: "wrong" })).type, "error");
|
|
assert.equal((await creator.request({ type: "room_invite", roomId })).type, "ack");
|
|
const invitation = await creator.wait(event => event.type === "room_invite" && event.roomId === roomId, "room invitation");
|
|
assert.equal(typeof invitation.requestId, "string");
|
|
const guest = await connect(t);
|
|
assert.equal(guest.welcome.type, "welcome");
|
|
assert.equal((await guest.request({ type: "enter_room", roomId, inviteKey: invitation.key })).type, "ack");
|
|
await guest.wait(event => event.type === "state" && event.state.channel.rooms.some(room => room.id === roomId && room.authorized), "private room grant after site Welcome");
|
|
const guestUser = guest.welcome.state.sessions.find(session => session.id === guest.welcome.sessionId).userId;
|
|
const privatePublication = randomUUID();
|
|
assert.equal((await creator.request({ type: "publish", publication: { id: privatePublication, roomId, kind: "screen", videoSettings, source } })).type, "ack");
|
|
assert.equal((await outsider.request({ type: "subscribe", publicationId: privatePublication, enabled: true })).type, "error");
|
|
assert.equal((await guest.request({ type: "subscribe", publicationId: privatePublication, enabled: true })).type, "ack");
|
|
assert.equal((await guest.request({ type: "browse", roomId, active: true })).type, "ack");
|
|
assert.equal((await creator.request({ type: "revoke_room_access", roomId, userId: guestUser })).type, "ack");
|
|
const revoked = await guest.wait(event => event.type === "state" && !event.state.channel.rooms.some(room => room.id === roomId), "private grant revoked");
|
|
assert(!revoked.state.publications.some(p => p.id === privatePublication));
|
|
assert(revoked.state.pairs.every(pair => !pair.incoming.some(flow => flow.publicationId === privatePublication) && !pair.outgoing.some(flow => flow.publicationId === privatePublication)));
|
|
assert.equal((await guest.request({ type: "history", roomId })).type, "error");
|
|
assert.equal((await creator.request({ type: "unpublish", publicationId: privatePublication })).type, "ack");
|
|
assert.equal((await creator.request({ type: "update_room", roomId, name: "Studio", icon: "couch", access: "public", hidden: false })).type, "ack");
|
|
});
|
|
|
|
test("a lightweight room cancellation round-trips on the current channel protocol", { timeout: 30_000 }, async t => {
|
|
const owner = await connect(t, { ownerKey });
|
|
assert.equal(owner.welcome.type, "welcome");
|
|
assert.equal(owner.welcome.protocol, CHANNEL_PROTOCOL);
|
|
const existing = owner.welcome.state.channel.rooms.find(room => room.available)
|
|
?? (await owner.wait(event => event.type === "state" && event.state.channel.rooms.some(room => room.available),
|
|
"registered fixture room")).state.channel.rooms.find(room => room.available);
|
|
const reservation = await owner.request({ type: "create_room", room: {
|
|
id: randomUUID(), creatorId: owner.welcome.selfProfile.id, name: "Cancelled reservation",
|
|
icon: "couch", access: "public", hidden: false, hasPassword: false,
|
|
} });
|
|
assert.equal(reservation.type, "room_created");
|
|
assert.equal((await owner.request({ type: "cancel_room_creation", roomId: reservation.room.id })).type, "ack");
|
|
assert.equal((await owner.request({ type: "cancel_room_creation", roomId: existing.id })).type, "ack");
|
|
assert.equal((await owner.request({ type: "browse", roomId: existing.id, active: true })).type, "ack");
|
|
assert.equal((await owner.request({ type: "leave" })).type, "ack");
|
|
});
|