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

inbound.ts

84 lines · 2.6 KB · TypeScript
/**
 * HTTP handler for the inbound signal endpoint: /signals/in/:sourceId.
 * Receives payloads, verifies HMAC, and runs the pipeline.
 *
 * Access: this is an app route inside the package app's fetch() handler, NOT
 * a platform-level webhook. Whether an external sender (Sentry, GitHub, etc.)
 * can POST here depends on the platform's access rules for hosted package apps.
 *
 * If the app is org-only (the default for private packages on kody.run),
 * external senders cannot reach this route. For those integrations, use the
 * platform webhook system instead (declared in package.json "webhooks", which
 * gets dedicated URLs, platform-level HMAC, rate limiting, and replay).
 *
 * This route is useful for: (a) internal testing from the same org, (b) app
 * routes on packages with public app access, or (c) a future platform feature
 * that proxies external webhook traffic to app routes.
 */
import { processSignal } from './pipeline.ts'
import { getSource } from './sources/index.ts'

export async function handleInboundSignal(
	request: Request,
	sourceId: string,
): Promise<Response> {
	if (request.method !== 'POST') {
		return Response.json({ ok: false, error: 'Use POST' }, { status: 405, headers: { allow: 'POST' } })
	}

	const source = await getSource(sourceId)
	if (!source) {
		return Response.json({ ok: false, error: 'Unknown source' }, { status: 404 })
	}
	if (!source.enabled) {
		return Response.json({ ok: false, error: 'Source is disabled' }, { status: 403 })
	}

	let payload: string
	try {
		payload = await request.text()
	} catch {
		return Response.json({ ok: false, error: 'Could not read request body' }, { status: 400 })
	}
	if (!payload) {
		return Response.json({ ok: false, error: 'Empty body' }, { status: 400 })
	}

	const signature = request.headers.get(source.signingHeader) ?? undefined
	const headers: Record<string, string> = {}
	for (const [key, value] of request.headers.entries()) {
		headers[key.toLowerCase()] = value
	}

	try {
		const result = await processSignal({
			sourceId,
			payload,
			signature,
			headers,
		})

		if (!result.verified) {
			return Response.json(
				{ ok: false, error: 'Signature verification failed', signalId: result.signalId },
				{ status: 401 },
			)
		}

		return Response.json(
			{
				ok: result.dispatched,
				signalId: result.signalId,
				routed: result.routed,
				dispatched: result.dispatched,
				destination: result.record.routingDecision?.destination ?? null,
			},
			{ status: result.dispatched ? 200 : 202 },
		)
	} catch (err) {
		return Response.json(
			{ ok: false, error: err instanceof Error ? err.message : String(err) },
			{ status: 500 },
		)
	}
}