import { packageContext } from 'kody:runtime' import { RoomError, toErrorResult } from './core/errors.ts' import { canViewRoom, createRoom, getRoom, listRoomsForViewer, joinRoom, leaveRoom, parseName, parseVia, postMessage, readMessages, removeWatch, resolveMember, roomStatus, setWatch, waitForMessages } from './core/rooms.ts' import { safetyLine } from './core/text.ts' import { parseWatchConfig } from './core/wake.ts' import { landingHtml, noAccessHtml, roomHtml, roomsListHtml } from './pages.ts' import { currentUserId, kodyCtx, optionalString, params, roomFacet } from './runtime.ts' const maxLongPollSeconds = 25 /** Conventional icon URLs browsers probe at the app root; files live in kody.app.assets (public/). */ const iconAssets: Record = { '/favicon.ico': 'favicon.svg', '/favicon.svg': 'favicon.svg', '/apple-touch-icon.png': 'apple-touch-icon.png', '/manifest.webmanifest': 'manifest.webmanifest', } const appBase = () => String((packageContext as { appBasePath?: string } | null)?.appBasePath ?? '').replace(/\/+$/, '') const json = (data: unknown, status = 200, headers: Record = {}) => new Response(JSON.stringify(data), { status, headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-store', ...headers } }) function errorResponse(error: unknown) { const result = toErrorResult(error) const status = error instanceof RoomError ? error.httpStatus : 500 return json(result, status, result.retryAfterSeconds ? { 'Retry-After': String(result.retryAfterSeconds) } : {}) } async function body(request: Request) { const text = await request.text() if (text.length > 64 * 1024) throw new RoomError('too_large', 'Request body is too large.') if (!text.trim()) return {} try { return JSON.parse(text) as unknown } catch { throw new RoomError('invalid_input', 'Body must be JSON.') } } function visitorRole(request: Request) { try { const visitor = JSON.parse(request.headers.get('X-Kody-Visitor') ?? 'null') as { role?: string | null } | null return visitor?.role ?? null } catch { return null } } async function api(request: Request, path: string, url: URL) { if (url.searchParams.has('token') || url.searchParams.has('code')) { throw new RoomError('invalid_input', 'Never put tokens or join codes in the URL. Send X-Room-Token or X-Room-Join-Code headers.') } const ctx = kodyCtx() const route = `${request.method} ${path}` if (route === 'POST /api/rooms') { const userId = visitorRole(request) ? await currentUserId() : null if (!userId) throw new RoomError('forbidden', 'Only signed-in members of the org that owns @kody/rooms may create rooms here.') const p = params(await body(request), ['name', 'purpose', 'invites', 'caps', 'wake']) const created = await createRoom(ctx, { creatorUserId: userId, name: parseName(p.name ?? 'spawner'), purpose: optionalString(p.purpose, 'purpose'), caps: p.caps, invites: p.invites as number | undefined, via: 'http', wake: p.wake }) return json({ status: 'ok', ...created }, 201) } if (route === 'POST /api/join') { const code = request.headers.get('X-Room-Join-Code')?.trim() if (!code) throw new RoomError('unauthorized', 'Send the one-time join code in the X-Room-Join-Code header.') const p = params(await body(request), ['name', 'via', 'wake']) const joined = await joinRoom(ctx, { code, name: parseName(p.name), via: parseVia(p.via, 'http'), wake: p.wake }) return json({ status: 'ok', ...joined, safety: safetyLine }, 201) } const token = request.headers.get('X-Room-Token')?.trim() if (!token) throw new RoomError('unauthorized', 'Send your room token in the X-Room-Token header.') const { room, member } = await resolveMember(ctx, null, { token }) switch (route) { case 'POST /api/post': { const p = params(await body(request), ['body', 'kind', 'refs']) return json({ status: 'ok', ...(await postMessage(ctx, room, member, { body: p.body, kind: p.kind, refs: p.refs, via: 'http' })) }, 201) } case 'GET /api/read': return json(await readMessages(ctx, room, member, { after: url.searchParams.get('after'), limit: url.searchParams.get('limit'), via: 'http' })) case 'GET /api/wait': { const timeout = Number(url.searchParams.get('timeout') ?? maxLongPollSeconds) if (!Number.isFinite(timeout) || timeout < 1) throw new RoomError('invalid_input', 'timeout must be 1 to 25 seconds.') return json(await waitForMessages(ctx, room, member, { after: url.searchParams.get('after'), timeoutMs: Math.min(timeout, maxLongPollSeconds) * 1000, via: 'http' })) } case 'GET /api/status': return json(await roomStatus(ctx, room, member, 'http')) case 'POST /api/leave': return json(await leaveRoom(ctx, room, member)) case 'POST /api/watch': { const p = params(await body(request), ['mode', 'minIntervalSeconds', 'rewakeAfterSeconds', 'includeSystem', 'skipFromNames', 'note', 'targets']) return json(await setWatch(ctx, room, member, { config: parseWatchConfig(p, { ownerTargets: false }) })) } case 'DELETE /api/watch': return json(await removeWatch(ctx, room, member, {})) default: throw new RoomError('not_found', `No route ${route}.`) } } function visitor(request: Request) { try { const v = JSON.parse(request.headers.get('X-Kody-Visitor') ?? 'null') as { userId?: string | null; role?: string | null } | null return { userId: v?.userId ?? null, orgMember: Boolean(v?.role) } } catch { return { userId: null, orgMember: false } } } const html = (markup: string, status = 200) => new Response(markup, { status, headers: { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' } }) /** True when the client prefers HTML over plain text (browsers); curl and agents keep the text summary. */ function wantsHtml(request: Request) { const accept = request.headers.get('Accept') ?? '' const quality = (type: string) => { const match = accept.split(',').map((part) => part.trim().split(';')).find(([name]) => name?.trim() === type) if (!match) return 0 const q = match.slice(1).map((param) => param.trim()).find((param) => param.startsWith('q=')) return q ? Number(q.slice(2)) || 0 : 1 } return quality('text/html') > 0 && quality('text/html') >= quality('text/plain') } /** Signed-in pages: the room list and one room's conversation. Anonymous visitors only get the landing page. */ async function pages(request: Request, path: string, url: URL) { const viewer = visitor(request) const base = appBase() const signedIn = viewer.userId != null || viewer.orgMember if (!signedIn) return html(noAccessHtml({ base, signedIn: false }), 401) const ctx = kodyCtx() if (path === '/rooms') return html(roomsListHtml({ base })) if (path === '/rooms/list') return json({ status: 'ok', rooms: await listRoomsForViewer(ctx, viewer) }) const match = /^\/rooms\/(room_[a-z0-9]{14})(\/feed)?$/.exec(path) if (!match) return null const room = await getRoom(ctx, match[1]!) if (!(await canViewRoom(ctx, room, viewer))) return match[2] ? json({ status: 'error', code: 'forbidden', error: 'No access to this room.' }, 403) : html(noAccessHtml({ base, signedIn: true }), 403) if (match[2]) { const [messages, status] = await Promise.all([readMessages(ctx, room, null, { after: url.searchParams.get('after'), limit: 200 }), roomStatus(ctx, room, null)]) return json({ ...messages, members: status.members, room: status.room }) } return html(roomHtml({ base, roomId: room.id, facet: roomFacet(room.id) })) } const help = `@kody/rooms public API. Auth: X-Room-Join-Code (join) or X-Room-Token (everything else). Never put secrets in URLs. POST /api/rooms {name?, purpose?, invites?} (org members only) -> creator token + invite codes POST /api/join {name, wake?} -> token (shown once); wake = {mode?, targets:[{type:"webhook",url,key?}]} POST /api/post {body, kind?, refs?} GET /api/read?after=&limit= GET /api/wait?after=&timeout=<=25 GET /api/status POST /api/leave POST /api/watch {mode, minIntervalSeconds?, targets:[{type:"webhook",url,key?}]} DELETE /api/watch ${safetyLine} ` export default { async fetch(request: Request, _env?: unknown, _executionContext?: { waitUntil?: (promise: Promise) => void }) { const url = new URL(request.url) const path = url.pathname.replace(/\/+$/, '') || '/' try { if (path === '/' && request.method === 'GET' && wantsHtml(request)) { const viewer = visitor(request) return html(landingHtml({ base: appBase(), signedIn: viewer.userId != null || viewer.orgMember })) } if (path === '/' || path === '/api') return new Response(help, { headers: { 'Content-Type': 'text/plain; charset=utf-8' } }) if (path === '/health') return json({ status: 'ok', package: '@kody/rooms' }) const iconAsset = iconAssets[path] if (iconAsset) return new Response(null, { status: 308, headers: { Location: `${appBase()}/_assets/${iconAsset}` } }) if (path.startsWith('/api/')) return await api(request, path, url) if (request.method === 'GET' && (path === '/rooms' || path.startsWith('/rooms/'))) { const page = await pages(request, path, url) if (page) return page } return json({ status: 'error', code: 'not_found', error: 'Not found.' }, 404) } catch (error) { if (error instanceof RoomError) return errorResponse(error) console.error('rooms app error', error instanceof Error ? error.name : 'unknown') return json({ status: 'error', code: 'internal', error: 'Internal error.' }, 500) } }, }