import { isObject, upstream, upstreamError, XrpcError, xrpcUrl } from "./xrpc"; type DidDocument = Record; function didDocumentUrl(did: string): string { if (/^did:plc:[a-z2-7]{24}$/.test(did)) { return `https://plc.directory/${did}`; } const web = /^did:web:([a-zA-Z0-9.-]+(?:%3A[0-9]+)?)$/.exec(did); if (web?.[1] !== undefined) { return `https://${decodeURIComponent(web[1])}/.well-known/did.json`; } throw new XrpcError(400, "InvalidRequest", `unsupported DID ${did}`); } export function didWeb(origin: string): string { return `did:web:${encodeURIComponent(new URL(origin).host)}`; } export async function resolveDid(did: string): Promise { const url = didDocumentUrl(did); const response = await upstream(url, 503); if (!response.ok) { throw upstreamError(url, 503, `HTTP ${response.status}`); } const doc: unknown = await response.json().catch(() => null); if (!isObject(doc) || doc["id"] !== did) { throw upstreamError(url, 503, `no DID document for ${did}`); } return doc; } function entry( doc: DidDocument, field: string, id: string, type: string, ): Record | undefined { const entries = doc[field]; return (Array.isArray(entries) ? entries : []).find( (item): item is Record => isObject(item) && (item["id"] === `#${id}` || item["id"] === `${String(doc["id"])}#${id}`) && item["type"] === type, ); } export function atprotoKey(doc: DidDocument): string | undefined { const key = entry(doc, "verificationMethod", "atproto", "Multikey")?.["publicKeyMultibase"]; return typeof key === "string" ? key : undefined; } export function serviceOrigin(doc: DidDocument, id: string, type: string): string | undefined { const endpoint = entry(doc, "service", id, type)?.["serviceEndpoint"]; if (typeof endpoint !== "string" || !URL.canParse(endpoint)) { return undefined; } const url = new URL(endpoint); return url.protocol === "https:" ? url.origin : undefined; } // Maps the repo DIDs that the owner declares to their names. export async function repoNames(owner: string): Promise> { const doc = await resolveDid(owner); const pds = serviceOrigin(doc, "atproto_pds", "AtprotoPersonalDataServer"); if (pds === undefined) { throw new XrpcError(503, "UpstreamUnavailable", `${owner} has no PDS`); } const aka = doc["alsoKnownAs"]; const handle = (Array.isArray(aka) ? aka : []) .find((name): name is string => typeof name === "string" && name.startsWith("at://")) ?.slice("at://".length); const prefix = handle === undefined ? "" : `${handle}/`; const names = new Map(); for (const record of await declarations(pds, owner)) { if (isObject(record) && isObject(record["value"]) && typeof record["uri"] === "string") { const rkey = record["uri"].slice(record["uri"].lastIndexOf("/") + 1); names.set(record["value"]["repo"], prefix + rkey); } } return names; } async function declarations(pds: string, owner: string, cursor?: string): Promise { const url = xrpcUrl(pds, "com.atproto.repo.listRecords", { repo: owner, collection: "org.tangled.repo.declaration", limit: "100", ...(cursor === undefined ? {} : { cursor }), }); const response = await upstream(url, 503); if (!response.ok) { throw upstreamError(url, 503, `HTTP ${response.status}`); } const body: unknown = await response.json().catch(() => null); const records: unknown[] = isObject(body) && Array.isArray(body["records"]) ? body["records"] : []; const next = isObject(body) ? body["cursor"] : undefined; return typeof next === "string" && next !== cursor && records.length > 0 ? [...records, ...(await declarations(pds, owner, next))] : records; }