didDocument

tcmts.atproto.didDocument · #c57eyul2 · term · runs on the server

uses tcmts.atproto.directory, which uses process

A DID's document: did:plc from the PLC directory, did:web from its host: a host name, and a port (%3A) alone, fetched as any server someone else names is (guardedFetch: https, public addresses only, no redirects).

import { directory, getJson, guardedFetch, HOSTNAME, isDid, okJson, Refused } from "#codebase/tcmts/atproto";
import type { DidDocument } from "#codebase/tcmts/atproto";

export async function didDocument(did: string): Promise<DidDocument> {
  if (!isDid(did)) throw new Refused(`${did} isn't a DID`);
  let doc: DidDocument;
  if (did.startsWith("did:plc:"))
    doc = await getJson<DidDocument>(`${directory() ?? "https://plc.directory"}/${did}`);
  else if (did.startsWith("did:web:")) {
    const [host, port, ...rest] = did.slice("did:web:".length).split("%3A");
    if (
      !host ||
      !HOSTNAME.test(host) ||
      rest.length ||
      (port !== undefined && !/^\d{1,5}$/.test(port))
    )
      throw new Refused(`${did} isn't a did:web tcm can look up: a host name, and a port, alone`);
    const url = `https://${host}${port ? `:${port}` : ""}/.well-known/did.json`;
    doc = await okJson<DidDocument>(
      await guardedFetch(url, `${did}'s host`, { headers: { accept: "application/json" } }),
      url,
    );
  } else throw new Refused(`${did} isn't a DID tcm can look up (did:plc or did:web)`);
  if (doc.id !== did) throw new Error(`the document of ${did} is ${doc.id}'s`);
  return doc;
}

uses

used by