licers 1.2.1

Licers license-key verification: Ed25519-signed responses, floating seats, usage credits, remote variables, offline licenses.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
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");

/// A key's credit balance, from a signed answer.
#[derive(Debug, Clone, PartialEq)]
pub struct Usage {
    pub used: i64,
    /// `None` = no cap.
    pub limit: Option<i64>,
    /// `None` (one-time pack), `"daily"` or `"monthly"`.
    pub reset: Option<String>,
    pub resets_at: Option<String>,
    /// Credits this call spent (0 for a read).
    pub spent: i64,
}
impl Usage {
    pub fn remaining(&self) -> Option<i64> { self.limit.map(|l| (l - self.used).max(0)) }
}

/// Outcome of [`LicenseClient::validate`].
#[derive(Debug, Clone)]
pub struct ValidationResult {
    pub valid: bool,
    pub product_id: Option<String>,
    /// ISO date, or `None` for a lifetime key.
    pub expires_at: Option<String>,
    /// Signed entitlements, e.g. `{"pro": true}`.
    pub features: Map<String, Value>,
    /// Credit balance for usage-based keys (signature-checked).
    pub usage: Option<Usage>,
    /// The server's message when not valid.
    pub error: Option<String>,
    /// Signed SDK-upgrade notice for the developer.
    pub notice: Option<String>,
    /// True when `key` was a sign-in token that stopped working (signed out or
    /// the license ended): forget it and sign in again.
    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,
    /// From a license server: when its server file ends. No seat lasts beyond it.
    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,
    /// NOT covered by the signature: check it is HTTPS on a host you expect.
    pub download_url: Option<String>,
    /// NOT covered by the signature.
    pub notes: Option<String>,
}

/// Builder for [`LicenseClient`].
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 {
    /// `api_url` is a customer's own Licers License Server. Only then is an
    /// answer signed by a license server's key accepted, and only for validate,
    /// lease and heartbeat: usage credits, remote variables and update checks
    /// always need your account's signature.
    pub fn local_server(mut self, on: bool) -> Self { self.local_server = on; self }
    /// License server base URL. Default `https://licers.com`.
    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 }
    /// The product this build is licensed for. Set it if you sell more than one
    /// product: one keypair signs for the whole account.
    pub fn product_id(mut self, id: impl Into<String>) -> Self { self.product_id = Some(id.into()); self }
    /// Your app's version ("2.4.1"), shown in the dashboard's Analytics.
    pub fn app_version(mut self, v: impl Into<String>) -> Self { self.app_version = Some(v.into().chars().take(40).collect()); self }
    /// Use this device id instead of [`get_hwid`].
    pub fn hwid(mut self, h: impl Into<String>) -> Self { self.hwid = Some(h.into()); self }
    /// Receives the server's signed "please upgrade the SDK" message, once.
    pub fn on_notice(mut self, f: impl Fn(&str) + Send + Sync + 'static) -> Self { self.on_notice = Some(Box::new(f)); self }
    /// For SDKs built on this crate (the C/C++ and Go wrappers): the User-Agent
    /// the server records in Analytics, e.g. `licers-c/1.0.0`.
    #[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()))?;
        // Never follow redirects: the request body carries the license key.
        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,
        })
    }
}

/// Verifies license keys against a Licers server. Every answer the app relies
/// on is Ed25519-signed with your account key and checked here, with a fresh
/// nonce each call, so a fake or replayed server response is refused.
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,
}

/// A local license server's file (sdks/server/FORMAT.md), checked with the
/// account key. Entitlements, end date and seat count come from here, never
/// from the server's answer.
#[derive(Clone)]
struct ServerFile { product_id: String, seats: i64, expires_at: i64, features: Map<String, Value>, key: VerifyingKey }

/// A sign-in token ("lst_...") goes in `token`, a license key in `key`.
fn key_body(key: &str) -> Value {
    if key.starts_with("lst_") { json!({ "token": key }) } else { json!({ "key": key }) }
}

/// The error for a refused call: SignedOut when a sign-in token stopped working.
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) }

/// Unix seconds as the server writes dates: "2100-01-01T00:00:00.000Z".
fn iso(secs: i64) -> String {
    let days = secs.div_euclid(86_400);
    let rem = secs.rem_euclid(86_400);
    // Civil from days (Howard Hinnant's algorithm).
    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 };
    // verify_strict: refuses non-canonical and small-order encodings.
    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()
}

/// Mirror of the server's sigPart(): null -> "", booleans -> "1"/"0".
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 {
    /// A client for the hosted service with default options.
    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) }

    /// A key's request body, with the product pin (a local license server picks its file by it).
    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
    }

    // ---- local license server ---------------------------------------------------
    /// Check a local license server's file with YOUR account key. The server signs
    /// answers with its own key; this file, signed by your account key, names that
    /// key and what the server may hand out.
    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)
    }

    /// The key that must have signed this answer, and the server file if a local
    /// license server sent it. A license server's key counts only with
    /// `local_server(true)`, and only for what a license server does (`from_server`).
    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(())
    }

    /// Verify `parts|issued_at` and the echoed nonce. Fails closed.
    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"))),
        }
    }

    // ---- validation --------------------------------------------------------------
    /// Validate a key online. A refusal is `Ok` with `valid == false`; a forged or
    /// replayed answer is [`Error::Signature`]; no network is [`Error::Network`].
    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))));
        }
        // Entitlements come from the SIGNED base64 copy, never the plaintext field.
        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"));
        // From a license server, the file decides entitlements and end date.
        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; }   // forged: ignore, never fail
        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 })
    }

    // ---- usage credits ---------------------------------------------------------------
    /// Spend `amount` credits. The device must already be activated (`validate`).
    /// All-or-nothing; [`Error::UsageExceeded`] when there aren't enough. Not
    /// retried: a network failure may come after the server took the credits.
    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) })
    }

    /// Read the balance without spending anything.
    pub fn get_usage(&self, key: &str) -> Result<Usage> { self.record_usage(key, 0) }

    // ---- remote variables ---------------------------------------------------------------
    /// Every remote variable this key may see (signature-checked).
    pub fn get_variables(&self, key: &str) -> Result<BTreeMap<String, String>> { self.variables(key, None) }

    /// One remote variable, or `None` when it isn't set for this key.
    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())
    }

    // ---- floating licenses -----------------------------------------------------------------
    /// Reserve a concurrent seat. [`Error::SeatUnavailable`] when every seat is taken.
    pub fn lease(&self, key: &str) -> Result<Lease> {
        // The server caps hwid at 200 chars before signing; cap it the same way.
        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,
        })
    }

    /// One heartbeat. `Unconfirmed` (server unreachable) must never extend a seat on its own.
    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"));
        // From a license server: never past the end of its signed file (same ISO format, so text order is time order).
        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)
    }

    /// Free a seat (idempotent; network errors are ignored).
    pub fn release(&self, lease_id: &str) { let _ = self.post("/api/v1/release", json!({ "lease_id": lease_id })); }

    // ---- updates ------------------------------------------------------------------------
    /// Is a newer build out? Signed — including "no update". `download_url` and
    /// `notes` are NOT signed: check the URL and verify the file against a hash you ship.
    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")),
        })
    }

    // ---- sign-in instead of a key -----------------------------------------------
    /// Start signing in. Show [`SignIn::code`], open [`SignIn::url`] in the browser,
    /// then [`SignIn::wait`] for the token. The customer signs in to the customer
    /// portal with the email on their license and approves this device. Needs
    /// `product_id` on the builder, and the product must allow it (Products page,
    /// "Sign in with email").
    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(),
        })
    }

    /// Sign in and return a token to use instead of a license key. Calls
    /// `on_code` so you can show the code and open the URL; then waits for the
    /// approval. Keep the token (it works only on this device) and pass it
    /// wherever a key goes. When it stops working, calls return
    /// [`Error::SignedOut`] (or `validate` gives `signed_out: true`).
    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)
    }

    /// End the sign-in on the server. Forget the token yourself too.
    pub fn sign_out(&self, token: &str) -> Result<()> {
        self.post("/api/v1/signout", json!({ "token": token })).map(|_| ())
    }
}

/// A sign-in waiting for the customer, from [`LicenseClient::start_sign_in`].
pub struct SignIn {
    /// Show this to the user, like `BCDF-GHJK`.
    pub code: String,
    /// Open this in the browser.
    pub url: String,
    /// Seconds until the code runs out.
    pub expires_in: u64,
    /// Who approved, once approved.
    pub email: Option<String>,
    poll: String,
    interval: u64,
    deadline: Instant,
    agent: ureq::Agent,
    api_url: String,
}

impl SignIn {
    /// Ask once: `Some(token)` when approved, else `None`. Errors with
    /// [`Error::SignInDenied`] or [`Error::SignInExpired`].
    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),
        }
    }

    /// Poll until approved and return the token. Network trouble is retried until
    /// the code runs out (or `timeout`, if shorter).
    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");
    }
}