licers 1.0.1

Licers license-key verification: Ed25519-signed responses, floating seats, usage credits, remote variables, offline licenses.
Documentation
//! A stable id for this machine: SHA-256 of `"licers:" + OS machine id`
//! (Windows MachineGuid, Linux /etc/machine-id, macOS IOPlatformUUID) — the
//! same value the Node and .NET SDKs produce on the same machine. Where none can
//! be read, a random id is stored once in the user's data folder.

use sha2::{Digest, Sha256};
use std::fs::{self, OpenOptions};
use std::io::Write;
use std::path::PathBuf;
use std::process::Command;
use std::sync::OnceLock;

static CACHED: OnceLock<String> = OnceLock::new();

fn run(cmd: &str, args: &[&str]) -> Option<String> {
    let mut c = Command::new(cmd);
    c.args(args);
    #[cfg(windows)]
    {
        use std::os::windows::process::CommandExt;
        c.creation_flags(0x0800_0000); // CREATE_NO_WINDOW
    }
    let out = c.output().ok()?;
    String::from_utf8(out.stdout).ok()
}

fn os_machine_id() -> Option<String> {
    if cfg!(windows) {
        let out = run("reg", &["query", r"HKLM\SOFTWARE\Microsoft\Cryptography", "/v", "MachineGuid", "/reg:64"])?;
        let line = out.lines().find(|l| l.contains("MachineGuid"))?;
        let id = line.split_whitespace().last()?;
        return (id.len() == 36).then(|| id.to_string());
    }
    if cfg!(target_os = "macos") {
        let out = run("ioreg", &["-rd1", "-c", "IOPlatformExpertDevice"])?;
        let line = out.lines().find(|l| l.contains("\"IOPlatformUUID\""))?;
        let v = line.split('=').nth(1)?.trim().trim_matches('"');
        return (!v.is_empty()).then(|| v.to_string());
    }
    for f in ["/etc/machine-id", "/var/lib/dbus/machine-id"] {
        if let Ok(s) = fs::read_to_string(f) {
            let s = s.trim();
            if !s.is_empty() {
                return Some(s.to_string());
            }
        }
    }
    None
}

fn data_dir() -> PathBuf {
    if let Some(d) = std::env::var_os("LICERS_HWID_DIR") {
        return PathBuf::from(d);
    }
    let home = std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" }).map(PathBuf::from).unwrap_or_default();
    if cfg!(windows) {
        std::env::var_os("LOCALAPPDATA").map(PathBuf::from).unwrap_or(home).join("licers")
    } else if cfg!(target_os = "macos") {
        home.join("Library/Application Support/licers")
    } else {
        std::env::var_os("XDG_DATA_HOME").map(PathBuf::from).unwrap_or_else(|| home.join(".local/share")).join("licers")
    }
}

/// Created exactly once even when several processes start together:
/// `create_new` lets the first writer win and everyone else adopts its id.
fn stored_id() -> String {
    let dir = data_dir();
    let file = dir.join("device_id");
    let read = || fs::read_to_string(&file).ok().map(|s| s.trim().to_string()).filter(|s| !s.is_empty());
    if let Some(id) = read() {
        return id;
    }
    let mut buf = [0u8; 16];
    let _ = getrandom::getrandom(&mut buf);
    let fresh: String = buf.iter().map(|b| format!("{b:02x}")).collect();
    let _ = fs::create_dir_all(&dir);
    match OpenOptions::new().write(true).create_new(true).open(&file) {
        Ok(mut f) => {
            let _ = f.write_all(fresh.as_bytes());
            fresh
        }
        Err(_) => read().unwrap_or(fresh),
    }
}

/// This machine's device id: 64 lowercase hex characters, stable across runs.
pub fn get_hwid() -> String {
    CACHED
        .get_or_init(|| {
            let source = os_machine_id().unwrap_or_else(stored_id);
            let digest = Sha256::digest(format!("licers:{source}").as_bytes());
            digest.iter().map(|b| format!("{b:02x}")).collect()
        })
        .clone()
}

/// "windows" | "macos" | "linux" | "" — the names the server uses.
pub fn detect_os() -> &'static str {
    if cfg!(target_os = "macos") {
        "macos"
    } else if cfg!(windows) {
        "windows"
    } else if cfg!(any(target_os = "linux", target_os = "android")) {
        "linux"
    } else {
        ""
    }
}

pub(crate) fn platform_string() -> String {
    let os = if cfg!(windows) { "Windows" } else if cfg!(target_os = "macos") { "Darwin" } else if cfg!(target_os = "linux") { "Linux" } else { std::env::consts::OS };
    format!("{os} {}", std::env::consts::ARCH)
}