licers 1.2.1

Licers license-key verification: Ed25519-signed responses, floating seats, usage credits, remote variables, offline licenses.
Documentation
use crate::error::{Error, Result};
use crate::hwid::{detect_os, get_hwid};
use base64::{engine::general_purpose::STANDARD as B64, Engine};
use ed25519_dalek::{Signature, VerifyingKey};
use serde_json::{Map, Value};
use std::path::Path;
use std::time::{SystemTime, UNIX_EPOCH};

/// The largest `.lic` file (or text) accepted, in bytes.
pub const MAX_LICENSE_FILE: usize = 64 * 1024;

/// Verify a signed offline `.lic` file (a path, or the token itself) with zero
/// network calls: signature, product, expiry, device and OS lock. Returns the
/// signed payload. The expiry uses the local clock, which the user controls —
/// keep offline files short-lived.
pub fn verify_offline_license(public_key: &str, token_or_path: &str, hwid: Option<&str>, expected_product_id: Option<&str>) -> Result<Map<String, Value>> {
    let mut token = token_or_path.to_string();
    let too_large = || Error::Signature(format!("License file is too large ({} KB at most)", MAX_LICENSE_FILE / 1024));
    if !token.contains('\n') && token.len() < 4096 && Path::new(&token).is_file() {
        // A license file is a few hundred bytes: a huge one is refused before it is read.
        let len = std::fs::metadata(&token).map(|m| m.len()).unwrap_or(u64::MAX);
        if len > MAX_LICENSE_FILE as u64 { return Err(too_large()); }
        let mut buf = String::new();
        use std::io::Read;
        std::fs::File::open(&token).and_then(|f| f.take(MAX_LICENSE_FILE as u64 + 1).read_to_string(&mut buf))
            .map_err(|_| Error::Signature("License file could not be read".into()))?;
        token = buf;
    }
    let token = token.trim();
    if token.len() > MAX_LICENSE_FILE { return Err(too_large()); }
    let bad = || Error::Signature("Invalid or tampered license file".into());

    let mut parts = token.split('.');
    let (Some(payload_b64), Some(sig_b64), None) = (parts.next(), parts.next(), parts.next()) else { return Err(bad()) };
    let key_bytes: [u8; 32] = B64.decode(public_key.trim()).map_err(|_| bad())?.try_into().map_err(|_| bad())?;
    let key = VerifyingKey::from_bytes(&key_bytes).map_err(|_| bad())?;
    let sig = Signature::from_slice(&B64.decode(sig_b64).map_err(|_| bad())?).map_err(|_| bad())?;
    key.verify_strict(payload_b64.as_bytes(), &sig).map_err(|_| bad())?;
    let data = match serde_json::from_slice::<Value>(&B64.decode(payload_b64).map_err(|_| bad())?) {
        Ok(Value::Object(m)) => m,
        _ => return Err(bad()),
    };

    if let Some(want) = expected_product_id {
        let got = data.get("product_id").and_then(Value::as_str).unwrap_or("");
        if got != want { return Err(Error::ProductMismatch { expected: want.to_string(), actual: got.to_string() }); }
    }
    match data.get("expires_at") {
        None | Some(Value::Null) => {}
        Some(v) if v.as_i64() == Some(0) => {}
        Some(v) => {
            let exp = v.as_f64().ok_or_else(|| Error::InvalidLicense { status: 0, message: "License file has an unreadable expiry".into() })?;
            let now = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs_f64()).unwrap_or(0.0);
            if now > exp { return Err(Error::InvalidLicense { status: 0, message: "License file has expired".into() }); }
        }
    }
    let me = hwid.map(str::to_string).unwrap_or_else(get_hwid);
    if let Some(h) = data.get("hwid").and_then(Value::as_str).filter(|h| !h.is_empty()) {
        if h != me { return Err(Error::InvalidLicense { status: 0, message: "License file is not valid for this machine".into() }); }
    }
    if let Some(os) = data.get("os_lock").and_then(Value::as_str).filter(|o| !o.is_empty()) {
        if os != detect_os() { return Err(Error::InvalidLicense { status: 0, message: "License file is not valid on this operating system".into() }); }
    }
    Ok(data)
}