kovlet 0.1.0

Kovlet's portable sync client core: sign-in, sync, merge, outbox and files for Rust, Tauri, Swift and Kotlin apps
Documentation
//! End-user sign-in for native apps (ADR 0021 §2, `docs/guides/end-users.md`):
//! people who use a public app without a Kovlet account. Each Data Space has
//! its own directory of end users. An app the space's owner turned end-user
//! sign-in on for signs them in with an email code, OAuth with the owner's
//! provider client, an ID token from an issuer the owner configured, a
//! sign-in code the app's server minted, or as a guest.
//!
//! ```no_run
//! # async fn demo(kovlet: kovlet::Client) -> kovlet::Result<()> {
//! let eu = kovlet.end_users("0192f3a4-5b6c-7d8e-9f01-23456789abcd", "app_todos");
//! eu.send_magic_code("ada@example.com").await?;
//! let signed = eu.sign_in_with_magic_code("ada@example.com", "123456").await?;
//! println!("signed in as {}", signed.user.id);
//! # Ok(()) }
//! ```
//!
//! The session is bound to the client's device key, refreshes by itself, and
//! is valid for that one space. While an end user is signed in, the client
//! syncs over protocol 2 only, with query subscriptions
//! ([`crate::Space::subscribe`]): the space's rules decide which rows arrive
//! and which writes are accepted. `Client::sign_out` ends the session and
//! forgets every open space's synced rows and queued writes, so the next
//! person on the device starts clean.

use std::future::Future;

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

use crate::api::seg;
use crate::auth::{EndUser, EndUserOAuthRequest, EndUserSignIn};
use crate::client::Client;
use crate::error::{Error, Result};

/// A sign-in method the owner configured (`kind`: `email`, `oauth` or `id_token`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EndUserProvider {
    pub name: String,
    pub kind: String,
}

/// `GET /v1/eu/{space}/config`: whether sign-in is on for this app, and how.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct EndUserConfig {
    #[serde(default)]
    pub enabled: bool,
    #[serde(default)]
    pub providers: Vec<EndUserProvider>,
}

/// End-user sign-in for one Data Space and app ([`Client::end_users`]).
#[derive(Clone)]
pub struct EndUsers {
    pub(crate) client: Client,
    pub space_id: String,
    pub app_id: String,
}

impl EndUsers {
    fn path(&self, rest: &str) -> String {
        format!("/v1/eu/{}/{rest}", seg(&self.space_id))
    }

    /// Redeems a grant (`token`) or signs in as a guest (`guest`), then
    /// makes every open space follow the new identity.
    async fn grant(&self, path: &'static str, fields: Map<String, Value>) -> Result<EndUserSignIn> {
        let (auth, space, app) = (self.client.ctx().auth.clone(), self.space_id.clone(), self.app_id.clone());
        let fut =
            Box::pin(async move { Ok(serde_json::to_value(auth.end_user_grant(&space, &app, path, fields).await?)?) });
        let before = self.client.identity();
        self.signed_in(before, self.client.run_json(fut, true).await?).await
    }

    async fn signed_in(&self, before: Option<String>, v: Value) -> Result<EndUserSignIn> {
        let r: EndUserSignIn = serde_json::from_value(v)?;
        self.client.identity_changed(before.as_deref(), Some(&format!("eu:{}", r.user.id))).await;
        Ok(r)
    }

    /// An unauthenticated call to the end-user API.
    async fn eu(&self, method: &'static str, path: String, body: Option<Value>) -> Result<Value> {
        let auth = self.client.ctx().auth.clone();
        let fut = Box::pin(async move { auth.eu_json(method, &path, body.as_ref(), vec![]).await });
        self.client.run_json(fut, false).await
    }

    /// Whether sign-in is on for this app, and the methods the owner configured.
    pub async fn config(&self) -> Result<EndUserConfig> {
        let query = form_urlencoded::Serializer::new(String::new()).append_pair("app_id", &self.app_id).finish();
        let v = self.eu("GET", self.path(&format!("config?{query}")), None).await?;
        Ok(serde_json::from_value(v).unwrap_or_default())
    }

    /// Emails a 6-digit sign-in code. Returns how long it is valid, in seconds.
    pub async fn send_magic_code(&self, email: &str) -> Result<u64> {
        let body = json!({ "app_id": self.app_id, "email": email });
        let v = self.eu("POST", self.path("codes"), Some(body)).await?;
        Ok(v.get("expires_in").and_then(Value::as_u64).unwrap_or(600))
    }

    /// Redeems the emailed code. A guest session is upgraded in place.
    pub async fn sign_in_with_magic_code(&self, email: &str, code: &str) -> Result<EndUserSignIn> {
        let f = json!({ "grant_type": "magic_code", "email": email, "code": code });
        self.grant("token", f.as_object().cloned().unwrap_or_default()).await
    }

    /// Signs in as a new guest end user; any later sign-in upgrades the guest.
    pub async fn sign_in_as_guest(&self) -> Result<EndUserSignIn> {
        self.grant("guest", Map::new()).await
    }

    /// Signs in with an ID token from an issuer the owner configured (Clerk,
    /// Firebase, Auth0, any OIDC issuer). `provider` is its name in the console.
    pub async fn sign_in_with_id_token(&self, provider: &str, id_token: &str) -> Result<EndUserSignIn> {
        let f = json!({ "grant_type": "id_token", "provider": provider, "id_token": id_token });
        self.grant("token", f.as_object().cloned().unwrap_or_default()).await
    }

    /// Redeems a one-time sign-in code the app's server minted
    /// (`POST /v1/spaces/{space}/end-users/{id}/sign-in-codes`).
    pub async fn sign_in_with_sign_in_code(&self, code: &str) -> Result<EndUserSignIn> {
        let f = json!({ "grant_type": "sign_in_code", "code": code });
        self.grant("token", f.as_object().cloned().unwrap_or_default()).await
    }

    /// Starts OAuth (`google`, `apple`, `github`, `linkedin`) for apps that
    /// drive the browser themselves: open `url` (ASWebAuthenticationSession,
    /// Custom Tabs, the system browser), then pass the redirect it reaches to
    /// [`EndUsers::oauth_finish`]. `redirect_uri` must be registered for the app.
    pub fn oauth_begin(&self, provider: &str, redirect_uri: &str) -> Result<EndUserOAuthRequest> {
        self.client.ctx().auth.end_user_oauth_begin(&self.space_id, &self.app_id, provider, redirect_uri)
    }

    /// Finishes OAuth from the redirect URL (`…?code=&state=`, or `error=`).
    pub async fn oauth_finish(&self, callback_url: &str, request: &EndUserOAuthRequest) -> Result<EndUserSignIn> {
        let (auth, space, app) = (self.client.ctx().auth.clone(), self.space_id.clone(), self.app_id.clone());
        let (cb, req) = (callback_url.to_string(), request.clone());
        let fut =
            Box::pin(
                async move { Ok(serde_json::to_value(auth.end_user_oauth_finish(&space, &app, &cb, &req).await?)?) },
            );
        let before = self.client.identity();
        self.signed_in(before, self.client.run_json(fut, true).await?).await
    }

    /// OAuth in one call: `authorize` opens the provider URL and resolves
    /// with the redirect URL it reached.
    pub async fn sign_in_with_oauth<F, Fut>(
        &self,
        provider: &str,
        redirect_uri: &str,
        authorize: F,
    ) -> Result<EndUserSignIn>
    where
        F: FnOnce(String) -> Fut,
        Fut: Future<Output = Result<String>>,
    {
        let req = self.oauth_begin(provider, redirect_uri)?;
        let callback = authorize(req.url.clone()).await?;
        self.oauth_finish(&callback, &req).await
    }

    /// The signed-in end user of this space, if any (stored; no network).
    pub fn user(&self) -> Option<EndUser> {
        let s = self.client.session()?;
        let eu = s.end_user?;
        (eu.space_id == self.space_id).then_some(eu.user)
    }

    /// Re-reads the signed-in end user from the server (`GET /me`).
    pub async fn me(&self) -> Result<EndUser> {
        if self.user().is_none() {
            return Err(Error::new("unauthenticated", "no end user of this space is signed in")
                .with_hint("Sign in first: sign_in_as_guest(), sign_in_with_magic_code(), sign_in_with_oauth() or sign_in_with_id_token()."));
        }
        let (api, path) = (self.client.ctx().api.waiting(false), self.path("me"));
        let v = self.client.run_json(Box::pin(async move { api.json("GET", &path, None).await }), false).await?;
        let user: EndUser = serde_json::from_value(v.get("user").cloned().unwrap_or(Value::Null))?;
        self.client.ctx().auth.set_end_user(user.clone())?;
        Ok(user)
    }

    /// Signs the end user out: the same as [`Client::sign_out`].
    pub async fn sign_out(&self) -> Result<()> {
        self.client.sign_out().await
    }
}

impl std::fmt::Debug for EndUsers {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("EndUsers").field("space_id", &self.space_id).field("app_id", &self.app_id).finish()
    }
}