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.
74 lines
1.9 KiB
TypeScript
74 lines
1.9 KiB
TypeScript
/*
|
|
SPDX-FileCopyrightText: © 2025 Hornwitser <code@hornwitser.no>
|
|
SPDX-License-Identifier: AGPL-3.0-or-later
|
|
*/
|
|
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";
|
|
|
|
export default defineEventHandler(async (event) => {
|
|
await requireServerSessionWithAdmin(event);
|
|
const { success, error, data: patch } = apiUserPatchSchema.safeParse(await readBody(event));
|
|
if (!success) {
|
|
throw createError({
|
|
status: 400,
|
|
statusText: "Bad Request",
|
|
message: z.prettifyError(error),
|
|
});
|
|
}
|
|
|
|
const users = await readUsers();
|
|
const user = users.find(user => user.id === patch.id);
|
|
if (!user || user.deleted) {
|
|
throw createError({
|
|
status: 409,
|
|
statusText: "Conflict",
|
|
message: "User does not exist",
|
|
});
|
|
|
|
}
|
|
|
|
let accessChanged = false;
|
|
if (patch.type && patch.type !== user.type) {
|
|
if (patch.type === "anonymous" || user.type === "anonymous") {
|
|
throw createError({
|
|
status: 409,
|
|
statusText: "Conflict",
|
|
message: "Anonymous user type cannot be changed.",
|
|
});
|
|
}
|
|
user.type = patch.type;
|
|
accessChanged = true;
|
|
}
|
|
if (patch.name) {
|
|
if (user.type === "anonymous") {
|
|
throw createError({
|
|
status: 409,
|
|
statusText: "Conflict",
|
|
message: "Anonymous user cannot have name set.",
|
|
});
|
|
}
|
|
user.name = patch.name;
|
|
}
|
|
user.updatedAt = new Date().toISOString();
|
|
await writeUsers(users);
|
|
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);
|
|
})
|