import { FreshContext } from '$fresh/server.ts' import { getCookies, setCookie } from '@std/http/cookie' import { SessionStore } from '../src/session/mod.ts' export async function handler(request: Request, ctx: FreshContext) { // Update fresh context state with session ctx.state = { ...ctx.state, session: SessionStore.getFromRequest(request) } // Allow service worker to serve root scope const response = await ctx.next() const url = new URL(request.url) if (url.pathname.endsWith('island-startserviceworker.js')) { response.headers.set('Service-Worker-Allowed', '/') } // Start session if (SessionStore.getFromRequest(request) === undefined) { // Clear outdated cookies for (const cookie in getCookies(request.headers)) { setCookie(response.headers, { name: cookie, value: '', path: '/', expires: 0, }) } // Create new session const session = SessionStore.createSession() ctx.state = { ...ctx.state, session } // Set session cookie setCookie(response.headers, { name: '_SESSION', value: session.uuid, httpOnly: true, sameSite: 'Strict', secure: true, path: '/', expires: SessionStore.maxAge, }) // Set csrf const csrf = crypto.randomUUID() session.set('_csrf', csrf) setCookie(response.headers, { name: '_CSRF', value: csrf, httpOnly: false, sameSite: 'Strict', secure: true, path: '/', expires: SessionStore.maxAge, }) } return response }