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.

7.2 KiB Raw
/**
 * Signing in to an account's PDS with a password, and asking it for
 * service-auth tokens (https://atproto.com/specs/xrpc#authentication).
 *
 * `createSession` resolves the account's handle or DID to its PDS and
 * calls `com.atproto.server.createSession` there, with the account's
 * password or, better, an app password. The PDS answers with a short-lived
 * access token and a longer-lived refresh token. `getServiceAuth` asks the
 * PDS for a token another service accepts as coming from the account (see
 * `atproto/service-auth`), refreshing the session once if the access token
 * has expired.
 *
 * `atproto/oauth` signs in with OAuth instead, and its sessions are
 * `AccountSession`s too, which `getServiceAuth` takes.
 */

import {Future} from 'zena:async';
import {JsonObject, JsonValue} from 'zena:json';
import {IdentityResolver} from './identity.zena';
import {isValidDid} from './syntax.zena';
import {XrpcClient, XrpcError} from './xrpc.zena';
import {
  SERVER_CREATE_SESSION, SERVER_DELETE_SESSION, SERVER_GET_SERVICE_AUTH, SERVER_REFRESH_SESSION
} from './methods.zena';

/** A session that cannot be created, read or used. */
export class SessionError extends Error {
  new(message: String) : super(message);
}

/**
 * A signed-in account, whichever way it signed in: with a password
 * (`Session`), or with OAuth (`atproto/oauth`'s `OAuthSession`).
 */
export interface AccountSession {
  /** The account's DID. */
  did: String;
  /** The PDS's origin. */
  pds: String;
  /**
   * Whether the tokens changed since the session was made or read, so that
   * whoever keeps it knows to write it again.
   */
  refreshed: boolean;

  /** The account's handle, for messages, or its DID when it has none. */
  handleOrDid(): String;

  /** An XRPC client for the PDS that authorizes its requests as the account. */
  client(): XrpcClient;

  /** Replaces the session's tokens with new ones from its PDS. */
  refresh(): Future<void>;

  /** The session as JSON, for keeping. It holds the tokens, so it is a secret. */
  toJson(): JsonObject;
}

/** An account signed in with a password, and its tokens. */
export final class Session implements AccountSession {
  /** The account's DID. */
  did: String;
  /** The account's handle, as its PDS gave it. */
  handle: String;
  /** The PDS's origin. */
  pds: String;
  var accessJwt: String;
  var refreshJwt: String;
  /**
   * Whether the tokens changed since the session was created or read, so
   * that whoever stores it knows to store it again.
   */
  var refreshed = false;

  new(did: String, handle: String, pds: String, accessJwt: String, refreshJwt: String)
      : did = did, handle = handle, pds = pds, accessJwt = accessJwt, refreshJwt = refreshJwt;

  /** An XRPC client for the PDS that sends the access token. */
  client(): XrpcClient {
    let client = new XrpcClient(this.pds);
    client.authorization = `Bearer ${this.accessJwt}`;
    return client;
  }

  handleOrDid(): String {
    return this.handle;
  }

  refresh(): Future<void> {
    return refreshSession(this);
  }

  /** The session as JSON, for storing. It holds the tokens, so it is a secret. */
  toJson(): JsonObject {
    let json = new JsonObject();
    json['did'] = this.did;
    json['handle'] = this.handle;
    json['pds'] = this.pds;
    json['accessJwt'] = this.accessJwt;
    json['refreshJwt'] = this.refreshJwt;
    return json;
  }

  /** Reads a session `toJson` wrote. Throws `SessionError`. */
  static fromJson(json: JsonValue): Session {
    if (!(json is JsonObject)) {
      throw new SessionError('a stored session is not a JSON object');
    }
    let object = json;
    let did = member(object, 'did');
    if (!isValidDid(did)) {
      throw new SessionError('a stored session has no DID');
    }
    return new Session(did, member(object, 'handle'), member(object, 'pds'),
        member(object, 'accessJwt'), member(object, 'refreshJwt'));
  }
}

/**
 * Signs in to the account `identifier`, a handle or a DID, at its PDS.
 * Throws `SessionError` when the account has no PDS or the PDS answers
 * for another account, `IdentityError` when the identifier does not
 * resolve, and `XrpcError` when the PDS refuses, as for a wrong password.
 */
export async function createSession(identifier: String, password: String,
    resolver: IdentityResolver): Future<Session> {
  let identity = await resolver.resolve(identifier);
  let pds = identity.document.pds;
  if (pds == null) {
    throw new SessionError(`${identity.did} has no PDS`);
  }
  let input = new JsonObject();
  input['identifier'] = identity.did;
  input['password'] = password;
  let answer = await new XrpcClient(pds).procedure(SERVER_CREATE_SESSION, input);
  let session = sessionFrom(answer, pds);
  if (session.did != identity.did) {
    throw new SessionError(`${pds} signed in ${session.did}, not ${identity.did}`);
  }
  return session;
}

/** Replaces the session's tokens with new ones from its PDS. */
export async function refreshSession(session: Session): Future<void> {
  let client = new XrpcClient(session.pds);
  client.authorization = `Bearer ${session.refreshJwt}`;
  let fresh = sessionFrom(await client.procedure(SERVER_REFRESH_SESSION, null),
      session.pds);
  if (fresh.did != session.did) {
    throw new SessionError(`${session.pds} refreshed ${fresh.did}, not ${session.did}`);
  }
  session.accessJwt = fresh.accessJwt;
  session.refreshJwt = fresh.refreshJwt;
  session.refreshed = true;
}

/** Ends the session at its PDS, so that its refresh token stops working. */
export async function deleteSession(session: Session): Future<void> {
  let client = new XrpcClient(session.pds);
  client.authorization = `Bearer ${session.refreshJwt}`;
  await client.procedure(SERVER_DELETE_SESSION, null);
}

/**
 * A service-auth token from the session's PDS for the service `audience`,
 * a DID, and the one method `method`. With `expiresAt`, in seconds since
 * the epoch, the token lasts until then; PDSes allow up to an hour for a
 * token bound to a method, and default to a minute.
 */
export async function getServiceAuth(session: AccountSession, audience: String, method: String,
    expiresAt: i64 = 0 as i64): Future<String> {
  let params = new GrowableArray<(String, String)>();
  params.push(('aud', audience));
  params.push(('lxm', method));
  if (expiresAt > 0) {
    params.push(('exp', `${expiresAt}`));
  }
  var answer: JsonValue = null;
  try {
    answer = await session.client().query(SERVER_GET_SERVICE_AUTH, params);
  } catch (e) {
    if (!(e is XrpcError) || e.error != 'ExpiredToken') {
      throw e;
    }
    await session.refresh();
    answer = await session.client().query(SERVER_GET_SERVICE_AUTH, params);
  }
  if (answer is JsonObject) {
    let token = answer['token'];
    if (token is String) {
      return token;
    }
  }
  throw new SessionError(`${session.pds} answered getServiceAuth without a token`);
}

function sessionFrom(answer: JsonValue, pds: String): Session {
  if (!(answer is JsonObject)) {
    throw new SessionError(`${pds} answered without a session`);
  }
  let object = answer;
  return new Session(member(object, 'did'), member(object, 'handle'), pds,
      member(object, 'accessJwt'), member(object, 'refreshJwt'));
}

function member(object: JsonObject, name: String): String {
  let value = object[name];
  if (!(value is String)) {
    throw new SessionError(`a session has no "${name}"`);
  }
  return value;
}
none
VersionPublishedDependenciesApproved by
0.0.1-preview.1 2026-11-19 none