/** * Resolving DIDs and handles (https://atproto.com/specs/did, * https://atproto.com/specs/handle). * * - A `did:plc` resolves through the PLC directory: `/`. * - A `did:web` resolves to `https:///.well-known/did.json`; atproto * allows a host name only, no path. * - A handle resolves to a DID through a DNS TXT record at `_atproto.` * holding `did=`, or else through `https:///.well-known/atproto-did`. * DNS is read over HTTPS, with the JSON API that Cloudflare and Google * serve, because WASI has no DNS TXT lookup. * * A handle belongs to an account only when the handle resolves to the * account's DID and the DID document claims the handle. `resolve` checks * both directions. */ import {StringBuilder, join} from 'zena:core'; import {fetch} from 'zena:fetch'; import {StreamLimitError} from 'zena:stream'; import {TimeoutError, timeout} from 'zena:task'; import {Duration, milliseconds} from 'zena:time'; import {JsonArray, JsonObject, parseJson} from 'zena:json'; import {DidDocument, parseDidDocument} from './did.zena'; import {PublicKey} from './didkey.zena'; import {SigningKeyLookup} from './service-auth.zena'; import {isValidDid, isValidHandle, normalizeHandle} from './syntax.zena'; /** A DID or handle that does not resolve. */ export class IdentityError extends Error { new(message: String) : super(message); } /** An account's DID, its DID document, and its handle if both directions agree. */ export final class Identity { did: String; /** The handle, when it resolves to `did` and the document claims it; otherwise null. */ handle: String | null; document: DidDocument; new(did: String, handle: String | null, document: DidDocument) : did = did, handle = handle, document = document; } /** The `did=` value of TXT records, given the data strings of a DNS JSON answer. */ function didFromTxt(answers: JsonArray): String | null { var found: String | null = null; var count = 0; for (var i = 0; i < answers.length; i += 1) { let answer = answers[i]; if (answer is JsonObject) { let data = answer['data']; if (data is String) { let text = unquoteTxt(data); if (text.startsWith('did=')) { found = text.sliceBytes(4, text.length); count += 1; } } } } // More than one did= record is ambiguous, and resolves to nothing. return if (count == 1) found else null; } /** * The text of TXT record data as DNS JSON APIs write it: one or more * quoted strings, which are joined. */ function unquoteTxt(data: String): String { let sb = new StringBuilder(data.length); var quoted = false; var sawQuote = false; for (var i = 0; i < data.length; i += 1) { let b = data.getByteAt(i); if (b == 34) { quoted = !quoted; sawQuote = true; } else if (quoted || !sawQuote) { sb.appendByte(b); } } return sb.toString(); } /** The public PLC directory, where `did:plc` DIDs are resolved by default. */ export let PUBLIC_PLC_DIRECTORY = 'https://plc.directory'; /** What a GET of a resolution answered: its status, and its body for a 200. */ final class Answer(status: i32, text: String) /** Resolves DIDs and handles. */ export final class IdentityResolver { /** The PLC directory's origin. */ var plcDirectory: String = PUBLIC_PLC_DIRECTORY; /** A DNS-over-HTTPS endpoint that answers `?name=&type=TXT` with JSON. */ var dnsOverHttps: String = 'https://cloudflare-dns.com/dns-query'; /** * The origin to send a host's requests to. `https://` unless a * test points it elsewhere. */ var originOf: (host: String) => String = (host) => `https://${host}`; /** * Whether a DID document's PDS endpoint is one its caller may read. One * it may not resolves as no PDS, keeping the document's handle and key: * a server that reads other people's PDSes refuses an endpoint on its * own network this way. Any endpoint by default. */ var allowsPds: (url: String) => boolean = (url) => true; /** * The most one read may take: a DID document, a DNS answer or a * handle's DID, in bytes. Whoever names a DID or a handle chooses the * server it is read from. */ var readLimit: i64 = (64 * 1024) as i64; /** How long one read may take, from connecting to its last byte. */ var readTimeout: Duration = milliseconds(10000 as i64); /** The DID document of `did`, a `did:plc` or `did:web`. */ async resolveDid(did: String): Future { if (!isValidDid(did)) { throw new IdentityError(`not a DID: ${did}`); } let url = if (did.startsWith('did:plc:')) { `${this.plcDirectory}/${did}` } else if (did.startsWith('did:web:')) { `${this.originOf(didWebHost(did))}/.well-known/did.json` } else { throw new IdentityError(`unsupported DID method: ${did}`) }; let answer = await this.#get(url, [('accept', 'application/json')]); if (answer.status != 200) { throw new IdentityError(`${did} did not resolve at ${url}: HTTP ${answer.status}`); } let document = parseDidDocument(parseJson(answer.text), did); let pds = document.pds; if (pds != null && !this.allowsPds(pds)) { return new DidDocument(document.id, document.handle, document.signingKey, null, document.json); } return document; } /** * Finds signing keys for `verifyServiceAuth` by resolving DIDs. This * resolver keeps no cache, so every lookup is fresh. A DID that does not * resolve throws `IdentityError`. */ signingKeys(): SigningKeyLookup { return async (did: String, fresh: boolean): Future => { let document = await this.resolveDid(did); return document.signingKey; }; } /** * The DID `handle` resolves to, or null when it resolves to none: its * DNS TXT record, else its `/.well-known/atproto-did`. A handle whose * host cannot be reached, as most have no web server, has no DID over * HTTPS. When the DNS-over-HTTPS resolver cannot be reached, HTTPS still * answers, as for a handle under `bsky.social`; if it has nothing * either, or cannot be reached, the resolver's failure is what is * thrown, since the handle may have a DNS record no one could read. */ async resolveHandle(handle: String): Future { if (!isValidHandle(handle)) { throw new IdentityError(`not a handle: ${handle}`); } let name = normalizeHandle(handle); var fromDns: String | null = null; var dnsFailure: Error | null = null; try { fromDns = await this.#resolveHandleDns(name); } catch (e) { dnsFailure = e; } if (fromDns != null) { return fromDns; } var fromHttps: String | null = null; try { fromHttps = await this.#resolveHandleHttps(name); } catch (e) { // Most handles have no web server, so one that cannot be reached has // no DID over HTTPS, and with DNS failed too, DNS's failure is the // one that says what went wrong. if (dnsFailure != null) { throw dnsFailure; } return null; } if (fromHttps == null && dnsFailure != null) { throw dnsFailure; } return fromHttps; } async #resolveHandleDns(handle: String): Future { let url = `${this.dnsOverHttps}?name=_atproto.${handle}&type=TXT`; let answer = await this.#get(url, [('accept', 'application/dns-json')]); if (answer.status != 200) { return null; } let json = parseJson(answer.text); if (!(json is JsonObject)) { return null; } let answers = json['Answer']; if (!(answers is JsonArray)) { return null; } let did = didFromTxt(answers); return if (did != null && isValidDid(did)) did else null; } async #resolveHandleHttps(handle: String): Future { let url = `${this.originOf(handle)}/.well-known/atproto-did`; let answer = await this.#get(url, []); if (answer.status != 200) { return null; } let did = answer.text.trim(); return if (isValidDid(did)) did else null; } /** * GETs `url` with `headers`, within `readTimeout` and `readLimit`, * reading the body only of a 200. Throws `IdentityError` for a server * that takes longer or sends more. */ async #get(url: String, headers: Array<(String, String)>): Future { let limit = this.readLimit; let budget = this.readTimeout; try { return await timeout(budget, async (): Future => { let response = await fetch(url, {headers: headers}); let status = response.status; if (status != 200) { return new Answer(status, ''); } return new Answer(status, await response.text(limit)); })(); } catch (e) { if (e is TimeoutError) { throw new IdentityError(`${url} did not answer within the read timeout`); } if (e is StreamLimitError) { throw new IdentityError(`${url} answered with more than ${limit} bytes`); } throw e; } } /** * Resolves a DID or a handle to an identity, checking the handle in both * directions. Resolving a handle that does not resolve, or whose DID * document does not claim it, throws `IdentityError`. */ async resolve(identifier: String): Future { if (identifier.startsWith('did:')) { let document = await this.resolveDid(identifier); let claimed = document.handle; if (claimed == null) { return new Identity(identifier, null, document); } let back = await this.resolveHandle(claimed); return new Identity(identifier, if (back == identifier) claimed else null, document); } let handle = normalizeHandle(identifier); let did = await this.resolveHandle(handle); if (did == null) { throw new IdentityError(`${handle} does not resolve to a DID`); } let document = await this.resolveDid(did); if (document.handle != handle) { throw new IdentityError(`${did} does not claim the handle ${handle}`); } return new Identity(did, handle, document); } } /** * The `did:web` of the server at `host`, a host name with an optional * port, which is percent-encoded: `did:web:127.0.0.1%3A2583`. */ export function didWebFor(host: String): String { return `did:web:${join(host.split(':'), '%3A')}`; } /** * The host of a `did:web`, with a percent-encoded port decoded: the only * origin that can hold its document. Throws for one with a path, which * atproto does not use. */ export function didWebHost(did: String): String { let id = did.sliceBytes(8, did.length); if (id.contains(':')) { throw new IdentityError(`did:web with a path is not used by atproto: ${did}`); } let sb = new StringBuilder(id.length); var i = 0; while (i < id.length) { if (i + 2 < id.length && id.getByteAt(i) == 37 && id.getByteAt(i + 1) == 51 && (id.getByteAt(i + 2) == 65 || id.getByteAt(i + 2) == 97)) { // %3A or %3a sb.appendByte(58); i += 3; } else { sb.appendByte(id.getByteAt(i)); i += 1; } } return sb.toString(); }