use crate::error::{Error, Result};
use crate::hwid::{get_hwid, platform_string};
use base64::{engine::general_purpose::{STANDARD as B64, URL_SAFE_NO_PAD as B64URL}, Engine};
use ed25519_dalek::{Signature, VerifyingKey};
use serde_json::{json, Map, Value};
use std::collections::{BTreeMap, HashMap, HashSet};
use std::sync::{Mutex, OnceLock};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
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>,
pub signed_out: bool,
}
impl ValidationResult {
fn refused(error: String, signed_out: bool) -> Self {
ValidationResult { valid: false, product_id: None, expires_at: None, features: Map::new(), usage: None, notice: None, error: Some(error), signed_out }
}
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,
pub not_after: Option<String>,
}
#[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>,
local_server: bool,
}
impl ClientBuilder {
pub fn local_server(mut self, on: bool) -> Self { self.local_server = on; self }
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,
server_files: Mutex::new(HashMap::new()), local_server: self.local_server,
})
}
}
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>>,
server_files: Mutex<HashMap<String, ServerFile>>,
local_server: bool,
}
#[derive(Clone)]
struct ServerFile { product_id: String, seats: i64, expires_at: i64, features: Map<String, Value>, key: VerifyingKey }
fn key_body(key: &str) -> Value {
if key.starts_with("lst_") { json!({ "token": key }) } else { json!({ "key": key }) }
}
fn refusal(status: u16, d: &Map<String, Value>, fallback: &str) -> Error {
let message = s(d.get("error")).unwrap_or_else(|| fallback.to_string());
if d.get("signed_out") == Some(&Value::Bool(true)) { Error::SignedOut { status, message } } else { Error::InvalidLicense { status, message } }
}
fn now_secs() -> i64 { SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0) }
fn iso(secs: i64) -> String {
let days = secs.div_euclid(86_400);
let rem = secs.rem_euclid(86_400);
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z - era * 146_097;
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
let y = yoe + era * 400 + i64::from(m <= 2);
format!("{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}.000Z", rem / 3600, rem % 3600 / 60, rem % 60)
}
fn device_name() -> String {
std::env::var("COMPUTERNAME").or_else(|_| std::env::var("HOSTNAME")).unwrap_or_default()
}
fn verify_with(key: &VerifyingKey, 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 };
key.verify_strict(message.as_bytes(), &sig).is_ok()
}
fn post_to(agent: &ureq::Agent, api_url: &str, path: &str, body: Value) -> Result<(u16, Map<String, Value>)> {
let resp = match agent.post(&format!("{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 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, local_server: false,
}
}
fn device(&self) -> String { self.hwid.clone().unwrap_or_else(get_hwid) }
fn verify(&self, message: &str, sig: Option<&Value>) -> bool { verify_with(&self.key, message, sig) }
fn post(&self, path: &str, body: Value) -> Result<(u16, Map<String, Value>)> { post_to(&self.agent, &self.api_url, path, body) }
fn body(&self, key: &str, extra: Value) -> Value {
let mut b = key_body(key);
if let Some(p) = &self.product_id { b["product_id"] = json!(p); }
if let (Value::Object(m), Value::Object(e)) = (&mut b, extra) { m.extend(e); }
b
}
fn server_file(&self, text: &Value) -> Result<ServerFile> {
let text = text.as_str().unwrap_or("");
let cached = self.server_files.lock().ok().and_then(|m| m.get(text).cloned());
let f = match cached {
Some(f) => f,
None => {
let parts: Vec<&str> = text.split('.').collect();
if parts.len() != 3 || parts[0] != "LSRV1" { return Err(Error::Signature("The license server sent an unreadable server file".into())); }
let not_ours = || Error::Signature("The license server's file is not signed by this app's seller".into());
let sig = B64URL.decode(parts[2]).map_err(|_| not_ours())?;
let sig = Signature::from_slice(&sig).map_err(|_| not_ours())?;
if self.key.verify_strict(format!("licers.server.v1|{}", parts[1]).as_bytes(), &sig).is_err() { return Err(not_ours()); }
let j: Value = B64URL.decode(parts[1]).ok().and_then(|b| serde_json::from_slice(&b).ok()).ok_or_else(not_ours)?;
let damaged = || Error::Signature("The license server's file is damaged".into());
if j.get("v").and_then(Value::as_i64) != Some(1) { return Err(damaged()); }
let seats = j.get("seats").and_then(Value::as_i64).ok_or_else(damaged)?;
let expires_at = j.get("expires_at").and_then(Value::as_i64).ok_or_else(damaged)?;
let server_pub = j.get("server_pub").and_then(Value::as_str).ok_or_else(damaged)?;
let key = B64.decode(server_pub).ok().and_then(|b| <[u8; 32]>::try_from(b).ok()).and_then(|b| VerifyingKey::from_bytes(&b).ok())
.ok_or_else(|| Error::Signature("The license server's file names an unusable key".into()))?;
let f = ServerFile {
product_id: j.get("product_id").map(part).unwrap_or_default(), seats, expires_at,
features: j.get("features").and_then(Value::as_object).cloned().unwrap_or_default(), key,
};
if let Ok(mut m) = self.server_files.lock() {
if m.len() > 16 { m.clear(); }
m.insert(text.to_string(), f.clone());
}
f
}
};
if f.expires_at <= now_secs() {
return Err(Error::InvalidLicense { status: 403, message: format!("The license server's license ended on {}. Its administrator needs a new server file.", &iso(f.expires_at)[..10]) });
}
Ok(f)
}
fn answer_key(&self, d: &Map<String, Value>, from_server: bool) -> Result<(VerifyingKey, Option<ServerFile>)> {
match d.get("server_file") {
None | Some(Value::Null) => Ok((self.key, None)),
Some(_) if !self.local_server => Err(Error::Signature("This answer came from a license server, but this client is not set up for one (local_server(true))".into())),
Some(_) if !from_server => Err(Error::Signature("A license server cannot answer this: usage credits, remote variables and updates come from Licers itself".into())),
Some(t) => {
let f = self.server_file(t)?;
let claimed = d.get("product_id").map(part).unwrap_or_else(|| f.product_id.clone());
if claimed != f.product_id { return Err(Error::Signature("The license server answered for another product than its file".into())); }
Ok((f.key, Some(f)))
}
}
}
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, from_server: bool) -> 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());
let (key, _) = self.answer_key(d, from_server)?;
if !verify_with(&key, &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 mut body = self.body(key, json!({ "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::refused(s(d.get("error")).unwrap_or_else(|| "License is not valid".into()), d.get("signed_out") == Some(&Value::Bool(true))));
}
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 (akey, file) = match self.answer_key(&d, true) {
Ok(x) => x,
Err(Error::InvalidLicense { message, .. }) => return Ok(ValidationResult::refused(message, false)),
Err(e) => return Err(e),
};
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 !verify_with(&akey, &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 mut features = Self::decode_signed(&fb64, "entitlements")?;
self.check_product(d.get("product_id"))?;
let mut expires_at = s(d.get("expires_at"));
if let Some(f) = &file {
features = f.features.clone();
expires_at = Some(iso(f.expires_at));
}
let from_licers = file.is_none();
Ok(ValidationResult {
valid: true, product_id: Some(product.clone()), expires_at, features,
usage: if from_licers { self.validate_usage(&d, &product, &hwid, &n, issued) } else { None },
notice: if from_licers { self.notice(&d, &n, issued) } else { None }, error: None, signed_out: false,
})
}
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 mut body = key_body(key);
body["hwid"] = json!(hwid); body["amount"] = json!(amount); body["nonce"] = json!(n);
let (status, d) = self.post("/api/v1/usage", body)?;
if status != 200 {
if d.get("code").and_then(Value::as_str) == Some("usage_exceeded") {
let message = s(d.get("error")).unwrap_or_else(|| "Usage could not be recorded".into());
return Err(Error::UsageExceeded { message, usage: d.get("usage").cloned().unwrap_or(Value::Null) });
}
return Err(refusal(status, &d, "Usage could not be recorded"));
}
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", false)?;
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 = key_body(key);
body["hwid"] = json!(hwid); body["nonce"] = json!(n);
if let Some(names) = names { body["names"] = json!(names); }
let (status, d) = self.post("/api/v1/variables", body)?;
if status != 200 { return Err(refusal(status, &d, "Variables could not be fetched")); }
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", false)?;
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", self.body(key, json!({ "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(refusal(status, &d, "Could not acquire a seat")); }
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", true)?;
let mut not_after = None;
if let (_, Some(f)) = self.answer_key(&d, true)? {
if seats.get("max").and_then(Value::as_i64).map_or(true, |m| m > f.seats) {
return Err(Error::Signature("The license server claims more seats than its file allows".into()));
}
not_after = Some(iso(f.expires_at));
}
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),
not_after,
})
}
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", true);
if ok.is_err() { return (HeartbeatState::Lost, None); }
let mut exp = s(d.get("expires_at"));
if let Ok((_, Some(f))) = self.answer_key(&d, true) {
let end = iso(f.expires_at);
if exp.as_deref().map_or(true, |e| e > end.as_str()) { exp = Some(end); }
}
(HeartbeatState::Held, exp)
}
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 mut body = key_body(key);
body["current_version"] = json!(current_version); body["channel"] = json!(channel); body["nonce"] = json!(n);
let (status, d) = self.post("/api/v1/update", body)?;
if status != 200 { return Err(refusal(status, &d, "Update check failed")); }
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", false)?;
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")),
})
}
pub fn start_sign_in(&self) -> Result<SignIn> {
let product = self.product_id.clone().ok_or_else(|| Error::Config("product_id is required to sign in: set it on the builder".into()))?;
let hwid: String = self.device().chars().take(256).collect();
let (status, d) = self.post("/api/v1/signin/start", json!({
"product_id": product, "hwid": hwid,
"device_name": device_name().chars().take(120).collect::<String>(), "platform": platform_string().chars().take(60).collect::<String>(),
}))?;
if status != 200 { return Err(Error::SignIn { status, message: s(d.get("error")).unwrap_or_else(|| "Could not start signing in".into()) }); }
let field = |k: &str| s(d.get(k)).ok_or_else(|| Error::Protocol(format!("The sign-in answer is missing {k}")));
let expires_in = d.get("expires_in").and_then(Value::as_u64).unwrap_or(600);
Ok(SignIn {
code: field("code")?, url: field("url")?, expires_in, email: None, poll: field("poll")?,
interval: d.get("interval").and_then(Value::as_u64).unwrap_or(5).max(1),
deadline: Instant::now() + Duration::from_secs(expires_in + 60),
agent: self.agent.clone(), api_url: self.api_url.clone(),
})
}
pub fn sign_in(&self, on_code: impl FnOnce(&SignIn)) -> Result<String> {
let mut s = self.start_sign_in()?;
on_code(&s);
s.wait(None)
}
pub fn sign_out(&self, token: &str) -> Result<()> {
self.post("/api/v1/signout", json!({ "token": token })).map(|_| ())
}
}
pub struct SignIn {
pub code: String,
pub url: String,
pub expires_in: u64,
pub email: Option<String>,
poll: String,
interval: u64,
deadline: Instant,
agent: ureq::Agent,
api_url: String,
}
impl SignIn {
pub fn check(&mut self) -> Result<Option<String>> {
let (status, d) = post_to(&self.agent, &self.api_url, "/api/v1/signin/poll", json!({ "poll": self.poll }))?;
if status != 200 { return Err(Error::SignIn { status, message: s(d.get("error")).unwrap_or_else(|| "Signing in failed".into()) }); }
match d.get("status").and_then(Value::as_str) {
Some("approved") => {
let token = s(d.get("token")).filter(|t| t.starts_with("lst_")).ok_or_else(|| Error::Protocol("The sign-in answer has no token".into()))?;
self.email = s(d.get("email"));
Ok(Some(token))
}
Some("denied") => Err(Error::SignInDenied(s(d.get("error")).unwrap_or_else(|| "Signing in was declined".into()))),
Some("expired") => Err(Error::SignInExpired(s(d.get("error")).unwrap_or_else(|| "The sign-in code ran out".into()))),
Some("slow_down") => {
self.interval = self.interval.max(d.get("interval").and_then(Value::as_u64).unwrap_or(self.interval + 2));
Ok(None)
}
_ => Ok(None),
}
}
pub fn wait(&mut self, timeout: Option<Duration>) -> Result<String> {
let end = timeout.map_or(self.deadline, |t| self.deadline.min(Instant::now() + t));
loop {
std::thread::sleep(Duration::from_secs(self.interval));
match self.check() {
Ok(Some(token)) => return Ok(token),
Ok(None) => {}
Err(e) if e.is_network() => {}
Err(e) => return Err(e),
}
if Instant::now() >= end { return Err(Error::SignInExpired("Gave up waiting for the sign-in to be approved".into())); }
}
}
}
#[cfg(test)]
mod tests {
#[test]
fn iso_dates() {
assert_eq!(super::iso(4_102_444_800), "2100-01-01T00:00:00.000Z");
assert_eq!(super::iso(1_796_000_000), "2026-11-30T00:53:20.000Z");
assert_eq!(super::iso(951_782_400), "2000-02-29T00:00:00.000Z");
assert_eq!(super::iso(0), "1970-01-01T00:00:00.000Z");
}
}