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
//! The pure heart of the gate: run a check against a provider, then **fold the result
//! into a status** honoring offline grace — and failing closed on an authoritative
//! denial. Extracted into a single pure, testable function.

use crate::core::error::CheckErr;
use crate::core::state::LicenseState;
use crate::core::status::LicenseStatus;
use crate::provider::LicenseProvider;

/// Run a full validation against the provider. The validate → activate → re-validate
/// dance is the provider's concern; `progress` receives human-readable step messages.
/// Returns a definitive verdict (`Ok(valid)`) or a [`CheckErr`] distinguishing an
/// authoritative denial from a transient connectivity failure.
pub fn run_check(
    provider: &dyn LicenseProvider,
    state: &LicenseState,
    progress: &mut dyn FnMut(String),
) -> Result<bool, CheckErr> {
    provider.check(state.key.trim(), &state.fingerprint, progress)
}

/// The verdict of a finished check, ready for the UI/log.
pub struct Resolution {
    pub status: LicenseStatus,
    /// A line to surface to the user/log, if any.
    pub message: Option<String>,
}

/// Fold a check result into a [`LicenseStatus`], stamping `last_validated` on success and
/// honoring the offline grace window. **Fail closed:** [`CheckErr::Denied`] never rides
/// grace. (Pure — the caller decides when to persist `state`.)
pub fn resolve(
    result: Result<bool, CheckErr>,
    state: &mut LicenseState,
    now: u64,
    grace_secs: u64,
) -> Resolution {
    match result {
        Ok(true) => {
            state.last_validated = Some(now);
            Resolution {
                status: LicenseStatus::Active,
                message: Some("license active".into()),
            }
        }
        // Valid=false but no error (e.g. revoked key returns HTTP 200 valid:false) → lock.
        Ok(false) => Resolution {
            status: LicenseStatus::Locked,
            message: None,
        },
        // Authoritative denial (bad account/key/policy, revoked) → fail closed, no grace.
        Err(CheckErr::Denied(e)) => Resolution {
            status: LicenseStatus::Locked,
            message: Some(format!("license invalid — {e}")),
        },
        // Transient connectivity failure → honor the offline grace window.
        Err(CheckErr::Offline(e)) => {
            if state.within_grace(now, grace_secs) {
                Resolution {
                    status: LicenseStatus::Grace,
                    message: Some("offline — using cached license (grace period)".into()),
                }
            } else {
                Resolution {
                    status: LicenseStatus::Locked,
                    message: Some(format!("license check failed — {e}")),
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    const GRACE: u64 = 14 * 24 * 60 * 60;

    fn state(last_validated: Option<u64>) -> LicenseState {
        LicenseState {
            key: "K".into(),
            fingerprint: "fp".into(),
            last_validated,
        }
    }

    #[test]
    fn ok_true_activates_and_stamps_now() {
        let mut s = state(None);
        let r = resolve(Ok(true), &mut s, 1000, GRACE);
        assert_eq!(r.status, LicenseStatus::Active);
        assert_eq!(s.last_validated, Some(1000), "stamps last_validated");
    }

    #[test]
    fn ok_false_locks() {
        let mut s = state(Some(1000));
        let r = resolve(Ok(false), &mut s, 1000, GRACE);
        assert_eq!(r.status, LicenseStatus::Locked);
    }

    #[test]
    fn denied_locks_even_within_grace() {
        // The original silent-unlock bug: a wrong-account/revoked license must NOT ride
        // grace. last_validated is "now", so grace would otherwise apply.
        let mut s = state(Some(1000));
        let r = resolve(Err(CheckErr::Denied("HTTP 403".into())), &mut s, 1000, GRACE);
        assert_eq!(r.status, LicenseStatus::Locked, "fail closed");
    }

    #[test]
    fn offline_within_grace_is_grace() {
        let mut s = state(Some(1000));
        let r = resolve(
            Err(CheckErr::Offline("network".into())),
            &mut s,
            1000 + GRACE - 1,
            GRACE,
        );
        assert_eq!(r.status, LicenseStatus::Grace);
    }

    #[test]
    fn offline_past_grace_locks() {
        let mut s = state(Some(1000));
        let r = resolve(
            Err(CheckErr::Offline("network".into())),
            &mut s,
            1000 + GRACE + 1,
            GRACE,
        );
        assert_eq!(r.status, LicenseStatus::Locked);
    }

    #[test]
    fn offline_with_no_prior_validation_locks() {
        let mut s = state(None);
        let r = resolve(Err(CheckErr::Offline("network".into())), &mut s, 5000, GRACE);
        assert_eq!(r.status, LicenseStatus::Locked, "no cache ⇒ no grace");
    }
}