sylphx 0.3.6

The Sylphx SDK: one API, one key, every Sylphx service. Generated from the Sylphx schema registry.
Documentation
// @generated by sylphx-gen. Do not edit.
//! Identifier-first Auth client API. These public-key calls do not use the
//! Resource API transport or retry mutations. A flow is single-use and bound
//! to the original browser User-Agent; pass that same value on both calls.
use serde::{Deserialize, Serialize};

/// Who receives the session. Server mode returns a one-time ticket for the BFF.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum SessionMode {
    #[default]
    Server,
    Browser,
}

#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ContinueMethod {
    EmailOtp,
}

/// POST /v1/client/continue. Optional values are omitted, never sent as null.
#[derive(Debug, Clone, Default, Serialize)]
pub struct ContinueRequest {
    pub email: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub method: Option<ContinueMethod>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub captcha_token: Option<String>,
    pub session_mode: SessionMode,
}

#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(tag = "step", rename_all = "snake_case")]
pub enum ContinueResponse {
    Password,
    EmailOtp { flow: String, expires_in: u64 },
}

#[derive(Debug, Clone, Serialize)]
pub struct FactorProof {
    pub factor_type: String,
    pub factor_id: String,
    pub response: String,
}

/// The session mode is bound at Continue, not supplied again at verification.
#[derive(Debug, Clone, Default, Serialize)]
pub struct ContinueVerifyRequest {
    pub flow: String,
    pub code: String,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub factor_proofs: Vec<FactorProof>,
}

#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct AuthUser {
    pub id: String,
    pub email: String,
    pub name: String,
    pub email_verified: bool,
}

#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct AuthSession {
    pub id: String,
    pub token: String,
    pub expires_at: i64,
}

#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(untagged)]
pub enum ContinueVerifyResponse {
    Ticket {
        ticket: String,
        expires_in: u64,
    },
    Session {
        user: AuthUser,
        session: AuthSession,
    },
}

/// The client API has its own error envelope, not Resource API problem details.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AuthApiError {
    pub status: u16,
    pub code: String,
    pub message: String,
    pub retry_after_seconds: Option<u64>,
}

#[derive(Debug)]
#[non_exhaustive]
pub enum AuthClientError {
    MfaRequired(AuthApiError),
    RateLimited(AuthApiError),
    Api(AuthApiError),
    Transport(reqwest::Error),
    Decode(serde_json::Error),
    InvalidArgument(&'static str),
}

impl std::fmt::Display for AuthClientError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::MfaRequired(e) | Self::RateLimited(e) | Self::Api(e) => {
                write!(f, "{} {}: {}", e.status, e.code, e.message)
            }
            Self::Transport(e) => write!(f, "transport: {e}"),
            Self::Decode(e) => write!(f, "decode: {e}"),
            Self::InvalidArgument(e) => write!(f, "invalid argument: {e}"),
        }
    }
}
impl std::error::Error for AuthClientError {}

/// Publishable-key sign-in client. Never pass a secret key. `user_agent` is
/// the original browser's header, not the backend's HTTP library identifier.
#[derive(Clone)]
pub struct AuthClient {
    http: reqwest::Client,
    base_url: reqwest::Url,
    publishable_key: String,
    user_agent: reqwest::header::HeaderValue,
}

impl AuthClient {
    pub fn new(
        publishable_key: impl Into<String>,
        user_agent: &str,
    ) -> Result<Self, AuthClientError> {
        Self::with_base_url(publishable_key, user_agent, "https://api.sylphx.com")
    }

    pub fn with_base_url(
        publishable_key: impl Into<String>,
        user_agent: &str,
        base_url: &str,
    ) -> Result<Self, AuthClientError> {
        let publishable_key = publishable_key.into();
        if !publishable_key.starts_with("sylphx_pk_") {
            return Err(AuthClientError::InvalidArgument(
                "expected a publishable key (sylphx_pk_...)",
            ));
        }
        if user_agent.trim().is_empty() {
            return Err(AuthClientError::InvalidArgument(
                "original User-Agent is required",
            ));
        }
        let user_agent = reqwest::header::HeaderValue::from_str(user_agent)
            .map_err(|_| AuthClientError::InvalidArgument("invalid User-Agent"))?;
        let base_url = reqwest::Url::parse(base_url)
            .map_err(|_| AuthClientError::InvalidArgument("invalid base URL"))?;
        if !matches!(base_url.scheme(), "http" | "https") {
            return Err(AuthClientError::InvalidArgument(
                "expected HTTP(S) base URL",
            ));
        }
        let http = reqwest::Client::builder()
            .connect_timeout(std::time::Duration::from_secs(5))
            .timeout(std::time::Duration::from_secs(120))
            .redirect(reqwest::redirect::Policy::none())
            .build()
            .map_err(AuthClientError::Transport)?;
        Ok(Self {
            http,
            base_url,
            publishable_key,
            user_agent,
        })
    }

    /// Identifier-first sign-in; defaults to server mode in ContinueRequest.
    pub async fn r#continue(
        &self,
        input: ContinueRequest,
    ) -> Result<ContinueResponse, AuthClientError> {
        self.post("/v1/client/continue", input).await
    }

    /// Complete a flow. `MfaRequired` leaves it usable for retry with proofs.
    pub async fn continue_verify(
        &self,
        input: ContinueVerifyRequest,
    ) -> Result<ContinueVerifyResponse, AuthClientError> {
        self.post("/v1/client/continue/verify", input).await
    }

    async fn post<I: Serialize, O: serde::de::DeserializeOwned>(
        &self,
        path: &str,
        input: I,
    ) -> Result<O, AuthClientError> {
        let mut url = self.base_url.clone();
        url.set_path(path);
        url.set_query(None);
        url.set_fragment(None);
        url.query_pairs_mut()
            .append_pair("publishable_key", &self.publishable_key);
        let response = self
            .http
            .post(url)
            .header(reqwest::header::USER_AGENT, self.user_agent.clone())
            .json(&input)
            .send()
            .await
            .map_err(AuthClientError::Transport)?;
        let status = response.status().as_u16();
        let retry_header = response
            .headers()
            .get(reqwest::header::RETRY_AFTER)
            .and_then(|v| v.to_str().ok())
            .and_then(|v| v.trim().parse::<u64>().ok());
        let bytes = response.bytes().await.map_err(AuthClientError::Transport)?;
        if !(200..300).contains(&status) {
            let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap_or_default();
            let code = body["code"]
                .as_str()
                .map(str::to_owned)
                .unwrap_or_else(|| format!("http_{status}"));
            let retry_after_seconds = retry_header.or_else(|| body["retry_after"].as_u64());
            let error = AuthApiError {
                status,
                code: code.clone(),
                retry_after_seconds,
                message: body["error"]
                    .as_str()
                    .unwrap_or("Auth request failed")
                    .to_owned(),
            };
            return Err(match (status, code.as_str()) {
                (401, "mfa_required") => AuthClientError::MfaRequired(error),
                (429, "rate_limited") => AuthClientError::RateLimited(error),
                _ => AuthClientError::Api(error),
            });
        }
        serde_json::from_slice(&bytes).map_err(AuthClientError::Decode)
    }
}