Skip to content
← Public packages

@kody/kody-factory

Forkable multi-project software factory: signals, priority queue, project UI, sweep job. Agent runners and Sentry reach it by events.

FollowFork

Files

access.ts

80 lines · 4.5 KB · TypeScript
/**
 * 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<string, never>) => Promise<{ user_id?: string; username?: string; role?: string | null }> }

export async function resolveVisitor(request: Request): Promise<Visitor | null> {
	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(`<!doctype html><html lang="en"><head><meta charset="utf-8"/><meta name="viewport" content="width=device-width,initial-scale=1"/><title>${title} · Kody Factory</title><style>body{font:16px/1.5 ui-sans-serif,system-ui,sans-serif;max-width:32rem;margin:15vh auto;padding:0 1.5rem;color:#2b3245;background:#f7f8fc}@media (prefers-color-scheme:dark){body{color:#d5d9e6;background:#111522}a{color:#a5b4fc}}h1{font-size:1.4rem}</style></head><body>${body}</body></html>`, {
		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<Visitor | null> = resolveVisitor): Promise<Response | null> {
	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', `<h1>No access</h1><p>You are signed in as <b>${escapeHtml(visitor.username || 'a Kody user')}</b>, but this factory is private to its org's members.</p><p><a href="/-/auth/logout?app=${encodeURIComponent(String(packageContext?.kodyId ?? 'kody-factory'))}">Sign out</a></p>`, 403)
}

function escapeHtml(s: string): string {
	return s.replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]!)
}