use crate::error::{Error, Result};
use crate::hwid::{get_hwid, platform_string};
use base64::{engine::general_purpose::STANDARD as B64, Engine};
use ed25519_dalek::{Signature, VerifyingKey};
use serde_json::{json, Map, Value};
use std::collections::{BTreeMap, HashSet};
use std::sync::{Mutex, OnceLock};
use std::time::Duration;
pub const DEFAULT_API: &str = "https://licers.com";
pub const SDK_VERSION: &str = env!("CARGO_PKG_VERSION");
#[derive(Debug, Clone, PartialEq)]
pub struct Usage {
pub used: i64,
pub limit: Option<i64>,
pub reset: Option<String>,
pub resets_at: Option<String>,
pub spent: i64,
}
impl Usage {
pub fn remaining(&self) -> Option<i64> { self.limit.map(|l| (l - self.used).max(0)) }
}
#[derive(Debug, Clone)]
pub struct ValidationResult {
pub valid: bool,
pub product_id: Option<String>,
pub expires_at: Option<String>,
pub features: Map<String, Value>,
pub usage: Option<Usage>,
pub error: Option<String>,
pub notice: Option<String>,
}
impl ValidationResult {
pub fn feature(&self, name: &str) -> Option<&Value> { self.features.get(name) }
}
#[derive(Debug, Clone)]
pub struct Lease {
pub lease_id: String,
pub product_id: String,
pub expires_at: String,
pub interval: u64,
pub seats_used: i64,
pub seats_max: i64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HeartbeatState { Held, Lost, Unconfirmed }
#[derive(Debug, Clone)]
pub struct UpdateInfo {
pub update_available: bool,
pub version: Option<String>,
pub channel: String,
pub product_id: String,
pub filename: Option<String>,
pub size: i64,
pub download_url: Option<String>,
pub notes: Option<String>,
}
pub struct ClientBuilder {
public_key: String,
api_url: String,
timeout: Duration,
product_id: Option<String>,
app_version: Option<String>,
hwid: Option<String>,
on_notice: Option<Box<dyn Fn(&str) + Send + Sync>>,
user_agent: Option<String>,
}
impl ClientBuilder {
pub fn api_url(mut self, url: impl Into<String>) -> Self { self.api_url = url.into(); self }
pub fn timeout(mut self, t: Duration) -> Self { self.timeout = t; self }
pub fn product_id(mut self, id: impl Into<String>) -> Self { self.product_id = Some(id.into()); self }
pub fn app_version(mut self, v: impl Into<String>) -> Self { self.app_version = Some(v.into().chars().take(40).collect()); self }
pub fn hwid(mut self, h: impl Into<String>) -> Self { self.hwid = Some(h.into()); self }
pub fn on_notice(mut self, f: impl Fn(&str) + Send + Sync + 'static) -> Self { self.on_notice = Some(Box::new(f)); self }
#[doc(hidden)]
pub fn user_agent(mut self, ua: impl Into<String>) -> Self { self.user_agent = Some(ua.into()); self }
pub fn build(self) -> Result<LicenseClient> {
let raw = B64.decode(self.public_key.trim()).map_err(|_| Error::Config("publicKey is not base64".into()))?;
let bytes: [u8; 32] = raw.try_into().map_err(|_| Error::Config("publicKey must be the 32-byte Ed25519 key from the dashboard".into()))?;
let key = VerifyingKey::from_bytes(&bytes).map_err(|_| Error::Config("publicKey is not a valid Ed25519 key".into()))?;
let agent = ureq::AgentBuilder::new().timeout(self.timeout).redirects(0).user_agent(&self.user_agent.clone().unwrap_or_else(|| format!("licers-rust/{SDK_VERSION}"))).build();
Ok(LicenseClient {
key, agent, api_url: self.api_url.trim_end_matches('/').to_string(),
product_id: self.product_id, app_version: self.app_version, hwid: self.hwid, on_notice: self.on_notice,
})
}
}
pub struct LicenseClient {
key: VerifyingKey,
agent: ureq::Agent,
api_url: String,
product_id: Option<String>,
app_version: Option<String>,
hwid: Option<String>,
on_notice: Option<Box<dyn Fn(&str) + Send + Sync>>,
}
fn nonce() -> String {
let mut b = [0u8; 8];
getrandom::getrandom(&mut b).expect("OS random number generator");
b.iter().map(|x| format!("{x:02x}")).collect()
}
fn part(v: &Value) -> String {
match v {
Value::Null => String::new(),
Value::Bool(b) => if *b { "1" } else { "0" }.to_string(),
Value::String(s) => s.clone(),
other => other.to_string(),
}
}
fn s(v: Option<&Value>) -> Option<String> { v.and_then(|x| x.as_str()).map(str::to_string) }
fn int_field(d: &Map<String, Value>, k: &str) -> Result<i64> {
d.get(k).and_then(Value::as_i64).ok_or_else(|| Error::Protocol(format!("Server sent a malformed numeric field: {k}")))
}
fn notices() -> &'static Mutex<HashSet<String>> {
static N: OnceLock<Mutex<HashSet<String>>> = OnceLock::new();
N.get_or_init(|| Mutex::new(HashSet::new()))
}
impl LicenseClient {
pub fn new(public_key: &str) -> Result<Self> { Self::builder(public_key).build() }
pub fn builder(public_key: &str) -> ClientBuilder {
ClientBuilder {
public_key: public_key.to_string(), api_url: DEFAULT_API.to_string(), timeout: Duration::from_secs(5),
product_id: None, app_version: None, hwid: None, on_notice: None, user_agent: None,
}
}
fn device(&self) -> String { self.hwid.clone().unwrap_or_else(get_hwid) }
fn verify(&self, message: &str, sig: Option<&Value>) -> bool {
let Some(sig) = sig.and_then(Value::as_str) else { return false };
let Ok(raw) = B64.decode(sig) else { return false };
let Ok(sig) = Signature::from_slice(&raw) else { return false };
self.key.verify_strict(message.as_bytes(), &sig).is_ok()
}
fn post(&self, path: &str, body: Value) -> Result<(u16, Map<String, Value>)> {
let resp = match self.agent.post(&format!("{}{}", self.api_url, path)).send_json(body) {
Ok(r) => r,
Err(ureq::Error::Status(_, r)) => r,
Err(ureq::Error::Transport(t)) => return Err(Error::Network(format!("Could not reach the license server: {t}"))),
};
let status = resp.status();
if status >= 500 { return Err(Error::Server { status, message: format!("The license server had an error (HTTP {status})") }); }
if (300..400).contains(&status) {
return Err(Error::Protocol(format!("The license server answered with a redirect (HTTP {status}), which is never followed. Check api_url.")));
}
let text = resp.into_string().map_err(|e| Error::Network(format!("Reading the reply failed: {e}")))?;
if text.trim().is_empty() { return Ok((status, Map::new())); }
match serde_json::from_str::<Value>(&text) {
Ok(Value::Object(m)) => Ok((status, m)),
Ok(_) => Err(Error::Protocol(format!("Server sent an unexpected response body (HTTP {status})"))),
Err(_) => Err(Error::Protocol(format!("Server sent a response that is not JSON (HTTP {status}) — a proxy or captive portal may be intercepting the connection"))),
}
}
fn check_product(&self, actual: Option<&Value>) -> Result<()> {
if let Some(want) = &self.product_id {
let got = actual.and_then(Value::as_str).unwrap_or("");
if got != want { return Err(Error::ProductMismatch { expected: want.clone(), actual: got.to_string() }); }
}
Ok(())
}
fn verify_signed(&self, d: &Map<String, Value>, parts: &[Value], n: &str, what: &str) -> Result<()> {
if !d.get("signature").map_or(false, Value::is_string) { return Err(Error::Signature(format!("{what} response was not signed — refusing to trust it"))); }
let issued = d.get("issued_at").and_then(Value::as_i64).ok_or_else(|| Error::Signature(format!("{what} response has no usable timestamp")))?;
let mut msg: Vec<String> = parts.iter().map(part).collect();
msg.push(issued.to_string());
if !self.verify(&msg.join("|"), d.get("signature")) { return Err(Error::Signature(format!("{what} signature verification failed — response may be forged"))); }
if d.get("nonce").and_then(Value::as_str) != Some(n) { return Err(Error::Signature(format!("{what} nonce mismatch — possible replay"))); }
Ok(())
}
fn decode_signed(b64: &str, what: &str) -> Result<Map<String, Value>> {
if b64.is_empty() { return Ok(Map::new()); }
let raw = B64.decode(b64).map_err(|_| Error::Signature(format!("Signed {what} could not be decoded")))?;
match serde_json::from_slice::<Value>(&raw) {
Ok(Value::Object(m)) => Ok(m),
Ok(_) => Err(Error::Signature(format!("Signed {what} were not an object"))),
Err(_) => Err(Error::Signature(format!("Signed {what} could not be decoded"))),
}
}
pub fn validate(&self, key: &str) -> Result<ValidationResult> {
let hwid = self.device();
let n = nonce();
let device_name = std::env::var("COMPUTERNAME").or_else(|_| std::env::var("HOSTNAME")).unwrap_or_default();
let mut body = json!({ "key": key, "hwid": hwid, "nonce": n, "device_name": device_name, "platform": platform_string() });
if let Some(v) = &self.app_version { body["app_version"] = json!(v); }
let (status, d) = self.post("/api/v1/validate", body)?;
if status != 200 || d.get("valid") != Some(&Value::Bool(true)) {
return Ok(ValidationResult {
valid: false, product_id: None, expires_at: None, features: Map::new(), usage: None, notice: None,
error: Some(s(d.get("error")).unwrap_or_else(|| "License is not valid".into())),
});
}
let fb64 = s(d.get("features_b64")).unwrap_or_default();
if !d.get("signature").map_or(false, Value::is_string) { return Err(Error::Signature("Response was not signed — refusing to trust it".into())); }
let issued = d.get("issued_at").and_then(Value::as_i64).ok_or_else(|| Error::Signature("Response has no usable timestamp".into()))?;
let product = d.get("product_id").map(part).unwrap_or_default();
let msg = format!("pylicense.v2|{product}|{hwid}|{}|{n}|{issued}|{fb64}", s(d.get("expires_at")).unwrap_or_default());
if !self.verify(&msg, d.get("signature")) { return Err(Error::Signature("Signature verification failed — response may be forged".into())); }
if d.get("nonce").and_then(Value::as_str) != Some(n.as_str()) { return Err(Error::Signature("Nonce mismatch — possible replay".into())); }
let features = Self::decode_signed(&fb64, "entitlements")?;
self.check_product(d.get("product_id"))?;
Ok(ValidationResult {
valid: true, product_id: Some(product.clone()), expires_at: s(d.get("expires_at")), features,
usage: self.validate_usage(&d, &product, &hwid, &n, issued),
notice: self.notice(&d, &n, issued), error: None,
})
}
fn notice(&self, d: &Map<String, Value>, n: &str, issued: i64) -> Option<String> {
let text = s(d.get("notice"))?;
let msg = ["pylicense.notice.v1".to_string(), text.clone(), d.get("notice_min_version").map(part).unwrap_or_default(), n.to_string(), issued.to_string()].join("|");
if !self.verify(&msg, d.get("notice_sig")) { return None; } let text: String = text.chars().take(300).collect();
if notices().lock().map(|mut set| set.insert(text.clone())).unwrap_or(false) {
match &self.on_notice {
Some(f) => f(&text),
None if std::env::var_os("LICERS_NO_NOTICE").is_none() => eprintln!("[licers] {text}"),
None => {}
}
}
Some(text)
}
fn validate_usage(&self, d: &Map<String, Value>, product: &str, hwid: &str, n: &str, issued: i64) -> Option<Usage> {
let u = d.get("usage")?.as_object()?;
let used = u.get("used")?.as_i64()?;
let limit = match u.get("limit") { None | Some(Value::Null) => None, Some(v) => Some(v.as_i64()?) };
let msg = format!("pylicense.usage.v1|{product}|{hwid}|0|{used}|{}|{n}|{issued}", limit.map(|l| l.to_string()).unwrap_or_default());
if !self.verify(&msg, d.get("usage_sig")) { return None; }
Some(Usage { used, limit, reset: s(u.get("reset")), resets_at: s(u.get("resets_at")), spent: 0 })
}
pub fn record_usage(&self, key: &str, amount: u32) -> Result<Usage> {
let hwid = self.device();
let n = nonce();
let (status, d) = self.post("/api/v1/usage", json!({ "key": key, "hwid": hwid, "amount": amount, "nonce": n }))?;
if status != 200 {
let message = s(d.get("error")).unwrap_or_else(|| "Usage could not be recorded".into());
if d.get("code").and_then(Value::as_str) == Some("usage_exceeded") {
return Err(Error::UsageExceeded { message, usage: d.get("usage").cloned().unwrap_or(Value::Null) });
}
return Err(Error::InvalidLicense { status, message });
}
let used = int_field(&d, "used")?;
let limit = match d.get("limit") { None | Some(Value::Null) => None, Some(_) => Some(int_field(&d, "limit")?) };
if int_field(&d, "amount")? != i64::from(amount) { return Err(Error::Signature("Usage response is for a different amount — refusing to trust it".into())); }
let product = d.get("product_id").cloned().unwrap_or(Value::String(String::new()));
self.verify_signed(&d, &[json!("pylicense.usage.v1"), product, json!(hwid), json!(amount), json!(used), limit.map_or(Value::Null, |l| json!(l)), json!(n)], &n, "Usage")?;
self.check_product(d.get("product_id"))?;
Ok(Usage { used, limit, reset: s(d.get("reset")), resets_at: s(d.get("resets_at")), spent: i64::from(amount) })
}
pub fn get_usage(&self, key: &str) -> Result<Usage> { self.record_usage(key, 0) }
pub fn get_variables(&self, key: &str) -> Result<BTreeMap<String, String>> { self.variables(key, None) }
pub fn get_variable(&self, key: &str, name: &str) -> Result<Option<String>> {
Ok(self.variables(key, Some(&[name]))?.remove(name))
}
fn variables(&self, key: &str, names: Option<&[&str]>) -> Result<BTreeMap<String, String>> {
let hwid = self.device();
let n = nonce();
let mut body = json!({ "key": key, "hwid": hwid, "nonce": n });
if let Some(names) = names { body["names"] = json!(names); }
let (status, d) = self.post("/api/v1/variables", body)?;
if status != 200 { return Err(Error::InvalidLicense { status, message: s(d.get("error")).unwrap_or_else(|| "Variables could not be fetched".into()) }); }
let vb64 = s(d.get("vars_b64")).unwrap_or_default();
let product = d.get("product_id").cloned().unwrap_or(Value::String(String::new()));
self.verify_signed(&d, &[json!("pylicense.vars.v1"), product, json!(hwid), json!(vb64), json!(n)], &n, "Variables")?;
self.check_product(d.get("product_id"))?;
Ok(Self::decode_signed(&vb64, "variables")?.into_iter().map(|(k, v)| (k, part(&v))).collect())
}
pub fn lease(&self, key: &str) -> Result<Lease> {
let hwid: String = self.device().chars().take(200).collect();
let n = nonce();
let (status, d) = self.post("/api/v1/lease", json!({ "key": key, "hwid": hwid, "nonce": n }))?;
if status == 409 { return Err(Error::SeatUnavailable(s(d.get("error")).unwrap_or_else(|| "All concurrent sessions are in use".into()))); }
if status != 200 { return Err(Error::InvalidLicense { status, message: s(d.get("error")).unwrap_or_else(|| "Could not acquire a seat".into()) }); }
let seats = d.get("seats").cloned().unwrap_or(Value::Null);
let product = d.get("product_id").cloned().unwrap_or(Value::String(String::new()));
self.verify_signed(&d, &[json!("pylicense.lease.v1"), product, json!(hwid), d.get("lease_id").cloned().unwrap_or(Value::Null),
d.get("expires_at").cloned().unwrap_or(Value::Null), json!(n), seats.get("used").cloned().unwrap_or(Value::Null), seats.get("max").cloned().unwrap_or(Value::Null)], &n, "Lease")?;
self.check_product(d.get("product_id"))?;
Ok(Lease {
lease_id: s(d.get("lease_id")).unwrap_or_default(), product_id: s(d.get("product_id")).unwrap_or_default(),
expires_at: s(d.get("expires_at")).unwrap_or_default(), interval: d.get("interval").and_then(Value::as_u64).unwrap_or(60),
seats_used: seats.get("used").and_then(Value::as_i64).unwrap_or(0), seats_max: seats.get("max").and_then(Value::as_i64).unwrap_or(0),
})
}
pub fn heartbeat(&self, lease_id: &str) -> (HeartbeatState, Option<String>) {
let n = nonce();
let (status, d) = match self.post("/api/v1/heartbeat", json!({ "lease_id": lease_id, "nonce": n })) {
Ok(x) => x,
Err(_) => return (HeartbeatState::Unconfirmed, None),
};
if status == 429 { return (HeartbeatState::Unconfirmed, None); }
if status != 200 { return (HeartbeatState::Lost, None); }
let ok = self.verify_signed(&d, &[json!("pylicense.heartbeat.v1"), json!(lease_id), d.get("expires_at").cloned().unwrap_or(Value::Null), json!(n)], &n, "Heartbeat");
if ok.is_err() { return (HeartbeatState::Lost, None); }
(HeartbeatState::Held, s(d.get("expires_at")))
}
pub fn release(&self, lease_id: &str) { let _ = self.post("/api/v1/release", json!({ "lease_id": lease_id })); }
pub fn check_update(&self, key: &str, current_version: &str, channel: &str) -> Result<UpdateInfo> {
let n = nonce();
let (status, d) = self.post("/api/v1/update", json!({ "key": key, "current_version": current_version, "channel": channel, "nonce": n }))?;
if status != 200 { return Err(Error::InvalidLicense { status, message: s(d.get("error")).unwrap_or_else(|| "Update check failed".into()) }); }
let size = match d.get("size") { None | Some(Value::Null) => 0, Some(_) => int_field(&d, "size")? };
let product = d.get("product_id").cloned().unwrap_or(Value::String(String::new()));
let g = |k: &str| d.get(k).cloned().unwrap_or(Value::Null);
self.verify_signed(&d, &[json!("pylicense.update.v1"), product, json!(channel), g("update_available"), g("version"), g("filename"), json!(size), json!(n)], &n, "Update check")?;
self.check_product(d.get("product_id"))?;
Ok(UpdateInfo {
update_available: d.get("update_available").and_then(Value::as_bool).unwrap_or(false), version: s(d.get("version")),
channel: channel.to_string(), product_id: s(d.get("product_id")).unwrap_or_default(), filename: s(d.get("filename")), size,
download_url: s(d.get("download_url")), notes: s(d.get("notes")),
})
}
}