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.
64 lines
1.5 KiB
TypeScript
64 lines
1.5 KiB
TypeScript
/*
|
|
SPDX-FileCopyrightText: © 2025 Hornwitser <code@hornwitser.no>
|
|
SPDX-License-Identifier: AGPL-3.0-or-later
|
|
*/
|
|
import { readUsers, writeUsers, nextUserId, type ServerUser } from "~/server/database";
|
|
import { broadcastEvent } from "~/server/streams";
|
|
|
|
export default defineEventHandler(async (event) => {
|
|
let session = await getServerSession(event, false);
|
|
if (session) {
|
|
throw createError({
|
|
status: 409,
|
|
message: "Cannot create account while having an active session."
|
|
});
|
|
}
|
|
|
|
const formData = await readFormData(event);
|
|
const name = formData.get("name");
|
|
|
|
const users = await readUsers();
|
|
let user: ServerUser;
|
|
if (typeof name === "string") {
|
|
if (name === "") {
|
|
throw createError({
|
|
status: 400,
|
|
message: "Name cannot be blank",
|
|
});
|
|
}
|
|
if (users.some(user => user.name && user.name.toLowerCase() === name.toLowerCase())) {
|
|
throw createError({
|
|
status: 409,
|
|
message: "User already exists",
|
|
});
|
|
}
|
|
|
|
const firstUser = users.every(user => user.type === "anonymous");
|
|
user = {
|
|
id: await nextUserId(),
|
|
updatedAt: new Date().toISOString(),
|
|
type: firstUser ? "admin" : "regular",
|
|
name,
|
|
};
|
|
|
|
} else if (name === null) {
|
|
user = {
|
|
id: await nextUserId(),
|
|
updatedAt: new Date().toISOString(),
|
|
type: "anonymous",
|
|
};
|
|
} else {
|
|
throw createError({
|
|
status: 400,
|
|
message: "Invalid name",
|
|
});
|
|
}
|
|
|
|
users.push(user);
|
|
await writeUsers(users);
|
|
await broadcastEvent({
|
|
type: "user-update",
|
|
data: user,
|
|
});
|
|
await setServerSession(event, user);
|
|
})
|