From 96d8b5c664f71589b87d862d4110fb631c8cd862 Mon Sep 17 00:00:00 2001 From: Maurice Date: Sat, 28 Nov 2026 00:33:42 +0100 Subject: [PATCH] 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. --- .../nest/auth-core/ephemeral-token.service.ts | 8 ++--- server/src/nest/auth-core/ephemeral-tokens.ts | 16 +++++++--- server/src/nest/auth/auth.controller.ts | 4 +-- server/src/nest/realtime/realtime.gateway.ts | 2 +- server/src/nest/realtime/realtime.service.ts | 9 ++++++ server/src/nest/realtime/ws-state.ts | 15 ++++++--- server/src/nest/sessions/sessions.service.ts | 2 +- server/src/nest/tokens/token.service.ts | 7 +++-- .../tests/unit/nest/auth.controller.test.ts | 31 ++++++++++++++----- .../tests/unit/nest/realtime.gateway.test.ts | 15 +++++++++ .../unit/nest/realtime.revocation.test.ts | 22 +++++++++++-- .../nest/sessions/sessions.service.test.ts | 17 ++++++---- server/tests/unit/nest/token.service.test.ts | 7 +++++ 13 files changed, 118 insertions(+), 37 deletions(-) diff --git a/server/src/nest/auth-core/ephemeral-token.service.ts b/server/src/nest/auth-core/ephemeral-token.service.ts index 812c07278..f21c38c35 100644 --- a/server/src/nest/auth-core/ephemeral-token.service.ts +++ b/server/src/nest/auth-core/ephemeral-token.service.ts @@ -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); } } diff --git a/server/src/nest/auth-core/ephemeral-tokens.ts b/server/src/nest/auth-core/ephemeral-tokens.ts index 0e83ce961..476068e45 100644 --- a/server/src/nest/auth-core/ephemeral-tokens.ts +++ b/server/src/nest/auth-core/ephemeral-tokens.ts @@ -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(); @@ -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 | null = null; diff --git a/server/src/nest/auth/auth.controller.ts b/server/src/nest/auth/auth.controller.ts index 5778d3b62..a5db0253a 100644 --- a/server/src/nest/auth/auth.controller.ts +++ b/server/src/nest/auth/auth.controller.ts @@ -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 }; } diff --git a/server/src/nest/realtime/realtime.gateway.ts b/server/src/nest/realtime/realtime.gateway.ts index 256a2eb97..928f4f876 100644 --- a/server/src/nest/realtime/realtime.gateway.ts +++ b/server/src/nest/realtime/realtime.gateway.ts @@ -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. diff --git a/server/src/nest/realtime/realtime.service.ts b/server/src/nest/realtime/realtime.service.ts index 6ee2c1d05..937c43a90 100644 --- a/server/src/nest/realtime/realtime.service.ts +++ b/server/src/nest/realtime/realtime.service.ts @@ -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); + } } diff --git a/server/src/nest/realtime/ws-state.ts b/server/src/nest/realtime/ws-state.ts index f77a26be7..62a6ccfd5 100644 --- a/server/src/nest/realtime/ws-state.ts +++ b/server/src/nest/realtime/ws-state.ts @@ -142,6 +142,8 @@ export const roomsSlot = new ProcessStoreSlot(processRooms); const socketUser = new WeakMap(); const socketId = new WeakMap(); +/** 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(); /** * 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 { /** * 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); diff --git a/server/src/nest/sessions/sessions.service.ts b/server/src/nest/sessions/sessions.service.ts index 8b8089c07..816752b9d 100644 --- a/server/src/nest/sessions/sessions.service.ts +++ b/server/src/nest/sessions/sessions.service.ts @@ -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 { 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; } diff --git a/server/src/nest/tokens/token.service.ts b/server/src/nest/tokens/token.service.ts index 6a485f2a0..a0c8e50d6 100644 --- a/server/src/nest/tokens/token.service.ts +++ b/server/src/nest/tokens/token.service.ts @@ -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 }; } diff --git a/server/tests/unit/nest/auth.controller.test.ts b/server/tests/unit/nest/auth.controller.test.ts index 63170fd40..b0e8940a7 100644 --- a/server/tests/unit/nest/auth.controller.test.ts +++ b/server/tests/unit/nest/auth.controller.test.ts @@ -529,7 +529,7 @@ describe('AuthController (authenticated)', () => { for (let i = 0; i < 120; i++) await s.check('ws_token', String(user.id), 120, 15 * 60 * 1000, now); expect( await thrownAsync(() => - ac(asvc({}), s, { createWsToken: vi.fn().mockReturnValue({ token: 'ws' }) }).wsToken(user), + ac(asvc({}), s, { createWsToken: vi.fn().mockReturnValue({ token: 'ws' }) }).wsToken(user, req), ), ).toEqual({ status: 429, body: { error: 'Too many attempts. Please try again later.' } }); // The login bucket is untouched: an exhausted socket loop must not lock the account out. @@ -551,15 +551,17 @@ describe('AuthController (authenticated)', () => { // Both users sit behind the same NAT address, and the first one burns its // whole ceiling. for (let i = 0; i < 120; i++) { - await ac(asvc({}), s, { createWsToken: vi.fn().mockReturnValue({ token: 'ws' }) }).wsToken(user); + await ac(asvc({}), s, { createWsToken: vi.fn().mockReturnValue({ token: 'ws' }) }).wsToken(user, req); } expect( await thrownAsync(() => - ac(asvc({}), s, { createWsToken: vi.fn().mockReturnValue({ token: 'ws' }) }).wsToken(user), + ac(asvc({}), s, { createWsToken: vi.fn().mockReturnValue({ token: 'ws' }) }).wsToken(user, req), ), ).toEqual({ status: 429, body: { error: 'Too many attempts. Please try again later.' } }); - expect(await ac(asvc({}), s, { createWsToken: vi.fn().mockReturnValue({ token: 'ws2' }) }).wsToken(other)).toEqual({ + expect( + await ac(asvc({}), s, { createWsToken: vi.fn().mockReturnValue({ token: 'ws2' }) }).wsToken(other, req), + ).toEqual({ token: 'ws2', }); expect( @@ -944,12 +946,25 @@ describe('AuthController (authenticated)', () => { it('ws-token maps error, else returns the token', async () => { expect( await thrownAsync(() => - ac(asvc({}), rl(), { createWsToken: vi.fn().mockRejectedValue(new DomainError(503, 'down')) }).wsToken(user), + ac(asvc({}), rl(), { createWsToken: vi.fn().mockRejectedValue(new DomainError(503, 'down')) }).wsToken( + user, + req, + ), ), ).toEqual({ status: 503, body: { error: 'down' } }); - expect(await ac(asvc({}), rl(), { createWsToken: vi.fn().mockReturnValue({ token: 'ws' }) }).wsToken(user)).toEqual( - { token: 'ws' }, - ); + expect( + await ac(asvc({}), rl(), { createWsToken: vi.fn().mockReturnValue({ token: 'ws' }) }).wsToken(user, req), + ).toEqual({ token: 'ws' }); + }); + + it('ws-token is minted under the session of the request, so ending that session closes its socket', async () => { + const createWsToken = vi.fn().mockReturnValue({ token: 'ws' }); + const ctl = ac(asvc({}), rl(), { createWsToken }); + await ctl.wsToken(user, req); + expect(createWsToken).toHaveBeenLastCalledWith(1, undefined); + const tracked = jwt.sign({ id: 1, pv: 0 }, JWT_SECRET, { algorithm: 'HS256', jwtid: 'sid-ws' }); + await ctl.wsToken(user, { ip: '9.9.9.9', headers: {}, cookies: { trek_session: tracked } } as unknown as Request); + expect(createWsToken).toHaveBeenLastCalledWith(1, 'sid-ws'); }); it('avatar saves when not in demo mode (env present but email is not a demo email)', async () => { diff --git a/server/tests/unit/nest/realtime.gateway.test.ts b/server/tests/unit/nest/realtime.gateway.test.ts index de08d9690..95c66b142 100644 --- a/server/tests/unit/nest/realtime.gateway.test.ts +++ b/server/tests/unit/nest/realtime.gateway.test.ts @@ -13,6 +13,7 @@ import { joinBook, leaveBook, broadcastToUser, + closeSockets, getOnlineUserIds, joinRoom, registerSocket, @@ -309,6 +310,20 @@ describe('RealtimeGateway heartbeat', () => { pong![1](); expect(ws.isAlive).toBe(true); }); + + it('WSGW-023: the socket keeps the session its token was minted under, so it closes with that session only', async () => { + consumeWithMeta.mockReturnValue({ userId: 3, pv: 2, session: 'sess-a' }); + const { ws: a } = await connect('/ws?token=x'); + consumeWithMeta.mockReturnValue({ userId: 3, pv: 2, session: 'sess-b' }); + const { ws: b } = await connect('/ws?token=y'); + setServer({ clients: new Set([a, b]) } as never); + + closeSockets(4001, 'Session ended', 3, 'sess-a'); + + expect(a.closedWith).toEqual([4001, 'Session ended']); + expect(b.closedWith).toBeNull(); + setServer(null); + }); }); describe('ws-state fan-out', () => { diff --git a/server/tests/unit/nest/realtime.revocation.test.ts b/server/tests/unit/nest/realtime.revocation.test.ts index b95bd4282..67e04eda4 100644 --- a/server/tests/unit/nest/realtime.revocation.test.ts +++ b/server/tests/unit/nest/realtime.revocation.test.ts @@ -1,5 +1,5 @@ /** - * WSREV-001 to WSREV-012: a socket is let into a room with one access check, + * WSREV-001 to WSREV-017: 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 @@ -54,9 +54,9 @@ let rooms: InMemoryRoomRegistry; let clients: Set; /** A socket of the user, open and registered, as the handshake leaves it. */ -function open(userId: number): FakeSocket { +function open(userId: number, sessionId?: string): FakeSocket { const ws = socket(); - registerSocket(ws, { id: userId, username: `u${userId}` } as User); + registerSocket(ws, { id: userId, username: `u${userId}` } as User, sessionId); clients.add(ws); return ws; } @@ -219,6 +219,22 @@ describe('closeSockets', () => { expect(theirs.sent).toContainEqual(expect.objectContaining({ type: 'journey:book:peers' })); }); + it('WSREV-017: one ended session closes its own sockets and those of no known session, never another device', async () => { + const ended = open(1, 'sess-a'); + const otherDevice = open(1, 'sess-b'); + const unknown = open(1); + const theirs = open(2, 'sess-a'); + rooms.join(otherDevice, 5); + + new RealtimeService().closeSessionSockets(1, 'sess-a', 'Session ended'); + + expect(ended.closedWith).toEqual([4001, 'Session ended']); + expect(unknown.closedWith).toEqual([4001, 'Session ended']); + expect(otherDevice.closedWith).toBeNull(); + expect(theirs.closedWith).toBeNull(); + expect(rooms.members(5)?.has(otherDevice)).toBe(true); + }); + it('WSREV-012: without a user closes every socket, which a replaced database asks for', async () => { const a = open(1); const b = open(2); diff --git a/server/tests/unit/nest/sessions/sessions.service.test.ts b/server/tests/unit/nest/sessions/sessions.service.test.ts index 419e5aa62..b4429228c 100644 --- a/server/tests/unit/nest/sessions/sessions.service.test.ts +++ b/server/tests/unit/nest/sessions/sessions.service.test.ts @@ -299,22 +299,27 @@ 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); + it('SESS-019: ending sessions ends their open sockets too, and nothing when no session ended', async () => { + const closeAll = vi.spyOn(RealtimeService.prototype, 'closeUserSockets').mockImplementation(() => undefined); + const closeOne = vi.spyOn(RealtimeService.prototype, 'closeSessionSockets').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 })); + // One session ended: only its sockets, the other device stays connected. expect(await svc.revoke(user.id, a.jti)).toBe(true); - expect(close).toHaveBeenLastCalledWith(user.id, 'Session ended'); + expect(closeOne).toHaveBeenLastCalledWith(user.id, a.jti, 'Session ended'); + expect(closeAll).not.toHaveBeenCalled(); expect(await svc.revokeAll(user.id)).toBe(1); - expect(close).toHaveBeenCalledTimes(2); + expect(closeAll).toHaveBeenLastCalledWith(user.id, 'Session ended'); // 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(); + expect(closeOne).toHaveBeenCalledTimes(1); + expect(closeAll).toHaveBeenCalledTimes(1); + closeAll.mockRestore(); + closeOne.mockRestore(); }); it('SESS-010: endSession ends the session a token names, and nothing for an untracked or missing token', async () => { diff --git a/server/tests/unit/nest/token.service.test.ts b/server/tests/unit/nest/token.service.test.ts index 837f9d625..7b70276c7 100644 --- a/server/tests/unit/nest/token.service.test.ts +++ b/server/tests/unit/nest/token.service.test.ts @@ -365,6 +365,13 @@ describe('ephemeral tokens', () => { expect(createEphemeralToken).toHaveBeenCalledWith(99999, 'ws', { pv: 0 }); }); + it('TOKEN-021: createWsToken carries the session it was asked under, so the socket can close with it', async () => { + const { user } = createUser(testDb); + vi.mocked(createEphemeralToken).mockReturnValueOnce('ws-tok'); + await asLegacyResult(svc.createWsToken(user.id, 'sess-1')); + expect(createEphemeralToken).toHaveBeenCalledWith(user.id, 'ws', { pv: 0, session: 'sess-1' }); + }); + it('TOKEN-008: createWsToken reports 503 when the store refuses', async () => { const { user } = createUser(testDb); vi.mocked(createEphemeralToken).mockReturnValueOnce(null as unknown as string);