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.
35 lines
1.3 KiB
TypeScript
35 lines
1.3 KiB
TypeScript
/*
|
|
SPDX-FileCopyrightText: © 2025 Hornwitser <code@hornwitser.no>
|
|
SPDX-License-Identifier: AGPL-3.0-or-later
|
|
*/
|
|
import { pipeline } from "node:stream";
|
|
import { addStream, deleteStream } from "~/server/streams";
|
|
|
|
export default defineEventHandler(async (event) => {
|
|
const session = await getServerSession(event, false);
|
|
|
|
const encoder = new TextEncoder();
|
|
const source = event.headers.get("x-forwarded-for");
|
|
console.log(`starting event stream for ${source}`)
|
|
const stream = new TransformStream<string, Uint8Array>({
|
|
transform(chunk, controller) {
|
|
controller.enqueue(encoder.encode(chunk));
|
|
},
|
|
flush(controller) {
|
|
console.log(`finished event stream for ${source}`);
|
|
deleteStream(stream.writable);
|
|
},
|
|
// @ts-expect-error experimental API
|
|
cancel(reason) {
|
|
console.log(`cancelled event stream for ${source}`);
|
|
deleteStream(stream.writable);
|
|
}
|
|
})
|
|
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", "*");
|
|
setHeader(event, "Content-Type", "text/event-stream");
|
|
pipeline(stream.readable as unknown as NodeJS.ReadableStream, event.node.res, (err) => { /* ignore */ });
|
|
event._handled = true;
|
|
});
|