@synonymdev/pubky
    Preparing search index...

    Class Pubky

    High-level entrypoint to the Pubky SDK.

    Index
    • Create a Pubky facade wired for mainnet defaults (public relays).

      Prefer to instantiate only once and use trough your application a single shared Pubky instead of constructing one per request. This avoids reinitializing transports and keeps the same client available for repeated usage.

      Returns Pubky

      A new facade instance. Use this to create signers, start auth flows, etc.

      const pubky = new Pubky();
      const signer = pubky.signer(Keypair.random());
    browserSessionStore: BrowserSessionStore

    Browser-backed store for explicitly persisted completed grant sessions.

    Use browserSessionStore.save(session) after a successful grant auth flow to make the session restorable after reload. The store supports multiple accounts and multiple grants per account.

    client: Client

    Access the underlying HTTP client (advanced).

    Use this for low-level fetch() calls or testing with raw URLs.

    const r = await pubky.client.fetch(`pubky://${userPk.z32()}/pub/app/file.txt`, { credentials: "include" });
    
    publicStorage: PublicStorage

    Public, unauthenticated storage API.

    Use for read-only public access via addressed paths: "pubky<user>/pub/…".

    const text = await pubky.publicStorage.getText(`${userPk.toString()}/pub/example.com/hello.txt`);
    
    • Returns void

    • Create an event stream builder for a specific homeserver.

      Use this when you already know the homeserver pubkey. This avoids Pkarr resolution overhead. Obtain a homeserver pubkey via getHomeserverOf().

      Parameters

      • homeserver: PublicKey

        The homeserver public key

      Returns EventStreamBuilder

      • Builder for configuring and subscribing to the stream
      const homeserver = await pubky.getHomeserverOf(user1);
      const stream = await pubky.eventStreamFor(homeserver)
      .addUsers([[user1.z32(), null], [user2.z32(), null]])
      .live()
      .subscribe();

      for await (const event of stream) {
      console.log(`${event.eventType}: ${event.resource.path}`);
      }
    • Create an event stream builder for a single user.

      This is the simplest way to subscribe to events for one user. The homeserver is automatically resolved from the user's Pkarr record.

      Parameters

      • user: PublicKey

        The user's public key

      • Optionalcursor: string | null

        Optional cursor position to start from

      Returns EventStreamBuilder

      • Builder for configuring and subscribing to the stream
      const user = PublicKey.from("o1gg96ewuojmopcjbz8895478wdtxtzzuxnfjjz8o8e77csa1ngo");
      const stream = await pubky.eventStreamForUser(user, null)
      .live()
      .subscribe();

      for await (const event of stream) {
      console.log(`${event.eventType}: ${event.resource.path}`);
      }
    • Returns void

    • Resolve the homeserver for a given public key (read-only).

      Uses an internal read-only Pkdns actor.

      Parameters

      Returns Promise<PublicKey | undefined>

      Homeserver public key, or undefined when the user has no resolvable homeserver record.

      When Pkarr resolution fails or a resolved _pubky target is malformed.

    • Restore a session from a previously exported token or snapshot, using this instance's client.

      Accepts grant secret tokens from session.exportLocalSecret() and legacy cookie secret tokens. Also accepts legacy cookie metadata snapshots from session.export(). Grant restore mints a fresh short-lived bearer.

      Parameters

      • exported: string

        A string produced by session.exportLocalSecret() or legacy session.export().

      Returns Promise<Session>

      A rehydrated session bound to this SDK's HTTP client.

      const restored = await pubky.restoreSession(localStorage.getItem("pubky-session")!);
      
    • Resume a previously started pubkyauth flow from its saved authorizationUrl.

      If the user refreshes or navigates away mid-flow, WASM memory is lost and the original AuthFlow object is gone. You can reconnect to the same relay channel by saving the authorizationUrl beforehand and calling this method after reload.

      The relay inbox retains messages for ~5 minutes. Resume is only viable within that window; afterwards start a fresh flow.

      Security: The URL contains the client_secret in plaintext. Store it in sessionStorage (scoped to the tab), not localStorage, and delete it as soon as the resumed flow completes or is abandoned. See startCookieAuthFlow() docs for full storage guidance.

      Parameters

      • authorization_url: string

      Returns AuthFlow

      A flow reconnected to the original relay channel.

      • { name: "AuthenticationError" } if the URL is invalid or not a signin/signup link
      • { name: "RequestError" } on network/relay failure
      // 1) Before a potential refresh, persist the URL.
      const flow = pubky.startCookieAuthFlow("/pub/my-cool-app/:rw", AuthFlowKind.signin());
      sessionStorage.setItem("pubky-auth-url", flow.authorizationUrl);
      renderQr(flow.authorizationUrl);

      // 2) After reload, resume from the saved URL.
      const savedUrl = sessionStorage.getItem("pubky-auth-url");
      if (savedUrl) {
      try {
      const resumed = pubky.resumeCookieAuthFlow(savedUrl);
      const session = await resumed.awaitApproval();
      } finally {
      sessionStorage.removeItem("pubky-auth-url");
      }
      }
    • Resume a previously saved pending delegated grant auth flow.

      Runtime: delegated grant keys require a secure browser context with WebCrypto crypto.subtle and IndexedDB. The saved keyId must still exist in IndexedDB for the same origin. Unsupported runtimes reject with ClientStateError.

      Parameters

      • saved_state: string

      Returns Promise<GrantAuthFlow>

    • Resume a previously saved pending grant auth flow.

      Security: savedState contains the relay secret and PoP client private key. Delete it from storage as soon as the resumed flow completes.

      Parameters

      • saved_state: string

      Returns GrantAuthFlow

      A flow reconnected to the original relay channel.

    • Create a Signer from an existing Keypair.

      Parameters

      • keypair: Keypair

        The user’s keys.

      Returns Signer

      const signer = pubky.signer(Keypair.random());
      await signer.signup(homeserverPk);
    • Start a pubkyauth flow.

      Provide a capabilities string and (optionally) a relay base URL. The capabilities string is a comma-separated list of entries: "<scope>:<actions>", where:

      • scope starts with / (e.g. /pub/example.com/).
      • actions is any combo of r and/or w (order normalized; wr -> rw). Pass "" for no scopes (read-only public session).

      Security: authorizationUrl contains the client_secret in plaintext. If you need resume after refresh/app switch, save it in sessionStorage (not localStorage), then delete it once approval arrives or is abandoned.

      Parameters

      • capabilities: Capabilities

        Comma-separated caps, e.g. "/pub/app/:rw,/pub/foo/file:r".

      • kind: AuthFlowKind

        The kind of authentication flow to perform. Examples:

        • AuthFlowKind.signin() - Sign in to an existing account.
        • AuthFlowKind.signup(homeserverPublicKey, signupToken) - Sign up for a new account.
      • Optionalrelay: string | null

        Optional HTTP relay base (e.g. "https://…/inbox/").

      • Optionalx_callback: XCallbackParams | null

      Returns AuthFlow

      A running auth flow. Show authorizationUrl as QR/deeplink, then awaitApproval() to obtain a Session.

      • { name: "InvalidInput" } for malformed capabilities or bad relay URL
      • { name: "RequestError" } if the flow cannot be started (network/relay)
      const flow = pubky.startCookieAuthFlow("/pub/my-cool-app/:rw");
      renderQr(flow.authorizationUrl);
      const session = await flow.awaitApproval();
    • Start a grant-backed pubkyauth flow.

      Grant auth uses a user-signed grant JWS plus Proof-of-Possession and returns a self-refreshing session.

      Parameters

      • capabilities: Capabilities

        Comma-separated caps, e.g. "/pub/app/:rw,/pub/foo/file:r".

      • kind: AuthFlowKind

        The kind of authentication flow to perform.

      • options: GrantAuthFlowOptions

        Options for the grant flow: { clientId, relay?, xCallback? }.

      Returns Promise<GrantAuthFlow>

      A running grant auth flow. Show authorizationUrl as QR/deeplink, then awaitApproval() to obtain a grant-backed Session.

      const flow = await pubky.startGrantAuthFlow(
      "/pub/my-cool-app/:rw",
      AuthFlowKind.signin(),
      { clientId: "my-cool-app.example" },
      );
    • Create a Pubky facade preconfigured for a local testnet.

      If host is provided, PKARR and HTTP endpoints are derived as http://<host>:ports/.... If omitted, "localhost" is assumed (handy for cargo install pubky-testnet).

      Parameters

      • Optionalhost: string | null

        Optional host (e.g. "localhost", "docker-host", "127.0.0.1").

      Returns Pubky

      const pubky = Pubky.testnet();              // localhost default
      const pubky = Pubky.testnet("docker-host"); // custom hostname/IP
    • Wrap an existing configured HTTP client into a Pubky facade.

      Parameters

      • client: Client

        A previously constructed client.

      Returns Pubky

      const client = Client.testnet();
      const pubky = Pubky.withClient(client);