MenuReading a space

Reading a space

Get a delegation token from the user's PDS, exchange it at the group's host for a space credential with authorizeSpaceSync, then read each writer's records from their own PDS.

Reading a group’s space takes three steps and involves all three kinds of server. The reference console does exactly this in readSpace and spaceCredential.

Space and record URIs

at://<authority>/space/<type>/<skey>                                  the space
at://<authority>/space/<type>/<skey>/<writer>/<collection>/<rkey>     a record in it
  • authority is always a DID: the group, or for an inbox the user.
  • The well-known spaces use the skey self: at://did:plc:…/space/fyi.opensocial.members/self.
  • writer is the DID of whoever wrote the record, which isn’t necessarily the authority.

1. Delegation token, from the user’s own PDS

Through the user’s OAuth session:

GET <user's PDS>/xrpc/com.atproto.space.getDelegationToken?space=at://did:plc:…/space/fyi.opensocial.members/self

The response is { "token": "<jwt>" }. The token is short-lived (about 60 seconds), single-use, and addressed to the space’s host. The PDS only issues it if the session’s scope covers reading that space type (see Signing in).

2. Space credential, from the group’s host

Generate a fresh P-256 key for this credential. The credential will be bound to it. Then exchange the token at the authority’s PDS, which for a group is its host, naming the key by its did:key:

POST https://opensocial.fyi/xrpc/com.atproto.space.authorizeSpaceSync
Content-Type: application/json

{
  "space": "at://did:plc:…/space/fyi.opensocial.members/self",
  "credentialKey": "<your key's did:key>",
  "delegationToken": "<delegation token>"
}

The response is { "credential": "<jwt>", "spaceRev": "<tid>" }, the credential bound to your key. It is valid for about ten minutes; its exp says exactly when it lapses. spaceRev is where the space has got to, for a service that keeps a copy.

Error Meaning
SpaceNotFound No such space under this group, or the user’s roles don’t include one the space’s access record lets read: a refusal doesn’t say the space exists. For members, this means not a member. Also the answer when no delegationToken was sent.
SpaceDeleted The space was deleted.
InvalidDelegationToken Expired, reused, or addressed elsewhere. Get a new one.

3. Read the records

Every read carries the credential, the DID the request is addressed to, and a signature over both:

Authorization: Atproto-Space-Credential <credential>
Atproto-Space-Audience: <audience DID>
Signature-Input: sig=("authorization" "atproto-space-audience");tag="atproto-space-credential"
Signature: sig=:<signature>:

The audience is the account whose data you’re asking for: the repo of a listRecords or getRecord, and the space’s authority for listWriters. Not a hostname: several accounts can share a PDS.

Records live with whoever wrote them, so a read is two hops:

GET https://opensocial.fyi/xrpc/com.atproto.space.listWriters?space=<space uri>
→ { "repos": [{ "$type": "com.atproto.space.defs#repoWrite", "repo": "did:plc:group…", … }, { "$type": "com.atproto.space.defs#repoRemoved", "repo": "did:plc:left…", … }, …], "cursor": "<tid>" }

GET <each writer's PDS>/xrpc/com.atproto.space.listRecords?space=<space uri>&repo=<writer did>&collection=fyi.opensocial.membership
→ { "records": [{ "collection": "…", "rkey": "…", "cid": "…", "value": { … } }], "cursor": … }
  • listWriters goes to the group’s host. It says who has written into the space; an entry of type com.atproto.space.defs#repoRemoved is someone taken out of it, whose records to leave out. It pages by cursor until a page comes back empty.
  • listRecords goes to each writer’s own PDS, found from their DID document’s #atproto_pds. Records the group wrote come from the host. A member’s acceptance or RSVP comes from that member’s PDS.
  • collection is optional in listRecords: leave it out to get every record the writer has in the space, each tagged with its collection. getRecord takes space, repo, collection and rkey.
  • The same credential works on every PDS. It carries no audience of its own; each request’s signature names one, so a credential lifted off one request can’t be replayed by anyone without your key.
  • listRecords is the read to use. The reads that return a commit or vouch for a single record (getRecord, getRepo, listRepoOps, getLatestCommit) also need an Accept-Signature header carrying a key share agreed against the writer’s #atproto_kem key, and answer with a MAC as an HTTP message signature; they’re for services that keep a verified copy. @atproto/space has the pieces (encapsulate, formatMacRequest, verifyCommit, verifyRepoStarFull, verifyRecord).

A space signature

A space signature is an RFC 9421 HTTP message signature tagged atproto-space-credential, made with ECDSA P-256 over SHA-256. A host finds it by that tag, under any label; sig is the usual one. The signed bytes are one line per covered header, then the signature parameters, joined by \n with no trailing newline:

"authorization": Atproto-Space-Credential <credential>
"atproto-space-audience": <audience DID>
"@signature-params": ("authorization" "atproto-space-audience");tag="atproto-space-credential"

The signature is the raw 64-byte r || s, base64-encoded with padding. WebCrypto produces exactly that:

const B58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
const base58 = (bytes: Uint8Array) => {
  let n = BigInt(`0x${[...bytes].map((b) => b.toString(16).padStart(2, "0")).join("")}`);
  let out = "";
  for (; n > 0n; n /= 58n) out = B58[Number(n % 58n)] + out;
  for (const b of bytes) if (b === 0) out = `1${out}`; else break;
  return out;
};

async function generateKey() {
  const pair = await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, false, ["sign"]);
  // A did:key holds the compressed point behind the p256-pub multicodec (0x80 0x24).
  const raw = new Uint8Array(await crypto.subtle.exportKey("raw", pair.publicKey));
  const point = [raw[64] & 1 ? 3 : 2, ...raw.subarray(1, 33)];
  return { pair, did: `did:key:z${base58(new Uint8Array([0x80, 0x24, ...point]))}` };
}

async function spaceSigHeaders(key: Awaited<ReturnType<typeof generateKey>>, credential: string, audience: string) {
  const authorization = `Atproto-Space-Credential ${credential}`;
  const params = '("authorization" "atproto-space-audience");tag="atproto-space-credential"';
  const lines = [
    `"authorization": ${authorization}`,
    `"atproto-space-audience": ${audience}`,
    `"@signature-params": ${params}`,
  ];
  const sig = await crypto.subtle.sign(
    { name: "ECDSA", hash: "SHA-256" },
    key.pair.privateKey,
    new TextEncoder().encode(lines.join("\n")),
  );
  return {
    authorization,
    "atproto-space-audience": audience,
    "signature-input": `sig=${params}`,
    signature: `sig=:${btoa(String.fromCharCode(...new Uint8Array(sig)))}:`,
  };
}

In Node, @atproto/space has this as createSpaceSigHeaders({ authorization, audience, keypair }), which answers { headers }, with a P256Keypair from @atproto/crypto as the keypair.

A signature depends only on the credential and the audience, so it can be reused for the same pair while the credential is valid.

Putting it together

A sketch of the reference console’s readSpace. pdsFor(did) resolves a DID document and returns its #atproto_pds endpoint.

async function spaceCredential(session: OAuthSession, space: string) {
  const { token } = await new Client(session).call(com.atproto.space.getDelegationToken, { space });
  const authority = space.match(/^at:\/\/(did:[^/]+)\/space\//)![1];
  const key = await generateKey();
  const url = `${await pdsFor(authority)}/xrpc/com.atproto.space.authorizeSpaceSync`;
  const res = await fetch(url, {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify({ space, credentialKey: key.did, delegationToken: token }),
  });
  if (!res.ok) throw new Error((await res.json().catch(() => ({}))).error ?? `HTTP ${res.status}`);
  const { credential } = await res.json();
  // A fetch that signs every request with the credential and this key,
  // addressed to the repo it reads, or else to the authority.
  const signed: typeof fetch = async (input, init) => {
    const req = new Request(input, init);
    const audience = new URL(req.url).searchParams.get("repo") ?? authority;
    const headers = await spaceSigHeaders(key, credential, audience);
    for (const [k, v] of Object.entries(headers)) req.headers.set(k, v);
    return fetch(req);
  };
  return signed;
}

async function readSpace(session: OAuthSession, space: string, collections: string[]) {
  const signed = await spaceCredential(session, space);
  const authority = space.match(/^at:\/\/(did:[^/]+)\/space\//)![1];
  const q = (params: Record<string, string>) => new URLSearchParams({ space, ...params });
  const { repos } = await (
    await signed(`${await pdsFor(authority)}/xrpc/com.atproto.space.listWriters?${q({})}`)
  ).json();
  const writers = repos.filter((r: { $type: string }) => r.$type === "com.atproto.space.defs#repoWrite");
  const out: { repo: string; collection: string; rkey: string; cid: string; value: any }[] = [];
  await Promise.all(
    writers.flatMap((r: { repo: string }) =>
      collections.map(async (collection) => {
        const url = `${await pdsFor(r.repo)}/xrpc/com.atproto.space.listRecords?${q({ repo: r.repo, collection })}`;
        const res = await signed(url);
        if (!res.ok) return;
        for (const rec of (await res.json()).records)
          out.push({ repo: r.repo, collection, rkey: rec.rkey, cid: rec.cid, value: rec.value });
      }),
    ),
  );
  return out;
}

A record’s URI is at://<authority>/space/<type>/<skey>/<repo>/<collection>/<rkey>. This sketch leaves out caching, refreshing and pagination (cursor).

Caching and expiry

  • Cache the credential and its key per (user DID, space).
  • Get a new credential, with a new key, shortly before the cached one’s exp. Don’t assume a fixed lifetime.
  • On a 401 before then (CredentialRevoked, or clock skew), get a new credential once, through the user’s session, and retry. A 401 that survives the retry means the user lost access (they left, were ejected, or the space’s access changed), so drop the cache entry and show them that.
  • Don’t cache a failed exchange.