Skip to main content

beyondigital_auth_sdk/
otp.rs

1//! OTP + SaaS checkout helpers — mirrors src/routes/otp.rs + src/routes/saas.rs
2use std::time::Duration;
3
4use serde::{Deserialize, Serialize};
5
6use crate::error::AuthError;
7
8fn issuer_base(issuer: &str) -> String {
9    issuer.trim_end_matches('/').to_string()
10}
11
12#[derive(Debug, Clone, Deserialize, Serialize)]
13pub struct OtpSendResponse {
14    pub status: String,
15    pub phone: Option<String>,
16    pub expires_in: Option<i64>,
17    pub resend_available_in: Option<i64>,
18    pub delivery_channel: Option<String>,
19}
20
21#[derive(Debug, Clone, Deserialize, Serialize)]
22pub struct LoginResponse {
23    pub access_token: String,
24    pub token_type: String,
25    pub expires_in: i64,
26    pub refresh_token: Option<String>,
27    pub scope: Option<String>,
28    pub session_id: Option<String>,
29    pub user: serde_json::Value,
30}
31
32#[derive(Debug, Clone, Deserialize, Serialize)]
33pub struct AuthenticatedUser {
34    pub id: String,
35    pub auth_user_id: String,
36    pub email: Option<String>,
37    pub phone: Option<String>,
38    pub full_name: Option<String>,
39    pub firm_id: Option<String>,
40    pub app: Option<String>,
41}
42
43#[derive(Debug, Clone, Deserialize, Serialize)]
44pub struct OtpIdentityResponse {
45    pub verified: bool,
46    pub user: AuthenticatedUser,
47}
48
49#[derive(Debug, Clone, Deserialize, Serialize)]
50#[serde(untagged)]
51pub enum OtpVerificationResponse {
52    Identity(OtpIdentityResponse),
53    Session(LoginResponse),
54}
55
56/// Nonce-bound OTP transport result. Wire fields remain flat via serde flatten.
57/// Presence is not verification: validate issuer/client/nonce/auth_time/amr/at_hash.
58/// Existing LoginResponse and OtpVerificationResponse literals remain unchanged.
59#[derive(Clone, Deserialize, Serialize)]
60pub struct OtpSessionReceipt {
61    #[serde(flatten)]
62    pub session: LoginResponse,
63    pub id_token: String,
64}
65
66/// Acknowledgement only; cancellation never returns credentials or session tokens.
67#[derive(Debug, Clone, Deserialize, Serialize)]
68pub struct OtpSessionCancellation {
69    pub status: String,
70}
71
72fn validate_otp_nonce(nonce: &str) -> Result<(), AuthError> {
73    use base64::Engine;
74    let codec = base64::engine::general_purpose::URL_SAFE_NO_PAD;
75    let valid = nonce.len() == 43
76        && codec
77            .decode(nonce)
78            .is_ok_and(|bytes| bytes.len() == 32 && codec.encode(bytes) == nonce);
79    if valid {
80        Ok(())
81    } else {
82        Err(AuthError::Config(
83            "nonce must be canonical unpadded base64url encoding of 32 bytes".into(),
84        ))
85    }
86}
87
88pub struct OtpClient {
89    issuer: String,
90    application: String,
91    channel: String,
92    http: reqwest::Client,
93}
94
95impl OtpClient {
96    pub fn new(issuer_url: impl Into<String>) -> Self {
97        Self {
98            issuer: issuer_base(&issuer_url.into()),
99            application: "shared_auth".into(),
100            channel: "sms".into(),
101            http: reqwest::Client::builder()
102                .timeout(Duration::from_secs(10))
103                .redirect(reqwest::redirect::Policy::none())
104                .build()
105                .unwrap_or_else(|_| reqwest::Client::new()),
106        }
107    }
108
109    /// Use the application's registered slug for both OTP send and verify.
110    pub fn with_application(mut self, application: impl Into<String>) -> Self {
111        self.application = application.into();
112        self
113    }
114
115    /// Login OTP delivery channel: sms, whatsapp, or email_otp.
116    pub fn with_channel(mut self, channel: impl Into<String>) -> Self {
117        self.channel = channel.into();
118        self
119    }
120
121    async fn post(
122        &self,
123        path: &str,
124        body: &serde_json::Value,
125        bearer: Option<&str>,
126    ) -> Result<serde_json::Value, AuthError> {
127        let mut req = self
128            .http
129            .post(format!("{}{}", self.issuer, path))
130            .json(body);
131        if let Some(t) = bearer {
132            req = req.bearer_auth(t);
133        }
134        let resp = req
135            .send()
136            .await
137            .map_err(|e| AuthError::Network(e.to_string()))?;
138        let status = resp.status().as_u16();
139        let val: serde_json::Value = resp.json().await.unwrap_or(serde_json::json!({}));
140        if status >= 400 {
141            let err = val
142                .get("error")
143                .and_then(|v| v.as_str())
144                .unwrap_or("unknown");
145            let desc = val
146                .get("error_description")
147                .and_then(|v| v.as_str())
148                .or_else(|| val.get("detail").and_then(|v| v.as_str()))
149                .unwrap_or(err);
150            return Err(AuthError::oauth(err, desc, status));
151        }
152        Ok(val)
153    }
154
155    pub async fn send_login_otp(
156        &self,
157        phone: &str,
158        client_id: &str,
159    ) -> Result<OtpSendResponse, AuthError> {
160        let v = self.post("/auth/otp/send", &serde_json::json!({"phone": phone, "app": self.application, "channel": self.channel, "client_id": client_id}), None).await?;
161        serde_json::from_value(v).map_err(|e| AuthError::Network(e.to_string()))
162    }
163    pub async fn verify_login_otp(
164        &self,
165        phone: &str,
166        otp: &str,
167        client_id: &str,
168    ) -> Result<LoginResponse, AuthError> {
169        let v = self.post("/auth/otp/verify", &serde_json::json!({"phone": phone, "otp": otp, "app": self.application, "channel": self.channel, "client_id": client_id}), None).await?;
170        serde_json::from_value(v).map_err(|e| AuthError::Network(e.to_string()))
171    }
172    pub async fn send_register_otp(
173        &self,
174        phone: &str,
175        full_name: &str,
176        client_id: &str,
177    ) -> Result<OtpSendResponse, AuthError> {
178        let v = self.post("/auth/register/otp", &serde_json::json!({"phone": phone, "full_name": full_name, "app": self.application, "client_id": client_id}), None).await?;
179        serde_json::from_value(v).map_err(|e| AuthError::Network(e.to_string()))
180    }
181    pub async fn verify_register_otp(
182        &self,
183        phone: &str,
184        otp: &str,
185        full_name: &str,
186        client_id: &str,
187    ) -> Result<LoginResponse, AuthError> {
188        let v = self.post("/auth/register/verify", &serde_json::json!({"phone": phone, "otp": otp, "full_name": full_name, "app": self.application, "client_id": client_id}), None).await?;
189        serde_json::from_value(v).map_err(|e| AuthError::Network(e.to_string()))
190    }
191    pub async fn password_login(
192        &self,
193        email: &str,
194        password: &str,
195    ) -> Result<LoginResponse, AuthError> {
196        let v = self.post("/auth/login", &serde_json::json!({"email": email, "password": password, "app": "admin", "client_id": "admin-panel"}), None).await?;
197        serde_json::from_value(v).map_err(|e| AuthError::Network(e.to_string()))
198    }
199}
200
201/// Explicit session binding. The API key separately pins the account/application.
202#[derive(Debug, Clone)]
203pub struct OtpSessionBinding {
204    pub client_id: String,
205    /// Console IdentityEnvironment Node ID or a raw UUID; validated by the service.
206    pub environment_id: String,
207}
208
209/// Server-only OTP client authenticated by an application-scoped API key.
210pub struct ServerOtpClient {
211    issuer: String,
212    http: reqwest::Client,
213    api_key: String,
214}
215
216impl ServerOtpClient {
217    pub fn new(issuer_url: impl Into<String>, api_key: impl Into<String>) -> Self {
218        Self {
219            issuer: issuer_base(&issuer_url.into()),
220            http: reqwest::Client::builder()
221                .timeout(Duration::from_secs(10))
222                .redirect(reqwest::redirect::Policy::none())
223                .build()
224                .unwrap_or_else(|_| reqwest::Client::new()),
225            api_key: api_key.into(),
226        }
227    }
228
229    async fn post<T: for<'de> Deserialize<'de>>(
230        &self,
231        path: &str,
232        body: &serde_json::Value,
233    ) -> Result<T, AuthError> {
234        let response = self
235            .http
236            .post(format!("{}{}", self.issuer, path))
237            .bearer_auth(&self.api_key)
238            .json(body)
239            .send()
240            .await
241            .map_err(|error| AuthError::Network(error.to_string()))?;
242        let status = response.status().as_u16();
243        let value: serde_json::Value = response.json().await.unwrap_or(serde_json::json!({}));
244        if !(200..300).contains(&status) {
245            let error = value
246                .get("error")
247                .and_then(|item| item.as_str())
248                .unwrap_or("unknown");
249            let description = value
250                .get("error_description")
251                .and_then(|item| item.as_str())
252                .or_else(|| value.get("detail").and_then(|item| item.as_str()))
253                .unwrap_or(error);
254            return Err(AuthError::oauth(error, description, status));
255        }
256        serde_json::from_value(value).map_err(|error| AuthError::Network(error.to_string()))
257    }
258
259    pub async fn send_otp(
260        &self,
261        recipient: &str,
262        app: &str,
263        channel: &str,
264    ) -> Result<OtpSendResponse, AuthError> {
265        self.post(
266            "/auth/otp/send",
267            &serde_json::json!({
268                "phone": recipient,
269                "app": app,
270                "channel": channel,
271                "mode": "verification_only"
272            }),
273        )
274        .await
275    }
276
277    pub async fn verify_otp(
278        &self,
279        recipient: &str,
280        otp: &str,
281        app: &str,
282        channel: &str,
283    ) -> Result<OtpVerificationResponse, AuthError> {
284        self.post::<OtpIdentityResponse>(
285            "/auth/otp/verify",
286            &serde_json::json!({
287                "phone": recipient,
288                "otp": otp,
289                "app": app,
290                "channel": channel,
291                "mode": "verification_only"
292            }),
293        )
294        .await
295        .map(OtpVerificationResponse::Identity)
296    }
297
298    /// Send a backend-mediated login OTP using an explicitly selected public client.
299    pub async fn send_session_otp(
300        &self,
301        recipient: &str,
302        app: &str,
303        channel: &str,
304        binding: &OtpSessionBinding,
305    ) -> Result<OtpSendResponse, AuthError> {
306        if binding.client_id.trim().is_empty() || binding.environment_id.trim().is_empty() {
307            return Err(AuthError::Config(
308                "session requires client_id and environment_id".into(),
309            ));
310        }
311        self.post(
312            "/auth/otp/send",
313            &serde_json::json!({
314                "phone": recipient, "app": app, "channel": channel,
315                "mode": "session", "client_id": binding.client_id,
316                "environment_id": binding.environment_id,
317            }),
318        )
319        .await
320    }
321
322    /// Opt in to a fresh OTP ID-token receipt. Store this exact nonce in the BFF attempt.
323    pub async fn send_session_otp_with_nonce(
324        &self,
325        recipient: &str,
326        app: &str,
327        channel: &str,
328        binding: &OtpSessionBinding,
329        nonce: &str,
330    ) -> Result<OtpSendResponse, AuthError> {
331        validate_otp_nonce(nonce)?;
332        if binding.client_id.trim().is_empty() || binding.environment_id.trim().is_empty() {
333            return Err(AuthError::Config(
334                "session requires client_id and environment_id".into(),
335            ));
336        }
337        self.post(
338            "/auth/otp/send",
339            &serde_json::json!({
340                "phone":recipient,"app":app,"channel":channel,"mode":"session",
341                "client_id":binding.client_id,"environment_id":binding.environment_id,"nonce":nonce,
342            }),
343        )
344        .await
345    }
346
347    /// Verify the same nonce/binding as send, using the actual returned delivery channel.
348    /// This checks transport shape only; verify the signed receipt before creating a BFF session.
349    pub async fn verify_session_otp_with_nonce(
350        &self,
351        recipient: &str,
352        otp: &str,
353        app: &str,
354        channel: &str,
355        binding: &OtpSessionBinding,
356        nonce: &str,
357    ) -> Result<OtpSessionReceipt, AuthError> {
358        validate_otp_nonce(nonce)?;
359        if binding.client_id.trim().is_empty() || binding.environment_id.trim().is_empty() {
360            return Err(AuthError::Config(
361                "session requires client_id and environment_id".into(),
362            ));
363        }
364        let result: OtpSessionReceipt = self.post("/auth/otp/verify", &serde_json::json!({
365            "phone":recipient,"otp":otp,"app":app,"channel":channel,"mode":"session",
366            "client_id":binding.client_id,"environment_id":binding.environment_id,"nonce":nonce,
367        })).await?;
368        if result.id_token.trim().is_empty() {
369            return Err(AuthError::Config(
370                "nonce-bound OTP response is missing id_token; no fresh login receipt is available"
371                    .into(),
372            ));
373        }
374        Ok(result)
375    }
376
377    /// Cancel one nonce-bound attempt using its original server API key (otp:verify).
378    /// Use a raw environment UUID. Persist/retry uncertain cancellations in the BFF;
379    /// this client never retries automatically and never recovers session tokens.
380    pub async fn cancel_session_otp(
381        &self,
382        app: &str,
383        binding: &OtpSessionBinding,
384        nonce: &str,
385    ) -> Result<OtpSessionCancellation, AuthError> {
386        validate_otp_nonce(nonce)?;
387        if app.trim().is_empty() || binding.client_id.trim().is_empty() {
388            return Err(AuthError::Config("app and client_id are required".into()));
389        }
390        if binding.environment_id.len() != 36
391            || uuid::Uuid::parse_str(&binding.environment_id).is_err()
392        {
393            return Err(AuthError::Config(
394                "environment_id must be a raw UUID".into(),
395            ));
396        }
397        let result: OtpSessionCancellation = self.post("/auth/otp/session/cancel", &serde_json::json!({
398            "app":app,"client_id":binding.client_id,"environment_id":binding.environment_id,"nonce":nonce,
399        })).await?;
400        if result.status != "cancelled" {
401            return Err(AuthError::Config(
402                "OTP cancellation was not acknowledged".into(),
403            ));
404        }
405        Ok(result)
406    }
407
408    /// Verify with the exact session binding used when sending the OTP.
409    pub async fn verify_session_otp(
410        &self,
411        recipient: &str,
412        otp: &str,
413        app: &str,
414        channel: &str,
415        binding: &OtpSessionBinding,
416    ) -> Result<LoginResponse, AuthError> {
417        if binding.client_id.trim().is_empty() || binding.environment_id.trim().is_empty() {
418            return Err(AuthError::Config(
419                "session requires client_id and environment_id".into(),
420            ));
421        }
422        self.post(
423            "/auth/otp/verify",
424            &serde_json::json!({
425                "phone": recipient, "otp": otp, "app": app, "channel": channel,
426                "mode": "session", "client_id": binding.client_id,
427                "environment_id": binding.environment_id,
428            }),
429        )
430        .await
431    }
432}
433
434// ── SaaS ─────────────────────────────────────────────────────────────────
435#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
436#[serde(rename_all = "snake_case")]
437pub enum ResourceStatus {
438    Pending,
439    Approved,
440    Suspended,
441    Rejected,
442    #[serde(other)]
443    Unknown,
444}
445
446/// Inert customer proposal; raw directory UUID or typed Node ID is passed unchanged.
447#[derive(Debug, Clone, Deserialize, Serialize)]
448#[serde(deny_unknown_fields)]
449pub struct ResourceProposal {
450    pub directory_id: String,
451    pub resource_uri: String,
452    pub proposed_scopes: Vec<String>,
453}
454
455#[derive(Debug, Clone, Deserialize, Serialize)]
456pub struct ResourceRegistration {
457    pub id: String,
458    pub account_id: String,
459    pub environment_id: String,
460    pub directory_id: String,
461    pub resource_uri: String,
462    pub proposed_scopes: Vec<String>,
463    pub approved_scopes: Vec<String>,
464    pub status: ResourceStatus,
465    pub public_clients: bool,
466    pub proposed_by_user_id: String,
467    pub reviewed_by_user_id: Option<String>,
468    pub reviewed_at: Option<String>,
469    pub created_at: String,
470    pub updated_at: String,
471}
472
473fn resources_path(account_id: &str, after: Option<&str>) -> String {
474    let mut url = reqwest::Url::parse("https://sdk.invalid/").expect("static URL");
475    url.path_segments_mut().expect("static base URL").extend([
476        "v1",
477        "console",
478        "accounts",
479        account_id,
480        "resources",
481    ]);
482    if let Some(after) = after {
483        url.query_pairs_mut().append_pair("after", after);
484    }
485    format!(
486        "{}{}",
487        url.path(),
488        url.query().map(|q| format!("?{q}")).unwrap_or_default()
489    )
490}
491
492pub struct SaasClient {
493    issuer: String,
494    http: reqwest::Client,
495}
496
497impl SaasClient {
498    pub fn new(issuer_url: impl Into<String>) -> Self {
499        Self {
500            issuer: issuer_base(&issuer_url.into()),
501            http: reqwest::Client::builder()
502                .timeout(Duration::from_secs(10))
503                .redirect(reqwest::redirect::Policy::none())
504                .build()
505                .expect("HTTP client with redirects disabled"),
506        }
507    }
508    async fn get(&self, path: &str, token: &str) -> Result<serde_json::Value, AuthError> {
509        let resp = self
510            .http
511            .get(format!("{}{}", self.issuer, path))
512            .bearer_auth(token)
513            .send()
514            .await
515            .map_err(|e| AuthError::Network(e.to_string()))?;
516        let status = resp.status().as_u16();
517        let v: serde_json::Value = resp.json().await.unwrap_or(serde_json::json!({}));
518        if !(200..300).contains(&status) {
519            let err = v.get("error").and_then(|x| x.as_str()).unwrap_or("unknown");
520            return Err(AuthError::oauth(
521                err,
522                v.get("detail").and_then(|x| x.as_str()).unwrap_or(err),
523                status,
524            ));
525        }
526        Ok(v)
527    }
528    async fn post(
529        &self,
530        path: &str,
531        token: &str,
532        body: &serde_json::Value,
533        extra: &[(&str, &str)],
534    ) -> Result<serde_json::Value, AuthError> {
535        let mut req = self
536            .http
537            .post(format!("{}{}", self.issuer, path))
538            .bearer_auth(token)
539            .json(body);
540        for (k, v) in extra {
541            req = req.header(*k, *v);
542        }
543        let resp = req
544            .send()
545            .await
546            .map_err(|e| AuthError::Network(e.to_string()))?;
547        let status = resp.status().as_u16();
548        let v: serde_json::Value = resp.json().await.unwrap_or(serde_json::json!({}));
549        if !(200..300).contains(&status) {
550            let err = v.get("error").and_then(|x| x.as_str()).unwrap_or("unknown");
551            return Err(AuthError::oauth(
552                err,
553                v.get("detail").and_then(|x| x.as_str()).unwrap_or(err),
554                status,
555            ));
556        }
557        Ok(v)
558    }
559
560    pub async fn list_accounts(&self, token: &str) -> Result<serde_json::Value, AuthError> {
561        self.get("/v1/console/accounts", token).await
562    }
563    /// One page of at most 100 rows. Continue with the last raw registration UUID.
564    pub async fn list_resources(
565        &self,
566        token: &str,
567        account_id: &str,
568        after: Option<&str>,
569    ) -> Result<Vec<ResourceRegistration>, AuthError> {
570        let value = self.get(&resources_path(account_id, after), token).await?;
571        serde_json::from_value(value).map_err(|error| AuthError::Network(error.to_string()))
572    }
573
574    /// Customer proposal only; approval is reserved for the operator control plane.
575    pub async fn propose_resource(
576        &self,
577        token: &str,
578        account_id: &str,
579        proposal: &ResourceProposal,
580    ) -> Result<ResourceRegistration, AuthError> {
581        let input =
582            serde_json::to_value(proposal).map_err(|error| AuthError::Config(error.to_string()))?;
583        let value = self
584            .post(&resources_path(account_id, None), token, &input, &[])
585            .await?;
586        serde_json::from_value(value).map_err(|error| AuthError::Network(error.to_string()))
587    }
588    pub async fn create_account(
589        &self,
590        token: &str,
591        name: &str,
592        slug: &str,
593    ) -> Result<serde_json::Value, AuthError> {
594        self.post(
595            "/v1/console/accounts",
596            token,
597            &serde_json::json!({"name": name, "slug": slug}),
598            &[],
599        )
600        .await
601    }
602    pub async fn list_applications(
603        &self,
604        token: &str,
605        account_id: &str,
606    ) -> Result<serde_json::Value, AuthError> {
607        self.get(
608            &format!("/v1/console/accounts/{account_id}/applications"),
609            token,
610        )
611        .await
612    }
613    pub async fn get_wallet(
614        &self,
615        token: &str,
616        account_id: &str,
617    ) -> Result<serde_json::Value, AuthError> {
618        self.get(&format!("/v1/console/accounts/{account_id}/wallet"), token)
619            .await
620    }
621    pub async fn create_checkout(
622        &self,
623        token: &str,
624        account_id: &str,
625        price_id: &str,
626        idempotency_key: &str,
627    ) -> Result<serde_json::Value, AuthError> {
628        self.post(
629            &format!("/v1/console/accounts/{account_id}/checkout"),
630            token,
631            &serde_json::json!({"token_pack_price_id": price_id}),
632            &[("Idempotency-Key", idempotency_key)],
633        )
634        .await
635    }
636    /// Supply a fresh, human-verified action-bound receipt for a customer policy.
637    /// The caller obtains it through the issuer continuation; this does not approve payment.
638    pub async fn create_checkout_with_proof(
639        &self,
640        token: &str,
641        account_id: &str,
642        price_id: &str,
643        idempotency_key: &str,
644        proof_id: &str,
645    ) -> Result<serde_json::Value, AuthError> {
646        self.post(
647            &format!("/v1/console/accounts/{account_id}/checkout"),
648            token,
649            &serde_json::json!({"token_pack_price_id":price_id}),
650            &[
651                ("Idempotency-Key", idempotency_key),
652                ("X-Auth-Proof", proof_id),
653            ],
654        )
655        .await
656    }
657    pub async fn reconcile(
658        &self,
659        token: &str,
660        account_id: &str,
661        purchase_id: &str,
662    ) -> Result<serde_json::Value, AuthError> {
663        self.post(
664            &format!("/v1/console/accounts/{account_id}/purchases/{purchase_id}/reconcile"),
665            token,
666            &serde_json::json!({}),
667            &[],
668        )
669        .await
670    }
671}
672
673#[cfg(test)]
674mod tests {
675    use super::OtpVerificationResponse;
676
677    #[test]
678    fn verification_only_response_deserializes_without_tokens() {
679        let response: OtpVerificationResponse = serde_json::from_value(serde_json::json!({
680            "verified": true,
681            "user": {
682                "id": "user-1",
683                "auth_user_id": "user-1",
684                "email": "person@example.com",
685                "phone": null,
686                "full_name": null,
687                "firm_id": null,
688                "app": "my-app"
689            }
690        }))
691        .expect("verification response");
692        let OtpVerificationResponse::Identity(response) = response else {
693            panic!("expected identity-only response");
694        };
695        assert!(response.verified);
696        assert_eq!(response.user.id, "user-1");
697    }
698
699    #[test]
700    fn token_response_deserializes_for_client_bound_application() {
701        let response: OtpVerificationResponse = serde_json::from_value(serde_json::json!({
702            "access_token": "access",
703            "refresh_token": "refresh",
704            "token_type": "Bearer",
705            "expires_in": 900,
706            "user": {"id": "user-1", "auth_user_id": "user-1"}
707        }))
708        .expect("token response");
709        let OtpVerificationResponse::Session(response) = response else {
710            panic!("expected token session response");
711        };
712        assert_eq!(response.access_token, "access");
713    }
714}