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
//! A blocking, no-UI driver: run a check on the calling thread and fold it into a
//! status, persisting on success. For CLIs, integration tests, and the example.

use crate::core::config::LicenseConfig;
use crate::core::engine::{resolve, run_check};
use crate::core::state::{now_secs, LicenseState};
use crate::core::status::LicenseStatus;
use crate::provider::LicenseProvider;

/// Validate `state`'s key against `provider`, fold the result into a [`LicenseStatus`]
/// (honoring offline grace, failing closed on denial), and persist `last_validated` on
/// success. An empty key short-circuits to [`LicenseStatus::Locked`] with no network call.
pub fn check_blocking(
    config: &LicenseConfig,
    provider: &dyn LicenseProvider,
    state: &mut LicenseState,
    mut progress: impl FnMut(String),
) -> LicenseStatus {
    if state.key.trim().is_empty() {
        return LicenseStatus::Locked;
    }
    let result = run_check(provider, state, &mut progress);
    let res = resolve(result, state, now_secs(), config.grace_secs);
    if let Some(msg) = res.message {
        progress(msg);
    }
    if res.status == LicenseStatus::Active {
        state.save(&config.storage);
    }
    res.status
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::config::StorageConfig;
    use crate::core::error::CheckErr;

    struct Mock(Result<bool, CheckErr>);
    impl LicenseProvider for Mock {
        fn check(
            &self,
            _key: &str,
            _fp: &str,
            progress: &mut dyn FnMut(String),
        ) -> Result<bool, CheckErr> {
            progress("mock check".into());
            self.0.clone()
        }
    }

    fn config(tag: &str) -> LicenseConfig {
        let mut p = std::env::temp_dir();
        p.push(format!("rustify-headless-{tag}-{}.env", std::process::id()));
        let _ = std::fs::remove_file(&p);
        LicenseConfig {
            account_id: "acct".into(),
            api_base: "https://example/v1".into(),
            grace_secs: 100,
            storage: StorageConfig {
                path: p,
                dev_shadow: None,
                env_key_var: None,
            },
            buy_url: "https://example/#pricing".into(),
        }
    }

    fn keyed() -> LicenseState {
        LicenseState {
            key: "K".into(),
            fingerprint: "fp".into(),
            last_validated: None,
        }
    }

    #[test]
    fn empty_key_locks_without_calling_provider() {
        let cfg = config("empty");
        // A mock that would panic if called proves we short-circuit.
        struct Boom;
        impl LicenseProvider for Boom {
            fn check(&self, _: &str, _: &str, _: &mut dyn FnMut(String)) -> Result<bool, CheckErr> {
                panic!("provider must not be called for an empty key");
            }
        }
        let mut st = LicenseState::default();
        assert_eq!(
            check_blocking(&cfg, &Boom, &mut st, |_| {}),
            LicenseStatus::Locked
        );
    }

    #[test]
    fn valid_key_activates_and_persists() {
        let cfg = config("ok");
        let mut st = keyed();
        let status = check_blocking(&cfg, &Mock(Ok(true)), &mut st, |_| {});
        assert_eq!(status, LicenseStatus::Active);
        assert!(st.last_validated.is_some());
        // Persisted to disk.
        let reloaded = LicenseState::load(&cfg.storage);
        assert!(reloaded.last_validated.is_some());
        let _ = std::fs::remove_file(cfg.storage.resolve());
    }

    #[test]
    fn denied_locks() {
        let cfg = config("denied");
        let mut st = keyed();
        let status = check_blocking(&cfg, &Mock(Err(CheckErr::Denied("403".into()))), &mut st, |_| {});
        assert_eq!(status, LicenseStatus::Locked);
        let _ = std::fs::remove_file(cfg.storage.resolve());
    }
}