fix(realtime): take a socket out of a room once its access ends

A socket was let into a trip room or a journey's book room with one access
check and then trusted: delivery went by room membership alone. So a member
removed from a trip kept receiving every broadcast of it on the socket they
had already joined, a contributor taken off a journey kept the book's
pointers and presence and could still send pointers, and a deleted account's
sockets stayed in every room.

The gateway now installs the checks its joins run, and every write that ends
access asks the sockets already in again once it is committed and its own
event went out: a member removed or leaving (REST, MCP and plugin RPC), a
trip deleted, a contributor removed, a journey deleted, a trip's journal
link replaced, narrowed or removed. Open books are asked again with every
trip change, since a book can be open through a trip's journal. A socket
that no longer passes leaves the room, and a book that loses somebody tells
the others. A deleted account's sockets are closed. An answer that cannot be
had counts as no access.
This commit is contained in:
Maurice
2026-11-27 21:29:34 +01:00
parent 512584b4f1
commit d8be9a40e7
11 changed files with 458 additions and 4 deletions
@@ -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();
}
}
@@ -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;
}
@@ -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);
}
}
+15 -2
View File
@@ -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, OnGa
onModuleDestroy(): 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')
+30 -1
View File
@@ -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);
}
}
+126
View File
@@ -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');
}
}
@@ -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. */
@@ -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;
}
+1
View File
@@ -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 };
}
}