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

@kentcdodds/pie-night

Pie night sign-ups: hosts start an event, guests add the pies they are bringing and watch the list fill in live. Installable, with optional push notifications.

FollowForkOpen app

Files

app.ts

455 lines · 22.5 KB · TypeScript
import runtime, { kody, packageContext, packageStorage } from 'kody:runtime'
import { HOME_REDIRECT_KEY, LIMITS, cleanHosts, cleanText, formatEventWhen, isHoneypotFilled, parseEventInput, parsePieBatch, parsePieInput, pieLook, slugify, validSlug, type EventInfo } from './pies.ts'
import { addPies, countEventsBy, countPies, createEvent, getEvent, getPushPublicKey, hasPushSub, heartbeat, leave, listEventsFor, listPies, listRemoved, newNight, presentPeople, removePie, removePushSub, restorePie, savePushSub, updateEvent, updatePie, type PieRow } from './store.ts'
import { FAVICON_SVG } from './art.ts'
import { eventPageHtml, homePageHtml, newEventPageHtml, notFoundHtml, offlineHtml } from './page.ts'
import { renderOgPng } from './og.ts'
import { notifyEvent, parseSubscription } from './push.ts'
import { serviceWorkerJs } from './sw.ts'

// Bump when public/app.js, public/home.js, public/styles.css, or the service worker change.
export const ASSET_VERSION = '8'


const HOST = /^[a-z0-9.-]+(:\d{1,5})?$/i
const JSON_HEADERS = { 'cache-control': 'no-store' }
const HTML_HEADERS = { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store', 'x-robots-tag': 'noindex' }

type Visitor = { userId: string; username: string; role: string | null } | null

function publicOrigin(request: Request, url: URL) {
	const raw = (request.headers.get('x-forwarded-host') || request.headers.get('host') || url.host).split(',')[0]!.trim()
	if (!HOST.test(raw)) return url.origin
	const local = /^(localhost|127\.|\[::1\])|\.localhost(:\d+)?$/i.test(raw)
	return `${local ? 'http' : 'https'}://${raw.toLowerCase()}`
}

function readVisitor(request: Request): Visitor {
	const raw = request.headers.get('x-kody-visitor')
	if (!raw) return null
	try {
		const value = JSON.parse(raw) as { userId?: unknown; username?: unknown; role?: unknown }
		if (!value.userId || !value.username) return null
		return { userId: String(value.userId), username: String(value.username).toLowerCase(), role: value.role == null ? null : String(value.role) }
	} catch {
		return null
	}
}

/**
 * Hosts of one event: its creator and co-hosts (Kody usernames). Members of
 * the org that owns this app can also manage every event (moderation).
 */
function isHost(visitor: Visitor, event: EventInfo) {
	if (!visitor) return false
	if (visitor.role) return true
	return visitor.username === event.creator || event.hosts.includes(visitor.username)
}

function clientIp(request: Request) {
	return (request.headers.get('cf-connecting-ip') || request.headers.get('x-real-ip') || request.headers.get('x-forwarded-for') || 'unknown').split(',')[0]!.trim().slice(0, 64)
}

async function limited(keys: Array<[string, number, number]>) {
	try {
		for (const [key, limit, windowSeconds] of keys) {
			const r = await kody.appRateLimit({ key, limit, windowSeconds })
			if (!r.allowed) return true
		}
		return false
	} catch {
		return false
	}
}

const writeLimited = (request: Request, slug: string) =>
	limited([
		[`write:ip:${clientIp(request)}`, 30, 600],
		[`write:event:${slug}`, 400, 3600],
		['write:all', 3000, 3600],
	])
const presenceLimited = (request: Request) =>
	limited([
		[`presence:ip:${clientIp(request)}`, 300, 600],
		['presence:all', 20000, 3600],
	])

type Realtime = { broadcast(input: { data: unknown; facet?: string }): Promise<unknown> }

/**
 * Push an update to every open page of one event over Kody realtime (facet =
 * event code). Pages that cannot open a socket (for example before the owner
 * approves anonymous realtime) still poll.
 */
async function broadcast(slug: string, data: Record<string, unknown>) {
	try {
		const rt = (runtime as unknown as { realtime?: Realtime }).realtime
		if (!rt?.broadcast) return
		// Socket messages are capped around 64 KiB. A very full list sends a
		// small "go refetch" nudge instead of the whole list.
		const body = JSON.stringify(data).length > 48_000 && 'pies' in data ? { ...data, pies: undefined, refetch: true } : data
		await rt.broadcast({ data: body, facet: slug })
	} catch (error) {
		console.warn('pie-night broadcast failed', error instanceof Error ? error.message : error)
	}
}

function tabId(request: Request) {
	const raw = request.headers.get('x-pie-tab') || ''
	return /^[a-z0-9-]{8,40}$/i.test(raw) ? raw.slice(0, 8) : ''
}

function publicPeople(people: Array<{ sid: string; name: string; typing: boolean }>) {
	return people.map((p) => ({ id: p.sid.slice(0, 8), name: p.name, typing: p.typing }))
}

function json(body: unknown, status = 200) {
	return Response.json(body, { status, headers: JSON_HEADERS })
}

function publicPie(row: PieRow) {
	return { id: row.id, who: row.who, pie: row.pie, note: row.note, createdAt: row.createdAt, look: pieLook(row.pie) }
}

/** What visitors see about an event. Hosts are only listed on the host page. */
function publicEvent(event: EventInfo) {
	return { slug: event.slug, code: event.code, title: event.title, date: event.date, time: event.time, place: event.place, blurb: event.blurb, theme: event.theme, night: event.night, version: event.version, when: formatEventWhen(event) }
}

async function readJson(request: Request): Promise<unknown> {
	const type = request.headers.get('content-type') || ''
	if (!type.includes('application/json')) throw new HttpError(415, 'Send JSON.')
	const length = Number(request.headers.get('content-length') || 0)
	if (length > 8192) throw new HttpError(413, 'That is a little too long.')
	const text = await request.text()
	if (text.length > 8192) throw new HttpError(413, 'That is a little too long.')
	try {
		return JSON.parse(text)
	} catch {
		throw new HttpError(400, 'Something went wrong. Try again?')
	}
}

/** Reject cross-site writes: browsers always send Origin on POST/PATCH/DELETE fetches. */
function sameOrigin(request: Request, url: URL) {
	const origin = request.headers.get('origin')
	if (!origin) return true
	return origin === publicOrigin(request, url) || origin === url.origin
}

class HttpError extends Error {
	constructor(
		public status: number,
		message: string,
	) {
		super(message)
	}
}

function paths() {
	const appBase = (packageContext?.appBasePath ?? '').replace(/\/+$/, '')
	const assetBase = (packageContext?.assetBasePath ?? `${appBase}/_assets`).replace(/\/+$/, '')
	const ctx = packageContext as unknown as { kodyId?: string; packageName?: string; name?: string } | undefined
	const leaf = String(ctx?.kodyId || ctx?.packageName || ctx?.name || 'pie-night').split('/').pop() || 'pie-night'
	return { appBase, assetBase, leaf }
}

async function state(night: string) {
	return (await listPies(night)).map(publicPie)
}

async function homeRedirect(): Promise<string> {
	const raw = await packageStorage().get(HOME_REDIRECT_KEY)
	const slug = typeof raw === 'string' ? slugify(raw) : ''
	return validSlug(slug) ? slug : ''
}

function redirect(location: string, status = 302) {
	return new Response(null, { status, headers: { location, 'cache-control': 'no-store' } })
}

function decodeCode(raw: string) {
	try {
		return decodeURIComponent(raw)
	} catch {
		return raw
	}
}

function listText(items: string[]) {
	if (items.length <= 1) return items[0] ?? 'a pie'
	return `${items.slice(0, -1).join(', ')} and ${items[items.length - 1]}`
}

export default {
	async fetch(request: Request, _env?: unknown, ctx?: { waitUntil?: (p: Promise<unknown>) => void }) {
		// Send pushes after the response when the runtime allows it, so adding a pie stays snappy.
		const later = (job: Promise<unknown>) => (ctx?.waitUntil ? ctx.waitUntil(job) : job)
		const url = new URL(request.url)
		const { appBase, assetBase, leaf } = paths()
		const path = url.pathname.slice(appBase.length).replace(/\/+$/, '') || '/'
		const method = request.method.toUpperCase()
		const origin = publicOrigin(request, url)
		const site = origin + appBase
		const read = method === 'GET' || method === 'HEAD'
		const loginUrl = (returnTo: string) => `/-/auth/login?app=${encodeURIComponent(leaf)}&return_to=${encodeURIComponent(appBase + returnTo)}`
		const shared = { appBase, assetBase, site, assetVersion: ASSET_VERSION, limits: LIMITS }

		try {
			// ---------- Pages ----------
			if (path === '/' && read) {
				const target = await homeRedirect()
				if (target && !url.searchParams.has('home')) return redirect(`${appBase}/e/${target}${url.search}`)
				const visitor = readVisitor(request)
				const mine = visitor ? (await listEventsFor(visitor.username)).map(publicEvent) : []
				return new Response(homePageHtml({ ...shared, visitor, mine, loginUrl: loginUrl('/new') }), { headers: HTML_HEADERS })
			}
			if (path === '/new' && read) {
				const visitor = readVisitor(request)
				return new Response(newEventPageHtml({ ...shared, visitor, loginUrl: loginUrl('/new') }), { headers: HTML_HEADERS })
			}
			if (path === '/admin' && read) {
				const target = await homeRedirect()
				return redirect(target ? `${appBase}/e/${target}/admin` : `${appBase}/`)
			}
			if (path === '/offline' && read) return new Response(offlineHtml(shared), { headers: { ...HTML_HEADERS, 'cache-control': 'no-cache' } })

			const eventPath = path.match(/^\/e\/([^/]+)(\/admin|\/og\.png|\/manifest\.webmanifest)?$/)
			if (eventPath && read) {
				const raw = decodeCode(eventPath[1]!)
				const slug = slugify(raw)
				const sub = eventPath[2] ?? ''
				if (slug && slug !== eventPath[1]) return redirect(`${appBase}/e/${slug}${sub}${url.search}`)
				const event = await getEvent(slug)
				if (!event) {
					if (sub === '/og.png') return redirect(`${assetBase}/og.png`)
					return new Response(notFoundHtml({ ...shared, code: raw }), { status: 404, headers: HTML_HEADERS })
				}
				if (sub === '/og.png') {
					const when = formatEventWhen(event)
					const png = await renderOgPng(`${event.slug}:${event.version}`, { title: event.title, day: when.medium, time: when.time, place: event.place, theme: event.theme })
					const versioned = url.searchParams.get('v') === String(event.version)
					return new Response(png as BodyInit, { headers: { 'content-type': 'image/png', 'cache-control': versioned ? 'public, max-age=31536000, immutable' : 'public, max-age=300' } })
				}
				if (sub === '/manifest.webmanifest') return manifest(appBase, assetBase, event)
				const visitor = readVisitor(request)
				const host = isHost(visitor, event)
				const mode = sub === '/admin' ? (host ? 'admin' : visitor ? 'not-admin' : 'sign-in') : 'guest'
				return new Response(
					eventPageHtml({ ...shared, event: publicEvent(event), pies: await state(event.night), mode, visitor, isHost: host, loginUrl: loginUrl(`/e/${event.slug}/admin`), pushKey: await getPushPublicKey() }),
					{ headers: HTML_HEADERS },
				)
			}

			// ---------- Static-ish ----------
			if (path === '/sw.js') {
				return new Response(serviceWorkerJs({ appBase, assetBase, version: ASSET_VERSION }), {
					headers: { 'content-type': 'text/javascript; charset=utf-8', 'cache-control': 'no-cache', 'service-worker-allowed': `${appBase}/` },
				})
			}
			if (path === '/favicon.svg') return new Response(FAVICON_SVG, { headers: { 'content-type': 'image/svg+xml', 'cache-control': 'public, max-age=86400' } })
			if (path === '/robots.txt') return new Response('User-agent: *\nDisallow: /\n', { headers: { 'content-type': 'text/plain' } })
			if (path === '/manifest.webmanifest') return manifest(appBase, assetBase, null)

			// ---------- API ----------
			if (path.startsWith('/api/') && !read && !sameOrigin(request, url)) return json({ error: 'Please use the pie night page.' }, 403)

			if (path === '/api/me' && read) {
				const visitor = readVisitor(request)
				return json({ visitor: visitor ? { username: visitor.username } : null, events: visitor ? (await listEventsFor(visitor.username)).map(publicEvent) : [] })
			}

			if (path === '/api/events' && method === 'POST') {
				const visitor = readVisitor(request)
				if (!visitor) return json({ error: 'Sign in with Kody to start a pie night.' }, 401)
				const body = (await readJson(request)) as Record<string, unknown>
				if (isHoneypotFilled(body)) return json({ error: 'Something went wrong. Try again?' }, 400)
				if (await limited([[`create:user:${visitor.userId}`, 10, 86400], [`create:ip:${clientIp(request)}`, 20, 86400], ['create:all', 500, 86400]])) return json({ error: 'That is a lot of pie nights for one day. Try again tomorrow.' }, 429)
				if ((await countEventsBy(visitor.username)) >= 50) return json({ error: 'You already have 50 pie nights. Reset an old one instead.' }, 409)
				const parsed = parseEventInput(body)
				if (!parsed.ok) return json({ error: parsed.error }, 400)
				const code = cleanText(body.code || parsed.value.title, LIMITS.code)
				const slug = slugify(code)
				if (!validSlug(slug)) return json({ error: 'Pick a code with letters or numbers, like "smith-pie-night-2026".' }, 400)
				const created = await createEvent({ slug, code, ...parsed.value, creator: visitor.username, hosts: cleanHosts(body.hosts, visitor.username) })
				if (!created) return json({ error: `The code "${code}" is taken. Try another one.` }, 409)
				return json({ ok: true, event: publicEvent(created), url: `${appBase}/e/${created.slug}` }, 201)
			}

			// Old single-event clients (cached pages) keep working against the home event.
			let apiPath = path
			if (/^\/api\/(pies(\/.*)?|presence)$/.test(path)) {
				const target = await homeRedirect()
				if (!target) return json({ error: 'Not found' }, 404)
				apiPath = `/api/e/${target}${path.slice(4)}`
			}

			const api = apiPath.match(/^\/api\/e\/([a-z0-9-]+)(\/.*)?$/)
			if (api) {
				const event = await getEvent(api[1]!)
				if (!event) return json({ error: 'That pie night does not exist.' }, 404)
				return await eventApi(request, event, api[2] ?? '', method, { site, origin, appBase, later })
			}

			if (path.startsWith('/api/')) return json({ error: 'Not found' }, 404)
			return new Response(notFoundHtml({ ...shared, code: '' }), { status: 404, headers: HTML_HEADERS })
		} catch (error) {
			if (error instanceof HttpError) return json({ error: error.message }, error.status)
			console.error('pie-night error', error)
			return json({ error: 'Oops, the oven hiccuped. Try again in a moment.' }, 500)
		}
	},
}

function manifest(appBase: string, assetBase: string, event: EventInfo | null) {
	const start = event ? `${appBase}/e/${event.slug}` : `${appBase}/`
	return new Response(
		JSON.stringify({
			id: start,
			name: event && event.title.toLowerCase() !== 'pie night' ? `${event.title} · Pie Night` : 'Pie Night',
			short_name: event ? event.title.slice(0, 20) : 'Pie Night',
			description: 'Sign up for a pie night: say which pie you are bringing and see everyone else’s.',
			start_url: start,
			scope: `${appBase}/`,
			display: 'standalone',
			background_color: '#fff4e4',
			theme_color: '#f6c177',
			icons: [
				{ src: `${assetBase}/icon-192.png`, sizes: '192x192', type: 'image/png', purpose: 'any' },
				{ src: `${assetBase}/icon-512.png`, sizes: '512x512', type: 'image/png', purpose: 'any' },
				{ src: `${assetBase}/icon-maskable-512.png`, sizes: '512x512', type: 'image/png', purpose: 'maskable' },
			],
		}),
		{ headers: { 'content-type': 'application/manifest+json; charset=utf-8', 'cache-control': 'no-cache' } },
	)
}

async function eventApi(request: Request, event: EventInfo, rest: string, method: string, ctx: { site: string; origin: string; appBase: string; later: (job: Promise<unknown>) => unknown }): Promise<Response> {
	const slug = event.slug
	const eventUrl = `${ctx.appBase}/e/${slug}`
	const subject = `${ctx.origin}/`

	if (rest === '' && method === 'GET') return json({ event: publicEvent(event), pies: await state(event.night) })
	if (rest === '/pies' && method === 'GET') return json({ event: publicEvent(event), pies: await state(event.night) })

	if (rest === '/presence' && method === 'POST') {
		const body = (await readJson(request)) as { sid?: unknown; name?: unknown; typing?: unknown; leave?: unknown }
		const sid = String(body?.sid ?? '')
		if (!/^[a-z0-9-]{8,40}$/i.test(sid)) return json({ error: 'Bad session.' }, 400)
		if (body.leave === true) {
			await leave(slug, sid)
			await broadcast(slug, { type: 'presence', people: publicPeople(await presentPeople(slug)) })
			return json({ ok: true })
		}
		const tooMany = await presenceLimited(request)
		const { people, changed } = await heartbeat(slug, tooMany ? null : { sid, name: cleanText(body.name, LIMITS.who), typing: body.typing === true })
		const list = publicPeople(people)
		if (changed) await broadcast(slug, { type: 'presence', people: list })
		return json({ ok: true, people: list })
	}

	if (rest === '/pies' && method === 'POST') {
		const body = (await readJson(request)) as Record<string, unknown>
		if (isHoneypotFilled(body)) return json({ ok: true, pies: await state(event.night) })
		if (await writeLimited(request, slug)) return json({ error: 'Whoa, lots of pies at once! Wait a few minutes and try again.' }, 429)
		const parsed = parsePieBatch(body)
		if (!parsed.ok) return json({ error: parsed.error }, 400)
		if ((await countPies(event.night)) + parsed.value.length > LIMITS.maxPies) return json({ error: 'The pie table is full! Talk to the hosts.' }, 409)
		const added = await addPies(event.night, parsed.value)
		const pies = await state(event.night)
		const who = added[0]!.who
		const items = added.map((p) => p.pie)
		await broadcast(slug, { type: 'pies', change: 'added', from: tabId(request), who, items, ids: added.map((p) => p.id), pies })
		await ctx.later(notifyEvent(slug, { title: `${who} is bringing ${listText(items)}! 🥧`, body: `${event.title}: ${pies.length} ${pies.length === 1 ? 'pie' : 'pies'} so far. Tap to see the list.`, path: eventUrl, tag: `pies-${slug}` }, { subject, exceptEndpoint: typeof body.pushEndpoint === 'string' ? body.pushEndpoint : undefined }))
		return json({ ok: true, added: added.map(publicPie), pie: publicPie(added[0]!), pies }, 201)
	}

	const pieMatch = rest.match(/^\/pies\/([0-9a-f-]{36})$/)
	if (pieMatch && (method === 'PATCH' || method === 'DELETE')) {
		const id = pieMatch[1]!
		if (method === 'PATCH') {
			const body = await readJson(request)
			if (isHoneypotFilled(body)) return json({ ok: true, pies: await state(event.night) })
			if (await writeLimited(request, slug)) return json({ error: 'Whoa, lots of changes at once! Wait a few minutes and try again.' }, 429)
			const parsed = parsePieInput(body)
			if (!parsed.ok) return json({ error: parsed.error }, 400)
			const pie = await updatePie(event.night, id, parsed.value)
			if (!pie) return json({ error: 'That pie is not on the list anymore.', pies: await state(event.night) }, 404)
			const pies = await state(event.night)
			await broadcast(slug, { type: 'pies', change: 'edited', from: tabId(request), who: pie.who, items: [pie.pie], ids: [pie.id], pies })
			return json({ ok: true, pie: publicPie(pie), pies })
		}
		if (await writeLimited(request, slug)) return json({ error: 'Whoa, lots of changes at once! Wait a few minutes and try again.' }, 429)
		const removed = await removePie(event.night, id)
		const pies = await state(event.night)
		if (removed) await broadcast(slug, { type: 'pies', change: 'removed', from: tabId(request), ids: [id], pies })
		return json({ ok: true, pies })
	}

	// ---------- Push opt-in (per device, per event) ----------
	if (rest === '/push' && method === 'POST') {
		const body = (await readJson(request)) as { subscription?: unknown; host?: unknown; check?: unknown; off?: unknown; endpoint?: unknown }
		if (body.check === true || body.off === true) {
			const endpoint = String(body.endpoint ?? '').slice(0, 1000)
			if (body.off === true) {
				await removePushSub(slug, endpoint)
				return json({ ok: true, on: false })
			}
			const sub = await hasPushSub(slug, endpoint)
			return json({ ok: true, on: !!sub, host: !!sub?.host })
		}
		if (!(await getPushPublicKey())) return json({ error: 'Notifications are not set up for this app yet.' }, 503)
		if (await limited([[`push:ip:${clientIp(request)}`, 30, 3600]])) return json({ error: 'Too many tries. Wait a bit and try again.' }, 429)
		const parsed = parseSubscription(body.subscription)
		if (!parsed.ok) return json({ error: parsed.error }, 400)
		const visitor = readVisitor(request)
		const host = body.host === true && isHost(visitor, event)
		await savePushSub({ event: slug, endpoint: parsed.endpoint, p256dh: parsed.p256dh, auth: parsed.auth, host, username: host && visitor ? visitor.username : '' })
		return json({ ok: true, on: true, host })
	}

	// ---------- Hosts ----------
	if (rest.startsWith('/admin/')) {
		const visitor = readVisitor(request)
		if (!isHost(visitor, event)) return json({ error: 'Only the hosts can do that.' }, 403)
		const action = rest.slice('/admin'.length)
		if (action === '/state' && method === 'GET') {
			return json({ event: { ...publicEvent(event), creator: event.creator, hosts: event.hosts }, removed: (await listRemoved(event.night)).map(publicPie), visitor: visitor ? { username: visitor.username } : null, pushReady: !!(await getPushPublicKey()) })
		}
		if (action === '/event' && method === 'POST') {
			const parsed = parseEventInput(await readJson(request), event)
			if (!parsed.ok) return json({ error: parsed.error }, 400)
			const next = await updateEvent({ ...event, ...parsed.value })
			await broadcast(slug, { type: 'event', event: publicEvent(next) })
			return json({ ok: true, event: publicEvent(next) })
		}
		if (action === '/reset' && method === 'POST') {
			const parsed = parseEventInput(await readJson(request), event)
			if (!parsed.ok) return json({ error: parsed.error }, 400)
			const next = await updateEvent({ ...event, ...parsed.value, night: newNight(slug) })
			await broadcast(slug, { type: 'event', event: publicEvent(next), pies: [] })
			return json({ ok: true, event: publicEvent(next), pies: [] })
		}
		const restoreMatch = action.match(/^\/restore\/([0-9a-f-]{36})$/)
		if (restoreMatch && method === 'POST') {
			await restorePie(event.night, restoreMatch[1]!)
			const restored = await state(event.night)
			await broadcast(slug, { type: 'pies', change: 'restored', pies: restored })
			return json({ ok: true, pies: restored, removed: (await listRemoved(event.night)).map(publicPie) })
		}
		if (action === '/hosts' && method === 'POST') {
			const body = (await readJson(request)) as { usernames?: unknown }
			const next = await updateEvent({ ...event, hosts: cleanHosts(body?.usernames, event.creator) })
			return json({ ok: true, hosts: next.hosts, creator: next.creator })
		}
		if (action === '/test-push' && method === 'POST') {
			const body = (await readJson(request)) as { endpoint?: unknown }
			const endpoint = String(body.endpoint ?? '')
			const result = await notifyEvent(slug, { title: 'Pie Night test 🥧', body: `Notifications for ${event.title} are working.`, path: `${eventUrl}/admin`, tag: `test-${slug}` }, { subject, onlyEndpoint: endpoint })
			return json({ ok: result.sent > 0, ...result })
		}
		return json({ error: 'Not found' }, 404)
	}
	return json({ error: 'Not found' }, 404)
}