import type { Handle, HandleServerError } from '@sveltejs/kit/hooks'; import { building } from '$app/env'; import { auth } from '#lib/server/auth.ts'; import { authRouteAllowed } from '#lib/server/auth-routes.ts'; import { withBodyFont } from '#lib/body-font.ts'; import { mailerConfigured } from '#lib/server/mail.ts'; import { declaredAddress, declaredOrigin } from '#lib/server/trusted-origin.ts'; import { ensureOwnerMembership } from '#lib/server/projects.ts'; import { ensureIndex } from '#lib/server/search.ts'; import { stampOpenedVersion } from '#lib/server/instance.ts'; import { pruneHistory } from '#lib/server/history-retention.ts'; const AUTH_PATH = '/api/auth'; /** * better-auth's SvelteKit helper matches a request to itself by comparing the * request's origin against a base URL, and behind a proxy that guess 404s every * auth call. The path identifies the handler, and `auth.handler` builds absolute * URLs from the declared origin instead. */ const handleAuth: Handle = async ({ event, resolve }) => { if (building) return resolve(event); const { request, url } = event; if (url.pathname === AUTH_PATH || url.pathname.startsWith(`${AUTH_PATH}/`)) { /* * A bare 404 is the shape better-auth answers with for a path it does not * have, so a probe cannot tell this gate from an endpoint that never existed. * Everything not listed carries a duplicate password path that would skip the * counters in the form actions. */ if (!authRouteAllowed(url.pathname, request.method)) { return new Response(null, { status: 404, statusText: 'Not Found' }); } return auth.handler(request); } const session = await auth.api.getSession({ headers: request.headers }); event.locals.user = session?.user; event.locals.session = session?.session; const response = await resolve(event, { transformPageChunk: ({ html }) => withBodyFont(html, session?.user.bodyFont) }); if (url.pathname.startsWith('/s/')) { response.headers.set('cache-control', 'private, no-store'); response.headers.set('referrer-policy', 'no-referrer'); response.headers.set('x-robots-tag', 'noindex, nofollow'); } return response; }; export const handle: Handle = handleAuth; export const handleError: HandleServerError = ({ error, kind }) => { // Hand the browser a safe message, and keep the detail in the server log. if (kind === 'framework' || kind === 'validation' || kind === 'app') { return { message: error.message, status: error.status }; } console.error('[fablewright]', error); return { message: 'The server could not complete the request. If you have unsaved words, keep the tab open and download them.', status: 500 }; }; /** * Run at boot, after the migrations and the FTS5 table creation in `db/index.ts`, * and never during a build, where there is no instance to repair. */ if (!building) { ensureIndex(); ensureOwnerMembership(); stampOpenedVersion(); expireHistory(); } /** * A prune failure must not stop the instance: a writer who cannot open the editor * has lost more than the space the versions hold. The next start tries again. */ function expireHistory() { try { const result = pruneHistory(); const removed = result.sceneVersions + result.itemVersions + result.projectVersions; if (removed > 0 && result.cutoff) { const day = result.cutoff.toISOString().slice(0, 10); console.info( `[fablewright] expired ${removed} ${removed === 1 ? 'version' : 'versions'} older than ${day}.` ); } } catch (error) { console.error('[fablewright] history was not expired at start:', error); } } /** Read once at boot, so the log says which address this instance advertises. */ const declared = declaredOrigin(); if (declared) { console.info(`[fablewright] public origin: ${declared}`); } else if (mailerConfigured() && !declaredAddress()) { /* * A reset link carries the instance's own address: the request that asks for it * names whatever host it likes. With no address there is nothing safe to mail, * so the link goes to this log. */ console.warn( '[fablewright] reset mail is off: this instance has no address to put in a link. Set ORIGIN, or INSTANCE_ORIGIN when the instance answers on several domains. Reset links go to this log.' ); }