/** * 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/`. 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": "", "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; } /** 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 | null, extra: Array<(String, String)> | null): Future> { 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> { 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 { 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 { 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, params: Array<(String, String)> | null = null): Future { 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): Future> { 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); }