import { PlatformAuth, RateLimiter } from "./auth"; import { HttpError, RecordNotFound, json } from "./errors"; import { validateMediaUrl, type OriginPolicy } from "./origins"; import { isResolverId, isValidCid, parseRecordUri, resolverUrl, showId, validateEpisode, validateShow } from "./validation"; import type { RecordReader, ResolverMapping } from "./types"; import type { SqliteStore } from "./store"; async function body(request: Request, fields: string[]): Promise> { if (!/^application\/json(?:;|$)/i.test(request.headers.get("content-type") ?? "")) { throw new HttpError(415, "unsupported_media_type", "Send application/json"); } if (Number(request.headers.get("content-length") ?? 0) > 16_384) throw new HttpError(413, "body_too_large", "Request body too large"); const reader = request.body?.getReader(); if (!reader) throw new HttpError(400, "invalid_body", "JSON object required"); const chunks: Uint8Array[] = []; let size = 0; while (true) { const { value, done } = await reader.read(); if (done) break; size += value.byteLength; if (size > 16_384) { await reader.cancel(); throw new HttpError(413, "body_too_large", "Request body too large"); } chunks.push(new Uint8Array(value)); } let parsed: unknown; try { parsed = JSON.parse(await new Blob(chunks).text()); } catch { throw new HttpError(400, "invalid_body", "JSON object required"); } if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || Object.keys(parsed).some((key) => !fields.includes(key))) { throw new HttpError(400, "invalid_body", "Unexpected registration fields"); } return parsed as Record; } function expectedCid(value: unknown): string { if (!isValidCid(value)) throw new HttpError(400, "invalid_cid", "Provide the CID returned by the PDS write"); return value; } function pagination(url: URL): { after: string; limit: number } { const after = url.searchParams.get("after") ?? ""; const rawLimit = url.searchParams.get("limit") ?? "50"; if ((after && !isResolverId(after)) || !/^\d{1,3}$/.test(rawLimit) || Number(rawLimit) < 1 || Number(rawLimit) > 100) { throw new HttpError(400, "invalid_pagination", "Use a valid after ID and a limit from 1 to 100"); } return { after, limit: Number(rawLimit) }; } export class RegistryApi { private readonly locks = new Map>(); private readonly limiter = new RateLimiter(); constructor( private readonly store: SqliteStore, private readonly reader: RecordReader, private readonly auth: PlatformAuth, private readonly policy: OriginPolicy, private readonly now: () => number = Date.now, ) {} // Serialize verification and writes for an episode inside this process. SQLite // version checks additionally reject races from another process sharing the DB. private async exclusive(key: string, operation: () => Promise): Promise { const previous = this.locks.get(key) ?? Promise.resolve(); let release!: () => void; const current = new Promise((resolve) => { release = resolve; }); this.locks.set(key, current); await previous; try { return await operation(); } finally { release(); if (this.locks.get(key) === current) this.locks.delete(key); } } private async read(uri: string, cid?: string) { const envelope = await this.reader.get(uri); if (envelope.uri !== uri) throw new HttpError(502, "invalid_record_response", "Record source returned a mismatched URI"); if (cid && envelope.cid !== cid) throw new HttpError(409, "record_pending", "Trusted source does not yet show the requested record CID; retry"); return envelope; } private async refresh(episodeUri: string, cid?: string, reactivate = false): Promise { return this.exclusive(episodeUri, async () => { const existing = this.store.getByUri(episodeUri); // Only an explicit authenticated platform request may undo withdrawal. if (!reactivate && existing?.status === "withdrawn") return existing; const envelope = await this.read(episodeUri, cid); try { const record = validateEpisode(envelope, this.policy.baseUrl); if (existing && (existing.showUri !== record.showUri || existing.episodeGuid !== record.guid)) { throw new HttpError(422, "identity_changed", "Keep the registered show URI and episode GUID unchanged"); } const expectedShowCid = this.store.getShow(showId(record.showUri))?.cid ?? null; const showEnvelope = await this.read(record.showUri); const show = validateShow(showEnvelope); await validateMediaUrl(record.media.primary.url, this.policy); if (record.media.source) await validateMediaUrl(record.media.source.url, this.policy); return this.store.activate(episodeUri, envelope.cid, record, showEnvelope.cid, show, new Date(this.now()).toISOString(), existing?.version ?? null, expectedShowCid); } catch (error) { if (existing && error instanceof HttpError && error.status === 422) { this.store.setStatus(existing.id, "unavailable", new Date(this.now()).toISOString(), existing.version); } throw error; } }); } private view(mapping: ResolverMapping) { return { ...mapping, resolverUrl: resolverUrl(this.policy.baseUrl, mapping.id) }; } async handle(request: Request): Promise { const url = new URL(request.url); const path = url.pathname; if (request.method === "GET") { const { after, limit } = pagination(url); if (path === "/v1/shows") { const entries = this.store.listShows(after, limit + 1); const more = entries.length > limit; const items = entries.slice(0, limit); return json({ items, next: more ? items.at(-1)!.id : null }); } const showMatch = /^\/v1\/shows\/([A-Za-z0-9_-]{43})(\/episodes)?$/.exec(path); if (showMatch) { const show = this.store.getShow(showMatch[1]); if (!show) throw new HttpError(404, "show_not_found", "Registered show not found"); if (!showMatch[2]) return json(show); const entries = this.store.listEpisodes(show.uri, after, limit + 1); const items = entries.slice(0, limit); return json({ items: items.map((entry) => this.view(entry)), next: entries.length > limit ? items.at(-1)!.id : null }); } const match = /^\/v1\/resolvers\/([A-Za-z0-9_-]{43})$/.exec(path); if (match) { const mapping = this.store.get(match[1]); if (!mapping) throw new HttpError(404, "episode_not_found", "Registered episode not found"); return json(this.view(mapping)); } throw new HttpError(404, "not_found", "Route not found"); } if (request.method !== "POST" && request.method !== "DELETE") return json({ error: "method_not_allowed" }, 405, { Allow: "GET, POST, DELETE" }); const grant = this.auth.authenticate(request); this.limiter.check(grant.platform, this.now()); if (path === "/v1/shows" && request.method === "POST") { const data = await body(request, ["showUri", "expectedCid"]); parseRecordUri(data.showUri, "place.pod.show"); const uri = data.showUri as string; const previousCid = this.store.getShow(showId(uri))?.cid ?? null; const envelope = await this.read(uri, expectedCid(data.expectedCid)); const show = validateShow(envelope); return json(this.store.putShow(uri, envelope.cid, show, new Date(this.now()).toISOString(), previousCid)); } if (path === "/v1/resolvers" && request.method === "POST") { const data = await body(request, ["episodeUri", "expectedCid"]); parseRecordUri(data.episodeUri, "place.pod.episode"); const uri = data.episodeUri as string; const mapping = await this.refresh(uri, expectedCid(data.expectedCid), true); return json(this.view(mapping)); } const match = /^\/v1\/resolvers\/([A-Za-z0-9_-]{43})(\/refresh)?$/.exec(path); if (match) { const mapping = this.store.get(match[1]); if (!mapping) throw new HttpError(404, "episode_not_found", "Registered episode not found"); if (request.method === "POST" && match[2]) { const data = await body(request, ["expectedCid"]); return json(this.view(await this.refresh(mapping.episodeUri, expectedCid(data.expectedCid), true))); } if (request.method === "DELETE" && !match[2]) { return json(this.view(this.store.setStatus(mapping.id, "withdrawn", new Date(this.now()).toISOString(), mapping.version)!)); } return json({ error: "method_not_allowed" }, 405, { Allow: match[2] ? "POST" : "GET, DELETE" }); } throw new HttpError(404, "not_found", "Route not found"); } async reconcile(freshnessMs: number): Promise { const due = this.store.due(new Date(this.now() - freshnessMs).toISOString()); for (const mapping of due) { try { await this.refresh(mapping.episodeUri); } catch (error) { if (error instanceof RecordNotFound) { // Avoid tombstoning a concurrent, successful explicit refresh. const current = this.store.get(mapping.id); if (current?.version === mapping.version && current.verifiedAt === mapping.verifiedAt) { this.store.setStatus(mapping.id, "withdrawn", new Date(this.now()).toISOString(), mapping.version); } } // Upstream failures do not extend verifiedAt; mappings eventually fail closed. } } } }