atproto 0.0.1-preview.1
AT Protocol data model, repositories, identity, XRPC, OAuth and sessions
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 inzena:encoding.atproto/cid: CIDs, their binary and string forms, and the CIDs atproto gives records and blobs.atproto/data: the data model (Valueand its cases), its JSON form, and blob references (BlobRef).atproto/cbor: DAG-CBOR encoding and strict decoding,cidForValue, andsortedKeys, the order DAG-CBOR writes map keys in.atproto/syntax: DIDs, handles, NSIDs, record keys, TIDs, datetimes, and CID strings.atproto/car: CAR files andBlockMap, 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 verifyingcom.atproto.sync.getRecordproofs.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 aRequestSignercan authorize one by one.atproto/methods: the NSIDs of standardcom.atprotomethods, andxrpcPath, a method's path on a server.atproto/plc:did:plcoperations: 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
/**
* A client for XRPC, atproto's HTTP API convention
* (https://atproto.com/specs/xrpc).
*
* An XRPC method is named by an NSID and served at `/xrpc/<nsid>`. A query
* is a GET with its parameters in the query string; a procedure is a POST
* with a body. An error answer is JSON, `{"error": "<Name>", "message":
* "..."}`, with a 4xx or 5xx status.
*/
import {Future} from 'zena:async';
import {Own, StringBuilder} from 'zena:core';
import {Response, fetch} from 'zena:fetch';
import {JsonObject, JsonValue, parseJson, stringify} from 'zena:json';
import {EncodeSet, percentEncode} from 'zena:url';
/** An XRPC call that was answered with an error. */
export class XrpcError extends Error {
/** The HTTP status. */
status: i32;
/** The error name the server gave, such as `RecordNotFound`, or an empty string. */
error: String;
new(status: i32, error: String, message: String) : status = status, error = error, super(message);
}
/**
* What authorizes each request a client sends with proof of possession, as
* an OAuth session's DPoP does (`atproto/oauth`): its headers are made for
* the one request, and an answer can call for the request to be sent again.
*/
export interface RequestSigner {
/** The headers that authorize a request of `method` to `url`, such as `authorization` and `dpop`. */
headers(method: String, url: String): Array<(String, String)>;
/**
* Learns from the answer to a request it signed, such as a new nonce,
* and says whether to sign the request again and send it once more, as
* after a refused nonce or an access token it has since refreshed.
*/
answered(status: i32, dpopNonce: String | null, wwwAuthenticate: String | null): Future<boolean>;
}
/** A client for the XRPC methods of one service, such as a PDS. */
export final class XrpcClient {
/** The service's origin, such as `https://pds.example.com`. */
service: String;
/** The `authorization` header to send, or null. */
var authorization: String | null = null;
/** What signs each request instead of `authorization`, or null. */
var signer: RequestSigner | null = null;
/** The `user-agent` header to send, naming the client, or null. */
var userAgent: String | null = null;
new(service: String) : service = service;
#url(nsid: String, params: Array<(String, String)> | null): String {
let sb = new StringBuilder();
sb.append(this.service);
sb.append('/xrpc/');
sb.append(nsid);
if (params != null) {
var first = true;
for (let (name, value) in params) {
sb.append(if (first) '?' else '&');
sb.append(percentEncode(name, EncodeSet.Component));
sb.append('=');
sb.append(percentEncode(value, EncodeSet.Component));
first = false;
}
}
return sb.toString();
}
#headers(method: String, url: String, contentType: String | null,
extra: Array<(String, String)> | null): GrowableArray<(String, String)> {
let headers = new GrowableArray<(String, String)>();
headers.push(('accept', 'application/json'));
if (contentType != null) {
headers.push(('content-type', contentType));
}
let signer = this.signer;
let authorization = this.authorization;
if (signer != null) {
for (let header in signer.headers(method, url)) {
headers.push(header);
}
} else if (authorization != null) {
headers.push(('authorization', authorization));
}
let userAgent = this.userAgent;
if (userAgent != null) {
headers.push(('user-agent', userAgent));
}
if (extra != null) {
for (let header in extra) {
headers.push(header);
}
}
return headers;
}
/**
* Sends a request and returns its answer, signed by the signer if there
* is one, and sent a second time when the signer asks for it.
*/
async #send(method: String, url: String, contentType: String | null,
body: String | FixedArray<u8> | null, extra: Array<(String, String)> | null): Future<Own<Response>> {
let response = await fetch(url, {method, headers: this.#headers(method, url, contentType, extra), body});
let signer = this.signer;
if (signer == null) {
return response;
}
let again = await signer.answered(response.status, response.header('dpop-nonce'),
response.header('www-authenticate'));
if (!again) {
return response;
}
let second = await fetch(url, {method, headers: this.#headers(method, url, contentType, extra), body});
await signer.answered(second.status, second.header('dpop-nonce'), second.header('www-authenticate'));
return second;
}
/**
* Calls a query and returns the raw answer, for methods that answer with
* something other than JSON, such as `com.atproto.sync.getRecord`, sending
* `headers` too, such as a `Range`. Throws `XrpcError` for an error
* answer.
*/
async queryRaw(nsid: String, params: Array<(String, String)> | null = null,
headers: Array<(String, String)> | null = null): Future<Own<Response>> {
let response = await this.#send('GET', this.#url(nsid, params), null, null, headers);
return await checkAnswer(nsid, response);
}
/** Calls a query that answers with JSON. Throws `XrpcError` for an error answer. */
async query(nsid: String, params: Array<(String, String)> | null = null): Future<JsonValue> {
let response = await this.queryRaw(nsid, params);
return parseJson(await response.text());
}
/**
* Calls a procedure with a JSON body, or none when `input` is null, and
* returns its JSON answer, or null when it has none.
*/
async procedure(nsid: String, input: JsonValue, params: Array<(String, String)> | null = null): Future<JsonValue> {
let body: String | null = if (input == null) null else stringify(input);
let contentType: String | null = if (input == null) null else 'application/json';
let response = await this.#send('POST', this.#url(nsid, params), contentType, body, null);
let answer = await checkAnswer(nsid, response);
let text = await answer.text();
return if (text.length == 0) null else parseJson(text);
}
/** Calls a procedure whose body is bytes of type `mimeType`, such as `com.atproto.repo.uploadBlob`. */
async upload(nsid: String, mimeType: String, bytes: FixedArray<u8>,
params: Array<(String, String)> | null = null): Future<JsonValue> {
let response = await this.#send('POST', this.#url(nsid, params), mimeType, bytes, null);
let answer = await checkAnswer(nsid, response);
return parseJson(await answer.text());
}
}
/**
* `response` when it is a success, for its body to be read; otherwise
* throws `XrpcError`, with what the body says about the failure.
*/
async function checkAnswer(nsid: String, response: Own<Response>): Future<Own<Response>> {
if (response.ok) {
return response;
}
let status = response.status;
var error = '';
var message = `${nsid} failed with HTTP ${status}`;
try {
let json = parseJson(await response.text());
if (json is JsonObject) {
let name = json['error'];
if (name is String) {
error = name;
message = `${nsid} failed: ${name}`;
}
let detail = json['message'];
if (detail is String) {
message = `${message}: ${detail}`;
}
}
} catch (e) {
// Not JSON: keep the status alone.
}
throw new XrpcError(status, error, message);
}
| Version | Published | Dependencies | Approved by |
|---|---|---|---|
| 0.0.1-preview.1 | 2026-11-19 | none |
|