keylight 0.3.5

Keylight licensing SDK — activate/validate licenses with offline Ed25519 lease verification.
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
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
//! The [`Keylight`] client: activation, validation, deactivation, offline state
//! resolution, trials, the keyless beacon, refresh timing, and lifecycle events.

use crate::clock::{clock_manipulated, clock_rolled_back};
use crate::http::retry::{MAX_ATTEMPTS, RetryDecision, backoff_ms, clamp_sleep_ms, decide};
use crate::http::{Transport, TransportOutcome, ureq_transport::UreqTransport};
use crate::state::{KeylessState, LicenseState, TrialStatus, resolve_state};
use crate::store::device::{DeviceIdentity, SystemDeviceIdentity};
use crate::store::{LicenseStore, account, encrypted_file::EncryptedFileStore};
use crate::{KeylightConfig, KeylightError, Lease, Result, telemetry, verify_lease};
use serde::Deserialize;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

#[derive(Debug, Clone)]
pub struct ActivationResult {
    pub activated: bool,
    pub instance_id: Option<String>,
    pub lease: Option<Lease>,
    pub license_expires_at: Option<i64>,
    pub error: Option<String>,
}
#[derive(Debug, Clone)]
pub struct ValidationResult {
    pub valid: bool,
    pub lease: Option<Lease>,
    pub license_expires_at: Option<i64>,
    pub error: Option<String>,
}

#[derive(Deserialize)]
struct ActivateResp {
    activated: bool,
    instance_id: Option<String>,
    license_expires_at: Option<i64>,
    lease: Option<Lease>,
    error: Option<String>,
}
#[derive(Deserialize)]
struct ValidateResp {
    /// Defaults to `false` when absent: the real worker's revoked /
    /// instance-not-active response is `{"error": "..."}` with no `valid`
    /// field at all, and that must be treated as a definitive rejection,
    /// not fail to deserialize.
    #[serde(default)]
    valid: bool,
    license_expires_at: Option<i64>,
    lease: Option<Lease>,
    error: Option<String>,
}
#[derive(Deserialize)]
struct ErrorResp {
    error: Option<String>,
}

pub struct Keylight {
    config: KeylightConfig,
    store: Arc<dyn LicenseStore>,
    transport: Arc<dyn Transport>,
    device: Arc<dyn DeviceIdentity>,
    on_event: Option<Box<dyn Fn(crate::state::LicenseLifecycleEvent) + Send + Sync>>,
    /// Debounce anchor for [`Keylight::active_revalidate`] — monotonic, so a
    /// wall-clock change can neither stretch nor shrink the window. See that
    /// method for why the window is deliberately per-process and unpersisted.
    last_active_revalidate_at: Mutex<Option<Instant>>,
}

impl Keylight {
    /// Construct with the default encrypted-file store + ureq transport.
    pub fn new(config: KeylightConfig) -> Result<Self> {
        let ns = format!("{}-{}", config.tenant_id, config.product_id);
        let store = Arc::new(EncryptedFileStore::new(&ns)?);
        Ok(Self::with_parts(
            config,
            store,
            Arc::new(UreqTransport::default()),
        ))
    }
    /// Construct with custom store + transport (tests, alternate backends).
    pub fn with_parts(
        config: KeylightConfig,
        store: Arc<dyn LicenseStore>,
        transport: Arc<dyn Transport>,
    ) -> Self {
        Self {
            config,
            store,
            transport,
            device: Arc::new(SystemDeviceIdentity),
            on_event: None,
            last_active_revalidate_at: Mutex::new(None),
        }
    }
    /// Register a handler invoked when the resolved license state crosses a lifecycle transition.
    pub fn with_event_handler(
        mut self,
        handler: impl Fn(crate::state::LicenseLifecycleEvent) + Send + Sync + 'static,
    ) -> Self {
        self.on_event = Some(Box::new(handler));
        self
    }
    /// Override the device identity used for `machine_hash` on the keyless heartbeat
    /// (tests, alternate platforms). Defaults to [`SystemDeviceIdentity`].
    pub fn with_device(mut self, device: Arc<dyn DeviceIdentity>) -> Self {
        self.device = device;
        self
    }

    fn request_id() -> String {
        use rand::Rng;
        let n: u32 = rand::thread_rng().r#gen();
        format!("{n:08x}")
    }
    fn headers(&self) -> Vec<(String, String)> {
        let mut h = vec![
            ("Content-Type".into(), "application/json".into()),
            ("X-Keylight-Request-Id".into(), Self::request_id()),
        ];
        if !self.config.sdk_key.is_empty() {
            h.push(("X-Keylight-SDK-Key".into(), self.config.sdk_key.clone()));
        }
        h
    }
    fn body_with_telemetry(&self, mut map: serde_json::Map<String, serde_json::Value>) -> String {
        telemetry::apply(&mut map, self.config.app_version.as_deref());
        serde_json::Value::Object(map).to_string()
    }

    /// True hardware id with a persisted cache: a fresh OS read wins (and refreshes the
    /// cache); on a transient read failure the last successfully read id is reused so the
    /// derived `machine_hash` stays stable across beacons. NO random fallback — if no id
    /// has ever been read this returns `None` and callers omit the field.
    fn cached_hardware_id(&self) -> Option<String> {
        match self.device.hardware_id() {
            Some(hw) => {
                let _ = self.store.set_string(account::CACHED_HARDWARE_ID, &hw);
                Some(hw)
            }
            None => self.store.get_string(account::CACHED_HARDWARE_ID),
        }
    }
    /// Cross-SDK `machine_hash` (lowercase hex) from the cached hardware id, if any.
    fn machine_hash(&self) -> Option<String> {
        self.cached_hardware_id().map(|hw| {
            crate::machine::machine_hash(&self.config.tenant_id, &self.config.product_id, &hw)
        })
    }

    /// POST with retry/backoff. `decodable_4xx` lets a caller opt a 4xx body in (validate's 422).
    fn post(&self, path: &str, body: &str, decodable_4xx: &[u16]) -> Result<(u16, String)> {
        let url = self.api_url(path);
        let headers = self.headers();
        let mut attempt = 0u32;
        loop {
            attempt += 1;
            match self.transport.post_json(&url, &headers, body) {
                TransportOutcome::Response(r) => {
                    if r.status == 200 || decodable_4xx.contains(&r.status) {
                        return Ok((r.status, r.body));
                    }
                    match decide(r.status, attempt, r.retry_after) {
                        RetryDecision::RetryAfter(ms) => {
                            std::thread::sleep(std::time::Duration::from_millis(ms + jitter_ms()));
                            continue;
                        }
                        RetryDecision::Stop => {
                            if r.status == 429 {
                                return Err(KeylightError::RateLimited {
                                    retry_after: r.retry_after.unwrap_or(0),
                                });
                            }
                            if (500..=599).contains(&r.status) || r.status == 408 {
                                return Err(KeylightError::ServerError { status: r.status });
                            }
                            let msg = serde_json::from_str::<ErrorResp>(&r.body)
                                .ok()
                                .and_then(|e| e.error)
                                .unwrap_or_default();
                            return Err(KeylightError::ClientError {
                                status: r.status,
                                message: msg,
                            });
                        }
                    }
                }
                TransportOutcome::Transient(_) if attempt < MAX_ATTEMPTS => {
                    std::thread::sleep(std::time::Duration::from_millis(
                        clamp_sleep_ms(backoff_ms(attempt)) + jitter_ms(),
                    ));
                    continue;
                }
                TransportOutcome::Transient(e) | TransportOutcome::Terminal(e) => {
                    return Err(KeylightError::NetworkFailure(e));
                }
                TransportOutcome::Timeout => return Err(KeylightError::Timeout),
            }
        }
    }

    fn now() -> i64 {
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs() as i64)
            .unwrap_or(0)
    }

    fn api_url(&self, path: &str) -> String {
        format!(
            "{}/{}/{}/{}",
            self.config.base_url, self.config.tenant_id, self.config.product_id, path
        )
    }

    /// Verify a lease against the configured trusted keys at the current time.
    fn verify(&self, lease: &Lease) -> crate::VerifyResult {
        verify_lease(
            lease,
            &self.config.trusted_keys,
            Self::now(),
            crate::SKEW_SECONDS,
        )
    }

    fn verify_or_reject(&self, lease: &Lease) -> Result<()> {
        if self.verify(lease).is_trusted() {
            Ok(())
        } else {
            Err(KeylightError::LeaseVerificationFailed)
        }
    }

    pub fn activate(&self, key: &str) -> Result<ActivationResult> {
        if !self.config.validate_key_format(key) {
            return Ok(ActivationResult {
                activated: false,
                instance_id: None,
                lease: None,
                license_expires_at: None,
                error: Some("Invalid license key format".into()),
            });
        }
        let machine = machine_name();
        let mut map = serde_json::Map::new();
        map.insert("license_key".into(), key.into());
        map.insert("instance_name".into(), machine.into());
        if let Some(ft) = self.store.get_string(account::FREE_TIER_INSTANCE_ID) {
            map.insert("free_tier_instance_id".into(), ft.into());
        }
        if let Some(hash) = self.machine_hash() {
            map.insert("machine_hash".into(), hash.into());
        }
        let body = self.body_with_telemetry(map);

        let (_, text) = match self.post("activate", &body, &[]) {
            Ok(v) => v,
            Err(KeylightError::ClientError { status, message }) => {
                return Ok(ActivationResult {
                    activated: false,
                    instance_id: None,
                    lease: None,
                    license_expires_at: None,
                    error: Some(if message.is_empty() {
                        format!("Activation failed (HTTP {status})")
                    } else {
                        message
                    }),
                });
            }
            Err(e) => return Err(e),
        };
        let resp: ActivateResp =
            serde_json::from_str(&text).map_err(|_| KeylightError::InvalidResponse)?;
        if !resp.activated {
            return Ok(ActivationResult {
                activated: false,
                instance_id: None,
                lease: None,
                license_expires_at: None,
                error: resp.error.or(Some("Activation failed".into())),
            });
        }
        if let Some(lease) = &resp.lease {
            self.verify_or_reject(lease)?;
        }

        self.store.set_string(account::LICENSE_KEY, key)?;
        if let Some(id) = &resp.instance_id {
            self.store.set_string(account::INSTANCE_ID, id)?;
        }
        if let Some(lease) = &resp.lease {
            self.store_lease(lease)?;
        }
        self.save_expiry(resp.license_expires_at)?;
        self.touch_last_seen()?;
        self.touch_validated_online()?;
        Ok(ActivationResult {
            activated: true,
            instance_id: resp.instance_id,
            lease: resp.lease,
            license_expires_at: resp.license_expires_at,
            error: None,
        })
    }

    pub fn validate(&self) -> Result<ValidationResult> {
        let key = self
            .store
            .get_string(account::LICENSE_KEY)
            .ok_or(KeylightError::NoStoredLicense)?;
        let instance = self
            .store
            .get_string(account::INSTANCE_ID)
            .ok_or(KeylightError::NoStoredLicense)?;
        let prev_state = self.state();
        let prev_expiry = self.store.get_i64(account::LICENSE_EXPIRES_AT);
        let mut map = serde_json::Map::new();
        map.insert("license_key".into(), key.into());
        map.insert("instance_id".into(), instance.into());
        if let Some(hash) = self.machine_hash() {
            map.insert("machine_hash".into(), hash.into());
        }
        let body = self.body_with_telemetry(map);

        let (_status, text) = match self.post("validate", &body, &[422]) {
            Ok(v) => v,
            Err(KeylightError::ClientError { status, message }) => {
                return Ok(ValidationResult {
                    valid: false,
                    lease: None,
                    license_expires_at: None,
                    error: Some(if message.is_empty() {
                        format!("Validation failed (HTTP {status})")
                    } else {
                        message
                    }),
                });
            }
            Err(e) => return Err(e),
        };
        let resp: ValidateResp =
            serde_json::from_str(&text).map_err(|_| KeylightError::InvalidResponse)?;
        if let Some(lease) = &resp.lease {
            self.verify_or_reject(lease)?;
        }
        if !resp.valid {
            // Definitive rejection: persist whatever lease the server sent (e.g.
            // "expired"/"fallback" so state() can resolve .limited/.expired), or
            // clear the cached one when it sent none at all. The real worker's
            // revoked/instance-not-active responses are `{"error": "..."}` with
            // no `lease` field, so leaving the old (still "active") lease in
            // place would let state() keep reporting Licensed off stale data.
            match &resp.lease {
                Some(lease) => self.store_lease(lease)?,
                None => self.store.delete(account::LEASE)?,
            }
            self.save_expiry(resp.license_expires_at)?;
            self.emit_lifecycle(&prev_state, prev_expiry);
            return Ok(ValidationResult {
                valid: false,
                lease: resp.lease,
                license_expires_at: resp.license_expires_at,
                error: resp.error,
            });
        }
        if let Some(lease) = &resp.lease {
            self.store_lease(lease)?;
        }
        self.save_expiry(resp.license_expires_at)?;
        self.touch_last_seen()?;
        self.touch_validated_online()?;
        self.emit_lifecycle(&prev_state, prev_expiry);
        Ok(ValidationResult {
            valid: true,
            lease: resp.lease,
            license_expires_at: resp.license_expires_at,
            error: None,
        })
    }

    pub fn deactivate(&self) -> Result<()> {
        let key = self.store.get_string(account::LICENSE_KEY);
        let instance = self.store.get_string(account::INSTANCE_ID);
        let mut net_err = None;
        if let (Some(k), Some(i)) = (key, instance) {
            let mut map = serde_json::Map::new();
            map.insert("license_key".into(), k.into());
            map.insert("instance_id".into(), i.into());
            let body = self.body_with_telemetry(map);
            if let Err(e) = self.post("deactivate", &body, &[]) {
                net_err = Some(e);
            }
        }
        for a in [
            account::LICENSE_KEY,
            account::INSTANCE_ID,
            account::LEASE,
            account::LICENSE_EXPIRES_AT,
            account::LAST_VALIDATED_ONLINE,
            account::LAST_SEEN,
        ] {
            self.store.delete(a)?;
        }
        net_err.map_or(Ok(()), Err)
    }

    pub fn cached_lease(&self) -> Option<Lease> {
        if let Some(max_days) = self.config.max_offline_days {
            let last = self.store.get_i64(account::LAST_VALIDATED_ONLINE)?;
            if Self::now() - last > (max_days as i64) * 86400 {
                return None;
            }
        }
        let lease: Lease = serde_json::from_str(&self.store.get_string(account::LEASE)?).ok()?;
        let r = self.verify(&lease);
        if r.is_trusted() && !r.expired && lease.status != "expired" {
            Some(lease)
        } else {
            None
        }
    }

    pub fn has_entitlement(&self, feature: &str) -> bool {
        self.cached_lease()
            .map(|l| l.entitlements.iter().any(|e| e == feature))
            .unwrap_or(false)
    }
    pub fn has_stored_license(&self) -> bool {
        self.store.get_string(account::LICENSE_KEY).is_some()
    }
    pub fn cached_license_key(&self) -> Option<String> {
        self.store.get_string(account::LICENSE_KEY)
    }
    /// The cached license expiry (epoch seconds), if one was stored on the last
    /// activate/validate. Parity with Swift `getCachedLicenseExpiresAt`.
    pub fn cached_license_expires_at(&self) -> Option<i64> {
        self.store.get_i64(account::LICENSE_EXPIRES_AT)
    }

    /// Persist a verified lease. Serializing a `Lease` (only owned strings, integers,
    /// and a string vec) cannot fail, so a serialization error here would be a logic
    /// bug rather than a recoverable condition.
    fn store_lease(&self, lease: &Lease) -> Result<()> {
        let json = serde_json::to_string(lease).expect("Lease serializes to JSON infallibly");
        self.store.set_string(account::LEASE, &json)
    }
    fn save_expiry(&self, e: Option<i64>) -> Result<()> {
        match e {
            Some(v) => self
                .store
                .set_string(account::LICENSE_EXPIRES_AT, &v.to_string()),
            None => self.store.delete(account::LICENSE_EXPIRES_AT),
        }
    }
    fn touch_last_seen(&self) -> Result<()> {
        self.store
            .set_string(account::LAST_SEEN, &Self::now().to_string())
    }
    fn touch_validated_online(&self) -> Result<()> {
        self.store
            .set_string(account::LAST_VALIDATED_ONLINE, &Self::now().to_string())
    }
}

impl Keylight {
    pub fn start_trial(&self) -> Result<()> {
        if self.store.get_string(account::TRIAL_START).is_none() {
            self.store
                .set_string(account::TRIAL_START, &Self::now().to_string())?;
        }
        if self
            .store
            .get_string(account::FREE_TIER_INSTANCE_ID)
            .is_none()
        {
            self.store.set_string(
                account::FREE_TIER_INSTANCE_ID,
                &crate::store::device::uuid_v4_pub(),
            )?;
        }
        Ok(())
    }
    pub fn check_trial(&self) -> TrialStatus {
        let start = match self.store.get_i64(account::TRIAL_START) {
            Some(v) => v,
            None => return TrialStatus::NotStarted,
        };
        let days_elapsed = (Self::now() - start) / 86400;
        let days_left = self.config.trial_duration_days as i64 - days_elapsed;
        if days_left > 0 {
            TrialStatus::Active { days_left }
        } else {
            TrialStatus::Expired
        }
    }
    pub fn is_clock_manipulated(&self) -> bool {
        let manipulated = self
            .store
            .get_i64(account::LAST_SEEN)
            .is_some_and(|last| clock_manipulated(last, Self::now()));
        if !manipulated {
            let _ = self.touch_last_seen();
        }
        manipulated
    }
    pub fn free_tier_instance_id(&self) -> Result<String> {
        if let Some(id) = self.store.get_string(account::FREE_TIER_INSTANCE_ID) {
            return Ok(id);
        }
        let id = crate::store::device::uuid_v4_pub();
        self.store.set_string(account::FREE_TIER_INSTANCE_ID, &id)?;
        Ok(id)
    }
    /// Anonymous keyless beacon, debounced 24h or on state change. Errors swallowed.
    pub fn report_keyless_state(&self, state: KeylessState) {
        let last_state = self.store.get_string(account::KEYLESS_LAST_STATE);
        let last_ping = self.store.get_i64(account::LAST_KEYLESS_PING_AT);
        let changed = last_state.as_deref() != Some(state.wire());
        let within = last_ping.map(|t| Self::now() - t < 86400).unwrap_or(false);
        if !changed && within {
            return;
        }
        let instance = match self.free_tier_instance_id() {
            Ok(i) => i,
            Err(_) => return,
        };
        let mut map = serde_json::Map::new();
        map.insert("instance_id".into(), instance.into());
        map.insert("state".into(), state.wire().into());
        if let Some(hash) = self.machine_hash() {
            map.insert("machine_hash".into(), hash.into());
        }
        let body = self.body_with_telemetry(map);
        // Route through the shared retry/backoff loop; with no decodable 4xx an
        // `Ok` here is exactly an HTTP 200, so the debounce state is persisted
        // only on success. Errors are swallowed (anonymous best-effort beacon).
        if self.post("keyless", &body, &[]).is_ok() {
            let _ = self
                .store
                .set_string(account::KEYLESS_LAST_STATE, state.wire());
            let _ = self
                .store
                .set_string(account::LAST_KEYLESS_PING_AT, &Self::now().to_string());
        }
    }
    /// Resolve the current high-level state from cached data (no network).
    pub fn state(&self) -> LicenseState {
        // Backward clock-rollback guard: if the system clock has jumped back more
        // than the tolerance since our last recorded contact, refuse to resolve a
        // usable state — this is the offline vector for reviving an expired lease.
        // Read-only (does not touch `last_seen`); the forward-jump component lives
        // in `is_clock_manipulated()`. Self-heals on the next successful
        // `validate()`, which re-anchors `last_seen`.
        if self
            .store
            .get_i64(account::LAST_SEEN)
            .is_some_and(|last| clock_rolled_back(last, Self::now()))
        {
            return LicenseState::Invalid;
        }
        // Offline bound: a validated license must not run forever without a
        // successful server re-check. When `max_offline_days` is configured the
        // cached lease is only usable if we have a `last_validated_online` anchor
        // within the cap. Both a *stale* anchor (older than the cap) and a
        // *missing* anchor are fail-closed — the latter matters because an
        // attacker who deletes the anchor to reset the offline clock must not
        // thereby revive the lease. This mirrors `cached_lease()` (whose `?` on
        // `get_i64` already short-circuits a missing anchor) and Swift's
        // `isWithinOfflineGrace`. When `max_offline_days` is `None` the cap is
        // disabled entirely (unlimited offline). Dropping the lease here lets a
        // stored license fall through to `Expired` via the `had_stored_license`
        // path in `resolve_state`, while trials / free-tier (no lease, no license)
        // are unaffected.
        let offline_bound_ok = match self.config.max_offline_days {
            Some(max_days) => self
                .store
                .get_i64(account::LAST_VALIDATED_ONLINE)
                .is_some_and(|last| Self::now() - last <= (max_days as i64) * 86400),
            None => true,
        };
        let lease = self
            .store
            .get_string(account::LEASE)
            .and_then(|s| serde_json::from_str::<Lease>(&s).ok());
        let (status, current) = match &lease {
            Some(l) if offline_bound_ok => {
                let r = self.verify(l);
                (r.is_trusted().then(|| l.status.clone()), !r.expired)
            }
            _ => (None, false),
        };
        resolve_state(
            status.as_deref(),
            current,
            self.has_stored_license(),
            &self.check_trial(),
            self.config.free_tier_enabled,
        )
    }
}

impl Keylight {
    /// Validate now only if enough time has passed (debounce 5min, stale 6h, or near expiry).
    pub fn refresh_if_needed(&self) -> Result<Option<ValidationResult>> {
        if !self.has_stored_license() {
            return Ok(None);
        }
        if let Some(last) = self.store.get_i64(account::LAST_VALIDATED_ONLINE) {
            let now = Self::now();
            if now - last < REFRESH_DEBOUNCE {
                return Ok(None);
            }
            let near_expiry = self
                .store
                .get_i64(account::LICENSE_EXPIRES_AT)
                .is_some_and(|exp| exp - now < 86400);
            if now - last < REFRESH_STALE && !near_expiry {
                return Ok(None);
            }
        }
        Ok(Some(self.validate()?))
    }
    /// Called on app launch: if a license is stored, **always** validate against
    /// the server (no staleness gate — unlike [`Self::refresh_if_needed`]), so a
    /// dashboard revoke or genuine expiry takes effect on the very next launch
    /// rather than lagging behind the in-session refresh cadence. `validate()`
    /// does not mutate state on a transient/network error, so a launch with no
    /// connectivity keeps running on the existing cached lease (last-known-good),
    /// subject to the offline bound enforced by [`Self::state`].
    pub fn check_on_launch(&self) -> Result<()> {
        if self.has_stored_license() {
            let _ = self.validate()?;
        }
        Ok(())
    }
    /// Force a re-validation on **active use** — app foreground, window focus,
    /// popover open — debounced to 60s in memory (parity with Swift
    /// `activeRevalidate()`).
    ///
    /// Unlike [`Self::refresh_if_needed`] this bypasses the debounce/stale/
    /// near-expiry gates entirely, so a dashboard revoke lands within minutes of
    /// the user next touching the app instead of waiting for the lease to go
    /// stale (up to 6h) or for a relaunch (up to the full lease lifetime).
    ///
    /// Behavior:
    /// - **No stored license key** — no-op, no network call, returns `None`.
    /// - **Inside the 60s window** — suppressed, returns `None`. The window is
    ///   in-memory only: it does not survive a process restart, and it is
    ///   consumed by the *attempt*, so a failed call also holds it (matching
    ///   Swift, and keeping a hammered foreground hook off the network).
    /// - **Definitive rejection** (`valid:false`, e.g. the revoke path's HTTP
    ///   422) — downgrades immediately through the same [`Self::validate`]
    ///   rejection branch, and returns `Some(result)` with `valid == false`.
    /// - **Transient failure** (offline, timeout, 5xx, rate limit) — returns
    ///   `None` with state untouched. This is the safety property: a network
    ///   blip must never downgrade a live session. `validate()` mutates nothing
    ///   on the error path, so the cached lease survives intact and access stays
    ///   governed by the offline bound in [`Self::state`].
    ///
    /// The error is intentionally swallowed rather than returned: this is a
    /// fire-and-forget UI hook whose whole contract is "never break the running
    /// session", so there is no failure a caller could act on differently. Use
    /// [`Self::validate`] directly when you need the error.
    pub fn active_revalidate(&self) -> Option<ValidationResult> {
        if !self.has_stored_license() {
            return None;
        }
        {
            // A panic while holding this lock is not reachable (the guarded
            // section is two moves), so recover from poisoning rather than
            // letting an unrelated panic elsewhere disable revalidation.
            let mut last = self
                .last_active_revalidate_at
                .lock()
                .unwrap_or_else(|e| e.into_inner());
            if last.is_some_and(|t| t.elapsed() < ACTIVE_REVALIDATE_DEBOUNCE) {
                return None;
            }
            *last = Some(Instant::now());
        }
        self.validate().ok()
    }

    /// Hosted upgrade URL pre-filled with the cached key (parity with Swift upgradeURL).
    pub fn upgrade_url(&self) -> Option<String> {
        let key = self.cached_license_key()?;
        Some(format!(
            "https://portal.keylight.dev/p/{}/upgrade/{}?key={}",
            self.config.tenant_id,
            self.config.product_id,
            urlencode(&key)
        ))
    }

    /// Compute the post-validation state and fire a lifecycle event if the resolved
    /// state crossed a transition. The previous state is re-derived from the persisted
    /// lease on each call (so transitions don't re-fire across restarts). Errors swallowed.
    fn emit_lifecycle(&self, prev_state: &LicenseState, prev_expiry: Option<i64>) {
        let next_state = self.state();
        // Option<i64> ordering: None < Some(_), so this is true exactly when a new
        // expiry exists and is later than the previous one (or there was none).
        let expiry_moved_later = self.store.get_i64(account::LICENSE_EXPIRES_AT) > prev_expiry;
        if let Some(ev) = crate::state::lifecycle_event(prev_state, &next_state, expiry_moved_later)
        {
            if let Some(h) = &self.on_event {
                h(ev);
            }
        }
    }
}

const REFRESH_DEBOUNCE: i64 = 300; // 5 min
const REFRESH_STALE: i64 = 21600; // 6 h
/// In-memory floor between two `active_revalidate()` network calls (Swift parity).
const ACTIVE_REVALIDATE_DEBOUNCE: Duration = Duration::from_secs(60);

fn urlencode(s: &str) -> String {
    use std::fmt::Write;
    let mut out = String::with_capacity(s.len());
    for b in s.bytes() {
        match b {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
                out.push(b as char)
            }
            _ => {
                let _ = write!(out, "%{b:02X}");
            }
        }
    }
    out
}

/// Best-effort human-readable machine name for the activation's `instance_name`
/// (display only — the seat identity is the server-issued `instance_id`). Falls back
/// through common env vars and the `hostname` command before a generic default.
fn machine_name() -> String {
    for var in ["HOSTNAME", "COMPUTERNAME", "HOST"] {
        if let Ok(v) = std::env::var(var) {
            let v = v.trim().to_string();
            if !v.is_empty() {
                return v;
            }
        }
    }
    if let Ok(out) = std::process::Command::new("hostname").output() {
        let v = String::from_utf8_lossy(&out.stdout).trim().to_string();
        if !v.is_empty() {
            return v;
        }
    }
    "device".to_string()
}

/// Small random backoff jitter (0..250ms) to avoid synchronized retries
/// (the retry policy in `http::retry` stays pure; jitter is applied here).
fn jitter_ms() -> u64 {
    use rand::Rng;
    rand::thread_rng().gen_range(0..250)
}