mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-28 07:30:04 +00:00
fix(sessions): close only the sockets of the session that ended
A ws token now carries the session it was minted under and the socket keeps it, so signing out on one device no longer drops the live socket of every other device. Ending all sessions still closes every socket of the account.
This commit is contained in:
@@ -52,11 +52,11 @@ export class EphemeralTokenService implements OnModuleInit, OnModuleDestroy {
|
||||
}
|
||||
|
||||
/**
|
||||
* The same, plus the password_version the token was minted with. Only the ws
|
||||
* handshake needs it, for the session gate that rejects a token minted before
|
||||
* a password change.
|
||||
* The same, plus the password_version and the session the token was minted
|
||||
* with. Only the ws handshake needs them, for the session gate that rejects a
|
||||
* token minted before a password change and to close the socket with its session.
|
||||
*/
|
||||
consumeWithMeta(token: string, purpose: string): { userId: number; pv?: number } | null {
|
||||
consumeWithMeta(token: string, purpose: string): { userId: number; pv?: number; session?: string } | null {
|
||||
return consumeEphemeralTokenWithMeta(token, purpose);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,11 +18,15 @@ interface TokenEntry {
|
||||
* treat as version 0 — mirroring the JWT `pv` claim semantics.
|
||||
*/
|
||||
pv?: number;
|
||||
/** The session the token was minted under, so a socket can be closed with it. */
|
||||
session?: string;
|
||||
}
|
||||
|
||||
export interface EphemeralTokenMeta {
|
||||
/** Bind the token to the user's current password_version (session gate). */
|
||||
pv?: number;
|
||||
/** The session (`user_sessions.id`) of the request that minted the token. */
|
||||
session?: string;
|
||||
}
|
||||
|
||||
const store = new Map<string, TokenEntry>();
|
||||
@@ -31,7 +35,7 @@ export function createEphemeralToken(userId: number, purpose: string, meta?: Eph
|
||||
if (store.size >= MAX_STORE_SIZE) return null;
|
||||
const token = crypto.randomBytes(32).toString('hex');
|
||||
const ttl = TTL[purpose] ?? 60_000;
|
||||
store.set(token, { userId, purpose, expiresAt: Date.now() + ttl, pv: meta?.pv });
|
||||
store.set(token, { userId, purpose, expiresAt: Date.now() + ttl, pv: meta?.pv, session: meta?.session });
|
||||
return token;
|
||||
}
|
||||
|
||||
@@ -46,14 +50,18 @@ export function consumeEphemeralToken(token: string, purpose: string): number |
|
||||
/**
|
||||
* Like `consumeEphemeralToken`, but also returns the `password_version` the
|
||||
* token was minted with. Used by the WebSocket handshake so a token issued
|
||||
* before a password change can be rejected even within its short TTL.
|
||||
* before a password change can be rejected even within its short TTL, and
|
||||
* so the socket knows the session it belongs to.
|
||||
*/
|
||||
export function consumeEphemeralTokenWithMeta(token: string, purpose: string): { userId: number; pv?: number } | null {
|
||||
export function consumeEphemeralTokenWithMeta(
|
||||
token: string,
|
||||
purpose: string,
|
||||
): { userId: number; pv?: number; session?: string } | null {
|
||||
const entry = store.get(token);
|
||||
if (!entry) return null;
|
||||
store.delete(token);
|
||||
if (entry.purpose !== purpose || Date.now() > entry.expiresAt) return null;
|
||||
return { userId: entry.userId, pv: entry.pv };
|
||||
return { userId: entry.userId, pv: entry.pv, session: entry.session };
|
||||
}
|
||||
|
||||
let cleanupInterval: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
@@ -368,14 +368,14 @@ export class AuthController {
|
||||
|
||||
@Post('ws-token')
|
||||
@HttpCode(200)
|
||||
async wsToken(@CurrentUser() user: User) {
|
||||
async wsToken(@CurrentUser() user: User, @Req() req: Request) {
|
||||
// Own bucket, not 'login': a client that reconnects its socket in a loop
|
||||
// must not be able to lock itself out of signing in. The ceiling is far
|
||||
// above any real client, which mints one token per socket connect, but it
|
||||
// stops a single account from filling the process-wide ephemeral store and
|
||||
// 503-ing every other user's ws and download tokens.
|
||||
await this.limitUser('ws_token', user.id, 120);
|
||||
const result = await this.tokens.createWsToken(user.id);
|
||||
const result = await this.tokens.createWsToken(user.id, currentSessionId(req));
|
||||
return { token: result.token };
|
||||
}
|
||||
|
||||
|
||||
@@ -168,7 +168,7 @@ export class RealtimeGateway implements OnGatewayInit, OnGatewayConnection, OnGa
|
||||
}
|
||||
|
||||
socket.isAlive = true;
|
||||
const sid = registerSocket(socket, user as User);
|
||||
const sid = registerSocket(socket, user as User, consumed.session);
|
||||
// The version lets a client that stayed open across a deploy notice it
|
||||
// runs the previous build: a deploy restarts the server, so every open
|
||||
// client reconnects and reads this again.
|
||||
|
||||
@@ -152,4 +152,13 @@ export class RealtimeService {
|
||||
closeUserSockets(userId: number, reason: string): void {
|
||||
closeSockets(4001, reason, userId);
|
||||
}
|
||||
|
||||
/**
|
||||
* The same for one ended session: only the sockets opened under it, so the
|
||||
* account's other devices stay connected. A socket whose session is not
|
||||
* known is closed with it.
|
||||
*/
|
||||
closeSessionSockets(userId: number, sessionId: string, reason: string): void {
|
||||
closeSockets(4001, reason, userId, sessionId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -142,6 +142,8 @@ export const roomsSlot = new ProcessStoreSlot<RoomRegistry>(processRooms);
|
||||
|
||||
const socketUser = new WeakMap<TrekWebSocket, User>();
|
||||
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>();
|
||||
|
||||
/**
|
||||
* A monotonic integer, NOT a uuid.
|
||||
@@ -164,10 +166,11 @@ export function getServer(): WebSocketServer | null {
|
||||
return wss;
|
||||
}
|
||||
|
||||
export function registerSocket(ws: TrekWebSocket, user: User): number {
|
||||
export function registerSocket(ws: TrekWebSocket, user: User, sessionId?: string): number {
|
||||
const sid = nextSocketId++;
|
||||
socketId.set(ws, sid);
|
||||
socketUser.set(ws, user);
|
||||
if (sessionId !== undefined) socketSession.set(ws, sessionId);
|
||||
roomsSlot.get().register(ws);
|
||||
return sid;
|
||||
}
|
||||
@@ -389,14 +392,16 @@ export async function recheckJourneyAccess(journeyId?: number): Promise<void> {
|
||||
/**
|
||||
* 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.
|
||||
* once the database was replaced. With `sessionId`, only the account's sockets
|
||||
* opened under that session, and those whose session is not known. 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 closeSockets(code: number, reason: string, userId?: number): void {
|
||||
export function closeSockets(code: number, reason: string, userId?: number, sessionId?: string): void {
|
||||
const rooms = roomsSlot.get();
|
||||
for (const ws of openSockets()) {
|
||||
if (userId != null && socketUser.get(ws)?.id !== userId) continue;
|
||||
if (sessionId !== undefined && (socketSession.get(ws) ?? sessionId) !== sessionId) continue;
|
||||
rooms.leaveAll(ws);
|
||||
for (const id of rooms.leaveAllBooks(ws)) announceBookPeers(id);
|
||||
ws.close(code, reason);
|
||||
|
||||
@@ -210,7 +210,7 @@ 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> {
|
||||
const revoked = await this.sessions.revokeForUser(sessionId, userId, dbNow());
|
||||
if (revoked) this.realtime.closeUserSockets(userId, 'Session ended');
|
||||
if (revoked) this.realtime.closeSessionSockets(userId, sessionId, 'Session ended');
|
||||
return revoked;
|
||||
}
|
||||
|
||||
|
||||
@@ -195,11 +195,12 @@ export class TokenService {
|
||||
// Ephemeral tokens
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
async createWsToken(userId: number): Promise<{ token?: string }> {
|
||||
async createWsToken(userId: number, sessionId?: string): Promise<{ token?: string }> {
|
||||
// Bind the ws-token to the user's current password_version so a token minted
|
||||
// before a password reset is rejected on connect (defence-in-depth session gate).
|
||||
// before a password reset is rejected on connect (defence-in-depth session gate),
|
||||
// and to the session asking for it, so ending that session closes the socket.
|
||||
const pv = (await this.users.getPasswordVersion(userId)) ?? 0;
|
||||
const token = this.ephemeral.create(userId, 'ws', { pv });
|
||||
const token = this.ephemeral.create(userId, 'ws', { pv, session: sessionId });
|
||||
if (!token) throw new DomainError(503, 'Service unavailable');
|
||||
return { token };
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user