atproto 0.0.1-preview.1

AT Protocol data model, repositories, identity, XRPC, OAuth and sessions

Readme Files Dependencies Versions

atproto#

Libraries for the AT Protocol in Zena: its data model, encodings, cryptography, identity resolution, and repositories.

Usage#

import {cidForValue, decodeCbor, encodeCbor} from 'atproto/cbor';
import {StringValue, newMap, stringField} from 'atproto/data';

let record = newMap([
  ('$type', new StringValue('app.bsky.feed.post')),
  ('text', new StringValue('Hello from Zena!')),
]);

let bytes = encodeCbor(record);
let cid = cidForValue(record);
let decoded = decodeCbor(bytes);

Libraries#

  • atproto/varint: multiformats unsigned varints.
  • atproto/multibase: multibase strings, and base58btc. The other base encodings are in zena:encoding.
  • atproto/cid: CIDs, their binary and string forms, and the CIDs atproto gives records and blobs.
  • atproto/data: the data model (Value and its cases), its JSON form, and blob references (BlobRef).
  • atproto/cbor: DAG-CBOR encoding and strict decoding, cidForValue, and sortedKeys, the order DAG-CBOR writes map keys in.
  • atproto/syntax: DIDs, handles, NSIDs, record keys, TIDs, datetimes, and CID strings.
  • atproto/car: CAR files and BlockMap, checking every block against its CID.
  • atproto/mst: the Merkle search tree: key heights, nodes, building a tree, and looking a key up through the nodes of a proof.
  • atproto/repo: commits, signing them, and verifying com.atproto.sync.getRecord proofs.
  • atproto/tid: timestamp identifiers, and a clock that hands out increasing ones.
  • atproto/didkey: public keys as multikeys, did:keys, and DID document verification methods, and checking atproto signatures with them.
  • atproto/did: what atproto reads from a DID document: the signing key, the PDS, and the claimed handle.
  • atproto/service-auth: service-auth JWTs, which an account's PDS signs so the account can call another service: creating them, checking them against the issuer's key, the audience, the method, and the time, and refusing a token presented twice (ReplayGuard).
  • atproto/session: signing in to an account's PDS with a password, refreshing and ending the session, and asking the PDS for service-auth tokens, with a password session or an OAuth one (AccountSession).
  • atproto/oauth: signing in with atproto OAuth as a public client, such as a command-line tool: finding the PDS's authorization server, the authorization request with PKCE and DPoP, trading the code for tokens, and a session that signs each request, follows the servers' nonces, refreshes and revokes its tokens.
  • atproto/dpop: DPoP keys and proofs: ES256 proofs for each request, checking them, and JWK thumbprints.
  • atproto/xrpc: an XRPC client, whose requests a RequestSigner can authorize one by one.
  • atproto/methods: the NSIDs of standard com.atproto methods, and xrpcPath, a method's path on a server.
  • atproto/plc: did:plc operations: building and signing them, the DID a genesis operation makes, and sending an operation to a PLC directory.
  • atproto/identity: resolving DIDs (did:plc, did:web) and handles (DNS over HTTPS, then HTTPS), checking handles in both directions.
  • atproto/sync: fetching a record and checking its proof against the DID document's key, fetching a blob and checking it against its CID, and listing a collection's records, which comes with no proof.

atproto/xrpc, atproto/identity, atproto/sync, atproto/session, atproto/oauth, and atproto/plc send requests with zena:fetch; atproto/oauth also reads the clock and draws random bytes. The other libraries have no imports from the host.

10.9 KiB Raw
/**
 * Resolving DIDs and handles (https://atproto.com/specs/did,
 * https://atproto.com/specs/handle).
 *
 * - A `did:plc` resolves through the PLC directory: `<directory>/<did>`.
 * - A `did:web` resolves to `https://<host>/.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.<handle>`
 *   holding `did=<did>`, or else through `https://<handle>/.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://<host>` 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<DidDocument> {
    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<PublicKey | null> => {
      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<String | null> {
    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<String | null> {
    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<String | null> {
    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<Answer> {
    let limit = this.readLimit;
    let budget = this.readTimeout;
    try {
      return await timeout<Answer>(budget, async (): Future<Answer> => {
        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<Identity> {
    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();
}
none
VersionPublishedDependenciesApproved by
0.0.1-preview.1 2026-11-19 none