export type Visitor = { userId: string; username: string } /** The platform sets `X-Kody-Visitor` on every signed-in request. It cannot be forged. */ export function readVisitor(request: Request): Visitor | null { const raw = request.headers.get('X-Kody-Visitor') if (!raw) return null try { const value = JSON.parse(raw) as Record if (typeof value['userId'] !== 'string' || !value['userId']) return null return { userId: value['userId'], username: typeof value['username'] === 'string' ? value['username'] : '', } } catch { return null } } /** The app's leaf name, read from its hosted URL (`leaf--owner.kody.run` or `owner.kody.run/leaf`). */ function appLeaf(hostedUrl: string | null | undefined) { if (!hostedUrl) return null try { const url = new URL(hostedUrl) const label = url.hostname.split('.')[0] ?? '' if (label.includes('--')) return label.split('--')[0] || null return url.pathname.split('/').filter(Boolean)[0] ?? null } catch { return null } } /** Sign-in and sign-out links. The platform serves `/-/auth/*` at the host root. */ export function authLinks(input: { hostedUrl: string | null | undefined returnTo: string }) { const params = new URLSearchParams({ return_to: input.returnTo }) const app = appLeaf(input.hostedUrl) if (app) params.set('app', app) return { signIn: `/-/auth/login?${params}`, signOut: `/-/auth/logout?${params}`, } }