decane
Server-side SDK for Decane Connect Kit, the Rust port of decane-node.
Verify a caller's Decane access token, resolve their wallet addresses, sign
users in from any Rust backend, read and write per-user records, and create
users and wallets before they sign in. Async-only, on tokio. Two verification
modes:
- Static verification key (Privy-style, offline): verify locally against your project's ES256 public key. No network call.
- JWKS (default): Decane publishes an ES256 JWKS that this crate fetches, caches for ten minutes, and refetches once when a signature fails, so key rotation needs no redeploy.
[]
= "1"
= { = "1", = ["rt-multi-thread", "macros"] }
Rust 1.85+, edition 2024. TLS is rustls; no OpenSSL.
Quick start
use DecaneClient;
// Static key (recommended for backends): copy the key from your Decane
// dashboard. app_id is checked against the token's project_id;
// verification_key is also read from DECANE_VERIFICATION_KEY if omitted.
let decane = builder
.app_id
.verification_key // ES256 SPKI PEM
.build?;
// In your auth middleware:
let token = authorization.strip_prefix.unwrap_or;
let claims = decane.verify_access_token.await?; // Err(DecaneError::Auth) if invalid
claims.user_id; // stable Decane user id: key your records off this
To use JWKS instead, just omit verification_key:
let decane = builder.app_id.build?;
// Base URL resolution: `api_base` option → `DECANE_API_BASE` env → the built-in
// https://backend.decane.app. An empty value at any step counts as unset, so a
// deploy template that writes `DECANE_API_BASE=` cannot break the client. The
// resolved value is readable as `decane.api_base()`.
Build one client per project and reuse it (or clone it: clones share the JWKS cache).
Fail-closed middleware
match decane.safe_verify_access_token.await?
The ? still propagates a JWKS fetch failure (NETWORK_ERROR), so an
outage answers 500, not 401.
Resolve the user's wallet addresses
let user = decane.get_user.await?;
user.id; // uid
user.addresses.evm; // Option<String>, "0x…"
user.addresses.solana;
user.addresses.tron;
user.linked_accounts; // Privy-compatible: [{ type: wallet, chain_type: ethereum, address }]
Sign-in (server-side)
The same sign-in flows the frontend SDKs offer, minus anything that needs a
browser or a device authenticator. Requires your developer API key
(dck_live_…, from the Decane dashboard): pass api_key or set the
DECANE_API_KEY env var. The key is a secret: server env only, never
shipped to a browser.
let decane = builder
.app_id
.api_key
.build?;
// Email OTP, two steps
decane.connect_with_email.await?; // emails a 6-digit code
let session = decane.verify_email_code.await?;
session.access_token; // Decane JWT (8 h): verify it, or hand it to the client
session.user_id; // stable Decane user id
session.is_new_user;
session.has_share; // false = no wallet yet
// Phone OTP, two steps; E.164 only
decane.connect_with_phone.await?;
let session = decane.verify_phone_code.await?;
// Token exchanges, one step each
decane.connect_with_google_token.await?; // Google ID token you already hold
decane.connect_with_kingschat_token.await?; // KingsChat OAuth access token
decane.connect_with_token.await?; // custom auth
// Sign-out
decane.revoke_access_token.await?;
get_user(&session.access_token) composes in one line when you also want
addresses. Google and KingsChat results carry a profile (name, email,
picture, each optional) passed through from the provider; Decane never
stores it.
Not available server-side (browser/authenticator required): the Google
redirect flow, the interactive KingsChat popup, and passkey sign-in. Signing
stays in the client SDKs. A has_share: false user has addresses of None
until a client creates the wallet, or your server does (below).
Sign-in caveats
- Rate limits: there is no per-IP limit on the auth endpoints, so a server funnelling every user through one egress IP is fine. OTP attempts are limited to 10 per 15 minutes per target email or phone, and code sends to 3 per hour per address.
- Tokens last 8 hours and can be renewed.
POST /auth/refreshwith a still-valid token as the Bearer returns a fresh one, capped at 7 days from the sign-in. The client SDKs do this automatically; this crate does not wrap it yet. connect_with_emailandconnect_with_phonealways succeed, whether or not the address is known (anti-enumeration by design): never surface "email not found".
Per-user records
Two small, flat JSON records live on every Decane user, the replacement for Privy's custom metadata, split by who may write them:
| Record | Written with | Read with | For |
|---|---|---|---|
preferences |
the user's access token, or the secret | either | the user's own choices (a settings screen) |
metadata |
the project secret only | either | your facts about the user: plan, flags, your own ids |
A user cannot change metadata, so an entitlement may live there. Values are
strings, numbers or booleans (RecordValue) under short keys; at most 100
keys and 32 KB. Record is a BTreeMap<String, RecordValue>; RecordPatch
is the same with Option values, where None removes the key.
use ;
// With the user's token, from a route that already verified it:
let prefs: Record = decane.get_preferences.await?; // { shine_perps: false, … }
let mut patch = new;
patch.insert;
patch.insert; // None removes
decane.update_preferences.await?; // merge
decane.set_preferences.await?; // replace
decane.get_metadata.await?; // read-only on this side
// By user id, with the project secret (dck_sk_…, from the project's page in
// the dashboard): pass `project_secret` or set DECANE_PROJECT_SECRET:
let decane = builder
.app_id
.project_secret
.build?;
decane.update_user_metadata.await?;
decane.get_user_metadata.await?;
decane.set_user_metadata.await?;
decane.get_user_preferences.await?; // and update / set
A write that breaks the rules fails with ApiErrorCode::InvalidRecord (the
message names the key); a user of another project is NotFound.
Server-side wallet creation
Create a user, and their wallet, before they have signed in. Decane keys the user exactly as the matching sign-in will, so their first sign-in opens the wallet made here and the client creates nothing. The key is generated in the enclave; your server sees only the addresses.
use ;
let made = decane
.create_user
.await?;
made.user.addresses.evm; // fund it now; Ada finds it when she signs in
made.wallet; // WalletOutcome::Created | Exists | None
decane.create_user.await?;
decane.create_user.await?;
decane.create_user_wallet.await?; // for an existing user with no wallet
Idempotent on the identifier. Off until the Decane team switches it on for
your project (ServerWalletsDisabled); sixty calls a minute per project.
Errors: InvalidIdentifier, WalletExists, WalletFrozen, RetryLater,
EnclaveUnavailable.
Token claims
Decane access tokens (ES256) carry uid, sub, project_id, jti, iat,
exp. verify_access_token checks the signature and expiry (zero clock
tolerance), and, when app_id is set, that project_id matches (the
audience-equivalent; Decane tokens set no iss/aud). It returns normalised
Claims (user_id, subject, project_id, token_id, issued_at,
expires_at, raw).
Errors
One enum, DecaneError, with three variants:
Auth { reason, message, source }: the token cannot be trusted.reasonisAuthErrorReason::InvalidToken,MissingUidorProjectMismatch(invalid_token,missing_uid,project_mismatchviaDisplay). Usesafe_verify_access_tokenfor anOption-returning variant.Api { code, status, message, source }: a backend call failed.codeis anApiErrorCode;statusis the HTTP status, 0 when the request never got a response.Config(String): a missing key or secret, an empty argument, a malformed verification key. Raised before any network call.
| Code | Meaning |
|---|---|
InvalidCode |
Email or phone OTP wrong or expired |
AuthFailed |
Provider token rejected |
InvalidToken |
Custom-auth JWT rejected |
NoProvider / AmbiguousProvider / MissingClaim |
Custom-auth provider config issues |
InvalidApiKey / AppIdMismatch |
Credential problems |
SmsNotConfigured |
Phone sign-in on a deployment with no SMS provider |
KingsChatNotConfigured / KingsChatUnavailable |
KingsChat setup / upstream outage |
InvalidRecord / NotFound / Unauthorized |
Record problems |
ServerWalletsDisabled / InvalidIdentifier / WalletExists / WalletFrozen / EnclaveUnavailable / RetryLater |
Creation problems |
RateLimited |
HTTP 429 with no envelope |
Unknown / NetworkError |
Unparseable response / request never completed (status: 0) |
Other(String) |
A code this version does not know by name; the wire string is kept |
ApiErrorCode implements Display and FromStr with the wire strings
(INVALID_CODE, …), so logs and dashboards read the same as the Node SDK's.
Notes
- Stateless. Verification checks signature + expiry + project, not
Decane's server-side revocation list. For immediate sign-out enforcement,
additionally gate sensitive routes on a fresh backend call.
(
revoke_access_tokendoes add the token to the revocation list, which backend calls likeget_addresseshonour immediately.) - Migrating from Privy? Decane's
uidis a UUID, not adid:privy:…. Rows keyed by a Privy id won't match a Decaneuid; map legacy ids during a re-auth window before cutting production over.
Config
Every builder setter is optional.
| Setter | Env fallback | Default | Purpose |
|---|---|---|---|
app_id |
— | — | Enforce project_id matches; sent as X-App-Id. |
verification_key |
DECANE_VERIFICATION_KEY |
— (falls back to JWKS) | ES256 SPKI PEM; verify offline, no JWKS fetch. Literal \n accepted. |
api_key |
DECANE_API_KEY |
— | dck_live_… key; required only for sign-in calls. |
project_secret |
DECANE_PROJECT_SECRET |
— | dck_sk_… key; required only for by-user-id records and creation. |
api_base |
DECANE_API_BASE |
https://backend.decane.app |
Backend base URL; trailing slashes stripped. |
jwks_url |
— | {api_base}/.well-known/jwks.json |
Override the JWKS location (ignored with a key). |
http_client |
— | a reqwest::Client with a 15 s timeout |
Your own reqwest::Client, used for every request including the JWKS fetch. |
timeout |
— | 15 s | Per-request timeout for the built-in client. |
Env vars are read in build(); an empty or whitespace-only value counts as
unset.
Deviations from decane-node
The wire format and every code, message and check are those of decane-node 1.5.0. What differs:
- A JWKS fetch failure is
Api { NetworkError, status: 0 }, not an auth error, andsafe_verify_access_tokenpropagates it (node returns null). A network outage must not read as "bad token". - snake_case names (
verify_access_token,user_id); the wire is unchanged. - Async-only, on tokio.
- The injected HTTP client is used for the JWKS fetch too (node's
josealways uses the global fetch). - Default request timeout 15 s (node has none).
- A malformed verification key fails at
build(), not on the first verify. - Config mistakes (missing
api_keyorproject_secret, empty arguments) areDecaneError::Configrather than a plainError. safe_verify_access_tokenreturnsResult<Option<Claims>>; there is no standalone cachedverify_access_tokenhelper (build one client and reuse it).ApiErrorCodehas anOther(String)variant for codes this version does not know by name.- Expired tokens keep node's
invalid_tokenreason and "Access token has expired." message.
Additionally connect_with_token takes Option<&str> for the provider id
instead of an options object, create_user takes a CreateUserOptions value
(CreateUserOptions::default() for none), and the phone methods
(connect_with_phone, verify_phone_code) are present as in node.
Changelog
- 1.0.0 — First release, mirroring decane-node 1.5.0: token verification
(static key or JWKS),
get_user/get_addresses, server-side sign-in (email, phone, Google token, KingsChat token, custom auth), revocation, per-user records with a user token or the project secret, andcreate_user/create_user_wallet. Deviations from decane-node are listed above.
License
MIT