Skip to content

Commit 09b16ff

Browse files
authored
fix(realtime): disconnect sockets whose session has ended (#10496)
1 parent 93b7597 commit 09b16ff

4 files changed

Lines changed: 224 additions & 2 deletions

File tree

‎apps/realtime/src/access-revalidation.ts‎

Lines changed: 78 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { db } from '@sim/db'
2+
import { session } from '@sim/db/schema'
13
import { createLogger } from '@sim/logger'
24
import { ROOM_MEMBERSHIP_ACTIONS, satisfiesRoomMembership } from '@sim/platform-authz/room-policy'
35
import type { AccessRevokedBroadcast } from '@sim/realtime-protocol/events'
@@ -9,7 +11,8 @@ import {
911
type RoomType,
1012
roomName,
1113
} from '@sim/realtime-protocol/rooms'
12-
import { sleep } from '@sim/utils/helpers'
14+
import { chunkArray, sleep } from '@sim/utils/helpers'
15+
import { and, gt, inArray } from 'drizzle-orm'
1316
import {
1417
evictSocketFromRoom,
1518
runRoomEvictionHandler,
@@ -73,6 +76,23 @@ const SCAN_PASS_BUDGET_MS = 20_000
7376

7477
const SCAN_TIMED_OUT = Symbol('scan-timed-out')
7578

79+
/** Keeps each session-liveness query's `IN` list well below Postgres' bind-parameter limit. */
80+
const SESSION_LOOKUP_BATCH_SIZE = 1_000
81+
82+
/** Returns the subset of `sessionIds` that still name an unexpired session row. */
83+
async function findLiveSessionIds(sessionIds: string[]): Promise<Set<string>> {
84+
const live = new Set<string>()
85+
const now = new Date()
86+
for (const batch of chunkArray(sessionIds, SESSION_LOOKUP_BATCH_SIZE)) {
87+
const rows = await db
88+
.select({ id: session.id })
89+
.from(session)
90+
.where(and(inArray(session.id, batch), gt(session.expiresAt, now)))
91+
for (const row of rows) live.add(row.id)
92+
}
93+
return live
94+
}
95+
7696
export interface AccessRevalidationSweep {
7797
/** Stop the periodic sweep (clears the interval). */
7898
stop: () => void
@@ -125,7 +145,9 @@ function collectScanTargets(io: IRoomManager['io']): ScanTarget[] {
125145
* no longer satisfies the room, closing the gap left by the join-only access
126146
* check. Without it, a member removed or downgraded mid-session keeps live
127147
* collaborative access (including durable document writes) for the whole lifetime
128-
* of an already-open socket.
148+
* of an already-open socket. Each pass first disconnects sockets whose Better Auth
149+
* session has ended (signed out, revoked, or expired), since the handshake is the
150+
* only other place the credential is checked.
129151
*
130152
* Blip-safety: eviction fires *only* when {@link resolveCurrentRoomPermission}
131153
* resolves to a permission that does not satisfy the room's membership level,
@@ -290,7 +312,61 @@ export function startAccessRevalidationSweep(roomManager: IRoomManager): AccessR
290312
}
291313
}
292314

315+
/** Set while a session lookup is outstanding, so a timed-out query is never stacked with another. */
316+
let sessionLookupRunning = false
317+
318+
/**
319+
* Disconnects every socket whose handshake session no longer exists or has
320+
* expired. Like the permission scan, only a successful query result acts: a
321+
* failed or timed-out lookup leaves every socket connected until the next pass.
322+
*/
323+
async function disconnectEndedSessions(): Promise<void> {
324+
if (sessionLookupRunning) {
325+
logger.warn('Skipping session liveness check; previous lookup still running')
326+
return
327+
}
328+
const sockets = [...io.sockets.sockets.values()].filter(
329+
(socket): socket is AuthenticatedSocket & { sessionId: string } =>
330+
Boolean((socket as AuthenticatedSocket).sessionId)
331+
)
332+
if (sockets.length === 0) return
333+
334+
sessionLookupRunning = true
335+
const lookup = findLiveSessionIds([...new Set(sockets.map((socket) => socket.sessionId))])
336+
lookup
337+
.catch(() => {})
338+
.finally(() => {
339+
sessionLookupRunning = false
340+
})
341+
342+
let live: Set<string> | typeof SCAN_TIMED_OUT
343+
try {
344+
live = await Promise.race([
345+
lookup,
346+
sleep(SCAN_SOCKET_TIMEOUT_MS).then((): typeof SCAN_TIMED_OUT => SCAN_TIMED_OUT),
347+
])
348+
} catch (error) {
349+
logger.warn('Session liveness check failed; leaving sockets connected', error)
350+
return
351+
}
352+
if (live === SCAN_TIMED_OUT) {
353+
logger.warn('Session liveness check timed out; leaving sockets connected')
354+
return
355+
}
356+
357+
for (const socket of sockets) {
358+
if (live.has(socket.sessionId)) continue
359+
logger.info('Disconnecting socket whose session ended', {
360+
socketId: socket.id,
361+
userId: socket.userId,
362+
})
363+
socket.disconnect(true)
364+
}
365+
}
366+
293367
async function scanMemberships(): Promise<void> {
368+
await disconnectEndedSessions()
369+
294370
const targets = collectScanTargets(io)
295371
if (targets.length === 0) return
296372

‎apps/realtime/src/middleware/auth.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ const logger = createLogger('SocketAuth')
1414
export interface AuthenticatedSocket extends Socket {
1515
data: { fileDocPresence?: { roomName: string; user: FileDocPresenceUser } }
1616
userId?: string
17+
/** Better Auth session the handshake token was minted from; the access sweep disconnects the socket once it ends. */
18+
sessionId?: string
1719
userName?: string
1820
userEmail?: string
1921
activeOrganizationId?: string
@@ -71,6 +73,7 @@ export async function authenticateSocket(socket: AuthenticatedSocket, next: (err
7173

7274
// Store user info in socket for later use
7375
socket.userId = session.user.id
76+
socket.sessionId = session.session.id
7477
socket.userName = session.user.name || session.user.email || 'Unknown User'
7578
socket.userEmail = session.user.email ?? undefined
7679
socket.userImage = session.user.image || null
Lines changed: 141 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,141 @@
1+
import { mkdir, writeFile } from 'node:fs/promises'
2+
import { createServer, type Server as HttpServer } from 'node:http'
3+
import { dirname, resolve } from 'node:path'
4+
import { db } from '@sim/db'
5+
import { session, user, verification } from '@sim/db/schema'
6+
import { getErrorMessage } from '@sim/utils/errors'
7+
import { generateId } from '@sim/utils/id'
8+
import { eq } from 'drizzle-orm'
9+
import { Server } from 'socket.io'
10+
import { io as connect, type Socket } from 'socket.io-client'
11+
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
12+
import { type AccessRevalidationSweep, startAccessRevalidationSweep } from '@/access-revalidation'
13+
import { env } from '@/env'
14+
import { authenticateSocket } from '@/middleware/auth'
15+
import { RedisRoomManager } from '@/rooms'
16+
17+
const userId = generateId()
18+
const checks: { name: string; status: string; durationMs: number; error?: string }[] = []
19+
const clients: Socket[] = []
20+
let http: HttpServer
21+
let io: Server
22+
let manager: RedisRoomManager
23+
let sweep: AccessRevalidationSweep
24+
let socketUrl: string
25+
26+
/** Inserts a session row and returns it with a one-time socket token minted from it. */
27+
async function createSession() {
28+
const id = generateId()
29+
const token = generateId()
30+
const oneTimeToken = generateId()
31+
const now = new Date()
32+
const expiresAt = new Date(Date.now() + 60 * 60 * 1000)
33+
await db.insert(session).values({ id, token, userId, expiresAt, createdAt: now, updatedAt: now })
34+
await db.insert(verification).values({
35+
id: generateId(),
36+
identifier: `one-time-token:${oneTimeToken}`,
37+
value: token,
38+
expiresAt: new Date(Date.now() + 60_000),
39+
createdAt: now,
40+
updatedAt: now,
41+
})
42+
return { id, oneTimeToken }
43+
}
44+
45+
/** Opens a socket through the real handshake middleware and records how it later disconnects. */
46+
async function openSocket(oneTimeToken: string) {
47+
const socket = connect(socketUrl, {
48+
auth: { token: oneTimeToken },
49+
reconnection: false,
50+
transports: ['websocket'],
51+
})
52+
clients.push(socket)
53+
const disconnected = new Promise<string>((done) => socket.on('disconnect', done))
54+
await new Promise<void>((done, fail) => {
55+
socket.on('connect', done)
56+
socket.on('connect_error', fail)
57+
})
58+
return { socket, disconnected }
59+
}
60+
61+
function check(name: string, run: () => Promise<void>) {
62+
it(name, async () => {
63+
const start = performance.now()
64+
try {
65+
await run()
66+
checks.push({ name, status: 'passed', durationMs: performance.now() - start })
67+
} catch (error) {
68+
checks.push({
69+
name,
70+
status: 'failed',
71+
durationMs: performance.now() - start,
72+
error: getErrorMessage(error),
73+
})
74+
throw error
75+
}
76+
})
77+
}
78+
79+
beforeAll(async () => {
80+
await db.insert(user).values({
81+
id: userId,
82+
name: 'Fixture',
83+
email: `${userId}@example.invalid`,
84+
emailVerified: true,
85+
createdAt: new Date(),
86+
updatedAt: new Date(),
87+
})
88+
http = createServer()
89+
io = new Server(http)
90+
io.use(authenticateSocket)
91+
manager = new RedisRoomManager(io, env.REDIS_URL)
92+
await manager.initialize()
93+
sweep = startAccessRevalidationSweep(manager)
94+
await new Promise<void>((done) => http.listen(0, '127.0.0.1', done))
95+
const address = http.address()
96+
if (!address || typeof address === 'string') throw new Error('Missing fixture port')
97+
socketUrl = `http://127.0.0.1:${address.port}`
98+
})
99+
100+
describe('session liveness over Socket.IO and Postgres', () => {
101+
check('a socket whose session is deleted is disconnected; a live session stays', async () => {
102+
const revoked = await createSession()
103+
const kept = await createSession()
104+
const revokedSocket = await openSocket(revoked.oneTimeToken)
105+
const keptSocket = await openSocket(kept.oneTimeToken)
106+
107+
await sweep.runOnce()
108+
expect([...io.sockets.sockets.keys()]).toContain(revokedSocket.socket.id)
109+
110+
await db.delete(session).where(eq(session.id, revoked.id))
111+
await sweep.runOnce()
112+
113+
expect(await revokedSocket.disconnected).toBe('io server disconnect')
114+
expect([...io.sockets.sockets.keys()]).toContain(keptSocket.socket.id)
115+
})
116+
117+
check('a socket whose session expired is disconnected', async () => {
118+
const expiring = await createSession()
119+
const { disconnected } = await openSocket(expiring.oneTimeToken)
120+
121+
await db
122+
.update(session)
123+
.set({ expiresAt: new Date(Date.now() - 1000) })
124+
.where(eq(session.id, expiring.id))
125+
await sweep.runOnce()
126+
127+
expect(await disconnected).toBe('io server disconnect')
128+
})
129+
})
130+
131+
afterAll(async () => {
132+
sweep?.stop()
133+
for (const socket of clients) socket.disconnect()
134+
if (io) await new Promise<void>((done) => io.close(() => done()))
135+
await manager?.shutdown()
136+
await db.delete(user).where(eq(user.id, userId))
137+
const report =
138+
process.env.SESSION_LIVENESS_REPORT_PATH ?? resolve('test-results/session-liveness.json')
139+
await mkdir(dirname(report), { recursive: true })
140+
await writeFile(report, JSON.stringify({ checks }, null, 2))
141+
})

‎packages/auth/src/verify.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ interface VerifiedOneTimeTokenSession {
2424
image?: string | null
2525
}
2626
session: {
27+
id: string
2728
activeOrganizationId?: string | null
2829
}
2930
}
@@ -83,6 +84,7 @@ export function createVerifyAuth(options: VerifyAuthOptions): VerifyAuth {
8384
image: result.user.image ?? null,
8485
},
8586
session: {
87+
id: result.session.id,
8688
activeOrganizationId:
8789
typeof result.session.activeOrganizationId === 'string'
8890
? result.session.activeOrganizationId

0 commit comments

Comments
 (0)