Skip to content

Black Friday

Annual Pro is $90 for the first year, normally $120. Or start monthly at $6 for two months, then $12.

Ends Dec 4, 11:59 PM PT.

Create an account
← Public packages

@kody/app-starter

A basic TanStack app with a design system, light and dark, sign-in, and storage already wired up.

FollowFork

Files

auth.ts

44 lines · 1.4 KB · TypeScript
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<string, unknown>
		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}`,
	}
}