From 4a5f6d0cf20d2dfda4918eca72048db32bdbd6ea Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 28 Nov 2026 12:39:27 -0800 Subject: [PATCH] fix(realtime): disconnect sockets whose session has ended --- apps/realtime/src/access-revalidation.ts | 80 +++++++++- apps/realtime/src/middleware/auth.ts | 3 + .../src/session-liveness.integration.ts | 141 ++++++++++++++++++ packages/auth/src/verify.ts | 2 + 4 files changed, 224 insertions(+), 2 deletions(-) create mode 100644 apps/realtime/src/session-liveness.integration.ts diff --git a/apps/realtime/src/access-revalidation.ts b/apps/realtime/src/access-revalidation.ts index 897b10f890e..8e11a3825c4 100644 --- a/apps/realtime/src/access-revalidation.ts +++ b/apps/realtime/src/access-revalidation.ts @@ -1,3 +1,5 @@ +import { db } from '@sim/db' +import { session } from '@sim/db/schema' import { createLogger } from '@sim/logger' import { ROOM_MEMBERSHIP_ACTIONS, satisfiesRoomMembership } from '@sim/platform-authz/room-policy' import type { AccessRevokedBroadcast } from '@sim/realtime-protocol/events' @@ -9,7 +11,8 @@ import { type RoomType, roomName, } from '@sim/realtime-protocol/rooms' -import { sleep } from '@sim/utils/helpers' +import { chunkArray, sleep } from '@sim/utils/helpers' +import { and, gt, inArray } from 'drizzle-orm' import { evictSocketFromRoom, runRoomEvictionHandler, @@ -73,6 +76,23 @@ const SCAN_PASS_BUDGET_MS = 20_000 const SCAN_TIMED_OUT = Symbol('scan-timed-out') +/** Keeps each session-liveness query's `IN` list well below Postgres' bind-parameter limit. */ +const SESSION_LOOKUP_BATCH_SIZE = 1_000 + +/** Returns the subset of `sessionIds` that still name an unexpired session row. */ +async function findLiveSessionIds(sessionIds: string[]): Promise> { + const live = new Set() + const now = new Date() + for (const batch of chunkArray(sessionIds, SESSION_LOOKUP_BATCH_SIZE)) { + const rows = await db + .select({ id: session.id }) + .from(session) + .where(and(inArray(session.id, batch), gt(session.expiresAt, now))) + for (const row of rows) live.add(row.id) + } + return live +} + export interface AccessRevalidationSweep { /** Stop the periodic sweep (clears the interval). */ stop: () => void @@ -125,7 +145,9 @@ function collectScanTargets(io: IRoomManager['io']): ScanTarget[] { * no longer satisfies the room, closing the gap left by the join-only access * check. Without it, a member removed or downgraded mid-session keeps live * collaborative access (including durable document writes) for the whole lifetime - * of an already-open socket. + * of an already-open socket. Each pass first disconnects sockets whose Better Auth + * session has ended (signed out, revoked, or expired), since the handshake is the + * only other place the credential is checked. * * Blip-safety: eviction fires *only* when {@link resolveCurrentRoomPermission} * resolves to a permission that does not satisfy the room's membership level, @@ -290,7 +312,61 @@ export function startAccessRevalidationSweep(roomManager: IRoomManager): AccessR } } + /** Set while a session lookup is outstanding, so a timed-out query is never stacked with another. */ + let sessionLookupRunning = false + + /** + * Disconnects every socket whose handshake session no longer exists or has + * expired. Like the permission scan, only a successful query result acts: a + * failed or timed-out lookup leaves every socket connected until the next pass. + */ + async function disconnectEndedSessions(): Promise { + if (sessionLookupRunning) { + logger.warn('Skipping session liveness check; previous lookup still running') + return + } + const sockets = [...io.sockets.sockets.values()].filter( + (socket): socket is AuthenticatedSocket & { sessionId: string } => + Boolean((socket as AuthenticatedSocket).sessionId) + ) + if (sockets.length === 0) return + + sessionLookupRunning = true + const lookup = findLiveSessionIds([...new Set(sockets.map((socket) => socket.sessionId))]) + lookup + .catch(() => {}) + .finally(() => { + sessionLookupRunning = false + }) + + let live: Set | typeof SCAN_TIMED_OUT + try { + live = await Promise.race([ + lookup, + sleep(SCAN_SOCKET_TIMEOUT_MS).then((): typeof SCAN_TIMED_OUT => SCAN_TIMED_OUT), + ]) + } catch (error) { + logger.warn('Session liveness check failed; leaving sockets connected', error) + return + } + if (live === SCAN_TIMED_OUT) { + logger.warn('Session liveness check timed out; leaving sockets connected') + return + } + + for (const socket of sockets) { + if (live.has(socket.sessionId)) continue + logger.info('Disconnecting socket whose session ended', { + socketId: socket.id, + userId: socket.userId, + }) + socket.disconnect(true) + } + } + async function scanMemberships(): Promise { + await disconnectEndedSessions() + const targets = collectScanTargets(io) if (targets.length === 0) return diff --git a/apps/realtime/src/middleware/auth.ts b/apps/realtime/src/middleware/auth.ts index ee78a24ce30..8397b788f26 100644 --- a/apps/realtime/src/middleware/auth.ts +++ b/apps/realtime/src/middleware/auth.ts @@ -14,6 +14,8 @@ const logger = createLogger('SocketAuth') export interface AuthenticatedSocket extends Socket { data: { fileDocPresence?: { roomName: string; user: FileDocPresenceUser } } userId?: string + /** Better Auth session the handshake token was minted from; the access sweep disconnects the socket once it ends. */ + sessionId?: string userName?: string userEmail?: string activeOrganizationId?: string @@ -71,6 +73,7 @@ export async function authenticateSocket(socket: AuthenticatedSocket, next: (err // Store user info in socket for later use socket.userId = session.user.id + socket.sessionId = session.session.id socket.userName = session.user.name || session.user.email || 'Unknown User' socket.userEmail = session.user.email ?? undefined socket.userImage = session.user.image || null diff --git a/apps/realtime/src/session-liveness.integration.ts b/apps/realtime/src/session-liveness.integration.ts new file mode 100644 index 00000000000..1534eacc1da --- /dev/null +++ b/apps/realtime/src/session-liveness.integration.ts @@ -0,0 +1,141 @@ +import { mkdir, writeFile } from 'node:fs/promises' +import { createServer, type Server as HttpServer } from 'node:http' +import { dirname, resolve } from 'node:path' +import { db } from '@sim/db' +import { session, user, verification } from '@sim/db/schema' +import { getErrorMessage } from '@sim/utils/errors' +import { generateId } from '@sim/utils/id' +import { eq } from 'drizzle-orm' +import { Server } from 'socket.io' +import { io as connect, type Socket } from 'socket.io-client' +import { afterAll, beforeAll, describe, expect, it } from 'vitest' +import { type AccessRevalidationSweep, startAccessRevalidationSweep } from '@/access-revalidation' +import { env } from '@/env' +import { authenticateSocket } from '@/middleware/auth' +import { RedisRoomManager } from '@/rooms' + +const userId = generateId() +const checks: { name: string; status: string; durationMs: number; error?: string }[] = [] +const clients: Socket[] = [] +let http: HttpServer +let io: Server +let manager: RedisRoomManager +let sweep: AccessRevalidationSweep +let socketUrl: string + +/** Inserts a session row and returns it with a one-time socket token minted from it. */ +async function createSession() { + const id = generateId() + const token = generateId() + const oneTimeToken = generateId() + const now = new Date() + const expiresAt = new Date(Date.now() + 60 * 60 * 1000) + await db.insert(session).values({ id, token, userId, expiresAt, createdAt: now, updatedAt: now }) + await db.insert(verification).values({ + id: generateId(), + identifier: `one-time-token:${oneTimeToken}`, + value: token, + expiresAt: new Date(Date.now() + 60_000), + createdAt: now, + updatedAt: now, + }) + return { id, oneTimeToken } +} + +/** Opens a socket through the real handshake middleware and records how it later disconnects. */ +async function openSocket(oneTimeToken: string) { + const socket = connect(socketUrl, { + auth: { token: oneTimeToken }, + reconnection: false, + transports: ['websocket'], + }) + clients.push(socket) + const disconnected = new Promise((done) => socket.on('disconnect', done)) + await new Promise((done, fail) => { + socket.on('connect', done) + socket.on('connect_error', fail) + }) + return { socket, disconnected } +} + +function check(name: string, run: () => Promise) { + it(name, async () => { + const start = performance.now() + try { + await run() + checks.push({ name, status: 'passed', durationMs: performance.now() - start }) + } catch (error) { + checks.push({ + name, + status: 'failed', + durationMs: performance.now() - start, + error: getErrorMessage(error), + }) + throw error + } + }) +} + +beforeAll(async () => { + await db.insert(user).values({ + id: userId, + name: 'Fixture', + email: `${userId}@example.invalid`, + emailVerified: true, + createdAt: new Date(), + updatedAt: new Date(), + }) + http = createServer() + io = new Server(http) + io.use(authenticateSocket) + manager = new RedisRoomManager(io, env.REDIS_URL) + await manager.initialize() + sweep = startAccessRevalidationSweep(manager) + await new Promise((done) => http.listen(0, '127.0.0.1', done)) + const address = http.address() + if (!address || typeof address === 'string') throw new Error('Missing fixture port') + socketUrl = `http://127.0.0.1:${address.port}` +}) + +describe('session liveness over Socket.IO and Postgres', () => { + check('a socket whose session is deleted is disconnected; a live session stays', async () => { + const revoked = await createSession() + const kept = await createSession() + const revokedSocket = await openSocket(revoked.oneTimeToken) + const keptSocket = await openSocket(kept.oneTimeToken) + + await sweep.runOnce() + expect([...io.sockets.sockets.keys()]).toContain(revokedSocket.socket.id) + + await db.delete(session).where(eq(session.id, revoked.id)) + await sweep.runOnce() + + expect(await revokedSocket.disconnected).toBe('io server disconnect') + expect([...io.sockets.sockets.keys()]).toContain(keptSocket.socket.id) + }) + + check('a socket whose session expired is disconnected', async () => { + const expiring = await createSession() + const { disconnected } = await openSocket(expiring.oneTimeToken) + + await db + .update(session) + .set({ expiresAt: new Date(Date.now() - 1000) }) + .where(eq(session.id, expiring.id)) + await sweep.runOnce() + + expect(await disconnected).toBe('io server disconnect') + }) +}) + +afterAll(async () => { + sweep?.stop() + for (const socket of clients) socket.disconnect() + if (io) await new Promise((done) => io.close(() => done())) + await manager?.shutdown() + await db.delete(user).where(eq(user.id, userId)) + const report = + process.env.SESSION_LIVENESS_REPORT_PATH ?? resolve('test-results/session-liveness.json') + await mkdir(dirname(report), { recursive: true }) + await writeFile(report, JSON.stringify({ checks }, null, 2)) +}) diff --git a/packages/auth/src/verify.ts b/packages/auth/src/verify.ts index 62db3b08858..f6a274d7730 100644 --- a/packages/auth/src/verify.ts +++ b/packages/auth/src/verify.ts @@ -24,6 +24,7 @@ interface VerifiedOneTimeTokenSession { image?: string | null } session: { + id: string activeOrganizationId?: string | null } } @@ -83,6 +84,7 @@ export function createVerifyAuth(options: VerifyAuthOptions): VerifyAuth { image: result.user.image ?? null, }, session: { + id: result.session.id, activeOrganizationId: typeof result.session.activeOrganizationId === 'string' ? result.session.activeOrganizationId