use std::time::{SystemTime, UNIX_EPOCH};
use rand::Rng;
use crate::core::config::StorageConfig;
pub fn now_secs() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0)
}
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()
}
#[derive(Default, Clone, Debug)]
pub struct LicenseState {
pub key: String,
pub fingerprint: String,
pub last_validated: Option<u64>,
}
impl LicenseState {
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); }
s
}
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);
}
pub fn within_grace(&self, now: u64, grace_secs: u64) -> bool {
self.last_validated
.is_some_and(|t| now.saturating_sub(t) < grace_secs)
}
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");
}
}