From 672f311880397179ed2ec511cdcb8c83c0920437 Mon Sep 17 00:00:00 2001 From: kzoeps Date: Wed, 11 Nov 2026 17:56:39 +0600 Subject: [PATCH 1/5] sdk: cache DID resolution per context and accept an app resolver createSDKContext takes an optional didResolver (a DidResolver or oauthClient.identityResolver). Without one, each context gets its own cached resolver instead of a new uncached one per lookup. Adds @atproto-labs/identity-resolver as a dev dependency to type-test the oauth shape. --- packages/sdk/package.json | 1 + packages/sdk/src/context.test.ts | 32 +++++ packages/sdk/src/context.ts | 88 +++++++++++-- packages/sdk/src/index.ts | 2 +- packages/sdk/src/internal/resolve-pds.ts | 33 ++++- .../src/internal/resolve-record-ref.test.ts | 122 ++++++++++++++---- .../sdk/src/internal/resolve-record-ref.ts | 9 +- pnpm-lock.yaml | 39 ++++++ 8 files changed, 277 insertions(+), 49 deletions(-) diff --git a/packages/sdk/package.json b/packages/sdk/package.json index e5c1ae2..2b02c40 100644 --- a/packages/sdk/package.json +++ b/packages/sdk/package.json @@ -72,6 +72,7 @@ "@hypercerts-org/lexicon": "^2.0.1" }, "devDependencies": { + "@atproto-labs/identity-resolver": "0.4.13", "@atproto/lex": "0.4.4", "@hypercerts-org/lexicon": "2.0.1" }, diff --git a/packages/sdk/src/context.test.ts b/packages/sdk/src/context.test.ts index 67e7799..ed6afc7 100644 --- a/packages/sdk/src/context.test.ts +++ b/packages/sdk/src/context.test.ts @@ -1,4 +1,6 @@ import { Client } from "@atproto/lex"; +import { createDidResolver, type DidResolver, DidResolverCommon } from "@atproto-labs/did-resolver"; +import type { IdentityResolver } from "@atproto-labs/identity-resolver"; import { describe, expect, it } from "vitest"; import { createSDKContext } from "./context.js"; @@ -47,4 +49,34 @@ describe("createSDKContext", () => { expect(create).toThrow(/new Client\(session\)/); }, ); + + it("accepts a DidResolver or an oauth client's IdentityResolver as they are", () => { + // These assignments are the test: they fail to compile if either type stops fitting. + const didResolvers: DidResolver<"plc" | "web">[] = [ + new DidResolverCommon(), + createDidResolver({}), + ]; + const identityResolver: IdentityResolver = { + resolve: () => Promise.reject(new Error("not called")), + }; + + for (const didResolver of [...didResolvers, identityResolver]) { + expect(createSDKContext({ client, didResolver }).didResolver).toBe(didResolver); + } + }); + + it.each([ + ["the oauth client instead of its identityResolver", { identityResolver: { resolve() {} } }], + ["a function", () => undefined], + ])( + "rejects a didResolver that is %s with a message that says how to fix it", + (_, didResolver) => { + // @ts-expect-error Deliberately not a `DidDocumentResolver`. + const create = () => createSDKContext({ client, didResolver }); + + expect(create).toThrow(TypeError); + expect(create).toThrow(/`didResolver` must be an object with a resolve\(did\) method/); + expect(create).toThrow(/oauthClient\.identityResolver/); + }, + ); }); diff --git a/packages/sdk/src/context.ts b/packages/sdk/src/context.ts index ec453bb..f5fd5b9 100644 --- a/packages/sdk/src/context.ts +++ b/packages/sdk/src/context.ts @@ -1,14 +1,16 @@ import type { Client } from "@atproto/lex"; +import type { AtprotoDid, AtprotoDidDocument } from "@atproto-labs/did-resolver"; import { describeValue } from "./internal/describe.js"; +import { createDefaultDidResolver } from "./internal/resolve-pds.js"; /** * Shared context passed as the first argument to every SDK operation. * * @remarks * Create it once with {@link createSDKContext} and reuse it for every call. It is frozen and - * holds only the application's client: no session, credentials or HTTP client of its own. - * Create a new context when the application replaces its client, for example after signing in - * as another account. + * holds only the application's client and a DID resolver: no session, credentials or HTTP client + * of its own. Create a new context when the application replaces its client, for example after + * signing in as another account. * * @example * ```ts @@ -20,6 +22,28 @@ import { describeValue } from "./internal/describe.js"; export interface SDKContext { /** The application's `@atproto/lex` client. Operations send all their requests through it. */ readonly client: Client; + /** + * Finds the DID document of an account other than the client's, to locate its PDS. The + * resolver passed to {@link createSDKContext}, or the SDK's cached default. + */ + readonly didResolver: DidDocumentResolver; +} + +/** + * Resolves a DID to its DID document. + * + * @remarks + * Both of these satisfy it as they are: + * - an `@atproto-labs/did-resolver` `DidResolver`, which returns the document; + * - an `@atproto/oauth-client` `IdentityResolver` (`oauthClient.identityResolver`), which returns + * `{ did, didDoc, handle }`. + * + * The SDK only calls `resolve` with a `did:plc` or `did:web` DID and reads the PDS from the + * `#atproto_pds` service of the document. It does not check that the document's `id` is the DID + * it asked for, so the resolver is trusted to do that. + */ +export interface DidDocumentResolver { + resolve(did: AtprotoDid): Promise; } /** Options for {@link createSDKContext}. */ @@ -32,6 +56,22 @@ export interface CreateSDKContextOptions { * `new Client(session)` first. */ client: Client; + /** + * Resolves a DID to its DID document. Pass `oauthClient.identityResolver` or your own resolver + * to reuse its cache and settings; defaults to a resolver that reads `did:plc` from + * plc.directory and `did:web` from the domain, and keeps documents in memory for up to an hour. + * + * @remarks + * Used to find the PDS of another account when an operation reads a record that account owns + * (an `{ uri }` of someone else's record). Operations on the client's own repository never + * call it. + * + * The default is created per context, so every call that uses the same context shares its + * cache, and a document is not fetched again until it expires. A new context starts with an + * empty cache. Failed lookups are not cached. The default has no way to be pointed at another + * PLC directory; pass a resolver for that. + */ + didResolver?: DidDocumentResolver; } /** @@ -50,10 +90,11 @@ export interface CreateSDKContextOptions { * `ERR_PNPM_IGNORED_BUILDS` for `core-js` until `core-js: false` is added to `allowBuilds` in * `pnpm-workspace.yaml`. * - * @param options - The application's client. - * @returns A frozen {@link SDKContext} holding `options.client`. + * @param options - The application's client and, optionally, a DID resolver. + * @returns A frozen {@link SDKContext} holding `options.client` and the DID resolver. * @throws {@link TypeError} If `client` is missing or has no `xrpc()` method, for example a raw - * OAuth session or an `@atproto/api` agent. + * OAuth session or an `@atproto/api` agent, or if `didResolver` is given without a `resolve()` + * method, for example the OAuth client itself instead of `oauthClient.identityResolver`. * * @example * ```ts @@ -64,6 +105,15 @@ export interface CreateSDKContextOptions { * export const context = createSDKContext({ client: new Client(session) }); * ``` * + * @example Reusing the OAuth client's resolver and its cache + * ```ts + * // `oauthClient` is the application's `@atproto/oauth-client` client; `session` comes from it. + * export const context = createSDKContext({ + * client: new Client(session), + * didResolver: oauthClient.identityResolver, + * }); + * ``` + * * @example Passing the session directly throws * ```ts * createSDKContext({ client: session }); // TypeError: wrap it with `new Client(session)` @@ -72,7 +122,9 @@ export interface CreateSDKContextOptions { export function createSDKContext(options: CreateSDKContextOptions): SDKContext { const client: unknown = options?.client; assertClient(client); - return Object.freeze({ client }); + const didResolver = options.didResolver ?? createDefaultDidResolver(); + if (!hasMethod(didResolver, "resolve")) throw notADidResolver(didResolver); + return Object.freeze({ client, didResolver }); } // Duck-typed instead of `instanceof Client`: an application can end up with more than one @@ -81,15 +133,25 @@ export function createSDKContext(options: CreateSDKContextOptions): SDKContext { // built on `xrpc`, so it is the one method any real client has. A session or agent has no // `xrpc` method, and the legacy `@atproto/api` agent exposes `xrpc` as an object. function assertClient(value: unknown): asserts value is Client { - const hasXrpcMethod = - typeof value === "object" && - value !== null && - "xrpc" in value && - typeof value.xrpc === "function"; - if (hasXrpcMethod) return; + if (hasMethod(value, "xrpc")) return; throw new TypeError( `createSDKContext: \`client\` must be an @atproto/lex Client (an object with an xrpc() method), but received ${describeValue(value)}. ` + "The SDK does not accept sessions or agents because authentication stays in your application. " + "Authenticate first, then pass `new Client(session)` (imported from @atproto/lex) as `client`.", ); } + +// Duck-typed for the same reason as `assertClient`. The common mistake is passing the OAuth client +// itself, which has no `resolve` method; its resolver is `oauthClient.identityResolver`. +function notADidResolver(value: unknown): TypeError { + return new TypeError( + `createSDKContext: \`didResolver\` must be an object with a resolve(did) method, but received ${describeValue(value)}. ` + + "Pass `oauthClient.identityResolver` or a DID resolver from @atproto-labs/did-resolver, or leave it out to use the SDK's cached default.", + ); +} + +function hasMethod(value: unknown, name: string): boolean { + return ( + typeof value === "object" && value !== null && typeof Reflect.get(value, name) === "function" + ); +} diff --git a/packages/sdk/src/index.ts b/packages/sdk/src/index.ts index ad74f83..cd4f6ec 100644 --- a/packages/sdk/src/index.ts +++ b/packages/sdk/src/index.ts @@ -1,5 +1,5 @@ // Public entry point for @hypercerts-org/sdk. // Operations are added by the domain cards and imported through their own subpath exports. // Keep this file free of imports that pull in operations, so the root entry stays tree-shakeable. -export type { CreateSDKContextOptions, SDKContext } from "./context.js"; +export type { CreateSDKContextOptions, DidDocumentResolver, SDKContext } from "./context.js"; export { createSDKContext } from "./context.js"; diff --git a/packages/sdk/src/internal/resolve-pds.ts b/packages/sdk/src/internal/resolve-pds.ts index 995e22b..dcd5990 100644 --- a/packages/sdk/src/internal/resolve-pds.ts +++ b/packages/sdk/src/internal/resolve-pds.ts @@ -1,29 +1,48 @@ import type { DidString } from "@atproto/lex"; import { + createDidResolver, + DidCacheMemory, DidError, - DidResolverCommon, extractPdsUrl, isAtprotoDid, } from "@atproto-labs/did-resolver"; +import type { DidDocumentResolver, SDKContext } from "../context.js"; import { describeError } from "./describe.js"; +/** + * The resolver a context uses when the application does not supply one: `did:plc` from + * plc.directory and `did:web` from the domain, with its own in-memory cache and one shared lookup + * for concurrent requests for the same DID. + * + * Internal. Each context gets its own, so documents are shared by the calls of one context only. + */ +export function createDefaultDidResolver(): DidDocumentResolver { + return createDidResolver({ + didCache: new DidCacheMemory(), + // Looked up when the request is made, not now, so replacing the global `fetch` after the + // context exists (a test stub, for example) still takes effect. + fetch: (input, init) => globalThis.fetch(input, init), + }); +} + /** * Finds the PDS that hosts `did`'s repository from its DID document. * - * Internal. Supports `did:plc` (read from plc.directory) and `did:web`, the methods atproto - * allows. Uses the global `fetch` and does not cache. + * Internal. Supports `did:plc` and `did:web`, the methods atproto allows, and asks + * `context.didResolver` for the document, so repeated lookups are as cached as that resolver is. * * Throws Error when the DID method is not supported, the document cannot be fetched or is * invalid, or it lists no atproto PDS. */ -export async function resolvePds(did: DidString): Promise { +export async function resolvePds(context: SDKContext, did: DidString): Promise { if (!isAtprotoDid(did)) { throw new Error(`cannot resolve the PDS of ${did}: only did:plc and did:web are supported.`); } try { - // Created per call so the global `fetch` is looked up when the request is made. - const document = await new DidResolverCommon().resolve(did); - return extractPdsUrl(document); + // An IdentityResolver (oauthClient.identityResolver) wraps the document; a DidResolver + // returns it as is. + const resolved = await context.didResolver.resolve(did); + return extractPdsUrl("didDoc" in resolved ? resolved.didDoc : resolved); } catch (error) { throw new Error(`cannot resolve the PDS of ${did}: ${describeDidError(error)}.`, { cause: error, diff --git a/packages/sdk/src/internal/resolve-record-ref.test.ts b/packages/sdk/src/internal/resolve-record-ref.test.ts index 4213a82..52204e9 100644 --- a/packages/sdk/src/internal/resolve-record-ref.test.ts +++ b/packages/sdk/src/internal/resolve-record-ref.test.ts @@ -1,9 +1,46 @@ +import type { AtprotoDidDocument } from "@atproto-labs/did-resolver"; import { afterEach, describe, expect, it, vi } from "vitest"; +import { createSDKContext, type DidDocumentResolver } from "../context.js"; import { CID, DID, fakePds, json } from "../test-utils/fake-pds.js"; import { resolveRecordRef } from "./resolve-record-ref.js"; const URI = `at://${DID}/org.hypercerts.claim.activity/3k2a4b5c6d7e8`; +const OWNER = "did:plc:ewvi7nxzyoun6zhxrhs64oiz"; +const OWNER_PDS = "https://owner-pds.test"; + +function ownerUri(rkey: string): string { + return `at://${OWNER}/org.hypercerts.claim.activity/${rkey}`; +} + +function ownerDocument(): AtprotoDidDocument { + return { + id: OWNER, + service: [ + { id: "#atproto_pds", type: "AtprotoPersonalDataServer", serviceEndpoint: OWNER_PDS }, + ], + }; +} + +/** + * Replaces the global `fetch`: plc.directory serves the owner's DID document and the owner's PDS + * serves any record asked for. Returns the URLs requested, in order. + */ +function stubOwnerNetwork(): URL[] { + const requested: URL[] = []; + vi.stubGlobal("fetch", async (input: Request | string | URL) => { + const url = new URL(input instanceof Request ? input.url : String(input)); + requested.push(url); + if (url.origin === "https://plc.directory") return json(200, ownerDocument()); + return json(200, { uri: ownerUri(url.searchParams.get("rkey") ?? ""), cid: CID, value: {} }); + }); + return requested; +} + +function didLookups(requested: URL[]): number { + return requested.filter((url) => url.origin === "https://plc.directory").length; +} + describe("resolveRecordRef", () => { afterEach(() => { vi.unstubAllGlobals(); @@ -59,36 +96,73 @@ describe("resolveRecordRef", () => { }); it("resolves an owner's PDS once for concurrent reads that share a client map", async () => { - const owner = "did:plc:ewvi7nxzyoun6zhxrhs64oiz"; - const uris = ["3k2a4b5c6d7e8", "3k2a4b5c6d7e9"].map( - (rkey) => `at://${owner}/org.hypercerts.claim.activity/${rkey}`, - ); - let didFetches = 0; - vi.stubGlobal("fetch", async (input: Request | string | URL) => { - const url = new URL(input instanceof Request ? input.url : String(input)); - if (url.origin === "https://plc.directory") { - didFetches += 1; - return json(200, { - id: owner, - service: [ - { - id: "#atproto_pds", - type: "AtprotoPersonalDataServer", - serviceEndpoint: "https://owner-pds.test", - }, - ], - }); - } - const rkey = url.searchParams.get("rkey"); - return json(200, { uri: uris.find((u) => u.endsWith(`/${rkey}`)), cid: CID, value: {} }); + // A resolver that does not cache, so only the shared client map can make this one lookup. + const lookups: string[] = []; + const didResolver: DidDocumentResolver = { + resolve: async (did) => { + lookups.push(did); + return ownerDocument(); + }, + }; + stubOwnerNetwork(); + const context = createSDKContext({ + client: fakePds(() => json(500, {})).context.client, + didResolver, }); - const { context } = fakePds(() => json(500, {})); + const uris = [ownerUri("3k2a4b5c6d7e8"), ownerUri("3k2a4b5c6d7e9")]; const pdsClients = new Map(); const refs = await Promise.all(uris.map((uri) => resolveRecordRef(context, uri, pdsClients))); expect(refs).toEqual(uris.map((uri) => ({ uri, cid: CID }))); - expect(didFetches).toBe(1); + expect(lookups).toEqual([OWNER]); + }); + + it("looks up an owner's DID once across separate calls on one context", async () => { + const requested = stubOwnerNetwork(); + const { context } = fakePds(() => json(500, {})); + + await resolveRecordRef(context, ownerUri("3k2a4b5c6d7e8")); + await resolveRecordRef(context, ownerUri("3k2a4b5c6d7e9")); + + expect(didLookups(requested)).toBe(1); + }); + + it("does not share looked-up DIDs between contexts", async () => { + const requested = stubOwnerNetwork(); + + await resolveRecordRef(fakePds(() => json(500, {})).context, ownerUri("3k2a4b5c6d7e8")); + await resolveRecordRef(fakePds(() => json(500, {})).context, ownerUri("3k2a4b5c6d7e8")); + + expect(didLookups(requested)).toBe(2); + }); + + it.each([ + ["a DidResolver, which returns the document", (document: AtprotoDidDocument) => document], + [ + "an IdentityResolver, which returns { did, didDoc, handle }", + (document: AtprotoDidDocument) => ({ did: document.id, didDoc: document, handle: "o.test" }), + ], + ])("finds the owner's PDS with the application's resolver: %s", async (_, answer) => { + const requested = stubOwnerNetwork(); + const lookups: string[] = []; + const didResolver: DidDocumentResolver = { + resolve: async (did) => { + lookups.push(did); + return answer(ownerDocument()); + }, + }; + const context = createSDKContext({ + client: fakePds(() => json(500, {})).context.client, + didResolver, + }); + const uri = ownerUri("3k2a4b5c6d7e8"); + + const ref = await resolveRecordRef(context, uri); + + expect(ref).toEqual({ uri, cid: CID }); + expect(lookups).toEqual([OWNER]); + expect(requested.map((url) => url.origin)).toEqual([OWNER_PDS]); }); it("fails without asking the client's PDS when the owner's PDS cannot be resolved", async () => { diff --git a/packages/sdk/src/internal/resolve-record-ref.ts b/packages/sdk/src/internal/resolve-record-ref.ts index c11a0d7..21a6831 100644 --- a/packages/sdk/src/internal/resolve-record-ref.ts +++ b/packages/sdk/src/internal/resolve-record-ref.ts @@ -52,9 +52,10 @@ export async function resolveRecordRef( * Boundaries: * - Reads with `com.atproto.repo.getRecord` from the PDS that hosts the record, the authoritative * copy. A record in the client's own repo is read through `context.client`. For another - * account's record the owner's PDS is found from their DID document (plc.directory for - * `did:plc`, `/.well-known/did.json` for `did:web`) and read without authentication, so only - * public records resolve. The client's PDS is not used for those reads because it would forward + * account's record the owner's PDS is found from their DID document, through + * `context.didResolver` (by default plc.directory for `did:plc` and `/.well-known/did.json` for + * `did:web`, cached per context), and read without authentication, so only public records + * resolve. The client's PDS is not used for those reads because it would forward * them to its AppView, which may not index the record or may return an outdated CID. * - Never falls back to an indexer: a failed read throws. * - Does not check the record's type or value, or whether the caller may reference it. That is @@ -139,7 +140,7 @@ async function clientForRepo( if (context.client.did === did) return context.client; let pending = pdsClients?.get(did); if (pending === undefined) { - pending = resolvePds(did).then((pds) => new Client(pds)); + pending = resolvePds(context, did).then((pds) => new Client(pds)); pdsClients?.set(did, pending); } return pending; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f724a28..43e97e9 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -203,6 +203,9 @@ importers: specifier: 0.1.7 version: 0.1.7 devDependencies: + '@atproto-labs/identity-resolver': + specifier: 0.4.13 + version: 0.4.13 '@atproto/lex': specifier: 0.4.4 version: 0.4.4 @@ -216,6 +219,10 @@ packages: resolution: {integrity: sha512-CeAC6VY3xaXQ8CaOXLz4EOopSvfcQBcuJvX3J5ew2nbf+BM0nes45ZvxUieP5ZlLPXbJborwJh5zDeJcYpwCFQ==} engines: {node: '>=22'} + '@atproto-labs/did-resolver@0.3.13': + resolution: {integrity: sha512-peNomkIMFcvsrq+1CHXiWv/sAakcYFenIWCB+EI94TPdDezNgRs39R6c8XaU3+UxSbzkfky7R3ywSOiKVVIY1g==} + engines: {node: '>=22'} + '@atproto-labs/fetch-node@0.4.3': resolution: {integrity: sha512-qENUCoXKKNegxin34IpFxNd8yRijTfHq9FEoAVk7ZSciedstUJrVbt4CbdGLkn1t5gcZUH+Csct+MTAEQzvNbA==} engines: {node: '>=22'} @@ -224,6 +231,10 @@ packages: resolution: {integrity: sha512-9HEcZuCU4nWAzV3XZ7nwbDPdV8tbhICzyYeyE5SPHTPuuKS6C3i5WOdwGP1diCCUaYF3Vadw5ArVlQPtXnn73w==} engines: {node: '>=22'} + '@atproto-labs/fetch@0.4.2': + resolution: {integrity: sha512-9mgISMM2eY/w373HUNrtWq4onPzES1K6DaeAv9BDcEgovcKTkcI60H9Jjp38thU2i/dQaGpKrxmxR9qc0FZocg==} + engines: {node: '>=22'} + '@atproto-labs/handle-resolver-node@0.2.15': resolution: {integrity: sha512-ksH6h268dkDAXft45guvYPI/8CnJFlibyBKqpzX75kezQ+Hj8RLbVaScpsnywkE6Jqt31y8E/dW8dyMXKDqidg==} engines: {node: '>=22'} @@ -232,10 +243,18 @@ packages: resolution: {integrity: sha512-hsYYvGhi6Tv6f4Fti//i/vllVIb/wrJaOcbT3Yh7oo10VxBKAyxzVaB7mIJcho2YJ5kHd2kbCYYPWLw8pvm/bg==} engines: {node: '>=22'} + '@atproto-labs/identity-resolver@0.4.13': + resolution: {integrity: sha512-zh7DfDemd5xOeVcuPKkrvObP9SUNrFt/gzkbywc0Obsx5LQMcP5q+ADAInFPpEuYJ5I4AOc4A7G6s6fKbL52KQ==} + engines: {node: '>=22'} + '@atproto-labs/pipe@0.2.4': resolution: {integrity: sha512-n67jCcrC+ouAeO10cWkpPzzLMlDi/lDCU30Us+LGqhOPhT6c4t5ASdBLQi9W3jUQtRzQBt3G9zipF+xKWNvVbw==} engines: {node: '>=22'} + '@atproto-labs/pipe@0.2.5': + resolution: {integrity: sha512-1R1nYs/nHmBcYa4yzTjk5H/46MF5nZm342Ha9kKQTOMp/fr2Yn67qD1pTXUS7L2Mx8AEf3m7Z/TTxRfnERLc8w==} + engines: {node: '>=22'} + '@atproto-labs/simple-store-memory@0.2.6': resolution: {integrity: sha512-DD1v7MEfYF3BAcEpMTTpzfBLWLoI2HuyBhku2YpjHoqPrRrhCtE1alkxfPHjtjJVIjuU/XNU0cF/wB3+5FiKsA==} engines: {node: '>=22'} @@ -1397,6 +1416,15 @@ snapshots: '@atproto/did': 0.5.6 zod: 3.25.76 + '@atproto-labs/did-resolver@0.3.13': + dependencies: + '@atproto-labs/fetch': 0.4.2 + '@atproto-labs/pipe': 0.2.5 + '@atproto-labs/simple-store': 0.5.1 + '@atproto-labs/simple-store-memory': 0.2.6 + '@atproto/did': 0.5.6 + zod: 3.25.76 + '@atproto-labs/fetch-node@0.4.3': dependencies: '@atproto-labs/fetch': 0.4.0 @@ -1410,6 +1438,10 @@ snapshots: dependencies: '@atproto-labs/pipe': 0.2.4 + '@atproto-labs/fetch@0.4.2': + dependencies: + '@atproto-labs/pipe': 0.2.5 + '@atproto-labs/handle-resolver-node@0.2.15': dependencies: '@atproto-labs/fetch-node': 0.4.3 @@ -1423,8 +1455,15 @@ snapshots: '@atproto/did': 0.5.6 zod: 3.25.76 + '@atproto-labs/identity-resolver@0.4.13': + dependencies: + '@atproto-labs/did-resolver': 0.3.13 + '@atproto-labs/handle-resolver': 0.4.10 + '@atproto-labs/pipe@0.2.4': {} + '@atproto-labs/pipe@0.2.5': {} + '@atproto-labs/simple-store-memory@0.2.6': dependencies: '@atproto-labs/simple-store': 0.5.1 From daf014b9b2bf2a1b626cc454bcacf1f56350d4ff Mon Sep 17 00:00:00 2001 From: kzoeps Date: Wed, 11 Nov 2026 17:56:40 +0600 Subject: [PATCH 2/5] skill: show passing oauthClient.identityResolver as didResolver --- .agents/skills/hypercerts-org-sdk/SKILL.md | 16 ++++++++++++++-- .../hypercerts-org-sdk/references/collection.md | 2 +- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/.agents/skills/hypercerts-org-sdk/SKILL.md b/.agents/skills/hypercerts-org-sdk/SKILL.md index a0624f9..ba0fcc4 100644 --- a/.agents/skills/hypercerts-org-sdk/SKILL.md +++ b/.agents/skills/hypercerts-org-sdk/SKILL.md @@ -3,7 +3,7 @@ name: hypercerts-org-sdk description: "Write Hypercerts and Certified records (org.hypercerts.*, app.certified.*) to a PDS from an app with @hypercerts-org/sdk: setting up the SDK context from an authenticated @atproto/lex Client, choosing the right operation and subpath, uploading blobs, and handling write errors without duplicates. Use when app code imports @hypercerts-org/sdk, or the user wants to create, link or write hypercert-related records from an app. Not for changing the SDK's own source." metadata: author: hypercerts-org - version: "4" + version: "5" --- # @hypercerts-org/sdk @@ -40,11 +40,22 @@ export const context = createSDKContext({ client: new Client(session) }); Make a new context when the signed-in account changes. Records are always written to the account behind `client`. +To read another account's record (a `{ uri }` that is not in your repo), the SDK looks up that account's DID document to find its PDS. By default it uses its own resolver and keeps each document in memory for up to an hour per context. If the app has an `@atproto/oauth-client` (or `@atproto/oauth-client-node`) client, pass its resolver to reuse the cache it already has: + +```ts +export const context = createSDKContext({ + client: new Client(session), + didResolver: oauthClient.identityResolver, // the resolver, not `oauthClient` itself +}); +``` + +`didResolver` accepts any object with `resolve(did)` that returns a DID document or `{ didDoc }`. + ## 3. Import from subpaths | Import from | Exports | | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `@hypercerts-org/sdk` | `createSDKContext`, `SDKContext` | +| `@hypercerts-org/sdk` | `createSDKContext`, `SDKContext`, `DidDocumentResolver` | | `@hypercerts-org/sdk/activity` | `createActivity`, `createRights`, `createContribution`, `createContributorInformation`, `WriteError`, `WriteRejectedError`, `WriteOutcomeUnknownError`, `WriteResultMismatchError`, input/result types | | `@hypercerts-org/sdk/actor` | `createProfile`, `ProfileAlreadyExistsError`, `RecordAlreadyExistsError`, the same `Write*` errors, `ProfileInput` | | `@hypercerts-org/sdk/location` | `createLocation`, the same `Write*` errors, `LocationInput`, `LocationValue` | @@ -178,6 +189,7 @@ try { ## Pitfalls - `createSDKContext({ client: session })` or passing an `@atproto/api` `Agent` throws. Wrap it: `new Client(session)`. +- `didResolver: oauthClient` throws. Pass `oauthClient.identityResolver`. - Passing an `uploadBlob` result as `image` throws. Pass the `Blob`/`File`. - Retrying blindly after `WriteOutcomeUnknownError` duplicates every record under new keys. The exception is a call whose records all have a fixed key and are only created if absent: `createProfile` and `createVocabularyTag`. `createOrganization` is also safe to repeat: the organization exists at most once, so a second call creates it or throws `OrganizationAlreadyExistsError`. `createFeature`, `createCollection` and `createWorkScopeTag` are not safe to repeat. - An item of `createCollection` is `{ activity }`, `{ feature }`, `{ collection }` or `{ uri }`, never a bare Activity input; `{ uri }` must be an Activity, Feature or Collection. diff --git a/.agents/skills/hypercerts-org-sdk/references/collection.md b/.agents/skills/hypercerts-org-sdk/references/collection.md index 6640aac..edb6477 100644 --- a/.agents/skills/hypercerts-org-sdk/references/collection.md +++ b/.agents/skills/hypercerts-org-sdk/references/collection.md @@ -30,7 +30,7 @@ collection.items[3]; // { uri, cid, type: "activity", created: false } ``` - An item is **exactly one** of `{ activity }`, `{ feature }`, `{ collection }` (the data of a new record, same input as `createActivity`, `createFeature` and `createCollection`) or `{ uri }`, plus an optional `weight`. The SDK never guesses from the fields: a bare Activity (`{ title, shortDescription }`) is a `TypeError`. -- `{ uri }` must be an Activity, Feature or Collection with a DID (`at:////`). It is read for its CID and reused unchanged; it may belong to another account if public. Another record type, or a handle, is a `TypeError` naming the item. +- `{ uri }` must be an Activity, Feature or Collection with a DID (`at:////`). It is read for its CID and reused unchanged; it may belong to another account if public. Another account's PDS is found with the context's `didResolver` ([SKILL.md](../SKILL.md#2-create-the-context-once)). Another record type, or a handle, is a `TypeError` naming the item. - `weight` is a positive decimal string (`"2"`, `"0.50"`), stored exactly as you pass it. Weights need not add up to anything. - Order is kept. Nothing is deduplicated or searched for: the same `{ uri }` twice gives two items, the same data twice gives two records. - `location` and `tags` take new records or `{ uri }` like in `createFeature`. A new tag's key is `.`: a taken key throws `RecordAlreadyExistsError` before anything is uploaded or written, and two new tags with the same key anywhere in the call are a `TypeError` (create it first and pass its `uri`). From d853e5056598cb008dee23c3ceeeaf3a2ad8a681 Mon Sep 17 00:00:00 2001 From: kzoeps Date: Wed, 11 Nov 2026 17:56:40 +0600 Subject: [PATCH 3/5] docs: e2e notes: the DID resolver can be replaced with didResolver --- docs/e2e-testing.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/e2e-testing.md b/docs/e2e-testing.md index e3b486a..0208295 100644 --- a/docs/e2e-testing.md +++ b/docs/e2e-testing.md @@ -51,7 +51,7 @@ pnpm test:e2e - The tests leave their records and blobs in the two accounts. Each test counts records only around its own call, so earlier runs do not matter. Destroy the sandbox (`deno task sandbox destroy --accept-destructive`) to start clean. - An account has one profile, so the `createProfile` tests delete the first account's profile (the `self` record) before each test. - A vocabulary tag's key is chosen by the caller and cannot be reused, so the tag tests give every tag a key that is different on every run. -- To reuse another account's record, the SDK finds that account's PDS in the `plc.directory` DID document, and it cannot be pointed at another directory. The sandbox's accounts exist only in its own PLC directory, so `e2e/plc.ts` redirects requests for `https://plc.directory` to `SDK_E2E_PLC_URL` while those tests run. +- To reuse another account's record, the SDK finds that account's PDS in the `plc.directory` DID document, and its default DID resolver cannot be pointed at another directory (an application can pass its own `didResolver`). The sandbox's accounts exist only in its own PLC directory, so `e2e/plc.ts` redirects requests for `https://plc.directory` to `SDK_E2E_PLC_URL` while those tests run. - One test uploads a 6 MiB file and expects the PDS to refuse it, which relies on the PDS's default upload limit of 5 MiB (`PDS_BLOB_UPLOAD_LIMIT`). Raise that limit in the sandbox and the test fails. - The test files run one after the other because the tests count the records of the two shared accounts. From fc3f853ac529480a3fbbfc8bf6071cf8be7235be Mon Sep 17 00:00:00 2001 From: kzoeps Date: Wed, 11 Nov 2026 17:56:41 +0600 Subject: [PATCH 4/5] changeset: cache DID lookups and add the didResolver option --- .changeset/did-resolver-cache.md | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 .changeset/did-resolver-cache.md diff --git a/.changeset/did-resolver-cache.md b/.changeset/did-resolver-cache.md new file mode 100644 index 0000000..7130ffc --- /dev/null +++ b/.changeset/did-resolver-cache.md @@ -0,0 +1,6 @@ +--- +"@hypercerts-org/sdk": minor +--- + +- Cache DID lookups per context, so repeated reads of another account's record no longer fetch from plc.directory each time. +- Add the `didResolver` option to `createSDKContext` and the `DidDocumentResolver` type. Pass `oauthClient.identityResolver` or your own resolver. From 369aa142ee52df58a0831b1fb9ef7e88b2782b4c Mon Sep 17 00:00:00 2001 From: kzoeps Date: Wed, 11 Nov 2026 18:01:30 +0600 Subject: [PATCH 5/5] sdk: cover stubbing fetch after the context is created --- packages/sdk/src/internal/resolve-record-ref.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/sdk/src/internal/resolve-record-ref.test.ts b/packages/sdk/src/internal/resolve-record-ref.test.ts index 52204e9..a2d8eca 100644 --- a/packages/sdk/src/internal/resolve-record-ref.test.ts +++ b/packages/sdk/src/internal/resolve-record-ref.test.ts @@ -119,8 +119,10 @@ describe("resolveRecordRef", () => { }); it("looks up an owner's DID once across separate calls on one context", async () => { - const requested = stubOwnerNetwork(); + // Created before the stub, so this also covers the default resolver using the `fetch` that is + // global when it makes a request, not when the context was created. const { context } = fakePds(() => json(500, {})); + const requested = stubOwnerNetwork(); await resolveRecordRef(context, ownerUri("3k2a4b5c6d7e8")); await resolveRecordRef(context, ownerUri("3k2a4b5c6d7e9"));