The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.
TypeScript budget-trackercollaborativedockeritinerarymcp-serveroffline-firstopen-sourceopenstreetmappacking-listpwareal-timeself-hostedselfhostedtraveltravel-apptravel-journaltravel-plannertripitwanderlog
fix(realtime): take a socket out of a room once its access ends
Mauriced8be9a40e71a
diff --git a/server/src/nest/auth/user-cleanup.service.ts b/server/src/nest/auth/user-cleanup.service.tsindex f373010fe..6cb4fa2dc 100644--- a/server/src/nest/auth/user-cleanup.service.ts+++ b/server/src/nest/auth/user-cleanup.service.ts@@ -28,6 +28,7 @@ import { BudgetService } from '../budget/budget.service';import { UnitOfWork } from '../database/unit-of-work';import { pluginsDataRoot } from '../plugins/paths';import { enqueueHookUserDataErasures } from '../plugins/user-erasure-enqueue';+import { RealtimeService } from '../realtime/realtime.service';import { StorageReleaseService } from '../storage/storage-release.service';import { InjectRepository } from '@mikro-orm/nestjs';import { Injectable } from '@nestjs/common';@@ -75,6 +76,9 @@ export class UserCleanupService {@InjectRepository(PluginUserErasureQueue)private readonly pluginUserErasureQueueRepo: PluginUserErasureQueueRepository,private readonly release: StorageReleaseService,+ // The sockets of the deleted account; the facade only reaches the process+ // wide socket registry, so a hand-built service can take its own.+ private readonly realtime: RealtimeService = new RealtimeService(),) {}/**@@ -213,5 +217,10 @@ export class UserCleanupService {await this.release.releaseValues([avatar], { bare: 'avatars' });const photoFiles = photos.flatMap((photo) => [photo.file_path, photo.thumbnail_path]);await this.release.releaseValues(photoFiles, { bare: 'journey' });+ // A socket is trusted after its joins, so an account that is gone has its+ // sockets ended, and the books it shared through a trip's journal are+ // asked again for everybody else.+ this.realtime.closeUserSockets(userId);+ await this.realtime.recheckJourneyAccess();}}diff --git a/server/src/nest/journey/journey-domain.service.ts b/server/src/nest/journey/journey-domain.service.tsindex e9fe16db4..2f6c2a347 100644--- a/server/src/nest/journey/journey-domain.service.ts+++ b/server/src/nest/journey/journey-domain.service.ts@@ -370,6 +370,7 @@ export class JourneyDomainService {const photoFiles = photos.flatMap((photo) => [photo.file_path, photo.thumbnail_path]);await this.release.releaseValues(photoFiles, { bare: 'journey' });await this.broadcastJourneyEvent(journeyId, 'journey:deleted', {}, sid, audience);+ await this.realtime.recheckJourneyAccess(journeyId);return true;}@@ -1613,6 +1614,8 @@ export class JourneyDomainService {// The owner, or someone who was never on the journey, leaves nothing to announce.if (removed > 0) {await this.broadcastJourneyEvent(journeyId, 'journey:contributor:changed', { targetUserId, role: null }, undefined, audience);+ // An open book trusts the sockets that joined it; the one taken off may still see it through a trip.+ await this.realtime.recheckJourneyAccess(journeyId);}return true;}diff --git a/server/src/nest/journey/trip-journal-link.service.ts b/server/src/nest/journey/trip-journal-link.service.tsindex c6f26452c..a51e27cf4 100644--- a/server/src/nest/journey/trip-journal-link.service.ts+++ b/server/src/nest/journey/trip-journal-link.service.ts@@ -170,6 +170,8 @@ export class TripJournalLinkService {await this.links.replaceMembers(tripId, allowed, now);});this.realtime.broadcast(tripId, 'trip:journal:changed', {}, socketId);+ // Whoever the link let into a book and no longer does leaves it.+ await this.realtime.recheckJourneyAccess();return this.get(tripId, actor);}@@ -191,6 +193,8 @@ export class TripJournalLinkService {await this.links.replaceMembers(tripId, allowed, Date.now());});this.realtime.broadcast(tripId, 'trip:journal:changed', {}, socketId);+ // Whoever the link let into a book and no longer does leaves it.+ await this.realtime.recheckJourneyAccess();return this.get(tripId, actor);}@@ -204,6 +208,8 @@ export class TripJournalLinkService {}await this.links.deleteForTrip(tripId);this.realtime.broadcast(tripId, 'trip:journal:changed', {}, socketId);+ // Whoever the link let into a book and no longer does leaves it.+ await this.realtime.recheckJourneyAccess();return this.get(tripId, actor);}}diff --git a/server/src/nest/realtime/realtime.gateway.ts b/server/src/nest/realtime/realtime.gateway.tsindex a19468534..d2d83d2c9 100644--- a/server/src/nest/realtime/realtime.gateway.ts+++ b/server/src/nest/realtime/realtime.gateway.ts@@ -11,13 +11,16 @@ import { toRowId } from '../common/row-id';import { TripAccessService } from '../trip-membership/trip-access.service';import { JOURNEY_ACCESS, type JourneyAccess } from './journey-access.types';import {+ announceBookPeers,bookPeers,broadcastToBook,registerSocket,+ roomAccessSlot,RoomRegistry,roomsSlot,socketIdOf,userOf,+ type RoomAccess,type TrekWebSocket,} from './ws-state';import { InjectRepository } from '@mikro-orm/nestjs';@@ -80,7 +83,16 @@ export class RealtimeGateway implements OnGatewayInit, OnGatewayConnection, OnGa// RealtimeGatewayModule also installs for the broadcast functions in// ws-state.ts; a hand-built gateway takes the installed one.private readonly rooms: RoomRegistry = roomsSlot.get(),- ) {}+ ) {+ // The checks a write that ends access asks again (RealtimeService.recheckTripAccess),+ // the same ones a join runs below.+ roomAccessSlot.install(this.access);+ }++ private readonly access: RoomAccess = {+ trip: async (tripId, userId) => !!(await this.trips.findAccessible(tripId, userId)),+ book: async (journeyId, userId) => !!(await this.journeys.canAccessJourney(journeyId, userId)),+ };afterInit(server: WebSocketServer): void {this.heartbeat = setInterval(() => {@@ -97,6 +109,7 @@ export class RealtimeGateway implements OnGatewayInit, OnGatewayConnection, OnGaonModuleDestroy(): void {if (this.heartbeat) clearInterval(this.heartbeat);this.heartbeat = null;+ roomAccessSlot.release(this.access);}/**@@ -287,7 +300,7 @@ export class RealtimeGateway implements OnGatewayInit, OnGatewayConnection, OnGa/** The whole list, to everyone in the book including whoever just changed it. */private announcePeers(journeyId: number): void {- broadcastToBook(journeyId, { type: 'journey:book:peers', peers: bookPeers(journeyId) });+ announceBookPeers(journeyId);}@SubscribeMessage('leave')diff --git a/server/src/nest/realtime/realtime.service.ts b/server/src/nest/realtime/realtime.service.tsindex 48105ec81..2110c950e 100644--- a/server/src/nest/realtime/realtime.service.ts+++ b/server/src/nest/realtime/realtime.service.ts@@ -1,4 +1,11 @@-import { broadcast, broadcastToUser, getOnlineUserIds } from './ws-state';+import {+ broadcast,+ broadcastToUser,+ closeUserSockets,+ getOnlineUserIds,+ recheckJourneyAccess,+ recheckTripAccess,+} from './ws-state';import { Injectable } from '@nestjs/common';import type { TrekWsPayload, TrekWsPluginEventName, TrekWsTripEventName, TrekWsUserEventName } from '@trek/shared';@@ -119,4 +126,26 @@ export class RealtimeService {getOnlineUserIds(): Set<number> {return getOnlineUserIds();}++ /**+ * A socket is let into a trip room once and then trusted, so a write that+ * ends somebody's access to a trip asks the sockets already in again, once+ * it is committed and its own event went out: one user's sockets in one+ * trip (a member removed), everybody in a trip (a trip deleted), or every+ * trip room a user is in. Open books are asked again with it, since a book+ * can be open through a trip's journal.+ */+ recheckTripAccess(scope: { tripId?: number; userId?: number }): Promise<void> {+ return recheckTripAccess(scope);+ }++ /** The same for the people looking at a book (#1973), one book or, without one, every open book. */+ recheckJourneyAccess(journeyId?: number): Promise<void> {+ return recheckJourneyAccess(journeyId);+ }++ /** Ends every socket of an account that was deleted. */+ closeUserSockets(userId: number): void {+ closeUserSockets(userId);+ }}diff --git a/server/src/nest/realtime/ws-state.ts b/server/src/nest/realtime/ws-state.tsindex 35fe5b32c..2f8ce84d4 100644--- a/server/src/nest/realtime/ws-state.ts+++ b/server/src/nest/realtime/ws-state.ts@@ -59,6 +59,10 @@ export abstract class RoomRegistry {abstract leaveBook(ws: TrekWebSocket, journeyId: number): void;/** Every book this socket had open, left in one go. */abstract leaveAllBooks(ws: TrekWebSocket): number[];+ /** The trip rooms this socket is in. */+ abstract tripsOf(ws: TrekWebSocket): number[];+ /** The books this socket has open. */+ abstract booksOf(ws: TrekWebSocket): number[];/** The sockets looking at a book; undefined when nobody is. */abstract bookMembers(journeyId: number): ReadonlySet<TrekWebSocket> | undefined;}@@ -126,6 +130,14 @@ export class InMemoryRoomRegistry extends RoomRegistry {bookMembers(journeyId: number): ReadonlySet<TrekWebSocket> | undefined {return this.bookRooms.get(journeyId);}++ tripsOf(ws: TrekWebSocket): number[] {+ return [...(this.socketRooms.get(ws) ?? [])];+ }++ booksOf(ws: TrekWebSocket): number[] {+ return [...(this.socketBooks.get(ws) ?? [])];+ }}/** The in-memory registry this process starts with, and what RealtimeGatewayModule provides unless overridden. */@@ -290,3 +302,117 @@ export function getOnlineUserIds(): Set<number> {}return ids;}++/**+ * Who may be in a room, asked again after a join. The gateway installs the+ * same checks its joins run (RealtimeGateway), so a second look gives the+ * answer the first one would give now.+ */+export interface RoomAccess {+ trip(tripId: number, userId: number): Promise<boolean>;+ book(journeyId: number, userId: number): Promise<boolean>;+}++/** Without a gateway no socket ever joined a room, so there is nothing to ask. */+export const roomAccessSlot = new ProcessStoreSlot<RoomAccess | null>(null);++/**+ * A room is entered with one access check and then trusted, so when access+ * ends the sockets that are already in have to be asked again (the trip+ * member removed, the contributor taken off a journey). An answer that cannot+ * be had counts as no access: the socket can join again, a leak cannot be+ * taken back.+ */+async function stillAllowed(check: () => Promise<boolean>): Promise<boolean> {+ try {+ return await check();+ } catch {+ return false;+ }+}++function userSockets(userId: number): TrekWebSocket[] {+ if (!wss) return [];+ return [...wss.clients].map((ws) => ws as TrekWebSocket).filter((ws) => socketUser.get(ws)?.id === userId);+}++/**+ * Asks again whether the sockets in a trip room may stay there, for one+ * user's sockets or, without one, for everybody in the room; and with only a+ * user, for every trip room that user's sockets are in. Every open book is+ * asked again after it, since a book can be open through a trip's journal.+ */+export async function recheckTripAccess(scope: { tripId?: number; userId?: number }): Promise<void> {+ const access = roomAccessSlot.get();+ if (!access) return;+ const rooms = roomsSlot.get();+ const checks: Array<{ ws: TrekWebSocket; tripId: number }> = [];+ if (scope.tripId != null) {+ for (const ws of rooms.members(scope.tripId) ?? []) {+ if (scope.userId == null || socketUser.get(ws)?.id === scope.userId) checks.push({ ws, tripId: scope.tripId });+ }+ } else if (scope.userId != null) {+ for (const ws of userSockets(scope.userId)) for (const tripId of rooms.tripsOf(ws)) checks.push({ ws, tripId });+ }+ const allowed = await Promise.all(+ checks.map(({ ws, tripId }) => {+ const user = socketUser.get(ws);+ return user ? stillAllowed(() => access.trip(tripId, user.id)) : false;+ }),+ );+ checks.forEach(({ ws, tripId }, i) => {+ if (!allowed[i]) rooms.leave(ws, tripId);+ });+ await recheckJourneyAccess();+}++/** Tells the people still looking at a book who is there now. */+export function announceBookPeers(journeyId: number): void {+ broadcastToBook(journeyId, { type: 'journey:book:peers', peers: bookPeers(journeyId) });+}++/**+ * Asks again whether the sockets looking at a book may stay, for one book or,+ * without one, for every open book. A book that loses somebody tells the rest.+ */+export async function recheckJourneyAccess(journeyId?: number): Promise<void> {+ const access = roomAccessSlot.get();+ if (!access) return;+ const rooms = roomsSlot.get();+ const checks: Array<{ ws: TrekWebSocket; journeyId: number }> = [];+ const books = journeyId != null ? [journeyId] : openBooks();+ for (const id of books) for (const ws of rooms.bookMembers(id) ?? []) checks.push({ ws, journeyId: id });+ const allowed = await Promise.all(+ checks.map(({ ws, journeyId: id }) => {+ const user = socketUser.get(ws);+ return user ? stillAllowed(() => access.book(id, user.id)) : false;+ }),+ );+ const changed = new Set<number>();+ checks.forEach(({ ws, journeyId: id }, i) => {+ if (allowed[i]) return;+ rooms.leaveBook(ws, id);+ changed.add(id);+ });+ for (const id of changed) announceBookPeers(id);+}++function openBooks(): number[] {+ if (!wss) return [];+ const books = new Set<number>();+ for (const ws of wss.clients) for (const id of roomsSlot.get().booksOf(ws as TrekWebSocket)) books.add(id);+ return [...books];+}++/**+ * Ends every socket of an account that no longer exists. It leaves its rooms+ * at once, before the close handshake, so nothing more reaches it.+ */+export function closeUserSockets(userId: number): void {+ const rooms = roomsSlot.get();+ for (const ws of userSockets(userId)) {+ rooms.leaveAll(ws);+ for (const journeyId of rooms.leaveAllBooks(ws)) announceBookPeers(journeyId);+ ws.close(4001, 'Account deleted');+ }+}diff --git a/server/src/nest/trip-members/trip-member-writes.service.ts b/server/src/nest/trip-members/trip-member-writes.service.tsindex b85bdb87c..15c926645 100644--- a/server/src/nest/trip-members/trip-member-writes.service.ts+++ b/server/src/nest/trip-members/trip-member-writes.service.ts@@ -54,6 +54,9 @@ export class TripMemberWritesService {async removeMember(tripId: number, targetUserId: number, writer: TripWriter): Promise<void> {await this.roster.removeMember(tripId, targetUserId, writer.userId);writer.events.emit('member:removed', { userId: targetUserId });+ // After the event, which tells the one taken off to leave: their sockets+ // already in the trip's room must not keep hearing it.+ await this.realtime.recheckTripAccess({ tripId, userId: targetUserId });}/** A companion without an account. No invitation: a guest has no inbox. */diff --git a/server/src/nest/trips/trip-writes.service.ts b/server/src/nest/trips/trip-writes.service.tsindex e2994293e..66ba3660d 100644--- a/server/src/nest/trips/trip-writes.service.ts+++ b/server/src/nest/trips/trip-writes.service.ts@@ -74,6 +74,7 @@ export class TripWritesService {const cover = ((await this.trips.getRaw(tripId)) as { cover_image?: string | null } | undefined)?.cover_image;const info = await this.trips.remove(tripId, writer.userId, writer.role);writer.events.emit('trip:deleted', { id: info.tripId });+ await this.realtime.recheckTripAccess({ tripId: info.tripId });await this.release.releaseValues([cover]);return info;}diff --git a/server/src/nest/trips/trips.rpc.ts b/server/src/nest/trips/trips.rpc.tsindex 50b34499d..47b23b6f3 100644--- a/server/src/nest/trips/trips.rpc.ts+++ b/server/src/nest/trips/trips.rpc.ts@@ -240,6 +240,7 @@ export class TripsRpc {if (ownerId !== null && ownerId === targetUserId) throw new ForbiddenResource('cannot remove the trip owner');await this.roster.removeMember(tripId, targetUserId, actor);this.realtime.broadcast(tripId, 'member:removed', { userId: targetUserId });+ await this.realtime.recheckTripAccess({ tripId, userId: targetUserId });return { removed: true };}}diff --git a/server/tests/unit/trips/trips.rpc.test.ts b/server/tests/unit/trips/trips.rpc.test.tsindex 28f0b7b7c..c1de0c45d 100644--- a/server/tests/unit/trips/trips.rpc.test.ts+++ b/server/tests/unit/trips/trips.rpc.test.ts@@ -135,7 +135,13 @@ export function build(const permissions = {checkPermission: vi.fn((a: string) => (opts.allow ? opts.allow(a) : true)),} as unknown as PermissionsService;- const realtime = { broadcast: vi.fn() } as unknown as RealtimeService & { broadcast: ReturnType<typeof vi.fn> };+ const realtime = {+ broadcast: vi.fn(),+ recheckTripAccess: vi.fn(async () => undefined),+ } as unknown as RealtimeService & {+ broadcast: ReturnType<typeof vi.fn>;+ recheckTripAccess: ReturnType<typeof vi.fn>;+ };const guards = new PluginGuards(db,permissions,@@ -429,6 +435,8 @@ describe('TripsRpc membership', () => {expect((await f.host().dispatch(req('trips.removeMember', { tripId: 1, userId: 7 }), 42)).ok).toBe(true);expect(f.roster.removeMember).toHaveBeenCalledWith(1, 7, 42);expect(f.realtime.broadcast).toHaveBeenCalledWith(1, 'member:removed', { userId: 7 });+ // The removed member's sockets already in the room are asked again.+ expect(f.realtime.recheckTripAccess).toHaveBeenCalledWith({ tripId: 1, userId: 7 });});it('TRIPS-RPC-018 without member_manage nothing changes', async () => {diff --git a/server/tests/websocket/room-revocation.test.ts b/server/tests/websocket/room-revocation.test.tsnew file mode 100644index 000000000..857ab060c--- /dev/null+++ b/server/tests/websocket/room-revocation.test.ts@@ -0,0 +1,255 @@+/**+ * WS-REVOKE-001 to WS-REVOKE-006: a socket is let into a trip room or a book+ * once, so a write that ends somebody's access asks the sockets already in+ * again. Real server, real `ws` clients, the routes a user calls.+ */+import { buildApp, getHttpServer } from '../../src/bootstrap';+import { createEphemeralToken } from '../../src/nest/auth-core/ephemeral-tokens';+import { RealtimeService } from '../../src/nest/realtime/realtime.service';+import { authCookie } from '../helpers/auth';+import type { FactoryOrm } from '../helpers/factories/context';+import { addJourneyContributor, makeJourney } from '../helpers/factories/journeys';+import { addTripMember, makeTrip } from '../helpers/factories/trips';+import { makeUser } from '../helpers/factories/users';+import { resetDatabase } from '../helpers/reset-database';+import { resetRateLimits } from '../helpers/test-db';+import { MikroORM } from '@mikro-orm/core';+import type { INestApplication } from '@nestjs/common';++import http from 'http';+import request from 'supertest';+import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';+import WebSocket from 'ws';++let server: http.Server;+let wsUrl: string;+let nestApp: INestApplication;+const orm = (): FactoryOrm => nestApp.get(MikroORM);++beforeAll(async () => {+ nestApp = await buildApp();+ server = getHttpServer();+ await new Promise<void>((resolve) => server.listen(0, resolve));+ wsUrl = `ws://127.0.0.1:${(server.address() as { port: number }).port}/ws`;+});++afterAll(async () => {+ await new Promise<void>((resolve, reject) => server.close((err) => (err ? reject(err) : resolve())));+ await nestApp.close();+});++beforeEach(async () => {+ await resetDatabase(orm());+ await resetRateLimits(nestApp);+});++interface Frame {+ type: string;+ [key: string]: unknown;+}++/** A socket of one user that keeps every frame it receives. */+class Client {+ readonly frames: Frame[] = [];+ closeCode: number | null = null;++ constructor(private readonly ws: WebSocket) {+ ws.on('message', (data) => this.frames.push(JSON.parse(data.toString()) as Frame));+ ws.on('close', (code) => {+ this.closeCode = code;+ });+ }++ send(message: object): void {+ this.ws.send(JSON.stringify(message));+ }++ async waitFor(match: (frame: Frame) => boolean, timeoutMs = 3000): Promise<Frame> {+ const end = Date.now() + timeoutMs;+ for (;;) {+ const found = this.frames.find(match);+ if (found) return found;+ if (Date.now() > end) throw new Error(`no matching frame, got ${this.frames.map((f) => f.type).join(', ')}`);+ await new Promise((resolve) => setTimeout(resolve, 20));+ }+ }++ close(): void {+ this.ws.close();+ }+}++async function connect(userId: number): Promise<Client> {+ const token = createEphemeralToken(userId, 'ws');+ if (!token) throw new Error('no ws token');+ const ws = new WebSocket(`${wsUrl}?token=${encodeURIComponent(token)}`);+ const client = new Client(ws);+ await new Promise<void>((resolve, reject) => {+ ws.once('open', () => resolve());+ ws.once('error', reject);+ });+ await client.waitFor((f) => f.type === 'welcome');+ return client;+}++/** Long enough for a broadcast that would arrive to have arrived. */+const settle = () => new Promise((resolve) => setTimeout(resolve, 150));++const realtime = () => nestApp.get(RealtimeService);++describe('a removed trip member', () => {+ it('WS-REVOKE-001 hears the removal and nothing of the trip after it', async () => {+ const { user: owner } = await makeUser(orm());+ const { user: member } = await makeUser(orm());+ const trip = await makeTrip(orm(), owner.id);+ await addTripMember(orm(), trip.id, member.id, owner.id);++ const socket = await connect(member.id);+ socket.send({ type: 'join', tripId: trip.id });+ await socket.waitFor((f) => f.type === 'joined');++ const removed = await request(server)+ .delete(`/api/trips/${trip.id}/members/${member.id}`)+ .set('Cookie', authCookie(owner.id));+ expect(removed.status).toBe(200);+ // The event that tells the client to leave still reaches it.+ await socket.waitFor((f) => f.type === 'member:removed' && f.userId === member.id);++ realtime().broadcast(trip.id, 'place:created', { place: { id: 1, name: 'AFTER-REMOVAL' } });+ await settle();+ expect(socket.frames.some((f) => f.type === 'place:created')).toBe(false);+ socket.close();+ });++ it('WS-REVOKE-002 the owner and the members who stay keep hearing the trip', async () => {+ const { user: owner } = await makeUser(orm());+ const { user: stays } = await makeUser(orm());+ const { user: leaves } = await makeUser(orm());+ const trip = await makeTrip(orm(), owner.id);+ await addTripMember(orm(), trip.id, stays.id, owner.id);+ await addTripMember(orm(), trip.id, leaves.id, owner.id);++ const sockets = await Promise.all([connect(owner.id), connect(stays.id)]);+ for (const s of sockets) {+ s.send({ type: 'join', tripId: trip.id });+ await s.waitFor((f) => f.type === 'joined');+ }++ // The member leaves on their own; the others are not asked to go.+ const left = await request(server)+ .delete(`/api/trips/${trip.id}/members/${leaves.id}`)+ .set('Cookie', authCookie(leaves.id));+ expect(left.status).toBe(200);+ for (const s of sockets) await s.waitFor((f) => f.type === 'member:removed');++ realtime().broadcast(trip.id, 'place:created', { place: { id: 2, name: 'STILL-SHARED' } });+ for (const s of sockets) await s.waitFor((f) => f.type === 'place:created');+ for (const s of sockets) s.close();+ });++ it('WS-REVOKE-003 a deleted trip empties its room', async () => {+ const { user: owner } = await makeUser(orm());+ const { user: member } = await makeUser(orm());+ const trip = await makeTrip(orm(), owner.id);+ await addTripMember(orm(), trip.id, member.id, owner.id);++ const socket = await connect(member.id);+ socket.send({ type: 'join', tripId: trip.id });+ await socket.waitFor((f) => f.type === 'joined');++ const deleted = await request(server).delete(`/api/trips/${trip.id}`).set('Cookie', authCookie(owner.id));+ expect(deleted.status).toBe(200);+ await socket.waitFor((f) => f.type === 'trip:deleted');++ realtime().broadcast(trip.id, 'place:created', { place: { id: 3, name: 'GONE' } });+ await settle();+ expect(socket.frames.some((f) => f.type === 'place:created')).toBe(false);+ socket.close();+ });+});++describe('a removed journey contributor', () => {+ it('WS-REVOKE-004 leaves the book: no pointers either way, and the others see them go', async () => {+ const { user: owner } = await makeUser(orm());+ const { user: editor } = await makeUser(orm());+ const journey = await makeJourney(orm(), owner.id);+ await addJourneyContributor(orm(), journey.id, editor.id, 'editor');++ const ownerSocket = await connect(owner.id);+ const editorSocket = await connect(editor.id);+ ownerSocket.send({ type: 'book:join', journeyId: journey.id });+ await ownerSocket.waitFor((f) => f.type === 'book:joined');+ editorSocket.send({ type: 'book:join', journeyId: journey.id });+ await editorSocket.waitFor((f) => f.type === 'book:joined');+ await ownerSocket.waitFor((f) => f.type === 'journey:book:peers' && (f.peers as unknown[]).length === 2);++ const removed = await request(server)+ .delete(`/api/journeys/${journey.id}/contributors/${editor.id}`)+ .set('Cookie', authCookie(owner.id));+ expect(removed.status).toBe(200);+ await ownerSocket.waitFor(+ (f) =>+ f.type === 'journey:book:peers' &&+ (f.peers as Array<{ userId: number }>).every((peer) => peer.userId !== editor.id),+ );++ editorSocket.frames.length = 0;+ ownerSocket.frames.length = 0;+ ownerSocket.send({ type: 'book:cursor', journeyId: journey.id, spreadIndex: 0, x: 10, y: 10 });+ editorSocket.send({ type: 'book:cursor', journeyId: journey.id, spreadIndex: 0, x: 20, y: 20 });+ await settle();+ expect(editorSocket.frames.some((f) => f.type === 'journey:book:cursor')).toBe(false);+ expect(ownerSocket.frames.some((f) => f.type === 'journey:book:cursor')).toBe(false);+ ownerSocket.close();+ editorSocket.close();+ });++ it('WS-REVOKE-005 a contributor who stays keeps exchanging pointers with the owner', async () => {+ const { user: owner } = await makeUser(orm());+ const { user: stays } = await makeUser(orm());+ const { user: removed } = await makeUser(orm());+ const journey = await makeJourney(orm(), owner.id);+ await addJourneyContributor(orm(), journey.id, stays.id, 'editor');+ await addJourneyContributor(orm(), journey.id, removed.id, 'viewer');++ const ownerSocket = await connect(owner.id);+ const staysSocket = await connect(stays.id);+ for (const s of [ownerSocket, staysSocket]) {+ s.send({ type: 'book:join', journeyId: journey.id });+ await s.waitFor((f) => f.type === 'book:joined');+ }++ const res = await request(server)+ .delete(`/api/journeys/${journey.id}/contributors/${removed.id}`)+ .set('Cookie', authCookie(owner.id));+ expect(res.status).toBe(200);++ ownerSocket.send({ type: 'book:cursor', journeyId: journey.id, spreadIndex: 1, x: 5, y: 5 });+ const cursor = await staysSocket.waitFor((f) => f.type === 'journey:book:cursor');+ expect(cursor.userId).toBe(owner.id);+ ownerSocket.close();+ staysSocket.close();+ });+});++describe('a deleted account', () => {+ it('WS-REVOKE-006 has its sockets closed and out of every room', async () => {+ const { user: owner } = await makeUser(orm());+ const { user: member } = await makeUser(orm());+ const trip = await makeTrip(orm(), owner.id);+ await addTripMember(orm(), trip.id, member.id, owner.id);+ const { user: admin } = await makeUser(orm(), { role: 'admin' });++ const socket = await connect(member.id);+ socket.send({ type: 'join', tripId: trip.id });+ await socket.waitFor((f) => f.type === 'joined');++ const deleted = await request(server).delete(`/api/admin/users/${member.id}`).set('Cookie', authCookie(admin.id));+ expect(deleted.status).toBe(200);++ realtime().broadcast(trip.id, 'place:created', { place: { id: 4, name: 'AFTER-DELETE' } });+ await settle();+ expect(socket.frames.some((f) => f.type === 'place:created')).toBe(false);+ expect(socket.closeCode).toBe(4001);+ });+});