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.8 KiB Raw
/**
 * Multibase strings: bytes in an encoding named by a one-character prefix
 * (https://github.com/multiformats/multibase), and base58btc, which
 * `zena:encoding` does not have.
 *
 * The encodings atproto uses, all unpadded:
 *
 * - `b`: base32, lowercase. CIDs.
 * - `z`: base58btc, the Bitcoin alphabet. `did:key` and multikey.
 * - `m`: base64. `$bytes` in atproto JSON, without the prefix.
 * - `u`: base64url. JWTs, without the prefix.
 * - `f`: base16, lowercase.
 */

import {StringBuilder} from 'zena:core';
import {EncodingError, base32Lower, base64, base64Url, hex} from 'zena:encoding';
import {div} from 'zena:math';

/** Text that is not valid in the encoding it claims. */
export class MultibaseError extends Error {
  new(message: String) : super(message);
}

let BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';

/** The multibase encodings this module reads and writes. */
export enum Base {
  Base16,
  Base32,
  Base58btc,
  Base64,
  Base64url
}

function base58Table() {
  let table = new FixedArray<i32>(256, -1);
  for (var i = 0; i < BASE58_ALPHABET.length; i += 1) {
    table[BASE58_ALPHABET.getByteAt(i)] = i;
  }
  return table;
}

let base58Values = base58Table();

/**
 * `bytes` in base58btc. Each leading zero byte becomes a leading `1`, and
 * the rest is the bytes read as one big-endian number, in base 58.
 */
export function encodeBase58btc(bytes: FixedArray<u8>): String {
  var zeros = 0;
  while (zeros < bytes.length && bytes[zeros] == 0) {
    zeros += 1;
  }
  // log(256) / log(58) is under 1.37, so 138 digits per 100 bytes suffice.
  let size = div((bytes.length - zeros) * 138, 100) + 1;
  let digits = new FixedArray<i32>(size, 0);
  var length = 0;
  for (var i = zeros; i < bytes.length; i += 1) {
    var carry = bytes[i] as i32;
    var j = 0;
    while (j < length || carry != 0) {
      if (j < length) {
        carry += digits[j] * 256;
      }
      digits[j] = carry % 58;
      carry = div(carry, 58);
      j += 1;
    }
    length = j;
  }
  let sb = new StringBuilder(zeros + length);
  for (var i = 0; i < zeros; i += 1) {
    sb.appendByte(49);
  }
  for (var i = length - 1; i >= 0; i -= 1) {
    sb.appendByte(BASE58_ALPHABET.getByteAt(digits[i]));
  }
  return sb.toString();
}

/** The bytes of base58btc text. */
export function decodeBase58btc(text: String): FixedArray<u8> {
  var zeros = 0;
  while (zeros < text.length && text.getByteAt(zeros) == 49) {
    zeros += 1;
  }
  // log(58) / log(256) is under 0.733, so 733 bytes per 1000 digits suffice.
  let size = div((text.length - zeros) * 733, 1000) + 1;
  let bytes = new FixedArray<i32>(size, 0);
  var length = 0;
  for (var i = zeros; i < text.length; i += 1) {
    var carry = base58Values[text.getByteAt(i)];
    if (carry < 0) {
      throw new MultibaseError(`invalid base58btc character at offset ${i}`);
    }
    var j = 0;
    while (j < length || carry != 0) {
      if (j < length) {
        carry += bytes[j] * 58;
      }
      bytes[j] = carry & 0xff;
      carry = carry >> 8;
      j += 1;
    }
    length = j;
  }
  let out = new FixedArray<u8>(zeros + length, 0 as u8);
  for (var i = 0; i < length; i += 1) {
    out[zeros + i] = bytes[length - 1 - i] as u8;
  }
  return out;
}

/** `bytes` as a multibase string in `base`. */
export function encodeMultibase(base: Base, bytes: FixedArray<u8>): String {
  return match (base) {
    case Base.Base16: `f${hex.encode(bytes)}`
    case Base.Base32: `b${base32Lower.encode(bytes, false)}`
    case Base.Base58btc: `z${encodeBase58btc(bytes)}`
    case Base.Base64: `m${base64.encode(bytes, false)}`
    case Base.Base64url: `u${base64Url.encode(bytes, false)}`
  };
}

/** The bytes of a multibase string in one of the encodings above. */
export function decodeMultibase(text: String): FixedArray<u8> {
  if (text.length == 0) {
    throw new MultibaseError('empty multibase string');
  }
  let body = text.sliceBytes(1, text.length);
  let prefix = text.getByteAt(0);
  if (prefix == 122) {
    return decodeBase58btc(body);
  }
  if (body.length > 0 && body.getByteAt(body.length - 1) == 61) {
    throw new MultibaseError('multibase text is unpadded');
  }
  try {
    return match (prefix) {
      case 102: decodeLowerHex(body)
      case 98: base32Lower.decode(body)
      case 109: base64.decode(body)
      case 117: base64Url.decode(body)
      case _: throw new MultibaseError(`unsupported multibase prefix '${text.sliceBytes(0, 1)}'`)
    };
  } catch (e) {
    if (e is EncodingError) {
      throw new MultibaseError(e.message);
    }
    throw e;
  }
}

/** Base16 in lowercase only, as multibase's `f` requires. */
function decodeLowerHex(text: String): FixedArray<u8> {
  for (var i = 0; i < text.length; i += 1) {
    let b = text.getByteAt(i);
    if (b >= 65 && b <= 70) {
      throw new MultibaseError(`uppercase base16 character at offset ${i}`);
    }
  }
  return hex.decode(text);
}
none
VersionPublishedDependenciesApproved by
0.0.1-preview.1 2026-11-19 none