import { KodyRuntime } from 'kody:runtime' import type { Action } from 'remix/router' import { redirect } from 'remix/response/redirect' import { getStorage, isPreviewToken, previewCookie } from '../data/site.ts' import { routes } from '../routes.ts' function cookiePath(appBase: string) { return appBase || '/' } /** Keep `to` inside the site: a path like "/galleries/x", never another origin. */ function safeTarget(appBase: string, to: string | null) { if (!to || !to.startsWith('/') || to.startsWith('//')) return routes.home.href() return `${appBase}${to}` } /** `/preview?token=…&to=/path`: switch this browser to the draft, then show the page. */ export const enterPreview = { async handler(context) { const appBase = context.get(KodyRuntime).packageContext?.appBasePath ?? '' const token = context.url.searchParams.get('token') if (!(await isPreviewToken(getStorage(context), token))) { return new Response( 'This preview link has expired. Ask your agent for a fresh one (get-preview-url).', { status: 403, headers: { 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-store', }, }, ) } const response = redirect( safeTarget(appBase, context.url.searchParams.get('to')), 303, ) response.headers.append( 'Set-Cookie', `${previewCookie}=${encodeURIComponent(token!)}; Path=${cookiePath(appBase)}; Max-Age=86400; HttpOnly; Secure; SameSite=Lax`, ) response.headers.set('Cache-Control', 'no-store') return response }, } satisfies Action /** `/preview/exit`: back to the live site. */ export const exitPreview = { async handler(context) { const appBase = context.get(KodyRuntime).packageContext?.appBasePath ?? '' const response = redirect(routes.home.href(), 303) response.headers.append( 'Set-Cookie', `${previewCookie}=; Path=${cookiePath(appBase)}; Max-Age=0; HttpOnly; Secure; SameSite=Lax`, ) response.headers.set('Cache-Control', 'no-store') return response }, } satisfies Action