owltide/server/api/auth/account.delete.ts
Hornwitser 011687b391 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.
2025-07-08 16:13:46 +02:00

62 lines
1.7 KiB
TypeScript

/*
SPDX-FileCopyrightText: © 2025 Hornwitser <code@hornwitser.no>
SPDX-License-Identifier: AGPL-3.0-or-later
*/
import {
readUsers, readSessions, readSubscriptions,
writeUsers, writeSessions, writeSubscriptions,
} from "~/server/database";
import { broadcastEvent, cancelAccountStreams } from "~/server/streams";
export default defineEventHandler(async (event) => {
const serverSession = await requireServerSessionWithUser(event);
let users = await readUsers();
// Expire sessions for this user
const expiredSessionIds = new Set<number>();
let sessions = await readSessions();
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);
}
}
cancelAccountStreams(serverSession.accountId);
await writeSessions(sessions);
await deleteCookie(event, "session");
// Remove subscriptions for this user
let subscriptions = await readSubscriptions();
subscriptions = subscriptions.filter(
subscription => !expiredSessionIds.has(subscription.sessionId)
);
await writeSubscriptions(subscriptions);
// Remove the user
const account = users.find(user => user.id === serverSession.accountId)!;
const now = new Date(nowMs).toISOString();
account.deleted = true;
account.updatedAt = now;
await writeUsers(users);
await broadcastEvent({
type: "user-update",
data: {
id: account.id,
updatedAt: now,
deleted: true,
}
});
// Update Schedule counts.
await updateScheduleInterestedCounts(users);
})