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.

5.9 KiB Raw
/**
 * Repository commits and record proofs
 * (https://atproto.com/specs/repository#commit-objects).
 *
 * A commit is a DAG-CBOR map signed by the repository's signing key:
 * `{did, version: 3, data, rev, prev, sig}`, where `data` is the root of
 * the MST and `sig` is a signature over the commit encoded without `sig`.
 *
 * `com.atproto.sync.getRecord` answers with a CAR file whose root is the
 * commit, holding the MST nodes on the path to the record and the record
 * itself. `verifyRecordProof` checks such a file. It takes the signature
 * check as a function, so this module needs no particular key type; the
 * caller gets the key from the repository's DID document.
 */

import {Car} from './car.zena';
import {decodeCbor, encodeCbor} from './cbor.zena';
import {Cid} from './cid.zena';
import {
  BytesValue,
  IntValue,
  LinkValue,
  MapValue,
  NullValue,
  StringValue,
  Value,
  field,
  newMap
} from './data.zena';
import {mstGet} from './mst.zena';

/** A commit or proof that is malformed or does not verify. */
export class RepoError extends Error {
  new(message: String) : super(message);
}

/** A decoded commit. */
export final class Commit {
  did: String;
  version: i64;
  /** The root of the record tree. */
  data: Cid;
  /** The revision, a TID that increases with every commit. */
  rev: String;
  prev: Cid | null;
  sig: FixedArray<u8>;
  /** The commit's fields without `sig`, as they were signed. */
  unsigned: MapValue;

  new(did: String, version: i64, data: Cid, rev: String, prev: Cid | null, sig: FixedArray<u8>, unsigned: MapValue)
    : did = did, version = version, data = data, rev = rev, prev = prev, sig = sig, unsigned = unsigned;

  /** The bytes the signature covers: the commit encoded without `sig`. */
  signedBytes(): FixedArray<u8> {
    return encodeCbor(this.unsigned);
  }
}

/** Reads a commit block. Accepts versions 2 and 3, which differ only in what `prev` means. */
export function decodeCommit(bytes: FixedArray<u8>): Commit {
  let value = decodeCbor(bytes);
  if (!(value is MapValue)) {
    throw new RepoError('commit is not a map');
  }
  let map = value;
  let did = field(map, 'did');
  let version = field(map, 'version');
  let data = field(map, 'data');
  let rev = field(map, 'rev');
  let sig = field(map, 'sig');
  if (!(did is StringValue) || !(version is IntValue) || !(data is LinkValue)
      || !(rev is StringValue) || !(sig is BytesValue)) {
    throw new RepoError('commit lacks did, version, data, rev or sig');
  }
  let versionNumber = version.value;
  if (versionNumber != 2 && versionNumber != 3) {
    throw new RepoError(`unsupported commit version ${versionNumber}`);
  }
  let prevValue = field(map, 'prev');
  var prev: Cid | null = null;
  if (prevValue is LinkValue) {
    prev = prevValue.cid;
  } else if (prevValue != null && !(prevValue is NullValue)) {
    throw new RepoError('commit prev is neither a CID nor null');
  }
  let unsigned = newMap();
  map.entries.forEach((key, item) => {
    if (key != 'sig') {
      unsigned.entries[key] = item;
    }
  });
  return new Commit(
    did.value,
    versionNumber,
    data.cid,
    rev.value,
    prev,
    sig.value,
    unsigned
  );
}

/** A commit, signed and encoded, ready to store. */
export final class SignedCommit {
  cid: Cid;
  bytes: FixedArray<u8>;

  new(cid: Cid, bytes: FixedArray<u8>) : cid = cid, bytes = bytes;
}

/**
 * A version 3 commit of `did`'s repository, whose record tree's root is
 * `data`, at revision `rev`, after the commit `prev`, if any. `sign` signs
 * the commit's encoding without `sig` with the repository's signing key.
 */
export function signCommit(did: String, data: Cid, rev: String, prev: Cid | null,
    sign: (bytes: FixedArray<u8>) => FixedArray<u8>): SignedCommit {
  let commit = newMap();
  commit.entries['did'] = new StringValue(did);
  commit.entries['version'] = new IntValue(3 as i64);
  commit.entries['data'] = new LinkValue(data);
  commit.entries['rev'] = new StringValue(rev);
  commit.entries['prev'] = if (prev == null) new NullValue() else new LinkValue(prev);
  commit.entries['sig'] = new BytesValue(sign(encodeCbor(commit)));
  let bytes = encodeCbor(commit);
  return new SignedCommit(Cid.forDagCbor(bytes), bytes);
}

/** A verified answer to `com.atproto.sync.getRecord`. */
export final class RecordProof {
  commit: Commit;
  /** The record's CID, or null when the proof shows the record is absent. */
  cid: Cid | null;
  /** The record, or null when it is absent. */
  record: Value | null;
  new(commit: Commit, cid: Cid | null, record: Value | null) : commit = commit, cid = cid, record = record;
}

/**
 * Checks a `getRecord` CAR file for `did`'s record at `collection/rkey`.
 *
 * The CAR file's blocks were already checked against their CIDs when it
 * was read. This checks that its root is a commit by `did` that
 * `verifySignature` accepts, and walks the record tree from the commit to
 * the key. The result names the record, or shows that the repository has
 * no record there.
 */
export function verifyRecordProof(
  car: Car,
  did: String,
  collection: String,
  rkey: String,
  verifySignature: (signed: FixedArray<u8>, sig: FixedArray<u8>) => boolean
): RecordProof {
  if (car.roots.length != 1) {
    throw new RepoError(`proof has ${car.roots.length} roots`);
  }
  let commitBytes = car.blocks.get(car.roots[0]);
  if (commitBytes == null) {
    throw new RepoError('proof lacks its commit');
  }
  let commit = decodeCommit(commitBytes);
  if (commit.did != did) {
    throw new RepoError(`commit is by ${commit.did}, not ${did}`);
  }
  if (!verifySignature(commit.signedBytes(), commit.sig)) {
    throw new RepoError('commit signature does not verify');
  }
  let cid = mstGet(commit.data, `${collection}/${rkey}`, car.blocks);
  if (cid == null) {
    return new RecordProof(commit, null, null);
  }
  let recordBytes = car.blocks.get(cid);
  if (recordBytes == null) {
    throw new RepoError('proof lacks the record');
  }
  return new RecordProof(commit, cid, decodeCbor(recordBytes));
}
none
VersionPublishedDependenciesApproved by
0.0.1-preview.1 2026-11-19 none