Files
famdone/frontend/src/lib/server/session.ts
T

53 lines
1.9 KiB
TypeScript

import type { Cookies } from '@sveltejs/kit';
// The PocketBase JWT lives in a single cookie shared by:
// - the server hooks (authRefresh -> locals.user)
// - the client SDK (seeded from page.data.pbToken -> authenticated famStore reads/subscribe)
// httpOnly keeps the token out of reach of browser JS/XSS; the client receives
// the token server-side via the layout load (pbToken) and seeds pb.authStore.
// Secure flag is set in prod so it's only sent over HTTPS.
export const SESSION_COOKIE = 'pb_token';
const MAX_AGE = 60 * 60 * 24 * 5; // 5 days — matches the PB users auth token duration
export function setSessionCookie(cookies: Cookies, token: string) {
cookies.set(SESSION_COOKIE, token, {
httpOnly: true,
sameSite: 'lax',
path: '/',
maxAge: MAX_AGE,
secure: import.meta.env.PROD
});
}
export function clearSessionCookie(cookies: Cookies) {
cookies.delete(SESSION_COOKIE, { path: '/' });
}
// Legacy pre-PB-auth child cookie. No longer issued anywhere; these deletes
// exist only to scrub it from browsers that still carry one.
const LEGACY_DEVICE_COOKIE = 'device_token';
export function clearLegacyCookies(cookies: Cookies) {
cookies.delete(LEGACY_DEVICE_COOKIE, { path: '/' });
}
// ── Platform-admin session (/admin) ──
// Holds a REAL PocketBase superuser JWT (minted by _superusers.authWithPassword
// at login) — verified per-request in hooks via authRefresh, so forging the
// cookie value gains nothing. Separate from the fam-user pb_token.
export const PLATFORM_SESSION_COOKIE = 'platform_session';
const PLATFORM_MAX_AGE = 60 * 60 * 24; // 24h; PB token expiry is the ceiling
export function setPlatformSession(cookies: Cookies, token: string) {
cookies.set(PLATFORM_SESSION_COOKIE, token, {
httpOnly: true,
sameSite: 'lax',
path: '/',
maxAge: PLATFORM_MAX_AGE,
secure: import.meta.env.PROD
});
}
export function clearPlatformSession(cookies: Cookies) {
cookies.delete(PLATFORM_SESSION_COOKIE, { path: '/' });
}