import { createHash, randomUUID } from 'node:crypto'; import { ConfigService } from '@nestjs/config'; import type { Call, CallAccess, CallsOverview, Conversation, Realm, } from '@repo/contracts'; import { AccessToken, TokenVerifier } from 'livekit-server-sdk'; import request from 'supertest'; import { CallRooms } from '../src/calls/call-rooms'; import { CallsStore } from '../src/calls/calls.store'; import type { Env } from '../src/config/env'; import { befriend, createTestApp, listen, nextEvent, TestAccounts, TestSockets, type ClientSocket, type TestApp, type TestUser, } from './helpers'; /** * Stands in for the media server: who is in which room is whatever the * test says, the way browsers joining and leaving would change it. */ class FakeCallRooms implements Pick< CallRooms, 'list' | 'participants' | 'remove' | 'close' > { private readonly rooms = new Map(); join(room: string, identity: string) { this.rooms.set(room, [...(this.rooms.get(room) ?? []), identity]); } leave(room: string, identity: string) { const left = (this.rooms.get(room) ?? []).filter((id) => id !== identity); if (left.length > 0) this.rooms.set(room, left); else this.rooms.delete(room); } list() { return Promise.resolve([...this.rooms.keys()]); } participants(room: string) { return Promise.resolve(this.rooms.get(room) ?? []); } remove(room: string, identity: string) { this.leave(room, identity); return Promise.resolve(); } close(room: string) { this.rooms.delete(room); return Promise.resolve(); } } /** How a report is signed, when not the way the media server would. */ interface Signing { secret?: string; /** Sign this instead of the body that is sent. */ body?: string; /** The answer to expect; 200 unless said. */ status?: number; } describe('Calls (e2e)', () => { let app: TestApp; let accounts: TestAccounts; let sockets: TestSockets; const rooms = new FakeCallRooms(); let apiKey: string; let apiSecret: string; // Alice is friends with Bob and Carol, who are friends too. Dave is // nobody's friend but joins Alice's realm. let alice: TestUser; let bob: TestUser; let carol: TestUser; let dave: TestUser; let aliceSocket: ClientSocket; let bobSocket: ClientSocket; let carolSocket: ClientSocket; let daveSocket: ClientSocket; /** Alice and Bob. */ let direct: Conversation; /** Alice (owner), Bob and Carol. */ let group: Conversation; /** Alice's, with Dave in it. */ let realm: Realm; let cauldronId: string; async function callsOf(account: TestUser): Promise { const overview: CallsOverview = ( await account.agent.get('/calls').expect(200) ).body; expect(overview.enabled).toBe(true); return overview.calls; } const idsIn = (call: Call | undefined) => call?.participants.map((participant) => participant.id); /** * Sends what the media server would, signed the way it signs, and checks * how the API answers. */ async function report( event: string, room: string, { status = 200, ...sign }: Signing = {}, ) { const body = JSON.stringify({ event, room: { name: room }, id: randomUUID(), }); const token = new AccessToken(apiKey, sign.secret ?? apiSecret); token.sha256 = createHash('sha256') .update(sign.body ?? body) .digest('base64'); return request(app.getHttpServer()) .post('/livekit/webhook') .set('Content-Type', 'application/webhook+json') .set('Authorization', await token.toJwt()) .send(body) .expect(status); } /** Someone's browser connects to a call, and the media server says so. */ async function joins(account: TestUser, conversationId: string) { rooms.join(conversationId, account.id); await report('participant_joined', conversationId); } async function leaves(account: TestUser, conversationId: string) { rooms.leave(conversationId, account.id); await report('participant_left', conversationId); } beforeAll(async () => { app = await createTestApp((builder) => builder.overrideProvider(CallRooms).useValue(rooms), ); const config = app.get>(ConfigService); apiKey = config.getOrThrow('LIVEKIT_API_KEY', { infer: true }); apiSecret = config.getOrThrow('LIVEKIT_API_SECRET', { infer: true }); sockets = new TestSockets(await listen(app)); accounts = new TestAccounts(app, '@calls-e2e.test'); await accounts.cleanup(); [alice, bob, carol, dave] = await Promise.all( ['Alice', 'Bob', 'Carol', 'Dave'].map((name) => accounts.signUp(name)), ); await befriend(alice, bob); await befriend(alice, carol); await befriend(bob, carol); direct = ( await alice.agent .post('/conversations/direct') .send({ userId: bob.id }) .expect(200) ).body; group = ( await alice.agent .post('/conversations/group') .send({ memberIds: [bob.id, carol.id] }) .expect(201) ).body; realm = (await alice.agent.post('/realms').send({ name: 'Calls' })).body; cauldronId = realm.cauldrons[0].id; const invite = ( await alice.agent.post(`/realms/${realm.id}/invites`).send({}).expect(201) ).body; await dave.agent.post(`/invites/${invite.code}/accept`).expect(200); [aliceSocket, bobSocket, carolSocket, daveSocket] = await Promise.all( [alice, bob, carol, dave].map((account) => sockets.connectAs(account)), ); }); afterAll(async () => { sockets.closeAll(); // Whatever a failed test left behind; the store is shared with the // API in development. const store = app.get(CallsStore); await Promise.all( [direct.id, group.id, cauldronId].map((id) => store.delete(id)), ); await accounts.cleanup(); await app.close(); }); describe('joining', () => { it('hands out a token for this user and this call alone', async () => { const access: CallAccess = ( await alice.agent.post(`/conversations/${direct.id}/call`).expect(200) ).body; expect(access.url).toBe('ws://livekit.invalid'); const claims = await new TokenVerifier(apiKey, apiSecret).verify( access.token, ); expect(claims.sub).toBe(alice.id); expect(claims.name).toBe('Alice'); expect(claims.video).toMatchObject({ room: direct.id, roomJoin: true, canPublish: true, canSubscribe: true, }); expect(claims.video?.roomAdmin).toBeUndefined(); // Good for minutes, not hours. const lifetime = (claims.exp ?? 0) - Date.now() / 1000; expect(lifetime).toBeGreaterThan(60); expect(lifetime).toBeLessThanOrEqual(5 * 60); }); it('lets in the members of a group and of a realm', async () => { await carol.agent.post(`/conversations/${group.id}/call`).expect(200); await dave.agent.post(`/conversations/${cauldronId}/call`).expect(200); }); it("answers 404 for a place the user can't read", async () => { await carol.agent.post(`/conversations/${direct.id}/call`).expect(404); await dave.agent.post(`/conversations/${group.id}/call`).expect(404); await bob.agent.post(`/conversations/${cauldronId}/call`).expect(404); await alice.agent.post(`/conversations/${randomUUID()}/call`).expect(404); await alice.agent.post('/conversations/nope/call').expect(400); }); it('asks for a session', async () => { await request(app.getHttpServer()) .post(`/conversations/${direct.id}/call`) .expect(401); await request(app.getHttpServer()).get('/calls').expect(401); }); it('takes the permission to post, in a realm', async () => { const everyone = realm.roles.find((role) => role.isDefault); const role = `/realms/${realm.id}/roles/${everyone?.id}`; await alice.agent .patch(role) .send({ permissions: ['createInvites'] }) .expect(200); await dave.agent.post(`/conversations/${cauldronId}/call`).expect(403); // The owner may do everything. await alice.agent.post(`/conversations/${cauldronId}/call`).expect(200); await alice.agent .patch(role) .send({ permissions: ['createInvites', 'sendMessages'] }) .expect(200); await dave.agent.post(`/conversations/${cauldronId}/call`).expect(200); }); }); describe('reports from the media server', () => { it('refuses what the media server did not sign', async () => { const unsigned = () => request(app.getHttpServer()) .post('/livekit/webhook') .set('Content-Type', 'application/webhook+json'); const body = JSON.stringify({ event: 'participant_joined', room: { name: direct.id }, }); rooms.join(direct.id, alice.id); await unsigned().send(body).expect(401); await unsigned().set('Authorization', 'nonsense').send(body).expect(401); await report('participant_joined', direct.id, { secret: 'someone-elses-secret-0123456789-0123456789', status: 401, }); // Signed, but for a different body. await report('participant_joined', direct.id, { body: '{}', status: 401, }); expect(await callsOf(alice)).toEqual([]); rooms.leave(direct.id, alice.id); }); it('takes no notice of rooms that are not calls of this app', async () => { rooms.join('some-other-room', 'someone'); await report('participant_joined', 'some-other-room'); rooms.leave('some-other-room', 'someone'); // A well-formed id of nothing: nobody to tell, so the room is closed. const nothing = randomUUID(); rooms.join(nothing, alice.id); await report('participant_joined', nothing); expect(await rooms.participants(nothing)).toEqual([]); expect(await callsOf(alice)).toEqual([]); }); }); describe('a call in a direct chat', () => { let startedAt: string; it('starts when the first person joins, and both are told', async () => { const forAlice = nextEvent(aliceSocket, 'call:changed'); const forBob = nextEvent(bobSocket, 'call:changed'); await joins(alice, direct.id); const call = await forBob; expect(call).toEqual({ conversationId: direct.id, realmId: null, participants: [ { id: alice.id, name: 'Alice', username: alice.username, image: null, }, ], startedAt: expect.any(String), }); expect(await forAlice).toEqual(call); startedAt = call.startedAt; expect(await callsOf(alice)).toEqual([call]); expect(await callsOf(bob)).toEqual([call]); // Nobody else hears of it. expect(await callsOf(carol)).toEqual([]); }); it('lists people in the order they joined', async () => { const forAlice = nextEvent(aliceSocket, 'call:changed'); await joins(bob, direct.id); const call = await forAlice; expect(idsIn(call)).toEqual([alice.id, bob.id]); expect(call.startedAt).toBe(startedAt); }); it('says nothing when a report changes nothing', async () => { let events = 0; const count = () => (events += 1); aliceSocket.on('call:changed', count); await report('participant_joined', direct.id); await report('track_published', direct.id); // An event that was sent would have arrived before this answer. await callsOf(alice); aliceSocket.off('call:changed', count); expect(events).toBe(0); }); it('is over when the last person leaves', async () => { const afterAlice = nextEvent(bobSocket, 'call:changed'); await leaves(alice, direct.id); expect(idsIn(await afterAlice)).toEqual([bob.id]); const afterBob = nextEvent(aliceSocket, 'call:changed'); await leaves(bob, direct.id); expect(await afterBob).toEqual({ conversationId: direct.id, realmId: null, participants: [], startedAt, }); expect(await callsOf(alice)).toEqual([]); }); }); describe('a call in a group', () => { it('reaches every member', async () => { const forCarol = nextEvent(carolSocket, 'call:changed'); await joins(alice, group.id); await joins(bob, group.id); expect((await forCarol).conversationId).toBe(group.id); expect(idsIn((await callsOf(carol)).at(0))).toEqual([alice.id, bob.id]); expect(await callsOf(dave)).toEqual([]); }); it('drops someone who is removed from the group', async () => { const forAlice = nextEvent(aliceSocket, 'call:changed'); await alice.agent .delete(`/conversations/${group.id}/members/${bob.id}`) .expect(204); expect(await rooms.participants(group.id)).toEqual([alice.id]); expect(idsIn(await forAlice)).toEqual([alice.id]); // And they can't get back in. await bob.agent.post(`/conversations/${group.id}/call`).expect(404); expect(await callsOf(bob)).toEqual([]); await leaves(alice, group.id); }); }); describe('a call in a cauldron', () => { it("reaches the realm's members", async () => { const forDave = nextEvent(daveSocket, 'call:changed'); await joins(alice, cauldronId); await joins(dave, cauldronId); expect(await forDave).toMatchObject({ conversationId: cauldronId, realmId: realm.id, }); expect(idsIn((await callsOf(dave)).at(0))).toEqual([alice.id, dave.id]); expect(await callsOf(bob)).toEqual([]); }); it('drops someone who leaves the realm', async () => { const forAlice = nextEvent(aliceSocket, 'call:changed'); await dave.agent .delete(`/realms/${realm.id}/members/${dave.id}`) .expect(204); expect(await rooms.participants(cauldronId)).toEqual([alice.id]); expect(idsIn(await forAlice)).toEqual([alice.id]); expect(await callsOf(dave)).toEqual([]); }); it('ends with the cauldron', async () => { const second: { id: string } = ( await alice.agent .post(`/realms/${realm.id}/cauldrons`) .send({ name: 'second' }) .expect(201) ).body; await joins(alice, second.id); expect((await callsOf(alice)).map((call) => call.conversationId)).toEqual( expect.arrayContaining([cauldronId, second.id]), ); await alice.agent .delete(`/realms/${realm.id}/cauldrons/${second.id}`) .expect(204); expect(await rooms.participants(second.id)).toEqual([]); expect(await app.get(CallsStore).get(second.id)).toBeUndefined(); }); it('ends with the realm', async () => { await alice.agent.delete(`/realms/${realm.id}`).expect(204); expect(await rooms.participants(cauldronId)).toEqual([]); expect(await app.get(CallsStore).get(cauldronId)).toBeUndefined(); expect(await callsOf(alice)).toEqual([]); }); }); describe('a friendship that ends', () => { it('ends the call between the two', async () => { await joins(alice, direct.id); await joins(bob, direct.id); const forBob = nextEvent(bobSocket, 'call:changed'); await alice.agent.delete(`/friends/${bob.id}`).expect(204); expect(await rooms.participants(direct.id)).toEqual([]); expect(idsIn(await forBob)).toEqual([]); expect(await callsOf(alice)).toEqual([]); // The chat is still theirs to read, but not to call in. await alice.agent.post(`/conversations/${direct.id}/call`).expect(403); }); }); });