# 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.
```toml
[dependencies]
decane = "1"
tokio = { version = "1", features = ["rt-multi-thread", "macros"] }
```
Rust 1.85+, edition 2024. TLS is rustls; no OpenSSL.
## Quick start
```rust
use decane::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 = DecaneClient::builder()
.app_id(std::env::var("DECANE_APP_ID")?)
.verification_key(std::env::var("DECANE_VERIFICATION_KEY")?) // ES256 SPKI PEM
.build()?;
// In your auth middleware:
let token = authorization.strip_prefix("Bearer ").unwrap_or("");
let claims = decane.verify_access_token(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`:
```rust
let decane = DecaneClient::builder().app_id("your-project-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
```rust
match decane.safe_verify_access_token(token).await? {
Some(claims) => claims,
None => return Err(StatusCode::UNAUTHORIZED), // None instead of an Auth error
}
```
The `?` still propagates a JWKS fetch failure (`NETWORK_ERROR`), so an
outage answers 500, not 401.
### Resolve the user's wallet addresses
```rust
let user = decane.get_user(token).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.
```rust
let decane = DecaneClient::builder()
.app_id(app_id)
.api_key(std::env::var("DECANE_API_KEY")?)
.build()?;
// Email OTP, two steps
decane.connect_with_email("user@example.com").await?; // emails a 6-digit code
let session = decane.verify_email_code("user@example.com", "123456").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("+2348012345678").await?;
let session = decane.verify_phone_code("+2348012345678", "123456").await?;
// Token exchanges, one step each
decane.connect_with_google_token(google_id_token).await?; // Google ID token you already hold
decane.connect_with_kingschat_token(kc_access_token).await?; // KingsChat OAuth access token
decane.connect_with_token(jwt_from_your_issuer, Some("prov-1")).await?; // custom auth
// Sign-out
decane.revoke_access_token(&session.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/refresh` with 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_email` and `connect_with_phone` always 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**:
| `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.
```rust
use decane::{Record, RecordPatch, RecordValue};
// With the user's token, from a route that already verified it:
let prefs: Record = decane.get_preferences(token).await?; // { shine_perps: false, … }
let mut patch = RecordPatch::new();
patch.insert("shine_perps".into(), Some(RecordValue::Bool(true)));
patch.insert("old".into(), None); // None removes
decane.update_preferences(token, &patch).await?; // merge
decane.set_preferences(token, &record).await?; // replace
decane.get_metadata(token).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 = DecaneClient::builder()
.app_id(app_id)
.project_secret(std::env::var("DECANE_PROJECT_SECRET")?)
.build()?;
decane.update_user_metadata(&claims.user_id, &patch).await?;
decane.get_user_metadata(&claims.user_id).await?;
decane.set_user_metadata(&claims.user_id, &Record::new()).await?;
decane.get_user_preferences(&claims.user_id).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.
```rust
use decane::{CreateUserOptions, UserIdentifier, WalletOutcome};
let made = decane
.create_user(UserIdentifier::email("ada@example.com"), CreateUserOptions::default())
.await?;
made.user.addresses.evm; // fund it now; Ada finds it when she signs in
decane.create_user(
UserIdentifier::phone("+2348012345678"),
CreateUserOptions { metadata: Some(patch), ..Default::default() },
).await?;
decane.create_user(
UserIdentifier::custom("auth0|123", provider_id),
CreateUserOptions { create_wallet: Some(false), ..Default::default() },
).await?;
decane.create_user_wallet(&made.user.id).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. `reason` is
`AuthErrorReason::InvalidToken`, `MissingUid` or `ProjectMismatch`
(`invalid_token`, `missing_uid`, `project_mismatch` via `Display`). Use
`safe_verify_access_token` for an `Option`-returning variant.
- `Api { code, status, message, source }`: a backend call failed. `code` is an
`ApiErrorCode`; `status` is 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.
| `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_token` does add the token to the revocation list, which
backend calls like `get_addresses` honour immediately.)
- **Migrating from Privy?** Decane's `uid` is a UUID, not a `did:privy:…`.
Rows keyed by a Privy id won't match a Decane `uid`; map legacy ids during
a re-auth window before cutting production over.
## Config
Every builder setter is optional.
| `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:
1. A JWKS fetch failure is `Api { NetworkError, status: 0 }`, not an auth
error, and `safe_verify_access_token` propagates it (node returns null). A
network outage must not read as "bad token".
2. snake_case names (`verify_access_token`, `user_id`); the wire is unchanged.
3. Async-only, on tokio.
4. The injected HTTP client is used for the JWKS fetch too (node's `jose`
always uses the global fetch).
5. Default request timeout 15 s (node has none).
6. A malformed verification key fails at `build()`, not on the first verify.
7. Config mistakes (missing `api_key` or `project_secret`, empty arguments)
are `DecaneError::Config` rather than a plain `Error`.
8. `safe_verify_access_token` returns `Result<Option<Claims>>`; there is no
standalone cached `verify_access_token` helper (build one client and
reuse it).
9. `ApiErrorCode` has an `Other(String)` variant for codes this version does
not know by name.
10. Expired tokens keep node's `invalid_token` reason 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, and
`create_user` / `create_user_wallet`. Deviations from decane-node are
listed above.
## License
MIT