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

push-api.ts

80 lines · 4.1 KB · TypeScript
/**
 * App routes for web push, all for the signed-in visitor only:
 * - GET  /api/push            public key, whether push is configured, this user's devices (host and label only)
 * - POST /api/push/subscribe  `{ subscription, label? }` from PushManager.subscribe()
 * - POST /api/push/unsubscribe `{ endpoint }` or `{ id }`
 * - POST /api/push/test       one test push to this user's devices
 * The visitor is `kody.metaGetCurrentUser()` (verified by the platform), so
 * one person can never list or change another person's devices.
 */
import { kody } from 'kody:runtime'
import { loadSettings } from '../lib/settings.ts'
import { sendPush } from '../push/send.ts'
import { endpointHost, listPushLog, listUserSubs, parseSubscription, removeSub, upsertSub } from '../push/store.ts'

type Visitor = { userId: string; username: string }
type MetaClient = { metaGetCurrentUser?: (input: Record<string, never>) => Promise<{ user_id?: string; username?: string }> }

let visitorForTests: (() => Promise<Visitor | null>) | null = null
export function setVisitorForTests(fn: (() => Promise<Visitor | null>) | null) {
	visitorForTests = fn
}

export async function currentVisitor(): Promise<Visitor | null> {
	if (visitorForTests) return visitorForTests()
	try {
		const me = await (kody as unknown as MetaClient).metaGetCurrentUser?.({})
		if (me?.user_id) return { userId: String(me.user_id), username: String(me.username ?? '') }
		return null
	} catch {
		return null
	}
}

function deviceView(s: { id: string; endpoint: string; label: string; createdAt: string; lastOkAt?: string; lastError?: string }) {
	return { id: s.id, host: endpointHost(s.endpoint), label: s.label, createdAt: s.createdAt, lastOkAt: s.lastOkAt ?? null, lastError: s.lastError ?? null }
}

function cleanLabel(raw: unknown): string {
	return typeof raw === 'string' ? raw.replace(/[^\w .,()/-]/g, '').trim().slice(0, 60) || 'This device' : 'This device'
}

export async function handlePushApi(path: string, request: Request): Promise<Response | null> {
	if (!path.startsWith('/api/push')) return null
	const visitor = await currentVisitor()
	if (!visitor) return Response.json({ error: 'Sign in to Kody to manage push on this device.' }, { status: 401 })
	const settings = await loadSettings()

	if (path === '/api/push' && request.method === 'GET') {
		const subs = await listUserSubs(visitor.userId)
		return Response.json(
			{ configured: Boolean(settings.webPushVapidPublicKey), publicKey: settings.webPushVapidPublicKey || null, devices: subs.map(deviceView), recent: (await listPushLog(5)).map((e) => ({ at: e.at, kind: e.kind, sent: e.sent, failed: e.failed })) },
			{ headers: { 'cache-control': 'no-store' } },
		)
	}
	if (request.method !== 'POST') return Response.json({ error: 'Method not allowed' }, { status: 405 })
	const body = (await request.json().catch(() => null)) as Record<string, unknown> | null
	if (!body) return Response.json({ error: 'Send JSON' }, { status: 400 })

	if (path === '/api/push/subscribe') {
		if (!settings.webPushVapidPublicKey) return Response.json({ error: 'Web push is not configured yet.' }, { status: 409 })
		const parsed = parseSubscription(body.subscription)
		if (!parsed.ok) return Response.json({ error: parsed.error }, { status: 400 })
		const saved = await upsertSub(visitor.userId, visitor.username, parsed, cleanLabel(body.label))
		return Response.json({ ok: true, device: deviceView(saved) })
	}
	if (path === '/api/push/unsubscribe') {
		const endpoint = typeof body.endpoint === 'string' ? body.endpoint : undefined
		const id = typeof body.id === 'string' ? body.id : undefined
		if (!endpoint && !id) return Response.json({ error: 'Send endpoint or id' }, { status: 400 })
		return Response.json({ ok: true, removed: await removeSub(visitor.userId, { endpoint, id }) })
	}
	if (path === '/api/push/test') {
		const result = await sendPush(
			{ kind: 'test', title: 'Kody Factory test push', body: 'Push works on this device. Tapping this opens the factory.', path: '/settings', tag: 'factory-test' },
			{ userId: visitor.userId },
		)
		return Response.json(result, { status: result.ok ? 200 : 502 })
	}
	return Response.json({ error: 'Not found' }, { status: 404 })
}