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

@ -64,6 +64,10 @@ export default defineEventHandler(async (event) => {
for (const session of sessions) {
if (session.accountId === user.id) {
session.expiresAtMs = 0;
broadcastEvent({
type: "session-expired",
sessionId: session.id,
});
}
}
await writeSessions(sessions);

View file

@ -12,16 +12,25 @@ export default defineEventHandler(async (event) => {
const serverSession = await requireServerSessionWithUser(event);
let users = await readUsers();
// Remove sessions for this user
const removedSessionIds = new Set<number>();
// Expire sessions for this user
const expiredSessionIds = new Set<number>();
let sessions = await readSessions();
sessions = sessions.filter(session => {
if (session.accountId === serverSession.accountId) {
removedSessionIds.add(session.id);
return false;
const nowMs = Date.now();
for (const session of sessions) {
if (
!session.finished
&& session.successor !== undefined
&& session.expiresAtMs < nowMs
&& session.accountId === serverSession.accountId
) {
session.expiresAtMs = nowMs;
broadcastEvent({
type: "session-expired",
sessionId: session.id,
});
expiredSessionIds.add(session.id);
}
return true;
});
}
cancelAccountStreams(serverSession.accountId);
await writeSessions(sessions);
await deleteCookie(event, "session");
@ -29,13 +38,13 @@ export default defineEventHandler(async (event) => {
// Remove subscriptions for this user
let subscriptions = await readSubscriptions();
subscriptions = subscriptions.filter(
subscription => !removedSessionIds.has(subscription.sessionId)
subscription => !expiredSessionIds.has(subscription.sessionId)
);
await writeSubscriptions(subscriptions);
// Remove the user
const account = users.find(user => user.id === serverSession.accountId)!;
const now = new Date().toISOString();
const now = new Date(nowMs).toISOString();
account.deleted = true;
account.updatedAt = now;
await writeUsers(users);

View file

@ -18,8 +18,5 @@ export default defineEventHandler(async (event) => {
}
}
if (session) {
cancelSessionStreams(session.id);
}
await clearServerSession(event);
})

View file

@ -2,23 +2,10 @@
SPDX-FileCopyrightText: © 2025 Hornwitser <code@hornwitser.no>
SPDX-License-Identifier: AGPL-3.0-or-later
*/
import { readSubscriptions, readUsers } from "~/server/database";
import type { ApiSession } from "~/shared/types/api";
export default defineEventHandler(async (event): Promise<ApiSession | undefined> => {
export default defineEventHandler(async event => {
const session = await getServerSession(event, false);
if (!session)
return;
const users = await readUsers();
const account = users.find(user => user.id === session.accountId);
const subscriptions = await readSubscriptions();
const push = Boolean(
subscriptions.find(sub => sub.type === "push" && sub.sessionId === session.id)
);
return {
id: session.id,
account,
push,
};
return await serverSessionToApi(event, session);
})

View file

@ -24,8 +24,8 @@ export default defineEventHandler(async (event) => {
console.log(`cancelled event stream for ${source}`);
deleteStream(stream.writable);
}
})
addStream(stream.writable, session?.id, session?.accountId);
});
addStream(event, stream.writable, session);
// Workaround to properly handle stream errors. See https://github.com/unjs/h3/issues/986
setHeader(event, "Access-Control-Allow-Origin", "*");

View file

@ -13,6 +13,7 @@ export interface ServerSession {
expiresAtMs: number,
discardAtMs: number,
successor?: Id,
finished: boolean,
};
export interface ServerUser {

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`);
}
}
}

View file

@ -13,6 +13,8 @@ import {
writeSessions,
writeSubscriptions
} from "~/server/database";
import { broadcastEvent } from "../streams";
import type { ApiSession } from "~/shared/types/api";
async function removeSessionSubscription(sessionId: number) {
const subscriptions = await readSubscriptions();
@ -27,9 +29,13 @@ async function clearServerSessionInternal(event: H3Event, sessions: ServerSessio
const existingSessionCookie = await getSignedCookie(event, "session");
if (existingSessionCookie) {
const sessionId = parseInt(existingSessionCookie, 10);
const sessionIndex = sessions.findIndex(session => session.id === sessionId);
if (sessionIndex !== -1) {
sessions.splice(sessionIndex, 1);
const session = sessions.find(session => session.id === sessionId);
if (session) {
session.finished = true;
broadcastEvent({
type: "session-expired",
sessionId,
});
await removeSessionSubscription(sessionId);
return true;
}
@ -56,6 +62,7 @@ export async function setServerSession(event: H3Event, account: ServerUser) {
access: account.type,
expiresAtMs: now + runtimeConfig.sessionExpiresTimeout * 1000,
discardAtMs: now + runtimeConfig.sessionDiscardTimeout * 1000,
finished: false,
id: await nextSessionId(),
};
@ -74,6 +81,7 @@ async function rotateSession(event: H3Event, sessions: ServerSession[], session:
access: account?.type ?? "anonymous",
expiresAtMs: now + runtimeConfig.sessionExpiresTimeout * 1000,
discardAtMs: now + runtimeConfig.sessionDiscardTimeout * 1000,
finished: false,
id: await nextSessionId(),
};
session.successor = newSession.id;
@ -90,6 +98,9 @@ export async function getServerSession(event: H3Event, ignoreExpired: boolean) {
const sessions = await readSessions();
const session = sessions.find(session => session.id === sessionId);
if (session) {
if (session.finished) {
return undefined;
}
if (!ignoreExpired && session.successor !== undefined) {
throw createError({
statusCode: 403,
@ -149,3 +160,18 @@ export async function requireServerSessionWithAdmin(event: H3Event) {
}
return { ...session, accountId: session.accountId };
}
export async function serverSessionToApi(event: H3Event, session: ServerSession): Promise<ApiSession> {
const users = await readUsers();
const account = users.find(user => user.id === session.accountId);
const subscriptions = await readSubscriptions();
const push = Boolean(
subscriptions.find(sub => sub.type === "push" && sub.sessionId === session.id)
);
return {
id: session.id,
account,
push,
};
}