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.

4.2 KiB Raw
/**
 * DID documents, and the parts of them atproto uses
 * (https://atproto.com/specs/did).
 *
 * - The signing key: the verification method whose id is `#atproto`
 *   (written either relative or as `<did>#atproto`).
 * - The PDS: the service whose id is `#atproto_pds` and whose type is
 *   `AtprotoPersonalDataServer`.
 * - The handle: the first `at://` URI in `alsoKnownAs`. A handle is only
 *   the account's if it also resolves back to the DID, which
 *   `atproto/identity` checks.
 */

import {JsonArray, JsonObject, JsonValue} from 'zena:json';
import {PublicKey, parseVerificationMethod} from './didkey.zena';
import {isValidHandle, normalizeHandle} from './syntax.zena';

/** A DID document that lacks what atproto needs from it. */
export class DidDocumentError extends Error {
  new(message: String) : super(message);
}

/** What atproto reads from a DID document. */
export final class DidDocument {
  /** The DID the document describes. */
  id: String;
  /** The handle the document claims, lowercased, or null. */
  handle: String | null;
  /** The repository signing key, or null when the document has none. */
  signingKey: PublicKey | null;
  /** The PDS's URL, or null when the document names none. */
  pds: String | null;
  /** The whole document. */
  json: JsonObject;

  new(id: String, handle: String | null, signingKey: PublicKey | null, pds: String | null, json: JsonObject)
    : id = id, handle = handle, signingKey = signingKey, pds = pds, json = json;

  /**
   * The endpoint of the service whose id is `fragment`, such as
   * `#atproto_pds`, written alone or after the DID, and whose type is
   * `type`; null when the document lists none. The first such service
   * counts.
   */
  serviceEndpoint(fragment: String, type: String): String | null {
    return serviceIn(this.json, this.id, fragment, type);
  }
}

function serviceIn(doc: JsonObject, did: String, fragment: String, type: String): String | null {
  let services = arrayOrEmpty(doc['service']);
  for (var i = 0; i < services.length; i += 1) {
    let service = services[i];
    if (service is JsonObject) {
      let serviceId = service['id'];
      let endpoint = service['serviceEndpoint'];
      if (serviceId is String && isFragment(serviceId, did, fragment) && service['type'] == type
          && endpoint is String) {
        return endpoint;
      }
    }
  }
  return null;
}

/** Whether `id` names `fragment` within the document for `did`. */
function isFragment(id: String, did: String, fragment: String) {
  return id == fragment || id == `${did}${fragment}`;
}

function arrayOrEmpty(value: JsonValue) {
  if (value is JsonArray) {
    return value;
  }
  return new JsonArray();
}

/**
 * Reads a DID document. When `expectedDid` is given, the document's `id`
 * must equal it.
 */
export function parseDidDocument(json: JsonValue, expectedDid: String | null = null): DidDocument {
  if (!(json is JsonObject)) {
    throw new DidDocumentError('DID document is not an object');
  }
  let doc = json;
  let id = doc['id'];
  if (!(id is String)) {
    throw new DidDocumentError('DID document has no id');
  }
  let did = id;
  if (expectedDid != null && did != expectedDid) {
    throw new DidDocumentError(`DID document is for ${did}, not ${expectedDid}`);
  }

  var handle: String | null = null;
  let aliases = arrayOrEmpty(doc['alsoKnownAs']);
  for (var i = 0; i < aliases.length; i += 1) {
    let alias = aliases[i];
    if (handle == null && alias is String && alias.startsWith('at://')) {
      let candidate = alias.sliceBytes(5, alias.length);
      if (isValidHandle(candidate)) {
        handle = normalizeHandle(candidate);
      }
    }
  }

  var signingKey: PublicKey | null = null;
  let methods = arrayOrEmpty(doc['verificationMethod']);
  for (var i = 0; i < methods.length; i += 1) {
    let method = methods[i];
    if (signingKey == null && method is JsonObject) {
      let methodId = method['id'];
      let type = method['type'];
      let key = method['publicKeyMultibase'];
      if (methodId is String && isFragment(methodId, did, '#atproto') && type is String && key is String) {
        signingKey = parseVerificationMethod(type, key);
      }
    }
  }

  let pds = serviceIn(doc, did, '#atproto_pds', 'AtprotoPersonalDataServer');
  return new DidDocument(did, handle, signingKey, pds, doc);
}
none
VersionPublishedDependenciesApproved by
0.0.1-preview.1 2026-11-19 none