rustify-licensing 0.1.0

Framework-agnostic in-app licensing (validate / machine-activate / offline-grace) for native Rust apps. Keygen provider + Bevy / egui / headless adapters.
Documentation
//! Keygen provider — the exact Keygen API contract, ported verbatim (every detail
//! here cost real debugging):
//!
//! - **validate** (no auth): `POST {api}/accounts/{acct}/licenses/actions/validate-key`
//!   with `{"meta":{"key","scope":{"fingerprint"}}}` → HTTP 200 with `meta.valid` +
//!   `meta.code`. A revoked/unknown key still returns 200 with `valid:false`.
//! - **activate** (node-lock): `POST {api}/accounts/{acct}/machines` with
//!   `Authorization: License <KEY>` — the **`License` scheme, NOT `Bearer`** (Bearer →
//!   `TOKEN_INVALID`). The policy must allow license authentication.
//! - **error mapping is the safety property:** `408 | 429 | 5xx`, network errors, and
//!   ambiguous non-JSON 2xx bodies → [`CheckErr::Offline`] (grace may apply); every other
//!   4xx → [`CheckErr::Denied`] (fail closed).

use serde_json::{json, Value};

use crate::core::config::LicenseConfig;
use crate::core::error::CheckErr;

use super::LicenseProvider;

/// Keygen-backed [`LicenseProvider`]. The account id is a public UUID; no secrets here
/// (clients ship no admin token — license-key auth only).
pub struct KeygenProvider {
    account_id: String,
    api_base: String,
}

impl KeygenProvider {
    pub fn new(account_id: impl Into<String>, api_base: impl Into<String>) -> Self {
        Self {
            account_id: account_id.into(),
            api_base: api_base.into(),
        }
    }

    /// Build from the shared [`LicenseConfig`].
    pub fn from_config(config: &LicenseConfig) -> Self {
        Self::new(config.account_id.clone(), config.api_base.clone())
    }

    /// `POST {api}/accounts/{acct}/{path}`. `auth` (the license key) adds the `License`
    /// scheme header. Maps transport/status into [`CheckErr`] per the safety rules above.
    fn post(&self, path: &str, auth: Option<&str>, body: &Value) -> Result<Value, CheckErr> {
        let url = format!("{}/accounts/{}/{}", self.api_base, self.account_id, path);
        let mut req = ureq::post(&url)
            .set("Content-Type", "application/vnd.api+json")
            .set("Accept", "application/vnd.api+json");
        // Keygen license-key authentication uses the `License` scheme (not `Bearer`,
        // which is for tokens). Requires the policy to allow license authentication.
        if let Some(key) = auth {
            req = req.set("Authorization", &format!("License {key}"));
        }
        let payload = serde_json::to_string(body).map_err(|e| CheckErr::Denied(e.to_string()))?;
        match req.send_string(&payload) {
            // validate-key always returns 200 (with meta.valid); machines returns 201.
            Ok(resp) => resp
                .into_json::<Value>()
                // A 2xx with a non-JSON body is ambiguous (proxy/captive portal) → grace.
                .map_err(|e| CheckErr::Offline(format!("decode: {e}"))),
            Err(ureq::Error::Status(code, resp)) => {
                let detail: String = resp
                    .into_string()
                    .unwrap_or_default()
                    .chars()
                    .take(200)
                    .collect();
                let msg = format!("HTTP {code}: {detail}");
                // 408/429/5xx are transient/server-side → grace; other 4xx are an
                // authoritative "no" (bad account/key/policy) → fail closed.
                if code == 408 || code == 429 || code >= 500 {
                    Err(CheckErr::Offline(msg))
                } else {
                    Err(CheckErr::Denied(msg))
                }
            }
            Err(e) => Err(CheckErr::Offline(format!("network: {e}"))),
        }
    }

    fn validate(&self, key: &str, fingerprint: &str) -> Result<Validation, CheckErr> {
        let body = json!({ "meta": { "key": key, "scope": { "fingerprint": fingerprint } } });
        let v = self.post("licenses/actions/validate-key", None, &body)?;
        Ok(Validation {
            valid: v["meta"]["valid"].as_bool().unwrap_or(false),
            code: v["meta"]["code"].as_str().unwrap_or("UNKNOWN").to_string(),
            license_id: v["data"]["id"].as_str().map(str::to_string),
        })
    }

    fn activate_machine(&self, key: &str, fingerprint: &str, license_id: &str) -> Result<(), CheckErr> {
        let body = json!({
            "data": {
                "type": "machines",
                "attributes": { "fingerprint": fingerprint },
                "relationships": { "license": { "data": { "type": "licenses", "id": license_id } } }
            }
        });
        self.post("machines", Some(key), &body).map(|_| ())
    }
}

struct Validation {
    valid: bool,
    code: String,
    license_id: Option<String>,
}

impl LicenseProvider for KeygenProvider {
    /// Validate, activating this machine first if a node-locked policy needs it, then
    /// re-validate. Returns `Ok(valid)` for a definitive verdict.
    fn check(
        &self,
        key: &str,
        fingerprint: &str,
        progress: &mut dyn FnMut(String),
    ) -> Result<bool, CheckErr> {
        progress("validating license…".into());
        let r = self.validate(key, fingerprint)?;
        if r.valid {
            return Ok(true);
        }
        // Node-locked policy with no machine yet → register this device, then re-validate.
        if matches!(
            r.code.as_str(),
            "NO_MACHINE" | "NO_MACHINES" | "FINGERPRINT_SCOPE_MISMATCH"
        ) {
            if let Some(id) = r.license_id {
                progress("activating this device…".into());
                let _ = self.activate_machine(key, fingerprint, &id); // ignore "already taken"
                return Ok(self.validate(key, fingerprint)?.valid);
            }
        }
        progress(format!("license not valid ({})", r.code));
        Ok(false)
    }
}