Pubky SDK
Ergonomic building blocks for Pubky apps: one facade (Pubky) plus focused actors for sessions, storage API, signer helpers, and QR auth flow for keyless apps.
Rust implementation of Pubky SDK.
Install
# Cargo.toml
[]
= "0.x" # this crate
# Optional helpers used in examples:
# pubky-testnet = "0.x"
Quick start
use *;
use ClientId;
# async
Error-body limits
HTTP status checking leaves successful response bodies unread. For HTTP errors, the client captures up to 4096 body bytes for the error message. Change this limit when creating the client:
use ;
let client = builder
.max_error_body_bytes
.build?;
let pubky = with_client;
# Ok::
The setting applies to all checked requests made through that client, including
credential-refresh errors. Set it to 0 to skip error-body reads and use the
HTTP status reason as the message. Positive limits preserve short messages and
mark longer ones with \n[response body truncated at N bytes].
The limit caps captured response bytes. Invalid UTF-8 can expand the message to three times that size, plus the truncation marker. Transport buffers and allocations add memory overhead.
In JavaScript, use Pubky.withClient(new Client({ maxErrorBodyBytes: 1024 })).
Event-stream limits
Event subscriptions use sse-core with a default limit of usize::MAX,
which is effectively unbounded.
Set a client-side limit per subscription to reject oversized or unterminated
SSE payloads in historical and live streams:
# async
In JavaScript, use .maxEventBytes(8192) on the event-stream builder.
Rust rejects zero at subscription time; JavaScript requires an integer in
1..=4294967295 when setting the limit.
The limit applies separately to accumulated event data, each event name, and
each ID. Data includes the newlines joining
data fields; repeated event and id fields replace their previous values.
Comments and unknown fields are skipped without buffering their contents.
Field prefixes, framing line endings and a leading UTF-8 BOM do not count.
There is no total block or stream byte limit. This setting is independent of
.limit() (event count) and max_error_body_bytes.
On overflow, the SDK closes the response and yields one validation error, then
ends the Rust stream or errors the JavaScript ReadableStream. It still skips
malformed Pubky events and unknown event types within the limit.
All subscriptions replace invalid UTF-8 and discard incomplete events at EOF. Transport errors release the response and end the stream. This changes the previous default parser's behavior, which reported UTF-8 errors and could continue after a transport error.
Parser memory is a multiple of the limit because data, event names and IDs have separate buffers, with additional UTF-8 replacement and URL encoding overhead. Transport buffers and events retained by the application are outside this limit.
Key formats (display vs transport)
PublicKey has two string representations:
- Display format:
pubky<z32>(used for logs/UI and human-facing identifiers). - Transport/storage format: raw
z32(used for hostnames, storage owner path segments, legacy headers, query params, serde/JSON, and database storage).
Use .z32() whenever you are building hostnames or transport values (for example _pubky.<z32>, /storage/<z32>/..., or the legacy pubky-host header). Use Display/.to_string() when you want the prefixed identifier for people.
Reuse a single facade across your app
Use a shared Pubky (via cloning it, passing down as argument or behind OnceCell) instead of constructing one per request. This avoids reinitializing transports and keeps the same client available for repeated usage.
Mental model
Pubky- facade, always start here! Owns the transport and constructs actors.PubkySigner- local key holder. Cansignup,signin, approve QR auth, publish PKDNS.PubkySession- authenticated “as me” handle. Exposes session-scoped storage.GrantManager- account-level grant listing and revocation using an authenticated root session.PublicStorage- unauthenticated reads of others’ public data.Pkdns- resolve/publish_pubkyrecords.
Transport:
PubkyHttpClient: handles requests to pubky public-key hosts.
Examples
Storage API (session & public)
Session (authenticated):
use ;
# async
Public (read-only):
use ;
# async
See the Public Storage example.
Path rules:
- Session storage uses absolute paths under
/pub/or/priv/. - Public storage uses addressed form
pubky<user>/pub/app/file.txt(preferred) orpubky://<user>/.... - A storage path cannot be both an exact file and an implicit folder prefix. For example:
- if
/pub/app/fooexists, writing/pub/app/foo/bar.jsonreturns409 Conflict. - if descendants under
/pub/app/foo/exist, writing/pub/app/fooreturns409 Conflict.
- if
Convention: put your app’s public data under a domain-like folder in /pub, e.g. /pub/my-new-app/.
See Private Storage for /priv/ access and events.
Resolve identifiers into transport URLs
Use [resolve_pubky] to turn a public resource identifier into its canonical HTTPS homeserver URL. PubkyHttpClient::request_async resolves the transport and falls back to legacy storage addressing when needed:
# use ;
# use Method;
# async
The high-level Rust storage APIs and JavaScript Client.fetch do this automatically, so their storage requests remain compatible with older homeservers. Other HTTP clients can send the canonical /storage/{owner}/... URL only to homeservers that advertise path-addressed-storage.
PKDNS (Pkarr)
Resolve another user’s homeserver (_pubky record), or publish your own via the signer.
use ;
# async
Pubky QR auth for third-party and keyless apps
Request an authorization URL and await approval.
Typical usage:
- Start an auth flow with
pubky.start_grant_auth_flow(&caps, ..). You can also usePubkyGrantAuthFlow::builder()to set a custom relay. The deprecated cookie flow remains available only for compatibility. - Show
authorization_url()(QR/deeplink) to the signing device (e.g., Pubky Ring — iOS / Android). - Await
await_approval()to obtain a session-boundPubkySession, orawait_credential()for a rawGrantCredential/CookieCredentialthat you can persist, inspect, or lift into a session later viaPubkySession::from_{grant,cookie}_credential.
# use ;
# async
Optional x-callback parameters let the authenticator return control to the requesting app after it has handled the deep link. They work with both cookie and grant flows:
# use ;
# use XCallbackParams;
#
Approve an auth request
signer.approve_auth.await?;
See the fully functional Auth Flow Example.
Relay & reliability
- If you don’t specify a relay, the auth flow defaults to a Synonym-hosted relay. If that relay is down, logins won’t complete.
- For production and larger apps, run your own relay (MIT, Docker): https://httprelay.io.
The channel is derived as
base64url(hash(secret)); the token is end-to-end encrypted with thesecretand cannot be decrypted by the relay.
Custom relay example
# use ;
# async
Tip: reuse
pubky.client()when customising the relay so the flow shares TLS and pkarr configuration with the rest of your application.
Features
json: enableStoragehelpers (.get_json()/.put_json()) and serde on certain types.
# Cargo.toml
[]
= { = "x.y.z", = ["json"] }
Testing locally
Spin up an ephemeral testnet (DHT + homeserver + relay) and run your tests fully offline:
# use ;
# async
Keypair and Session persistence
Encrypted Keypair secrets (.pkarr):
use Pubky;
#
Grant session secrets:
signin creates a grant-backed session. Export its secret with
[GrantSessionView::export_local_secret] and restore it with [Pubky::restore_session].
This example loads the keypair of an account that has already signed up.
use ;
# async
The deprecated .sess helpers are cookie-only; write_secret_file
panics on grant sessions.
Security: the exported secret is unencrypted and contains the grant and its private proof-of-possession key. Anyone holding it can act within the granted capabilities until the grant expires or is revoked. Store it securely and never log it.
Example code
Check more examples using the Pubky SDK.
JS bindings
Find a wrapper of this crate using wasm_bindgen in npmjs.com. Or build on pubky-sdk codebase under pubky-sdk/bindings/js.
License: MIT Relay: https://httprelay.io (open source; run your own for production)