Skip to main content

rustify_licensing/core/
state.rs

1//! Persisted license state: the key, a stable node-lock fingerprint, and the last
2//! successful validation timestamp (which drives offline grace).
3//!
4//! The on-disk format is plain `KEY=value` lines so an existing install
5//! refactored onto this crate keeps its activation **and its fingerprint** (a fresh
6//! fingerprint would register a new machine and could trip `TOO_MANY_MACHINES`).
7
8use std::time::{SystemTime, UNIX_EPOCH};
9
10use rand::Rng;
11
12use crate::core::config::StorageConfig;
13
14/// Unix seconds now (saturating to 0 on a pre-epoch clock).
15pub fn now_secs() -> u64 {
16    SystemTime::now()
17        .duration_since(UNIX_EPOCH)
18        .map(|d| d.as_secs())
19        .unwrap_or(0)
20}
21
22/// A stable per-install id: 32 random hex chars. Minted once, then persisted.
23fn new_fingerprint() -> String {
24    let mut rng = rand::thread_rng();
25    (0..32)
26        .map(|_| std::char::from_digit(rng.gen_range(0..16), 16).unwrap())
27        .collect()
28}
29
30/// Persisted license state. The key is a secret-ish credential — never log it.
31#[derive(Default, Clone, Debug)]
32pub struct LicenseState {
33    pub key: String,
34    /// Stable per-install id used to node-lock the license (generated once).
35    pub fingerprint: String,
36    /// Unix seconds of the last successful online validation (drives offline grace).
37    pub last_validated: Option<u64>,
38}
39
40impl LicenseState {
41    /// Load from the resolved storage file. The configured env var (if any) overrides the
42    /// key. Mints + persists a fingerprint on first run so the node-lock stays stable.
43    pub fn load(storage: &StorageConfig) -> Self {
44        let mut s = LicenseState {
45            key: storage
46                .env_key_var
47                .as_ref()
48                .and_then(|v| std::env::var(v).ok())
49                .unwrap_or_default(),
50            ..Default::default()
51        };
52        if let Ok(contents) = std::fs::read_to_string(storage.resolve()) {
53            for line in contents.lines() {
54                if let Some(v) = line.strip_prefix("LICENSE_KEY=") {
55                    if s.key.is_empty() && !v.trim().is_empty() {
56                        s.key = v.trim().to_string();
57                    }
58                } else if let Some(v) = line.strip_prefix("FINGERPRINT=") {
59                    s.fingerprint = v.trim().to_string();
60                } else if let Some(v) = line.strip_prefix("LAST_VALIDATED=") {
61                    s.last_validated = v.trim().parse().ok();
62                }
63            }
64        }
65        if s.fingerprint.is_empty() {
66            s.fingerprint = new_fingerprint();
67            s.save(storage); // persist immediately so the node-lock id is stable
68        }
69        s
70    }
71
72    /// Persist back to the resolved storage file (the `KEY=value` format).
73    pub fn save(&self, storage: &StorageConfig) {
74        let body = format!(
75            "LICENSE_KEY={}\nFINGERPRINT={}\nLAST_VALIDATED={}\n",
76            self.key.trim(),
77            self.fingerprint,
78            self.last_validated
79                .map(|t| t.to_string())
80                .unwrap_or_default(),
81        );
82        let _ = std::fs::write(storage.resolve(), body);
83    }
84
85    /// Within the offline grace window off the last successful validation?
86    pub fn within_grace(&self, now: u64, grace_secs: u64) -> bool {
87        self.last_validated
88            .is_some_and(|t| now.saturating_sub(t) < grace_secs)
89    }
90
91    /// Optimistic synchronous guess for startup (the async check refines it shortly
92    /// after): we have a key **and** are within grace.
93    pub fn probably_active(&self, now: u64, grace_secs: u64) -> bool {
94        !self.key.trim().is_empty() && self.within_grace(now, grace_secs)
95    }
96}
97
98#[cfg(test)]
99mod tests {
100    use super::*;
101
102    fn temp_storage(tag: &str) -> StorageConfig {
103        let mut p = std::env::temp_dir();
104        p.push(format!(
105            "rustify-licensing-test-{tag}-{}.env",
106            std::process::id()
107        ));
108        let _ = std::fs::remove_file(&p);
109        StorageConfig {
110            path: p,
111            dev_shadow: None,
112            env_key_var: None,
113        }
114    }
115
116    #[test]
117    fn mints_then_keeps_fingerprint_across_loads() {
118        let s = temp_storage("fp");
119        let a = LicenseState::load(&s);
120        assert_eq!(a.fingerprint.len(), 32, "32 hex chars");
121        assert!(a.fingerprint.chars().all(|c| c.is_ascii_hexdigit()));
122        let b = LicenseState::load(&s);
123        assert_eq!(a.fingerprint, b.fingerprint, "fingerprint must be stable");
124        let _ = std::fs::remove_file(s.resolve());
125    }
126
127    #[test]
128    fn round_trips_key_and_timestamp_preserving_fingerprint() {
129        let s = temp_storage("rt");
130        let mut a = LicenseState::load(&s);
131        let fp = a.fingerprint.clone();
132        a.key = "ABC-123".into();
133        a.last_validated = Some(42);
134        a.save(&s);
135
136        let b = LicenseState::load(&s);
137        assert_eq!(b.key, "ABC-123");
138        assert_eq!(b.last_validated, Some(42));
139        assert_eq!(b.fingerprint, fp, "fingerprint survives a save/load");
140        let _ = std::fs::remove_file(s.resolve());
141    }
142
143    #[test]
144    fn grace_window_boundaries() {
145        let s = LicenseState {
146            key: "K".into(),
147            fingerprint: "fp".into(),
148            last_validated: Some(1000),
149        };
150        let grace = 100;
151        assert!(s.within_grace(1099, grace), "just inside");
152        assert!(!s.within_grace(1100, grace), "exactly at the edge is out");
153        assert!(!s.within_grace(2000, grace), "well past");
154        assert!(s.probably_active(1099, grace));
155        assert!(!s.probably_active(1100, grace), "no grace ⇒ not probably active");
156
157        let no_key = LicenseState {
158            key: "   ".into(),
159            ..s.clone()
160        };
161        assert!(!no_key.probably_active(1099, grace), "blank key ⇒ not active");
162    }
163}