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

View file

@ -9,20 +9,20 @@ import {
import { broadcastEvent, cancelAccountStreams } from "~/server/streams";
export default defineEventHandler(async (event) => {
const serverSession = await requireServerSession(event);
const serverSession = await requireServerSessionWithUser(event);
let users = await readUsers();
// Remove sessions for this user
const removedSessionIds = new Set<number>();
let sessions = await readSessions();
sessions = sessions.filter(session => {
if (session.account.id === serverSession.account.id) {
if (session.accountId === serverSession.accountId) {
removedSessionIds.add(session.id);
return false;
}
return true;
});
cancelAccountStreams(serverSession.account.id);
cancelAccountStreams(serverSession.accountId);
await writeSessions(sessions);
await deleteCookie(event, "session");
@ -34,7 +34,7 @@ export default defineEventHandler(async (event) => {
await writeSubscriptions(subscriptions);
// Remove the user
const account = users.find(user => user.id === serverSession.account.id)!;
const account = users.find(user => user.id === serverSession.accountId)!;
const now = new Date().toISOString();
account.deleted = true;
account.updatedAt = now;

View file

@ -9,7 +9,7 @@ import { z } from "zod/v4-mini";
export default defineEventHandler(async (event) => {
const session = await requireServerSession(event);
const session = await requireServerSessionWithUser(event);
const { success, error, data: patch } = apiAccountPatchSchema.safeParse(await readBody(event));
if (!success) {
throw createError({
@ -39,7 +39,7 @@ export default defineEventHandler(async (event) => {
}
const users = await readUsers();
const account = users.find(user => user.id === session.account.id);
const account = users.find(user => user.id === session.accountId);
if (!account) {
throw Error("Account does not exist");
}

View file

@ -6,7 +6,7 @@ import { readUsers, writeUsers, nextUserId, type ServerUser } from "~/server/dat
import { broadcastEvent } from "~/server/streams";
export default defineEventHandler(async (event) => {
let session = await getServerSession(event);
let session = await getServerSession(event, false);
if (session) {
throw createError({
status: 409,

View file

@ -2,12 +2,15 @@
SPDX-FileCopyrightText: © 2025 Hornwitser <code@hornwitser.no>
SPDX-License-Identifier: AGPL-3.0-or-later
*/
import { readUsers } from "~/server/database";
import { cancelSessionStreams } from "~/server/streams";
export default defineEventHandler(async (event) => {
const session = await getServerSession(event);
const session = await getServerSession(event, true);
if (session) {
if (session.account.type === "anonymous") {
const users = await readUsers();
const account = users.find(user => user.id === session.accountId);
if (account?.type === "anonymous") {
throw createError({
status: 409,
message: "Cannot log out of an anonymous account",

View file

@ -2,23 +2,23 @@
SPDX-FileCopyrightText: © 2025 Hornwitser <code@hornwitser.no>
SPDX-License-Identifier: AGPL-3.0-or-later
*/
import { readSubscriptions } from "~/server/database";
import { readSubscriptions, readUsers } from "~/server/database";
import type { ApiSession } from "~/shared/types/api";
export default defineEventHandler(async (event): Promise<ApiSession | undefined> => {
const session = await getServerSession(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)
);
await refreshServerSession(event, session);
return {
id: session.id,
account: session.account,
account,
push,
};
})

View file

@ -6,8 +6,7 @@ import { pipeline } from "node:stream";
import { addStream, deleteStream } from "~/server/streams";
export default defineEventHandler(async (event) => {
const session = await getServerSession(event);
const accountId = session?.account.id;
const session = await getServerSession(event, false);
const encoder = new TextEncoder();
const source = event.headers.get("x-forwarded-for");
@ -26,7 +25,7 @@ export default defineEventHandler(async (event) => {
deleteStream(stream.writable);
}
})
addStream(stream.writable, session?.id, accountId);
addStream(stream.writable, session?.id, session?.accountId);
// Workaround to properly handle stream errors. See https://github.com/unjs/h3/issues/986
setHeader(event, "Access-Control-Allow-Origin", "*");

View file

@ -9,9 +9,9 @@ import { apiScheduleSchema } from "~/shared/types/api";
import { applyUpdatesToArray } from "~/shared/utils/update";
export default defineEventHandler(async (event) => {
const session = await requireServerSession(event);
const session = await requireServerSessionWithUser(event);
if (session.account.type !== "admin" && session.account.type !== "crew") {
if (session.access !== "admin" && session.access !== "crew") {
throw createError({
status: 403,
statusMessage: "Forbidden",
@ -45,7 +45,7 @@ export default defineEventHandler(async (event) => {
}
// Validate edit restrictions for crew
if (session.account.type === "crew") {
if (session.access === "crew") {
if (update.locations?.length) {
throw createError({
status: 403,

View file

@ -5,7 +5,7 @@
import { readSchedule } from "~/server/database";
export default defineEventHandler(async (event) => {
const session = await getServerSession(event);
const session = await getServerSession(event, false);
const schedule = await readSchedule();
return canSeeCrew(session?.account.type) ? schedule : filterSchedule(schedule);
return canSeeCrew(session?.access) ? schedule : filterSchedule(schedule);
});

View file

@ -11,7 +11,7 @@ const subscriptionSchema = z.strictObject({
});
export default defineEventHandler(async (event) => {
const session = await requireServerSession(event);
const session = await requireServerSessionWithUser(event);
const { success, error, data: body } = subscriptionSchema.safeParse(await readBody(event));
if (!success) {
throw createError({

View file

@ -5,7 +5,7 @@
import { readSubscriptions, writeSubscriptions } from "~/server/database";
export default defineEventHandler(async (event) => {
const session = await requireServerSession(event);
const session = await requireServerSessionWithUser(event);
const subscriptions = await readSubscriptions();
const existingIndex = subscriptions.findIndex(
sub => sub.type === "push" && sub.sessionId === session.id

View file

@ -5,13 +5,13 @@
import { readUsers } from "~/server/database"
export default defineEventHandler(async (event) => {
const session = await requireServerSession(event);
const session = await requireServerSessionWithUser(event);
const users = await readUsers();
if (session.account.type === "admin") {
if (session.access === "admin") {
return users.map(serverUserToApi);
}
if (session.account.type === "crew") {
if (session.access === "crew") {
return users.filter(u => u.type === "crew" || u.type === "admin").map(serverUserToApi);
}
throw createError({