decane 1.1.0

Server-side SDK for Decane Connect Kit: verify access tokens, sign users in, per-user records and server-side wallet creation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
//! Data types. Field names are snake_case in Rust and camelCase on the wire,
//! exactly as decane-node sends and receives them.

use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};

/// Default Decane backend base URL. Override per environment with
/// [`DecaneClientBuilder::api_base`](crate::DecaneClientBuilder::api_base)
/// or the `DECANE_API_BASE` env var.
pub const DEFAULT_API_BASE: &str = "https://backend.decane.app";

// ── Verification ─────────────────────────────────────────────────────────────

/// Verified, normalised claims from a Decane access token.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Claims {
    /// Stable Decane user id: the value to key your own records off.
    pub user_id: String,
    /// Hashed subject identifier (HMAC of the auth-provider identity).
    pub subject: String,
    /// Project (app) the token was issued for, if present.
    pub project_id: Option<String>,
    /// Token id, unique per issued token (Decane's `jti`).
    pub token_id: Option<String>,
    /// Issued-at, seconds since the epoch.
    pub issued_at: Option<u64>,
    /// Expiry, seconds since the epoch.
    pub expires_at: Option<u64>,
    /// The raw verified JWT payload, for any claim not surfaced above.
    pub raw: Map<String, Value>,
}

/// A user's public wallet addresses. Never contains key material.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Addresses {
    /// EIP-55 EVM address.
    #[serde(default)]
    pub evm: Option<String>,
    /// Base58 Solana address.
    #[serde(default)]
    pub solana: Option<String>,
    /// Base58check Tron address.
    #[serde(default)]
    pub tron: Option<String>,
}

/// The kind of a [`LinkedAccount`]; only wallets today.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum LinkedAccountType {
    /// A wallet address.
    Wallet,
}

/// The chain family of a [`LinkedAccount`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ChainType {
    /// Any EVM chain.
    Ethereum,
    /// Solana.
    Solana,
    /// Tron.
    Tron,
}

/// A linked-wallet account, in a Privy-compatible shape for easy migration.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LinkedAccount {
    /// Always [`LinkedAccountType::Wallet`].
    #[serde(rename = "type")]
    pub account_type: LinkedAccountType,
    /// Which chain family the address is on.
    pub chain_type: ChainType,
    /// The address.
    pub address: String,
}

/// A resolved user: verified identity plus their on-chain addresses.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct User {
    /// Stable Decane user id.
    pub id: String,
    /// The user's wallet addresses; any may be `None`.
    pub addresses: Addresses,
    /// The same addresses as Privy-shaped linked accounts.
    pub linked_accounts: Vec<LinkedAccount>,
}

// ── Server-side user and wallet creation ─────────────────────────────────────

/// Who a pre-created user is, in the terms the matching sign-in will use. The
/// person's first sign-in with this identifier lands on the same user (and the
/// wallet made for them), because Decane keys the row exactly as that sign-in
/// would.
///
/// Serialises as `{"type": "email", "value": "…"}` and so on; `Custom` adds
/// `providerId`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum UserIdentifier {
    /// Any case; a later email-code OR Google sign-in with this verified
    /// address resolves to this user.
    Email {
        /// The email address.
        value: String,
    },
    /// E.164, `+<country><number>`.
    Phone {
        /// The phone number.
        value: String,
    },
    /// The subject your own JWTs assert (the provider's identity claim), with
    /// the provider's id from the dashboard.
    Custom {
        /// The subject.
        value: String,
        /// The custom-auth provider id.
        #[serde(rename = "providerId")]
        provider_id: String,
    },
    /// The KingsChat user id (never an @handle).
    KingsChat {
        /// The KingsChat user id.
        value: String,
    },
    /// The X (Twitter) user id (never an @handle).
    X {
        /// The X user id.
        value: String,
    },
}

impl UserIdentifier {
    /// An email identifier.
    pub fn email(value: impl Into<String>) -> Self {
        Self::Email {
            value: value.into(),
        }
    }

    /// A phone identifier (E.164).
    pub fn phone(value: impl Into<String>) -> Self {
        Self::Phone {
            value: value.into(),
        }
    }

    /// A custom-auth identifier: the subject and the provider id.
    pub fn custom(value: impl Into<String>, provider_id: impl Into<String>) -> Self {
        Self::Custom {
            value: value.into(),
            provider_id: provider_id.into(),
        }
    }

    /// A KingsChat identifier.
    pub fn kingschat(value: impl Into<String>) -> Self {
        Self::KingsChat {
            value: value.into(),
        }
    }

    /// An X identifier.
    pub fn x(value: impl Into<String>) -> Self {
        Self::X {
            value: value.into(),
        }
    }
}

/// Options for [`DecaneClient::create_user`](crate::DecaneClient::create_user).
/// Unset fields are left out of the request.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CreateUserOptions {
    /// Also create the wallet. The backend defaults to `true`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub create_wallet: Option<bool>,
    /// Written to the user's `metadata` record (merge) in the same call.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub metadata: Option<RecordPatch>,
}

/// The wallet outcome of a creation call.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum WalletOutcome {
    /// Made by this call.
    Created,
    /// Was already there.
    Exists,
    /// `create_wallet: false` and no wallet yet.
    None,
}

/// The user part of a [`CreatedUser`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CreatedUserInfo {
    /// Stable Decane user id.
    pub id: String,
    /// How the user signs in, e.g. `email`.
    pub auth_method: String,
    /// The masked identifier as the dashboard shows it, e.g. `ad*@example.com`.
    #[serde(default)]
    pub identifier: Option<String>,
    /// The wallet addresses; all `None` when there is no wallet yet.
    pub addresses: Addresses,
}

/// What `create_user` and `create_user_wallet` resolve to.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CreatedUser {
    /// The user.
    pub user: CreatedUserInfo,
    /// True when this call made the user row; false when it already existed.
    pub created: bool,
    /// What happened to the wallet.
    pub wallet: WalletOutcome,
}

// ── Per-user records ─────────────────────────────────────────────────────────

/// A value in a per-user record: a string, a number or a boolean.
///
/// Untagged on the wire. Integers that fit an `i64` deserialise as
/// [`Int`](Self::Int), other numbers as [`Float`](Self::Float).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum RecordValue {
    /// A boolean.
    Bool(bool),
    /// An integer.
    Int(i64),
    /// A non-integer number.
    Float(f64),
    /// A string of at most 2048 characters.
    String(String),
}

impl From<bool> for RecordValue {
    fn from(v: bool) -> Self {
        Self::Bool(v)
    }
}

impl From<i64> for RecordValue {
    fn from(v: i64) -> Self {
        Self::Int(v)
    }
}

impl From<i32> for RecordValue {
    fn from(v: i32) -> Self {
        Self::Int(v.into())
    }
}

impl From<f64> for RecordValue {
    fn from(v: f64) -> Self {
        Self::Float(v)
    }
}

impl From<&str> for RecordValue {
    fn from(v: &str) -> Self {
        Self::String(v.to_owned())
    }
}

impl From<String> for RecordValue {
    fn from(v: String) -> Self {
        Self::String(v)
    }
}

/// A per-user record as Decane stores it: flat, with string, number and
/// boolean values under short keys (`[A-Za-z0-9_.-]{1,64}`). At most 100 keys
/// and 32 KB serialised; strings at most 2048 characters.
///
/// Two records exist per user, split by who may write them:
/// - `preferences`: the user's own choices. Written with the user's access
///   token or the project secret. What a settings screen stores.
/// - `metadata`: the app's facts about the user (plan, flags, ids in your own
///   systems). Written ONLY with the project secret; a user token can read it
///   and never change it, so an entitlement may live here.
pub type Record = BTreeMap<String, RecordValue>;

/// A merge: each key is set to its value, or removed when the value is
/// `None`. Keys not named are untouched.
pub type RecordPatch = BTreeMap<String, Option<RecordValue>>;

// ── Sign-in ──────────────────────────────────────────────────────────────────

/// Provider profile passed through at sign-in: Google returns name, email and
/// picture; KingsChat name and email. Decane never stores it; it exists only
/// in the sign-in response.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct AuthProfile {
    /// Display name.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Email address.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub email: Option<String>,
    /// Avatar URL.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub picture: Option<String>,
}

/// The result of a successful server-side sign-in.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthResult {
    /// The Decane access token (ES256 JWT, 8-hour expiry). Pass it to
    /// `verify_access_token`, `get_user`, `get_addresses`, or hand it to the
    /// end user's client. The backend calls this field `jwt`.
    #[serde(rename = "jwt")]
    pub access_token: String,
    /// Stable Decane user id (the same value `verify_access_token` returns as
    /// `user_id`).
    pub user_id: String,
    /// True when this sign-in was the user's first.
    #[serde(default)]
    pub is_new_user: bool,
    /// False when the user has no wallet yet. The client SDK creates one on
    /// this sign-in, unless your server already did (`create_user`).
    #[serde(default)]
    pub has_share: bool,
    /// Present for Google and KingsChat sign-ins; absent for email and custom
    /// auth.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub profile: Option<AuthProfile>,
}

/// The outcome of [`DecaneClient::link_external_login`](crate::DecaneClient::link_external_login).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LinkResult {
    /// The login was already on this account; nothing changed.
    #[serde(default)]
    pub already_linked: bool,
    /// The new link's id, when one was made.
    #[serde(default)]
    pub id: Option<String>,
}

/// A login attached to an account with
/// [`DecaneClient::link_external_login`](crate::DecaneClient::link_external_login).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LinkedLogin {
    /// The link's id, for [`DecaneClient::unlink_login`](crate::DecaneClient::unlink_login).
    pub id: String,
    /// The provider it came from.
    pub provider_id: Option<String>,
    /// The provider's name as set in the dashboard.
    pub provider_name: Option<String>,
    /// Masked, for display.
    pub identifier: Option<String>,
    /// When it was linked.
    pub linked_at: String,
}

#[derive(Deserialize)]
pub(crate) struct LinkedLogins {
    pub logins: Vec<LinkedLogin>,
}

/// The project's KingsChat OAuth client config, for building a consent URL.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct KingsChatConfig {
    /// The OAuth client id.
    pub client_id: String,
    /// The authorization endpoint.
    pub authorization_url: String,
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn user_identifier_is_tagged_on_type() {
        assert_eq!(
            serde_json::to_value(UserIdentifier::email("Ada@Example.com")).unwrap(),
            json!({"type": "email", "value": "Ada@Example.com"})
        );
        assert_eq!(
            serde_json::to_value(UserIdentifier::custom("auth0|1", "prov-1")).unwrap(),
            json!({"type": "custom", "value": "auth0|1", "providerId": "prov-1"})
        );
        assert_eq!(
            serde_json::to_value(UserIdentifier::kingschat("kc-9")).unwrap(),
            json!({"type": "kingschat", "value": "kc-9"})
        );
        assert_eq!(
            serde_json::to_value(UserIdentifier::x("123")).unwrap(),
            json!({"type": "x", "value": "123"})
        );
    }

    #[test]
    fn record_values_are_untagged_with_bool_before_int() {
        let record: Record =
            serde_json::from_value(json!({"shine_perps": false, "plan": "pro", "n": 1, "f": 1.5}))
                .unwrap();
        assert_eq!(record["shine_perps"], RecordValue::Bool(false));
        assert_eq!(record["plan"], RecordValue::String("pro".into()));
        assert_eq!(record["n"], RecordValue::Int(1));
        assert_eq!(record["f"], RecordValue::Float(1.5));

        let patch: RecordPatch = serde_json::from_value(json!({"old": null, "a": true})).unwrap();
        assert_eq!(patch["old"], None);
        assert_eq!(patch["a"], Some(RecordValue::Bool(true)));
        assert_eq!(
            serde_json::to_value(&patch).unwrap(),
            json!({"a": true, "old": null})
        );
    }

    #[test]
    fn auth_result_renames_jwt_to_access_token() {
        let r: AuthResult = serde_json::from_value(
            json!({"jwt": "t", "userId": "u", "isNewUser": true, "hasShare": false}),
        )
        .unwrap();
        assert_eq!(r.access_token, "t");
        assert_eq!(r.profile, None);
    }

    #[test]
    fn create_user_options_omit_unset_fields() {
        assert_eq!(
            serde_json::to_value(CreateUserOptions::default()).unwrap(),
            json!({})
        );
    }
}