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
//! Persisted license state: the key, a stable node-lock fingerprint, and the last
//! successful validation timestamp (which drives offline grace).
//!
//! The on-disk format is plain `KEY=value` lines so an existing install
//! refactored onto this crate keeps its activation **and its fingerprint** (a fresh
//! fingerprint would register a new machine and could trip `TOO_MANY_MACHINES`).

use std::time::{SystemTime, UNIX_EPOCH};

use rand::Rng;

use crate::core::config::StorageConfig;

/// Unix seconds now (saturating to 0 on a pre-epoch clock).
pub fn now_secs() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0)
}

/// A stable per-install id: 32 random hex chars. Minted once, then persisted.
fn new_fingerprint() -> String {
    let mut rng = rand::thread_rng();
    (0..32)
        .map(|_| std::char::from_digit(rng.gen_range(0..16), 16).unwrap())
        .collect()
}

/// Persisted license state. The key is a secret-ish credential — never log it.
#[derive(Default, Clone, Debug)]
pub struct LicenseState {
    pub key: String,
    /// Stable per-install id used to node-lock the license (generated once).
    pub fingerprint: String,
    /// Unix seconds of the last successful online validation (drives offline grace).
    pub last_validated: Option<u64>,
}

impl LicenseState {
    /// Load from the resolved storage file. The configured env var (if any) overrides the
    /// key. Mints + persists a fingerprint on first run so the node-lock stays stable.
    pub fn load(storage: &StorageConfig) -> Self {
        let mut s = LicenseState {
            key: storage
                .env_key_var
                .as_ref()
                .and_then(|v| std::env::var(v).ok())
                .unwrap_or_default(),
            ..Default::default()
        };
        if let Ok(contents) = std::fs::read_to_string(storage.resolve()) {
            for line in contents.lines() {
                if let Some(v) = line.strip_prefix("LICENSE_KEY=") {
                    if s.key.is_empty() && !v.trim().is_empty() {
                        s.key = v.trim().to_string();
                    }
                } else if let Some(v) = line.strip_prefix("FINGERPRINT=") {
                    s.fingerprint = v.trim().to_string();
                } else if let Some(v) = line.strip_prefix("LAST_VALIDATED=") {
                    s.last_validated = v.trim().parse().ok();
                }
            }
        }
        if s.fingerprint.is_empty() {
            s.fingerprint = new_fingerprint();
            s.save(storage); // persist immediately so the node-lock id is stable
        }
        s
    }

    /// Persist back to the resolved storage file (the `KEY=value` format).
    pub fn save(&self, storage: &StorageConfig) {
        let body = format!(
            "LICENSE_KEY={}\nFINGERPRINT={}\nLAST_VALIDATED={}\n",
            self.key.trim(),
            self.fingerprint,
            self.last_validated
                .map(|t| t.to_string())
                .unwrap_or_default(),
        );
        let _ = std::fs::write(storage.resolve(), body);
    }

    /// Within the offline grace window off the last successful validation?
    pub fn within_grace(&self, now: u64, grace_secs: u64) -> bool {
        self.last_validated
            .is_some_and(|t| now.saturating_sub(t) < grace_secs)
    }

    /// Optimistic synchronous guess for startup (the async check refines it shortly
    /// after): we have a key **and** are within grace.
    pub fn probably_active(&self, now: u64, grace_secs: u64) -> bool {
        !self.key.trim().is_empty() && self.within_grace(now, grace_secs)
    }
}

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

    fn temp_storage(tag: &str) -> StorageConfig {
        let mut p = std::env::temp_dir();
        p.push(format!(
            "rustify-licensing-test-{tag}-{}.env",
            std::process::id()
        ));
        let _ = std::fs::remove_file(&p);
        StorageConfig {
            path: p,
            dev_shadow: None,
            env_key_var: None,
        }
    }

    #[test]
    fn mints_then_keeps_fingerprint_across_loads() {
        let s = temp_storage("fp");
        let a = LicenseState::load(&s);
        assert_eq!(a.fingerprint.len(), 32, "32 hex chars");
        assert!(a.fingerprint.chars().all(|c| c.is_ascii_hexdigit()));
        let b = LicenseState::load(&s);
        assert_eq!(a.fingerprint, b.fingerprint, "fingerprint must be stable");
        let _ = std::fs::remove_file(s.resolve());
    }

    #[test]
    fn round_trips_key_and_timestamp_preserving_fingerprint() {
        let s = temp_storage("rt");
        let mut a = LicenseState::load(&s);
        let fp = a.fingerprint.clone();
        a.key = "ABC-123".into();
        a.last_validated = Some(42);
        a.save(&s);

        let b = LicenseState::load(&s);
        assert_eq!(b.key, "ABC-123");
        assert_eq!(b.last_validated, Some(42));
        assert_eq!(b.fingerprint, fp, "fingerprint survives a save/load");
        let _ = std::fs::remove_file(s.resolve());
    }

    #[test]
    fn grace_window_boundaries() {
        let s = LicenseState {
            key: "K".into(),
            fingerprint: "fp".into(),
            last_validated: Some(1000),
        };
        let grace = 100;
        assert!(s.within_grace(1099, grace), "just inside");
        assert!(!s.within_grace(1100, grace), "exactly at the edge is out");
        assert!(!s.within_grace(2000, grace), "well past");
        assert!(s.probably_active(1099, grace));
        assert!(!s.probably_active(1100, grace), "no grace ⇒ not probably active");

        let no_key = LicenseState {
            key: "   ".into(),
            ..s.clone()
        };
        assert!(!no_key.probably_active(1099, grace), "blank key ⇒ not active");
    }
}