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/rooms

Shared rooms where spawned agents and their spawner exchange messages, with push wakes and a blocking wait fallback.

FollowForkOpen app

Files

runtime.ts

94 lines · 3.8 KB · TypeScript
import runtime, { credential, events, kody, packageContext, packageStorage } from 'kody:runtime'
import type { Db } from './core/db.ts'
import { invalid, RoomError, toErrorResult } from './core/errors.ts'
import type { Ctx, Deps } from './core/rooms.ts'
import { aesSealer, hexBytes, type Sealer } from './core/seal.ts'

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

export const roomFacet = (roomId: string) => `room-${roomId}`

function appUrl() {
	const context = packageContext as { hostedUrl?: string | null } | null
	const url = context?.hostedUrl
	return typeof url === 'string' && url ? url.replace(/\/+$/, '') : null
}

/**
 * Kody HMAC-signs only for a host approved on the key. `.invalid` never
 * resolves, so approving it lets the key sign here and never leave Kody.
 */
export const wakeKeyHost = 'wake-key.rooms.invalid'

let sealerPromise: Promise<Sealer> | null = null

/**
 * Wake-key encryption: AES-256-GCM with a key derived as HMAC-SHA256 of a
 * fixed label under the package secret `rooms-wake-key-root`. Kody never reveals
 * the secret; package code only sees the derived key, and only while running.
 */
function wakeSealer() {
	sealerPromise ??= (async () => {
		try {
			const root = await credential('rooms-wake-key-root')
			if (!root.sign) throw new Error('credential has no sign()')
			const hex = await root.sign({ type: 'hmac', algorithm: 'hmac-sha256', message: 'kody-rooms:wake-key-encryption:v1', encoding: 'hex', host: wakeKeyHost })
			return await aesSealer(hexBytes(hex))
		} catch (error) {
			sealerPromise = null
			const code = (error as { code?: string })?.code ?? 'not_available'
			const detail = error instanceof Error ? error.message.replace(/\s+/g, ' ').slice(0, 200) : ''
			throw new RoomError('unavailable', `Webhook wakes need the package secret rooms-wake-key-root (${code}: ${detail}).`, { hint: 'Ask the package owner to save rooms-wake-key-root; see README "Setup for the owner".' })
		}
	})()
	return sealerPromise
}

/** Bind the core to Kody: package storage, fetch gateway, jobs, events, realtime. */
export function kodyCtx(): Ctx {
	const realtime = (runtime as unknown as { realtime?: Realtime }).realtime
	const deps: Deps = {
		fetch: (input, init) => fetch(input, init),
		runJob: (jobId) => kody.jobRunNow({ id: jobId }),
		dispatchEvent: events ? (event) => events!.dispatch(event) : null,
		broadcast: realtime ? (roomId, data) => realtime.broadcast({ data, facet: roomFacet(roomId) }) : undefined,
		appUrl: appUrl(),
		sealer: wakeSealer,
	}
	return { db: packageStorage() as unknown as Db, now: () => Date.now(), deps }
}

/** Kody user id of the caller, or null for anonymous visitors. */
export async function currentUserId(): Promise<string | null> {
	try {
		const me = (await kody.metaGetCurrentUser({})) as { user_id?: string }
		return me?.user_id ?? null
	} catch {
		return null
	}
}

/** Validate a params object and reject unknown fields (they could change intent). */
export function params(input: unknown, allowed: Array<string>): Record<string, unknown> {
	const value = input ?? {}
	if (typeof value !== 'object' || Array.isArray(value)) invalid('Params must be an object.')
	for (const key of Object.keys(value)) {
		if (!allowed.includes(key)) invalid(`Unknown field "${key}". Allowed: ${allowed.join(', ')}.`)
	}
	return value as Record<string, unknown>
}

export function optionalString(value: unknown, label: string) {
	if (value == null) return null
	if (typeof value !== 'string') invalid(`${label} must be a string.`)
	return value.trim() || null
}

/** Run an export body and return `{ status: 'error' }` for room errors. */
export async function handle<T>(work: () => Promise<T>) {
	try {
		return await work()
	} catch (error) {
		return toErrorResult(error)
	}
}