mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-28 23:50:08 +00:00
fix(realtime): refuse a ws token of a session whose sockets were just closed
A token minted shortly before its session ended could still open a socket within its 30 seconds, and no later close would reach it.
This commit is contained in:
@@ -18,6 +18,7 @@ import {
|
||||
roomAccessSlot,
|
||||
RoomRegistry,
|
||||
roomsSlot,
|
||||
sessionClosed,
|
||||
socketIdOf,
|
||||
userOf,
|
||||
type RoomAccess,
|
||||
@@ -167,6 +168,11 @@ export class RealtimeGateway implements OnGatewayInit, OnGatewayConnection, OnGa
|
||||
return;
|
||||
}
|
||||
|
||||
if (consumed.session && sessionClosed(consumed.session)) {
|
||||
socket.close(4001, 'Invalid or expired token');
|
||||
return;
|
||||
}
|
||||
|
||||
socket.isAlive = true;
|
||||
const sid = registerSocket(socket, user as User, consumed.session);
|
||||
// The version lets a client that stayed open across a deploy notice it
|
||||
|
||||
@@ -145,6 +145,21 @@ const socketId = new WeakMap<TrekWebSocket, number>();
|
||||
/** The session (`user_sessions.id`) the socket's ws token was minted under, where the request that minted it had one. */
|
||||
const socketSession = new WeakMap<TrekWebSocket, string>();
|
||||
|
||||
/**
|
||||
* Sessions whose sockets were just closed, by the time it happened. A ws token
|
||||
* minted under one of them shortly before lives on for its 30 seconds and
|
||||
* would open a socket no later close reaches, so the handshake refuses it. An
|
||||
* ended session cannot mint a new token, so a minute covers every one left.
|
||||
*/
|
||||
const closedSessions = new Map<string, number>();
|
||||
const CLOSED_SESSION_MEMORY_MS = 60_000;
|
||||
|
||||
/** Whether the sockets of `sessionId` were closed within the last minute. */
|
||||
export function sessionClosed(sessionId: string, now = Date.now()): boolean {
|
||||
for (const [id, at] of closedSessions) if (now - at >= CLOSED_SESSION_MEMORY_MS) closedSessions.delete(id);
|
||||
return closedSessions.has(sessionId);
|
||||
}
|
||||
|
||||
/**
|
||||
* A monotonic integer, NOT a uuid.
|
||||
*
|
||||
@@ -398,6 +413,7 @@ export async function recheckJourneyAccess(journeyId?: number): Promise<void> {
|
||||
* them; a client whose session still holds connects again and joins what it may.
|
||||
*/
|
||||
export function closeSockets(code: number, reason: string, userId?: number, sessionId?: string): void {
|
||||
if (sessionId !== undefined) closedSessions.set(sessionId, Date.now());
|
||||
const rooms = roomsSlot.get();
|
||||
for (const ws of openSockets()) {
|
||||
if (userId != null && socketUser.get(ws)?.id !== userId) continue;
|
||||
|
||||
Reference in New Issue
Block a user