@@ -3,14 +3,19 @@ import { toError } from '@sim/utils/errors'
33import { sleep } from '@sim/utils/helpers'
44import { NextResponse } from 'next/server'
55import { SSE_HEADERS } from '@/lib/core/utils/sse'
6+ import { withPermissionGroupScope } from '@/lib/permission-groups/request-scope.server'
67import type { EventLogEntry , EventLogReadResult } from '@/lib/realtime/event-log'
78
89const logger = createLogger ( 'EventStreamRoute' )
910
11+ const ROTATE_FRAME = `event: rotate\ndata: {}\n\n`
12+
1013const POLL_INTERVAL_MS = 500
1114const HEARTBEAT_INTERVAL_MS = 15_000
1215/** Defensive ceiling; the client reconnects (resuming from lastEventId) past this. */
1316const MAX_STREAM_DURATION_MS = 4 * 60 * 60 * 1000
17+ /** Matches the realtime access-revalidation sweep, so a revoked member loses both live channels on the same cadence. */
18+ const ACCESS_REVALIDATION_INTERVAL_MS = 30_000
1419
1520export interface EventStreamResponseOptions < E extends EventLogEntry > {
1621 requestId : string
@@ -20,6 +25,12 @@ export interface EventStreamResponseOptions<E extends EventLogEntry> {
2025 fromEventId : number | undefined
2126 getLatestEventId : ( streamId : string ) => Promise < number >
2227 readEventsSince : ( streamId : string , afterEventId : number ) => Promise < EventLogReadResult < E > >
28+ /**
29+ * Re-runs the route's authorization every {@link ACCESS_REVALIDATION_INTERVAL_MS}:
30+ * `false` closes the stream with `rotate`, a throw errors it, and either way the
31+ * client's reconnect meets the route's own check.
32+ */
33+ revalidateAccess : ( ) => Promise < boolean >
2334 /** Extra response headers (e.g. `{ 'X-Table-Id': id }`). */
2435 extraHeaders ?: Record < string , string >
2536 /** Short label for logs (e.g. 'table'). */
@@ -39,7 +50,15 @@ export interface EventStreamResponseOptions<E extends EventLogEntry> {
3950export function createEventStreamResponse < E extends EventLogEntry > (
4051 options : EventStreamResponseOptions < E >
4152) : NextResponse {
42- const { requestId, streamId, fromEventId, getLatestEventId, readEventsSince, label } = options
53+ const {
54+ requestId,
55+ streamId,
56+ fromEventId,
57+ getLatestEventId,
58+ readEventsSince,
59+ revalidateAccess,
60+ label,
61+ } = options
4362
4463 logger . info ( `${ label } event stream opened` , { requestId, streamId, fromEventId } )
4564
@@ -51,6 +70,7 @@ export function createEventStreamResponse<E extends EventLogEntry>(
5170 let lastEventId = fromEventId ?? 0
5271 const deadline = Date . now ( ) + MAX_STREAM_DURATION_MS
5372 let nextHeartbeatAt = Date . now ( ) + HEARTBEAT_INTERVAL_MS
73+ let nextRevalidationAt = Date . now ( ) + ACCESS_REVALIDATION_INTERVAL_MS
5474
5575 const enqueue = ( text : string ) => {
5676 if ( closed ) return
@@ -69,10 +89,8 @@ export function createEventStreamResponse<E extends EventLogEntry>(
6989 }
7090 }
7191
72- const sendPrunedAndClose = ( earliestEventId : number | undefined ) => {
73- enqueue (
74- `event: pruned\ndata: ${ JSON . stringify ( { earliestEventId : earliestEventId ?? null } ) } \n\n`
75- )
92+ const closeWith = ( frame : string ) => {
93+ enqueue ( frame )
7694 if ( ! closed ) {
7795 closed = true
7896 try {
@@ -81,6 +99,12 @@ export function createEventStreamResponse<E extends EventLogEntry>(
8199 }
82100 }
83101
102+ const sendPrunedAndClose = ( earliestEventId : number | undefined ) => {
103+ closeWith (
104+ `event: pruned\ndata: ${ JSON . stringify ( { earliestEventId : earliestEventId ?? null } ) } \n\n`
105+ )
106+ }
107+
84108 const sendHeartbeat = ( ) => {
85109 // SSE comment line — keeps proxies (ALB default 60s idle) from closing
86110 // the connection during quiet periods.
@@ -109,6 +133,17 @@ export function createEventStreamResponse<E extends EventLogEntry>(
109133 await sleep ( POLL_INTERVAL_MS )
110134 if ( closed ) return
111135
136+ if ( Date . now ( ) >= nextRevalidationAt ) {
137+ // A fresh scope per check: the loop inherits the opening request's
138+ // permission-group memo, which would replay its answer for hours.
139+ if ( ! ( await withPermissionGroupScope ( revalidateAccess ) ) ) {
140+ logger . info ( `${ label } event stream access revoked` , { requestId, streamId } )
141+ closeWith ( ROTATE_FRAME )
142+ return
143+ }
144+ nextRevalidationAt = Date . now ( ) + ACCESS_REVALIDATION_INTERVAL_MS
145+ }
146+
112147 const result = await readEventsSince ( streamId , lastEventId )
113148 if ( result . status === 'pruned' ) {
114149 sendPrunedAndClose ( result . earliestEventId )
@@ -129,13 +164,7 @@ export function createEventStreamResponse<E extends EventLogEntry>(
129164
130165 // Reached the defensive duration ceiling — close cleanly so the client
131166 // reconnects with the latest lastEventId.
132- if ( ! closed ) {
133- enqueue ( `event: rotate\ndata: {}\n\n` )
134- closed = true
135- try {
136- controller . close ( )
137- } catch { }
138- }
167+ closeWith ( ROTATE_FRAME )
139168 } catch ( error ) {
140169 logger . error ( `${ label } event stream error` , {
141170 requestId,
0 commit comments