Skip to content

armgit / TREK

Public Imported from GitHub
0

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.

fix(realtime): end a socket with its session and after a database swap

Maurice1fb20a542c22
diff --git a/server/src/nest/auth/user-cleanup.service.ts b/server/src/nest/auth/user-cleanup.service.ts
index 6cb4fa2dc..41d885362 100644
--- a/server/src/nest/auth/user-cleanup.service.ts
+++ b/server/src/nest/auth/user-cleanup.service.ts
@@ -220,7 +220,7 @@ export class UserCleanupService {
// 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);
+ this.realtime.closeUserSockets(userId, 'Account deleted');
await this.realtime.recheckJourneyAccess();
}
}
diff --git a/server/src/nest/journey/journey-domain.service.ts b/server/src/nest/journey/journey-domain.service.ts
index 2f6c2a347..8225ac75d 100644
--- a/server/src/nest/journey/journey-domain.service.ts
+++ b/server/src/nest/journey/journey-domain.service.ts
@@ -1607,14 +1607,11 @@ export class JourneyDomainService {
if (!(await this.isOwner(journeyId, userId))) return false;
// Read first, so the one taken off hears it too and leaves the journey.
const audience = await this.journeysRepo.listRecipientUserIds(journeyId);
- // JG119 — R5: the owner-protection guard stays INSIDE the repository's
- // own statement (`deleteNonOwner`'s `role != 'owner'` condition, Task
- // 1's build), never split into a find-then-conditional-delete.
+ // JG119 R5: the owner guard stays inside `deleteNonOwner`'s own statement, never a find-then-delete.
const removed = await this.contributorsRepo.deleteNonOwner(journeyId, targetUserId);
// 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/realtime/realtime-gateway.module.ts b/server/src/nest/realtime/realtime-gateway.module.ts
index 8cde00ac8..1b5eeee9b 100644
--- a/server/src/nest/realtime/realtime-gateway.module.ts
+++ b/server/src/nest/realtime/realtime-gateway.module.ts
@@ -2,9 +2,11 @@ import { AppSettings } from '../../db/entities/AppSettings.entity';
import { Trips } from '../../db/entities/Trips.entity';
import { Users } from '../../db/entities/Users.entity';
import { EphemeralTokenModule } from '../auth-core/ephemeral-token.module';
+import { DatabaseLifecycleModule } from '../database/database-lifecycle.module';
+import { DatabaseLifecycle } from '../database/database-lifecycle.service';
import { TripMembershipModule } from '../trip-membership/trip-membership.module';
import { RealtimeGateway } from './realtime.gateway';
-import { processRooms, RoomRegistry, roomsSlot } from './ws-state';
+import { closeSockets, processRooms, RoomRegistry, roomsSlot } from './ws-state';
import { MikroOrmModule } from '@mikro-orm/nestjs';
import { Module, type OnModuleDestroy } from '@nestjs/common';
@@ -29,15 +31,30 @@ import { Module, type OnModuleDestroy } from '@nestjs/common';
// DatabaseService onto UsersRepository/AppSettingsRepository. Trips: Plan 4
// Task 2 — handleJoin's own canAccessTrip delegate, now TripsRepository
// directly.
- imports: [TripMembershipModule, EphemeralTokenModule, MikroOrmModule.forFeature([Users, AppSettings, Trips])],
+ imports: [
+ TripMembershipModule,
+ EphemeralTokenModule,
+ DatabaseLifecycleModule,
+ MikroOrmModule.forFeature([Users, AppSettings, Trips]),
+ ],
// The room registry is the process-wide in-memory one; the constructor
// below hands whichever one the container resolved to the broadcast
// functions, so the gateway and the broadcasts never use two registries.
providers: [RealtimeGateway, { provide: RoomRegistry, useValue: processRooms }],
})
export class RealtimeGatewayModule implements OnModuleDestroy {
- constructor(private readonly rooms: RoomRegistry) {
+ constructor(
+ private readonly rooms: RoomRegistry,
+ lifecycle: DatabaseLifecycle,
+ ) {
roomsSlot.install(rooms);
+ // A restore or the demo reset puts another database in place, so every
+ // room may now hold sockets of people who cannot see it (and on SQLite a
+ // restored id can name another trip). Every socket starts again.
+ lifecycle.onReopened(() => {
+ closeSockets(1012, 'Database replaced');
+ return Promise.resolve();
+ });
}
onModuleDestroy(): void {
diff --git a/server/src/nest/realtime/realtime.gateway.ts b/server/src/nest/realtime/realtime.gateway.ts
index d2d83d2c9..256a2eb97 100644
--- a/server/src/nest/realtime/realtime.gateway.ts
+++ b/server/src/nest/realtime/realtime.gateway.ts
@@ -207,10 +207,16 @@ export class RealtimeGateway implements OnGatewayInit, OnGatewayConnection, OnGa
// so this guard is defence in depth, not the only fix. toRowId, not
// Number(): '0x1' or '1e0' joined trip 1's room.
const tripId = toRowId(message.tripId);
- if (tripId === null || !(await this.trips.findAccessible(tripId, user.id))) {
+ if (tripId === null || !(await this.access.trip(tripId, user.id))) {
return { type: 'error', message: 'Access denied' };
}
this.rooms.join(socket, tripId);
+ // Asked once more from inside the room: a removal that committed while the
+ // first answer was on its way asked the room before this socket was in it.
+ if (!(await this.access.trip(tripId, user.id))) {
+ this.rooms.leave(socket, tripId);
+ return { type: 'error', message: 'Access denied' };
+ }
return { type: 'joined', tripId };
}
@@ -231,11 +237,16 @@ export class RealtimeGateway implements OnGatewayInit, OnGatewayConnection, OnGa
if (!user || !message?.journeyId) return undefined;
const journeyId = toRowId(message.journeyId);
- if (journeyId === null || !(await this.journeys.canAccessJourney(journeyId, user.id))) {
+ if (journeyId === null || !(await this.access.book(journeyId, user.id))) {
return { type: 'error', message: 'Access denied' };
}
this.rooms.joinBook(socket, journeyId);
+ // Asked once more from inside the book, for the same reason as a trip join.
+ if (!(await this.access.book(journeyId, user.id))) {
+ this.rooms.leaveBook(socket, journeyId);
+ return { type: 'error', message: 'Access denied' };
+ }
this.announcePeers(journeyId);
return { type: 'book:joined', journeyId };
}
diff --git a/server/src/nest/realtime/realtime.service.ts b/server/src/nest/realtime/realtime.service.ts
index 2110c950e..6ee2c1d05 100644
--- a/server/src/nest/realtime/realtime.service.ts
+++ b/server/src/nest/realtime/realtime.service.ts
@@ -1,7 +1,7 @@
import {
broadcast,
broadcastToUser,
- closeUserSockets,
+ closeSockets,
getOnlineUserIds,
recheckJourneyAccess,
recheckTripAccess,
@@ -130,12 +130,11 @@ export class RealtimeService {
/**
* 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.
+ * it is committed and its own event went out: one user's sockets (a member
+ * removed) or everybody's (a trip deleted). 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> {
+ recheckTripAccess(scope: { tripId: number; userId?: number }): Promise<void> {
return recheckTripAccess(scope);
}
@@ -144,8 +143,13 @@ export class RealtimeService {
return recheckJourneyAccess(journeyId);
}
- /** Ends every socket of an account that was deleted. */
- closeUserSockets(userId: number): void {
- closeUserSockets(userId);
+ /**
+ * Ends every socket of an account whose sessions ended or that was deleted.
+ * A socket outlives the session it was opened with, so a stolen one would
+ * otherwise keep hearing every room; a device whose session still holds
+ * connects again on its own.
+ */
+ closeUserSockets(userId: number, reason: string): void {
+ closeSockets(4001, reason, userId);
}
}
diff --git a/server/src/nest/realtime/ws-state.ts b/server/src/nest/realtime/ws-state.ts
index 2f8ce84d4..f77a26be7 100644
--- a/server/src/nest/realtime/ws-state.ts
+++ b/server/src/nest/realtime/ws-state.ts
@@ -59,8 +59,6 @@ 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. */
@@ -131,10 +129,6 @@ export class InMemoryRoomRegistry extends RoomRegistry {
return this.bookRooms.get(journeyId);
}
- tripsOf(ws: TrekWebSocket): number[] {
- return [...(this.socketRooms.get(ws) ?? [])];
- }
-
booksOf(ws: TrekWebSocket): number[] {
return [...(this.socketBooks.get(ws) ?? [])];
}
@@ -331,38 +325,45 @@ async function stillAllowed(check: () => Promise<boolean>): Promise<boolean> {
}
}
-function userSockets(userId: number): TrekWebSocket[] {
- if (!wss) return [];
- return [...wss.clients].map((ws) => ws as TrekWebSocket).filter((ws) => socketUser.get(ws)?.id === userId);
+/** Every socket that is open in this process. */
+function openSockets(): TrekWebSocket[] {
+ return wss ? [...wss.clients].map((ws) => ws as TrekWebSocket) : [];
}
-/**
- * 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 });
- }
+/** The rooms a socket stays in only as long as its user may: one check per room it holds. */
+async function keepAllowed(
+ checks: Array<{ ws: TrekWebSocket; id: number }>,
+ ask: (id: number, userId: number) => Promise<boolean>,
+ leave: (ws: TrekWebSocket, id: number) => void,
+): Promise<Set<number>> {
const allowed = await Promise.all(
- checks.map(({ ws, tripId }) => {
+ checks.map(({ ws, id }) => {
const user = socketUser.get(ws);
- return user ? stillAllowed(() => access.trip(tripId, user.id)) : false;
+ return user ? stillAllowed(() => ask(id, user.id)) : false;
}),
);
- checks.forEach(({ ws, tripId }, i) => {
- if (!allowed[i]) rooms.leave(ws, tripId);
+ const left = new Set<number>();
+ checks.forEach(({ ws, id }, i) => {
+ if (allowed[i]) return;
+ leave(ws, id);
+ left.add(id);
});
+ return left;
+}
+
+/**
+ * Asks again whether the sockets in a trip room may stay there, one user's
+ * or, without one, everybody's. 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 = [...(rooms.members(scope.tripId) ?? [])]
+ .filter((ws) => scope.userId == null || socketUser.get(ws)?.id === scope.userId)
+ .map((ws) => ({ ws, id: scope.tripId }));
+ await keepAllowed(checks, access.trip, (ws, id) => rooms.leave(ws, id));
await recheckJourneyAccess();
}
@@ -379,40 +380,25 @@ 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];
+ const books = journeyId != null ? [journeyId] : [...new Set(openSockets().flatMap((ws) => rooms.booksOf(ws)))];
+ const checks = books.flatMap((id) => [...(rooms.bookMembers(id) ?? [])].map((ws) => ({ ws, id })));
+ const left = await keepAllowed(checks, access.book, (ws, id) => rooms.leaveBook(ws, id));
+ for (const id of left) announceBookPeers(id);
}
/**
- * 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.
+ * Ends sockets that may not go on as they were opened: every socket of an
+ * account whose sessions ended or that was deleted, or every socket at all
+ * once the database was replaced. They leave their rooms at once, before the
+ * close handshake, so nothing more reaches them; a client whose session still
+ * holds connects again and joins what it may.
*/
-export function closeUserSockets(userId: number): void {
+export function closeSockets(code: number, reason: string, userId?: number): void {
const rooms = roomsSlot.get();
- for (const ws of userSockets(userId)) {
+ for (const ws of openSockets()) {
+ if (userId != null && socketUser.get(ws)?.id !== userId) continue;
rooms.leaveAll(ws);
- for (const journeyId of rooms.leaveAllBooks(ws)) announceBookPeers(journeyId);
- ws.close(4001, 'Account deleted');
+ for (const id of rooms.leaveAllBooks(ws)) announceBookPeers(id);
+ ws.close(code, reason);
}
}
diff --git a/server/src/nest/sessions/sessions.service.ts b/server/src/nest/sessions/sessions.service.ts
index 1b32cf1dd..5940c25fb 100644
--- a/server/src/nest/sessions/sessions.service.ts
+++ b/server/src/nest/sessions/sessions.service.ts
@@ -2,6 +2,7 @@ import { JWT_SECRET, SESSION_DURATION_SECONDS, SESSION_DURATION_REMEMBER_SECONDS
import { UserSessions } from '../../db/entities/UserSessions.entity';
import type { UserSessionsRepository } from '../../db/repositories/UserSessions.repository';
import { dbNow } from '../../db/types';
+import { RealtimeService } from '../realtime/realtime.service';
import { InjectRepository } from '@mikro-orm/nestjs';
import { Injectable } from '@nestjs/common';
import type { UserSession } from '@trek/shared';
@@ -67,7 +68,13 @@ export function sessionClientFrom(req: Pick<Request, 'headers'>): SessionClient
*/
@Injectable()
export class SessionsService {
- constructor(@InjectRepository(UserSessions) private readonly sessions: UserSessionsRepository) {}
+ constructor(
+ @InjectRepository(UserSessions) private readonly sessions: UserSessionsRepository,
+ // An open WebSocket outlives the session it was opened with; ending the
+ // session ends the user's sockets too. The facade only reaches the process
+ // wide socket registry, so a hand-built service can take its own.
+ private readonly realtime: RealtimeService = new RealtimeService(),
+ ) {}
/**
* Mint a session token for the user and record its session.
@@ -181,7 +188,9 @@ export class SessionsService {
/** End one of the user's sessions. False when the user has no active session by that id. */
async revoke(userId: number, sessionId: string): Promise<boolean> {
- return this.sessions.revokeForUser(sessionId, userId, dbNow());
+ const revoked = await this.sessions.revokeForUser(sessionId, userId, dbNow());
+ if (revoked) this.realtime.closeUserSockets(userId, 'Session ended');
+ return revoked;
}
/**
@@ -199,7 +208,9 @@ export class SessionsService {
* password change revokes the sessions with the password write).
*/
async revokeAll(userId: number, exceptId?: string): Promise<number> {
- return this.sessions.revokeAllForUser(userId, dbNow(), exceptId);
+ const revoked = await this.sessions.revokeAllForUser(userId, dbNow(), exceptId);
+ if (revoked > 0) this.realtime.closeUserSockets(userId, 'Session ended');
+ return revoked;
}
/**
diff --git a/server/tests/unit/nest/process-state-ports.test.ts b/server/tests/unit/nest/process-state-ports.test.ts
index abf2bc02a..5cd591b83 100644
--- a/server/tests/unit/nest/process-state-ports.test.ts
+++ b/server/tests/unit/nest/process-state-ports.test.ts
@@ -14,6 +14,7 @@ import { ProcessStoreSlot } from '../../../src/nest/common/process-store-slot';
import { RateLimitModule } from '../../../src/nest/common/rate-limit.module';
import { RateLimitService } from '../../../src/nest/common/rate-limit.service';
import { InMemoryRateLimitStore, RateLimitStore } from '../../../src/nest/common/rate-limit.store';
+import type { DatabaseLifecycle } from '../../../src/nest/database/database-lifecycle.service';
import { OauthModule } from '../../../src/nest/oauth/oauth.module';
import {
InMemoryPendingCodeStore,
@@ -313,7 +314,7 @@ describe('the WebSocket rooms', () => {
const bookMembers = vi.spyOn(fake, 'bookMembers');
const send = vi.fn();
const live = { readyState: 1, send } as unknown as TrekWebSocket;
- const gatewayModule = new RealtimeGatewayModule(fake);
+ const gatewayModule = new RealtimeGatewayModule(fake, { onReopened: vi.fn() } as unknown as DatabaseLifecycle);
try {
expect(roomsSlot.get()).toBe(fake);
fake.register(live);
diff --git a/server/tests/unit/nest/realtime.revocation.test.ts b/server/tests/unit/nest/realtime.revocation.test.ts
new file mode 100644
index 000000000..b95bd4282
--- /dev/null
+++ b/server/tests/unit/nest/realtime.revocation.test.ts
@@ -0,0 +1,283 @@
+/**
+ * WSREV-001 to WSREV-012: a socket is let into a room with one access check,
+ * so the writes that end access ask the sockets already in again
+ * (recheckTripAccess, recheckJourneyAccess), and the sockets of a user whose
+ * sessions ended, or of every user once the database was replaced, are
+ * closed (closeSockets). The end-to-end side is tests/websocket/room-revocation.test.ts.
+ */
+import type { AppSettingsRepository } from '../../../src/db/repositories/AppSettings.repository';
+import type { UsersRepository } from '../../../src/db/repositories/Users.repository';
+import type { EphemeralTokenService } from '../../../src/nest/auth-core/ephemeral-token.service';
+import type { DatabaseLifecycle } from '../../../src/nest/database/database-lifecycle.service';
+import { RealtimeGatewayModule } from '../../../src/nest/realtime/realtime-gateway.module';
+import { RealtimeGateway } from '../../../src/nest/realtime/realtime.gateway';
+import { RealtimeService } from '../../../src/nest/realtime/realtime.service';
+import {
+ bookPeers,
+ closeSockets,
+ InMemoryRoomRegistry,
+ recheckJourneyAccess,
+ recheckTripAccess,
+ registerSocket,
+ roomAccessSlot,
+ roomsSlot,
+ setServer,
+ type RoomAccess,
+ type TrekWebSocket,
+} from '../../../src/nest/realtime/ws-state';
+import type { TripAccessService } from '../../../src/nest/trip-membership/trip-access.service';
+import type { User } from '../../../src/types';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('../../../src/plugin-event-sink', () => ({ emitPluginEvent: vi.fn(), pluginEventMeta: vi.fn(() => ({})) }));
+
+interface FakeSocket extends TrekWebSocket {
+ sent: Array<Record<string, unknown>>;
+ closedWith: [number, string] | null;
+}
+
+function socket(): FakeSocket {
+ const s = {
+ readyState: 1,
+ sent: [] as Array<Record<string, unknown>>,
+ closedWith: null as [number, string] | null,
+ send: (raw: string) => s.sent.push(JSON.parse(raw) as Record<string, unknown>),
+ close: (code: number, reason: string) => {
+ s.closedWith = [code, reason];
+ },
+ };
+ return s as unknown as FakeSocket;
+}
+
+let rooms: InMemoryRoomRegistry;
+let clients: Set<FakeSocket>;
+
+/** A socket of the user, open and registered, as the handshake leaves it. */
+function open(userId: number): FakeSocket {
+ const ws = socket();
+ registerSocket(ws, { id: userId, username: `u${userId}` } as User);
+ clients.add(ws);
+ return ws;
+}
+
+/** Who may be where: trip and book ids per user. */
+function access(trips: Record<number, number[]>, books: Record<number, number[]> = {}): RoomAccess {
+ return {
+ trip: vi.fn(async (tripId: number, userId: number) => (trips[userId] ?? []).includes(tripId)),
+ book: vi.fn(async (journeyId: number, userId: number) => (books[userId] ?? []).includes(journeyId)),
+ };
+}
+
+beforeEach(() => {
+ rooms = new InMemoryRoomRegistry();
+ roomsSlot.install(rooms);
+ clients = new Set();
+ setServer({ clients } as never);
+});
+
+afterEach(() => {
+ roomsSlot.release(rooms);
+ roomAccessSlot.install(null);
+ setServer(null);
+});
+
+describe('recheckTripAccess', () => {
+ it('WSREV-001: does nothing before a gateway installed the checks', async () => {
+ const ws = open(1);
+ rooms.join(ws, 5);
+ await recheckTripAccess({ tripId: 5 });
+ expect(rooms.members(5)?.has(ws)).toBe(true);
+ });
+
+ it('WSREV-002: takes out the one user that lost the trip and leaves their other sockets elsewhere alone', async () => {
+ const gone = open(1);
+ const stays = open(2);
+ const other = open(1);
+ rooms.join(gone, 5);
+ rooms.join(stays, 5);
+ rooms.join(other, 6);
+ const checks = access({ 1: [6], 2: [5] });
+ roomAccessSlot.install(checks);
+
+ await recheckTripAccess({ tripId: 5, userId: 1 });
+
+ expect([...(rooms.members(5) ?? [])]).toEqual([stays]);
+ expect(rooms.members(6)?.has(other)).toBe(true);
+ // Only the named user was asked.
+ expect(checks.trip).toHaveBeenCalledTimes(1);
+ });
+
+ it('WSREV-003: without a user it asks everybody in the room, and empties a deleted trip', async () => {
+ const a = open(1);
+ const b = open(2);
+ rooms.join(a, 5);
+ rooms.join(b, 5);
+ roomAccessSlot.install(access({}));
+
+ await recheckTripAccess({ tripId: 5 });
+
+ expect(rooms.members(5)).toBeUndefined();
+ });
+
+ it('WSREV-004: a check that fails counts as no access', async () => {
+ const ws = open(1);
+ rooms.join(ws, 5);
+ roomAccessSlot.install({ trip: vi.fn().mockRejectedValue(new Error('db down')), book: vi.fn() });
+
+ await recheckTripAccess({ tripId: 5 });
+
+ expect(rooms.members(5)).toBeUndefined();
+ });
+
+ it('WSREV-005: a socket in a room without a user is taken out', async () => {
+ const stray = socket();
+ rooms.register(stray);
+ rooms.join(stray, 5);
+ roomAccessSlot.install(access({}));
+
+ await recheckTripAccess({ tripId: 5 });
+
+ expect(rooms.members(5)).toBeUndefined();
+ });
+
+ it('WSREV-006: asks every open book again, since a book can be open through the trip', async () => {
+ const ws = open(1);
+ rooms.joinBook(ws, 9);
+ roomAccessSlot.install(access({}, {}));
+
+ await recheckTripAccess({ tripId: 5 });
+
+ expect(rooms.bookMembers(9)).toBeUndefined();
+ });
+
+ it('WSREV-007: an empty room asks nobody', async () => {
+ const checks = access({});
+ roomAccessSlot.install(checks);
+ await recheckTripAccess({ tripId: 5 });
+ expect(checks.trip).not.toHaveBeenCalled();
+ });
+});
+
+describe('recheckJourneyAccess', () => {
+ it('WSREV-008: does nothing before a gateway installed the checks', async () => {
+ const ws = open(1);
+ rooms.joinBook(ws, 9);
+ await recheckJourneyAccess(9);
+ expect(rooms.bookMembers(9)?.has(ws)).toBe(true);
+ });
+
+ it('WSREV-009: takes out whoever lost the book and tells the ones who stay', async () => {
+ const gone = open(1);
+ const stays = open(2);
+ rooms.joinBook(gone, 9);
+ rooms.joinBook(stays, 9);
+ roomAccessSlot.install(access({}, { 2: [9] }));
+
+ await recheckJourneyAccess(9);
+
+ expect(bookPeers(9).map((p) => p.userId)).toEqual([2]);
+ expect(stays.sent).toContainEqual(
+ expect.objectContaining({
+ type: 'journey:book:peers',
+ journeyId: 9,
+ peers: [expect.objectContaining({ userId: 2 })],
+ }),
+ );
+ expect(gone.sent).toEqual([]);
+ });
+
+ it('WSREV-010: without a book it asks every open book; a book nobody lost says nothing', async () => {
+ const a = open(1);
+ const b = open(2);
+ rooms.joinBook(a, 9);
+ rooms.joinBook(b, 10);
+ roomAccessSlot.install(access({}, { 1: [9] }));
+
+ await recheckJourneyAccess();
+
+ expect(rooms.bookMembers(9)?.has(a)).toBe(true);
+ expect(rooms.bookMembers(10)).toBeUndefined();
+ expect(a.sent).toEqual([]);
+ });
+});
+
+describe('closeSockets', () => {
+ it('WSREV-011: closes one user’s sockets, out of every room first, and tells their books', async () => {
+ const mine = open(1);
+ const theirs = open(2);
+ rooms.join(mine, 5);
+ rooms.joinBook(mine, 9);
+ rooms.joinBook(theirs, 9);
+
+ new RealtimeService().closeUserSockets(1, 'Session ended');
+
+ expect(mine.closedWith).toEqual([4001, 'Session ended']);
+ expect(theirs.closedWith).toBeNull();
+ expect(rooms.members(5)).toBeUndefined();
+ expect(bookPeers(9).map((p) => p.userId)).toEqual([2]);
+ expect(theirs.sent).toContainEqual(expect.objectContaining({ type: 'journey:book:peers' }));
+ });
+
+ it('WSREV-012: without a user closes every socket, which a replaced database asks for', async () => {
+ const a = open(1);
+ const b = open(2);
+ closeSockets(1012, 'Database replaced');
+ expect([a.closedWith, b.closedWith]).toEqual([
+ [1012, 'Database replaced'],
+ [1012, 'Database replaced'],
+ ]);
+ });
+
+ it('WSREV-013: the gateway module closes every socket after the database is reopened', async () => {
+ const listeners: Array<() => Promise<void>> = [];
+ const lifecycle = { onReopened: (listener: () => Promise<void>) => listeners.push(listener) };
+ const module = new RealtimeGatewayModule(rooms, lifecycle as unknown as DatabaseLifecycle);
+ const ws = open(1);
+
+ await Promise.all(listeners.map((listener) => listener()));
+
+ expect(ws.closedWith).toEqual([1012, 'Database replaced']);
+ module.onModuleDestroy();
+ });
+
+ it('WSREV-014: the facade asks the trip rooms and the books again', async () => {
+ const ws = open(1);
+ rooms.join(ws, 5);
+ rooms.joinBook(ws, 9);
+ roomAccessSlot.install(access({}, {}));
+ const facade = new RealtimeService();
+
+ await facade.recheckJourneyAccess(9);
+ expect(rooms.bookMembers(9)).toBeUndefined();
+ await facade.recheckTripAccess({ tripId: 5, userId: 1 });
+ expect(rooms.members(5)).toBeUndefined();
+ });
+});
+
+describe('the gateway asks again from inside the room', () => {
+ const tokens = { consumeWithMeta: vi.fn() } as unknown as EphemeralTokenService;
+ const users = {} as UsersRepository;
+ const appSettings = {} as AppSettingsRepository;
+
+ it('WSREV-015: a trip join whose access ended while the first answer was on its way is refused', async () => {
+ const findAccessible = vi.fn().mockResolvedValueOnce({ id: 5 }).mockResolvedValueOnce(undefined);
+ const trips = { findAccessible } as unknown as TripAccessService;
+ const gw = new RealtimeGateway(trips, tokens, { canAccessJourney: vi.fn() }, users, appSettings, rooms);
+ const ws = open(1);
+
+ expect(await gw.handleJoin({ tripId: 5 }, ws)).toEqual({ type: 'error', message: 'Access denied' });
+ expect(rooms.members(5)).toBeUndefined();
+ });
+
+ it('WSREV-016: so is a book join', async () => {
+ const canAccessJourney = vi.fn().mockResolvedValueOnce({ id: 9 }).mockResolvedValueOnce(null);
+ const trips = { findAccessible: vi.fn() } as unknown as TripAccessService;
+ const gw = new RealtimeGateway(trips, tokens, { canAccessJourney }, users, appSettings, rooms);
+ const ws = open(1);
+
+ expect(await gw.handleBookJoin({ journeyId: 9 }, ws)).toEqual({ type: 'error', message: 'Access denied' });
+ expect(rooms.bookMembers(9)).toBeUndefined();
+ gw.onModuleDestroy();
+ });
+});
diff --git a/server/tests/unit/nest/sessions/sessions.service.test.ts b/server/tests/unit/nest/sessions/sessions.service.test.ts
index 62b2be667..8b34572f6 100644
--- a/server/tests/unit/nest/sessions/sessions.service.test.ts
+++ b/server/tests/unit/nest/sessions/sessions.service.test.ts
@@ -2,6 +2,7 @@ import { JWT_SECRET, SESSION_DURATION_REMEMBER_SECONDS, SESSION_DURATION_SECONDS
import { UserSessions } from '../../../../src/db/entities/UserSessions.entity';
import { Users } from '../../../../src/db/entities/Users.entity';
import { verifyJwtAndLoadUser } from '../../../../src/nest/auth-core/jwt-verify';
+import { RealtimeService } from '../../../../src/nest/realtime/realtime.service';
import {
SessionsService,
USER_AGENT_MAX_LENGTH,
@@ -297,6 +298,24 @@ describe('SessionsService list and revoke', () => {
expect(await svc.revokeAll(user.id)).toBe(1);
});
+ it('SESS-019: ending sessions ends the user’s open sockets too, and nothing when no session ended', async () => {
+ const close = vi.spyOn(RealtimeService.prototype, 'closeUserSockets').mockImplementation(() => undefined);
+ const { user } = createUser(testDb);
+ const a = claimsOf(await svc.issue({ id: user.id, pv: 0 }));
+ const b = claimsOf(await svc.issue({ id: user.id, pv: 0 }));
+
+ expect(await svc.revoke(user.id, a.jti)).toBe(true);
+ expect(close).toHaveBeenLastCalledWith(user.id, 'Session ended');
+ expect(await svc.revokeAll(user.id)).toBe(1);
+ expect(close).toHaveBeenCalledTimes(2);
+
+ // Nothing left to end: the sockets stay.
+ expect(await svc.revoke(user.id, b.jti)).toBe(false);
+ expect(await svc.revokeAll(user.id)).toBe(0);
+ expect(close).toHaveBeenCalledTimes(2);
+ close.mockRestore();
+ });
+
it('SESS-010: endSession ends the session a token names, and nothing for an untracked or missing token', async () => {
const { user } = createUser(testDb);
const mine = claimsOf(await svc.issue({ id: user.id, pv: 0 }));