// A vendor's browser session: the bookkeeping used by its own sign-in and sign-out pages. import type { HandlerContext } from './derived-core.ts'; import { personOf, type Person } from './people.ts'; type Writer = Pick; /** The value of the cookie `name` the request carries, as a browser sends it back. */ export function cookieOf(request: Request, name: string): string | undefined { for (const part of (request.headers.get('cookie') ?? '').split(';')) { const at = part.indexOf('='); if (at > 0 && part.slice(0, at).trim() === name) return decodeURIComponent(part.slice(at + 1).trim()); } return undefined; } /** The named session cookie; malformed encodings do not name a session. */ export function browserSessionToken(request: Request, name: string): string | undefined { try { return cookieOf(request, name); } catch { return undefined; } } /** The person the request's session cookie names, or undefined when nobody is signed in; with `scope`, only a session * begun in it (a vendor's sandbox dashboard and its production one sign a person in apart). */ export function signedIn(ctx: HandlerContext, cookie: string, scope?: string): Person | undefined { const token = cookieOf(ctx.call.request, cookie); const session = token ? ctx.rowsRaw('_web_session').find((s) => s.token === token && (scope === undefined || s.scope === scope)) : undefined; return session ? personOf(ctx, String(session.email)) : undefined; } /** A new, independent sign-in, returning the cookie the vendor places on its response. */ export async function startBrowserSession(ctx: Writer, email: string, cookie: string, scope?: string): Promise { const issued = await ctx.record('_web_session_issue', { email, ...(scope !== undefined ? { scope } : {}) }); const token = await ctx.secret(`web-session:${issued}`); await ctx.record('_web_session', { token, email, ...(scope !== undefined ? { scope } : {}), created_at: ctx.occurredAt }, `websession:${token}`); return `${cookie}=${token}; path=/; HttpOnly; Secure; SameSite=Lax`; } /** End the session the request holds, then clear its cookie. Unknown cookies create no rows. */ export async function endBrowserSession(ctx: Pick, cookie: string): Promise { const token = browserSessionToken(ctx.call.request, cookie); const session = token ? ctx.rowsRaw('_web_session').find((s) => s.token === token) : undefined; if (session) await ctx.record('_web_session', { token: null, ended_at: ctx.occurredAt }, String(session.id)); return `${cookie}=; path=/; Max-Age=0; HttpOnly; Secure; SameSite=Lax`; }