Refactor sessions to frequently rotate

In order to minimise the window of opportunity to steal a session,
automatically rotate it onto a new session on a frequent basis.  This
makes a session cookie older than the automatic rollover time less
likely to grant access and more likely to be detected.

Should a stolen session cookie get rotated while the attacker is using
it, the user will be notificed that their session has been taken the
next time they open the app if the user re-visits the website before the
session is discarded.
This commit is contained in:
Hornwitser 2025-07-07 22:42:49 +02:00
parent d9b78bff69
commit 1775fac5fd
18 changed files with 168 additions and 73 deletions

View file

@ -40,7 +40,7 @@ export default defineEventHandler(async (event) => {
// Only keep sessions that match the account id in both sets to avoid
// resurrecting deleted sessions. This will still cause session cross
// pollution if a snapshot from another instance is loaded here.
return current && current.account.id === session.account.id;
return current?.accountId !== undefined && current.accountId === session.accountId;
}));
await writeSubscriptions(snapshot.subscriptions);
await writeSchedule(snapshot.schedule);

View file

@ -2,7 +2,7 @@
SPDX-FileCopyrightText: © 2025 Hornwitser <code@hornwitser.no>
SPDX-License-Identifier: AGPL-3.0-or-later
*/
import { readUsers, writeUsers } from "~/server/database";
import { readSessions, readUsers, writeSessions, writeUsers } from "~/server/database";
import { apiUserPatchSchema } from "~/shared/types/api";
import { z } from "zod/v4-mini";
import { broadcastEvent } from "~/server/streams";
@ -29,7 +29,8 @@ export default defineEventHandler(async (event) => {
}
if (patch.type) {
let accessChanged = false;
if (patch.type && patch.type !== user.type) {
if (patch.type === "anonymous" || user.type === "anonymous") {
throw createError({
status: 409,
@ -38,6 +39,7 @@ export default defineEventHandler(async (event) => {
});
}
user.type = patch.type;
accessChanged = true;
}
if (patch.name) {
if (user.type === "anonymous") {
@ -54,7 +56,18 @@ export default defineEventHandler(async (event) => {
broadcastEvent({
type: "user-update",
data: serverUserToApi(user),
})
});
// Expire sessions with the user in it if the access changed
if (accessChanged) {
const sessions = await readSessions();
for (const session of sessions) {
if (session.accountId === user.id) {
session.expiresAtMs = 0;
}
}
await writeSessions(sessions);
}
// Update Schedule counts.
await updateScheduleInterestedCounts(users);