/** * App access gate for `appAccess: 'members'`. * * While the app is not internet-visible, Kody itself only lets people who can * run the app through, and this gate is a second check that changes nothing. * Once the app is internet-visible (needed for a custom domain at the host * root), Kody lets anyone reach the app, so this gate keeps it private: only * signed-in members of the owning org get in. Anonymous visitors are sent to * Sign in with Kody (`/-/auth/login`), signed-in non-members get a no-access * page, and API calls get 401 or 403 JSON. * * Identity comes from the platform: the `X-Kody-Visitor` header (Kody strips * any inbound `X-Kody-*` header before setting it) or, when that is absent, * `kody.metaGetCurrentUser()`. */ import { kody, packageContext } from 'kody:runtime' export type Visitor = { userId: string; username: string; role: string | null } type MetaClient = { metaGetCurrentUser?: (input: Record) => Promise<{ user_id?: string; username?: string; role?: string | null }> } export async function resolveVisitor(request: Request): Promise { const header = request.headers.get('x-kody-visitor') if (header) { try { const v = JSON.parse(header) as { userId?: unknown; username?: unknown; role?: unknown } if (typeof v.userId === 'string' && v.userId) { return { userId: v.userId, username: typeof v.username === 'string' ? v.username : '', role: typeof v.role === 'string' && v.role ? v.role : null } } } catch {} } try { const me = await (kody as unknown as MetaClient).metaGetCurrentUser?.({}) if (me?.user_id) return { userId: String(me.user_id), username: String(me.username ?? ''), role: typeof me.role === 'string' && me.role ? me.role : null } } catch {} return null } /** Paths that carry no factory data and stay open (uptime check, icons). */ export function isOpenPath(path: string): boolean { return path === '/health' || path === '/favicon.svg' || path === '/favicon.ico' || path === '/notification-badge-v1.png' } function wantsJson(request: Request, path: string): boolean { return path.startsWith('/api/') || request.method !== 'GET' || (request.headers.get('accept') ?? '').includes('application/json') && !(request.headers.get('accept') ?? '').includes('text/html') } function page(title: string, body: string, status: number): Response { return new Response(`${title} ยท Kody Factory${body}`, { status, headers: { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' }, }) } /** Sign in with Kody, then come back to `returnTo`. */ export function loginUrl(returnTo: string): string { const app = String(packageContext?.kodyId ?? 'kody-factory') return `/-/auth/login?app=${encodeURIComponent(app)}&return_to=${encodeURIComponent(returnTo)}` } /** * Null when the visitor may continue; otherwise the response to send. * `returnTo` is the full path and query the visitor asked for. */ export async function gateRequest(request: Request, path: string, returnTo: string, visitorOf: (r: Request) => Promise = resolveVisitor): Promise { if (isOpenPath(path)) return null const visitor = await visitorOf(request) if (visitor?.role) return null if (wantsJson(request, path)) { return visitor ? Response.json({ error: 'You need to be a member of the org that owns this factory.' }, { status: 403, headers: { 'cache-control': 'no-store' } }) : Response.json({ error: 'Sign in with Kody first.', login: loginUrl(returnTo) }, { status: 401, headers: { 'cache-control': 'no-store' } }) } if (!visitor) return new Response(null, { status: 302, headers: { Location: loginUrl(returnTo), 'cache-control': 'no-store' } }) return page('No access', `

No access

You are signed in as ${escapeHtml(visitor.username || 'a Kody user')}, but this factory is private to its org's members.

Sign out

`, 403) } function escapeHtml(s: string): string { return s.replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]!) }