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

github-readonly.ts

86 lines · 4.2 KB · TypeScript
/**
 * Read-only GitHub REST helper. Every GitHub call goes through
 * `kody:@kody/github/request` (its one `github` credential need, which this
 * package inherits as an importer), so factory code never opens a GitHub
 * credential itself. `githubReadonlyRequest` additionally refuses anything but
 * GET https://api.github.com.
 */
import githubRequest from 'kody:@kody/github/request'

export const GITHUB_API_HOST = 'api.github.com'

export type GithubFetch = (url: string, init?: RequestInit) => Promise<Response>

export class GithubSetupError extends Error {
	readonly code = 'github-credential-missing'
}

const SAFE = new Set(['GET', 'HEAD', 'OPTIONS'])
/** Marks the 401 the client returns when @kody/github could not open its credential. */
export const SETUP_HEADER = 'x-factory-github-setup'
export const GITHUB_SETUP_MESSAGE =
	'GitHub is not connected for this package. Map the package credential "github" (inherited from @kody/github) to a GitHub token or connection (host api.github.com) in Kody.'

/**
 * A fetch-shaped client over `@kody/github/request` for api.github.com.
 * Writes pass `confirm: true` (the caller already decided to write). A GitHub
 * setup failure (no credential mapped) answers as a 401 response.
 */
export function githubPackageFetch(): GithubFetch {
	return async (url, init) => {
		const u = new URL(url, `https://${GITHUB_API_HOST}`)
		if (u.protocol !== 'https:' || u.host !== GITHUB_API_HOST) throw new Error(`refusing non-GitHub API host ${u.host}`)
		const method = String(init?.method ?? 'GET').toUpperCase()
		const headers: Record<string, string> = {}
		new Headers(init?.headers).forEach((v, k) => { headers[k] = v })
		const body = init?.body == null ? undefined : typeof init.body === 'string' ? init.body : String(init.body)
		let r: { ok?: boolean; status?: number; text?: string; data?: unknown; headers?: Record<string, string> }
		try {
			r = await githubRequest({ path: u.toString(), method, headers, ...(body !== undefined ? { body } : {}), ...(SAFE.has(method) ? {} : { confirm: true }) })
		} catch (error) {
			const message = error instanceof Error ? error.message.slice(0, 300) : 'GitHub request failed'
			return new Response(JSON.stringify({ message }), { status: 401, headers: { 'content-type': 'application/json', [SETUP_HEADER]: '1' } })
		}
		const status = typeof r.status === 'number' && r.status >= 200 && r.status <= 599 ? r.status : r.ok ? 200 : 502
		const text = typeof r.text === 'string' ? r.text : r.data === undefined || r.data === null ? '' : JSON.stringify(r.data)
		const out = new Headers({ 'content-type': 'application/json' })
		for (const [k, v] of Object.entries(r.headers ?? {})) if (k.toLowerCase() !== 'content-length' && typeof v === 'string') out.set(k, v)
		return new Response(status === 204 || status === 304 ? null : text, { status, headers: out })
	}
}

/**
 * The GitHub client for factory reads and writes (through @kody/github).
 * Throws GithubSetupError when @kody/github cannot open its credential here.
 */
export async function githubCredentialFetch(): Promise<GithubFetch> {
	const gh = githubPackageFetch()
	const probe = await gh(`https://${GITHUB_API_HOST}/rate_limit`, { method: 'GET' })
	if (probe.headers.get(SETUP_HEADER)) throw new GithubSetupError(GITHUB_SETUP_MESSAGE)
	return gh
}

/** GET a GitHub API path and parse JSON. Throws on non-2xx without echoing headers. */
export async function githubReadonlyRequest<T>(
	fetchFn: GithubFetch,
	path: string,
): Promise<T> {
	const url = new URL(path, `https://${GITHUB_API_HOST}`)
	if (url.protocol !== 'https:' || url.host !== GITHUB_API_HOST) {
		throw new Error(`refusing non-GitHub API host ${url.host}`)
	}
	const res = await fetchFn(url.toString(), {
		method: 'GET',
		headers: { accept: 'application/vnd.github+json', 'x-github-api-version': '2022-11-28' },
	})
	if (!res.ok) {
		if (res.headers.get(SETUP_HEADER)) throw new GithubSetupError(GITHUB_SETUP_MESSAGE)
		if (res.status === 401 || res.status === 403) {
			throw new GithubSetupError(`GitHub refused the request (${res.status}). Check the "github" credential's access to this repository.`)
		}
		throw new Error(`GitHub ${res.status} for ${url.pathname}`)
	}
	return (await res.json()) as T
}

export const REPO_REF_RE = /^[A-Za-z0-9][A-Za-z0-9-]{0,38}\/[A-Za-z0-9._-]{1,100}$/