export class XrpcError extends Error { readonly status: number; readonly error: string; constructor(status: number, error: string, message: string) { super(message); this.status = status; this.error = error; } } export function invalidRequest(message: string): XrpcError { return new XrpcError(400, "InvalidRequest", message); } export function string(value: unknown): string | undefined { return typeof value === "string" ? value : undefined; } export function isPairList(value: unknown): value is { key: string; value: string }[] { return ( Array.isArray(value) && value.every( (item) => isObject(item) && typeof item["key"] === "string" && typeof item["value"] === "string", ) ); } export function isObject(value: unknown): value is Record { return typeof value === "object" && value !== null && !Array.isArray(value); } export function isDid(value: unknown): value is string { return typeof value === "string" && /^did:[a-z]+:[a-zA-Z0-9._:%-]+$/.test(value); } // 503 tells knot2 the whole spindle is unreachable; 500 refuses only this repo's event. type FailureStatus = 500 | 503; export function upstreamError(url: string | URL, status: FailureStatus, detail: string): XrpcError { const { origin, pathname } = new URL(url); const error = status === 503 ? "UpstreamUnavailable" : "InternalError"; return new XrpcError(status, error, `${origin}${pathname}: ${detail}`); } // A pending timer keeps a Durable Object event open, so the deadline ends with the read. export async function fetchWithin( url: string | URL, init: RequestInit, timeoutMs: number, read: (response: Response) => Promise, ): Promise { const controller = new AbortController(); const timer = setTimeout(() => { controller.abort(new DOMException("The operation timed out.", "TimeoutError")); }, timeoutMs); try { // Zone cache rules apply to subrequests, and a cached record can name a deleted repo. return await read( await fetch(url, { cache: "no-store", ...init, signal: controller.signal }), ); } finally { clearTimeout(timer); } } export async function buffered(response: Response, maxBytes = 1024 * 1024): Promise { if (response.body === null || response.webSocket !== null) { return response; } const chunks: Uint8Array[] = []; let size = 0; const body: ReadableStream = response.body; for await (const chunk of body) { if (!(chunk instanceof Uint8Array)) { throw new TypeError("response body is not bytes"); } size += chunk.byteLength; if (size > maxBytes) { throw new DOMException("response is too large", "ResponseTooLarge"); } chunks.push(chunk); } return new Response(new Blob(chunks), response); } export async function upstream( url: string | URL, status: FailureStatus, init?: RequestInit, { timeoutMs = 10_000, read = buffered } = {}, ): Promise { try { return await fetchWithin(url, { redirect: "manual", ...init }, timeoutMs, read); } catch (error) { throw upstreamError(url, status, error instanceof Error ? error.name : "request failed"); } } export function xrpcUrl(base: string, method: string, params: Record): URL { const url = new URL(`/xrpc/${method}`, base); url.search = new URLSearchParams(params).toString(); return url; } export async function errorName(response: Response): Promise { const body: unknown = await response.json().catch(() => null); return isObject(body) && typeof body["error"] === "string" ? body["error"] : undefined; } export async function getRecord( base: string, repo: string, collection: string, rkey: string, status: FailureStatus, ): Promise | undefined> { const url = xrpcUrl(base, "com.atproto.repo.getRecord", { repo, collection, rkey }); const response = await upstream(url, status); if (!response.ok) { const name = await errorName(response); if (name === "RecordNotFound" || name === "RepoNotFound") { return undefined; } throw upstreamError(url, status, `HTTP ${response.status}`); } const body: unknown = await response.json().catch(() => null); if (!isObject(body) || !isObject(body["value"])) { throw upstreamError(url, status, "response has no record value"); } return body["value"]; } // An IPv6 client usually holds a whole /64, so it counts as one client. export function limitKey(ip: string): string { if (!ip.includes(":")) { return ip; } const [head = [], tail = []] = ip .split("::") .map((part) => (part === "" ? [] : part.split(":"))); const zeros = Array(8 - head.length - tail.length).fill("0"); return [...head, ...zeros, ...tail].slice(0, 4).join(":"); } export async function rateLimit(request: Request, limiter: RateLimit, scope = ""): Promise { const ip = request.headers.get("CF-Connecting-IP"); if (ip !== null && !(await limiter.limit({ key: scope + limitKey(ip) })).success) { throw new XrpcError(429, "RateLimitExceeded", "too many requests"); } } export function errorMessage(error: unknown): string { return error instanceof Error ? error.message : String(error); }