Close event streams for expired sessions

When a session expires close any event streams that have been opened
with that session.  This prevents an attacker with a leaked session
cookie from opening a stream and receiving updates indefinitely without
being detected.

By sending the session the event stream is opened with when the stream
is established this closure on session expiry also serves as a way for
a user agent to be notified whenever its own access level changes.
This commit is contained in:
Hornwitser 2025-07-08 15:43:14 +02:00
parent 2d5af78568
commit 011687b391
12 changed files with 132 additions and 44 deletions

View file

@ -2,8 +2,10 @@
SPDX-FileCopyrightText: © 2025 Hornwitser <code@hornwitser.no>
SPDX-License-Identifier: AGPL-3.0-or-later
*/
import { readUsers } from "~/server/database";
import { readUsers, ServerSession } from "~/server/database";
import type { ApiAccount, ApiEvent } from "~/shared/types/api";
import { serverSessionToApi } from "./utils/session";
import { H3Event } from "h3";
function sendMessage(
stream: WritableStream<string>,
@ -31,18 +33,30 @@ function sendMessageAndClose(
;
}
const streams = new Map<WritableStream<string>, { sessionId?: number, accountId?: number }>();
const streams = new Map<WritableStream<string>, { sessionId?: number, accountId?: number, expiresAtMs: number }>();
let keepaliveInterval: ReturnType<typeof setInterval> | null = null
export function addStream(stream: WritableStream<string>, sessionId?: number, accountId?: number) {
export async function addStream(
event: H3Event,
stream: WritableStream<string>,
session?: ServerSession,
) {
if (streams.size === 0) {
console.log("Starting keepalive")
keepaliveInterval = setInterval(sendKeepalive, 4000)
}
streams.set(stream, { sessionId, accountId });
// Produce a response immediately to avoid the reply waiting for content.
const message = `data: connected sid:${sessionId ?? '-'} aid:${accountId ?? '-'}\n\n`;
sendMessage(stream, message);
const runtimeConfig = useRuntimeConfig(event);
streams.set(stream, {
sessionId: session?.id,
accountId: session?.accountId,
expiresAtMs: session?.expiresAtMs ?? Date.now() + runtimeConfig.sessionExpiresTimeout * 1000,
});
// Produce a response immediately to avoid the reply waiting for content.
const update: ApiEvent = {
type: "connected",
session: session ? await serverSessionToApi(event, session) : undefined,
};
sendMessage(stream, `event: update\ndata: ${JSON.stringify(update)}\n\n`);
}
export function deleteStream(stream: WritableStream<string>) {
streams.delete(stream);
@ -119,6 +133,13 @@ export async function broadcastEvent(event: ApiEvent) {
if (!streams.size) {
return;
}
// Session expiry events cause the streams belonging to that session to be terminated
if (event.type === "session-expired") {
cancelSessionStreams(event.sessionId);
return;
}
const users = await readUsers();
for (const [stream, streamData] of streams) {
// Account events are specially handled and only sent to the user they belong to.
@ -139,7 +160,12 @@ export async function broadcastEvent(event: ApiEvent) {
}
function sendKeepalive() {
for (const stream of streams.keys()) {
sendMessage(stream, ": keepalive\n");
const now = Date.now();
for (const [stream, streamData] of streams) {
if (streamData.expiresAtMs > now) {
sendMessage(stream, ": keepalive\n");
} else {
sendMessageAndClose(stream, `data: cancelled\n\n`);
}
}
}