lean-ctx-protocol 0.10.0

Open wire contracts for lean-ctx: events, observations, assignments, evidence gaps.
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
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
// SPDX-License-Identifier: Apache-2.0

//! Device-flow enrollment and instance access tokens.
//!
//! - `POST /v1/device/code` [`DeviceCodeRequestV1`] → [`DeviceCodeV1`]
//! - `POST /v1/device/token` [`DeviceTokenRequestV1`] → [`EnrollmentV1`], or
//!   400 `authorization_pending` / `slow_down` / `expired_token` / `access_denied`,
//!   402 `plan_required`, 409 `instance_limit`
//! - `POST /v1/instances/{instance_id}/token` [`InstanceTokenRequestV1`] → [`AccessTokenV1`]
//! - `POST /v1/instances/{instance_id}/lease/renew` (empty body) → lease envelope
//! - `DELETE /v1/instances/{instance_id}` → 204, frees the seat
//!
//! There is no refresh token: the instance's Ed25519 key is its only
//! long-lived secret and mints short access tokens through a signed assertion.

use serde::{Deserialize, Serialize};
use std::fmt;

pub use super::app_keys::{
    AppKeyAnnouncementV1, AppKeyKind, AppKeyOfferV1, FEATURE_DEVICE_APP_KEYS,
    app_key_bind_signing_input,
};
use super::app_keys::{decode_b64url_exact, validate_app_keys};
use super::lease::{CloudLeaseEnvelopeV1, EnrollmentKeySet};
use super::{
    CLOUD_ENGINE_CLIENT_ID, TOKEN_ASSERTION_DOMAIN, require_schema, validate_b64_len, validate_id,
    validate_text,
};
use crate::ValidationError;

pub const DEVICE_CODE_REQUEST_SCHEMA: &str = "leanctx.cloud.device-code-request/v1";
pub const DEVICE_CODE_SCHEMA: &str = "leanctx.cloud.device-code/v1";
pub const DEVICE_TOKEN_REQUEST_SCHEMA: &str = "leanctx.cloud.device-token-request/v1";
pub const ENROLLMENT_SCHEMA: &str = "leanctx.cloud.enrollment/v1";
pub const TOKEN_REQUEST_SCHEMA: &str = "leanctx.cloud.token-request/v1";
pub const ACCESS_TOKEN_SCHEMA: &str = "leanctx.cloud.access-token/v1";

/// Longest instance label, in characters.
pub const MAX_INSTANCE_LABEL_CHARS: usize = 64;
/// Accepted distance between `iat` and service time.
pub const MAX_ASSERTION_SKEW_SECONDS: i64 = 300;
/// Longest access-token lifetime the service issues.
pub const MAX_ACCESS_TOKEN_SECONDS: u32 = 3600;

/// Operating-system family of the engine.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EngineOs {
    Macos,
    Linux,
    Windows,
    Other,
}

fn validate_engine_version(value: &str) -> Result<(), ValidationError> {
    let ok = !value.is_empty()
        && value.len() <= 32
        && value.as_bytes()[0].is_ascii_digit()
        && value
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-' | b'+'));
    if ok {
        Ok(())
    } else {
        Err(ValidationError::new(
            "instance_version must be a semantic version of at most 32 characters",
        ))
    }
}

/// `POST /v1/device/code`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct DeviceCodeRequestV1 {
    pub schema: String,
    /// Always [`CLOUD_ENGINE_CLIENT_ID`].
    pub client_id: String,
    pub instance_version: String,
    pub os: EngineOs,
    /// The name the user gave this engine (`--label`), shown on the approval
    /// page and prefilled as its name (Cloud task #11). Like `instance_version`
    /// and `os` it is the requester's claim. Absent when the user gave none:
    /// the host-name default goes only into [`DeviceTokenRequestV1`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub instance_label: Option<String>,
    /// One-step trial (`lean-ctx cloud connect --trial`): why the code is
    /// asked for. Absent for a sign-in, so a Cloud that does not know the
    /// member (it refuses unknown fields) still serves every plain connect.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub intent: Option<DeviceIntent>,
    /// Only with `intent: "trial"`: the plan whose trial the browser starts.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub plan: Option<TrialPlan>,
    /// f3129 S2: the app keys this pairing binds, sorted by kind, one per
    /// kind. Sent before the code answer shows [`FEATURE_DEVICE_APP_KEYS`]:
    /// a Cloud without it refuses the unknown member and nothing is bound.
    /// Absent when empty, so every older request stays byte-identical.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub app_keys: Vec<AppKeyAnnouncementV1>,
}

/// `DeviceCodeRequestV1.intent`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DeviceIntent {
    SignIn,
    Trial,
}

/// `DeviceCodeRequestV1.plan`: the plan a one-step trial starts.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TrialPlan {
    Personal,
    Team,
}

impl TrialPlan {
    /// The wire name (`personal`, `team`).
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Personal => "personal",
            Self::Team => "team",
        }
    }

    /// `--plan personal|team`.
    pub fn parse(value: &str) -> Option<Self> {
        match value {
            "personal" => Some(Self::Personal),
            "team" => Some(Self::Team),
            _ => None,
        }
    }
}

impl DeviceCodeRequestV1 {
    pub fn new(instance_version: impl Into<String>, os: EngineOs) -> Self {
        Self {
            schema: DEVICE_CODE_REQUEST_SCHEMA.into(),
            client_id: CLOUD_ENGINE_CLIENT_ID.into(),
            instance_version: instance_version.into(),
            os,
            instance_label: None,
            intent: None,
            plan: None,
            app_keys: Vec::new(),
        }
    }

    /// The same request announcing `keys` (f3129 S2), sorted by kind.
    #[must_use]
    pub fn with_app_keys(mut self, mut keys: Vec<AppKeyAnnouncementV1>) -> Self {
        keys.sort_by_key(|key| key.kind);
        self.app_keys = keys;
        self
    }

    /// The same request naming the engine (`--label`).
    #[must_use]
    pub fn with_label(mut self, label: Option<String>) -> Self {
        self.instance_label = label;
        self
    }

    /// The same request asking for a one-step trial of `plan` (`None`: a
    /// plain sign-in, which sends neither member).
    #[must_use]
    pub fn with_trial(mut self, plan: Option<TrialPlan>) -> Self {
        self.intent = plan.map(|_| DeviceIntent::Trial);
        self.plan = plan;
        self
    }

    pub fn validate(&self) -> Result<(), ValidationError> {
        require_schema(&self.schema, DEVICE_CODE_REQUEST_SCHEMA)?;
        if self.client_id != CLOUD_ENGINE_CLIENT_ID {
            return Err(ValidationError::new(format!(
                "client_id must be {CLOUD_ENGINE_CLIENT_ID}"
            )));
        }
        if let Some(label) = &self.instance_label {
            validate_text(label, MAX_INSTANCE_LABEL_CHARS, "instance_label", false)?;
        }
        if self.plan.is_some() && self.intent != Some(DeviceIntent::Trial) {
            return Err(ValidationError::new(
                "plan is only allowed with intent trial",
            ));
        }
        validate_app_keys(&self.app_keys)?;
        validate_engine_version(&self.instance_version)
    }
}

/// Response of `POST /v1/device/code`.
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DeviceCodeV1 {
    pub schema: String,
    /// Secret polling handle; never shown or logged.
    pub device_code: String,
    /// Short code the user confirms in the browser, e.g. `WDJB-MJHT`.
    pub user_code: String,
    pub verification_uri: String,
    pub verification_uri_complete: String,
    /// Minimum seconds between token polls.
    pub interval: u32,
    /// Seconds until `device_code` expires.
    pub expires_in: u32,
    /// C0 2.1: what this Cloud offers beyond C0 1, e.g.
    /// [`FEATURE_DEVICE_SETUP`]; empty (absent) on older ones.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub features: Vec<String>,
    /// One-step trial: the Cloud echoes the request's `intent` and `plan`
    /// (`device_code_trial.response.json`); absent for a sign-in.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub intent: Option<DeviceIntent>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub plan: Option<TrialPlan>,
}

impl DeviceCodeV1 {
    /// Whether this code starts the trial of `plan` the request asked for.
    pub fn starts_trial(&self, plan: TrialPlan) -> bool {
        self.intent == Some(DeviceIntent::Trial) && self.plan.is_none_or(|p| p == plan)
    }

    /// Whether this Cloud takes `POST /v1/device/setup` for this code.
    pub fn offers_device_setup(&self) -> bool {
        self.features.iter().any(|f| f == FEATURE_DEVICE_SETUP)
    }

    /// Whether this Cloud binds app keys in the device flow (f3129 S2+S3).
    /// Without it the engine announces, offers and binds none.
    pub fn offers_app_keys(&self) -> bool {
        self.features.iter().any(|f| f == FEATURE_DEVICE_APP_KEYS)
    }
}

/// C0 2.1 `features` entry: the approval page shares the project too.
pub const FEATURE_DEVICE_SETUP: &str = "device_setup";
pub const DEVICE_SETUP_REQUEST_SCHEMA: &str = "leanctx.cloud.device-setup/v1";
pub const DEVICE_SETUP_RESULT_SCHEMA: &str = "leanctx.cloud.device-setup-result/v1";

/// C0 2.1 `POST /v1/device/setup` (no token; the pending `device_code`):
/// the project this engine runs in and what it shares, shown on the
/// approval page (`routes/device_setup.request.json`). Requester's claims.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct DeviceSetupRequestV1 {
    pub schema: String,
    pub device_code: String,
    pub project: Option<DeviceSetupProjectV1>,
    /// `knowledge`, `usage`, `receipts`, `bus`, sorted.
    pub shares: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct DeviceSetupProjectV1 {
    /// The checkout's folder name, 1-64 characters.
    pub name: String,
    /// The git remote as the engine sees it, for the person to recognise.
    pub remote: Option<String>,
}

/// C0 2.1 `POST /v1/device/setup/result` (instance token):
/// `routes/device_setup_result.request.json`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct DeviceSetupResultV1 {
    pub schema: String,
    /// `shared`, `kept_local`, `no_project` or `failed`.
    pub state: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub vault: Option<String>,
}

impl fmt::Debug for DeviceCodeV1 {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("DeviceCodeV1")
            .field("device_code", &"<redacted>")
            .field("user_code", &self.user_code)
            .field("verification_uri", &self.verification_uri)
            .field("interval", &self.interval)
            .field("expires_in", &self.expires_in)
            .finish_non_exhaustive()
    }
}

/// `http://localhost[:port]…` or `http://127.0.0.1[:port]…`.
fn is_loopback_http(uri: &str) -> bool {
    uri.strip_prefix("http://")
        .and_then(|rest| rest.split(['/', ':', '?']).next())
        .is_some_and(|host| host == "localhost" || host == "127.0.0.1")
}

impl DeviceCodeV1 {
    pub fn validate(&self) -> Result<(), ValidationError> {
        require_schema(&self.schema, DEVICE_CODE_SCHEMA)?;
        validate_text(&self.device_code, 256, "device_code", false)?;
        validate_text(&self.user_code, 16, "user_code", false)?;
        for uri in [&self.verification_uri, &self.verification_uri_complete] {
            if !(uri.starts_with("https://") || is_loopback_http(uri)) || uri.len() > 512 {
                return Err(ValidationError::new(
                    "verification uri must be https (http only on localhost/127.0.0.1)",
                ));
            }
        }
        if !(1..=60).contains(&self.interval) || !(60..=3600).contains(&self.expires_in) {
            return Err(ValidationError::new(
                "interval must be 1-60 s and expires_in 60-3600 s",
            ));
        }
        Ok(())
    }
}

/// `POST /v1/device/token`: poll until the user approved, then enroll the
/// instance with its public keys.
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct DeviceTokenRequestV1 {
    pub schema: String,
    pub device_code: String,
    /// Ed25519 public key (32 bytes, base64) the instance signs assertions with.
    pub instance_public_key: String,
    /// X25519 public key (32 bytes, base64); enrollment carries it.
    pub instance_kx_public_key: String,
    /// User-visible name, e.g. the host name when labels are on.
    pub instance_label: String,
    pub instance_version: String,
    pub os: EngineOs,
    /// f3129 offers of the announced app keys, each with its own
    /// `bind_signature`. Together they must equal `app_keys` of the code
    /// request; absent when none was announced.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub chat_key: Option<AppKeyOfferV1>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub optin_key: Option<AppKeyOfferV1>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub task_propose_key: Option<AppKeyOfferV1>,
    /// f3129 S3: base64url (no padding) Ed25519 signature of
    /// `instance_public_key` over [`app_key_bind_signing_input`]. Required
    /// whenever app keys were announced; absent otherwise.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub app_keys_bind_signature: Option<String>,
}

impl fmt::Debug for DeviceTokenRequestV1 {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("DeviceTokenRequestV1")
            .field("device_code", &"<redacted>")
            .field("instance_public_key", &self.instance_public_key)
            .field("instance_label", &self.instance_label)
            .field("instance_version", &self.instance_version)
            .field("os", &self.os)
            .finish_non_exhaustive()
    }
}

impl DeviceTokenRequestV1 {
    pub fn validate(&self) -> Result<(), ValidationError> {
        require_schema(&self.schema, DEVICE_TOKEN_REQUEST_SCHEMA)?;
        validate_text(&self.device_code, 256, "device_code", false)?;
        validate_b64_len(&self.instance_public_key, 32, "instance_public_key")?;
        validate_b64_len(&self.instance_kx_public_key, 32, "instance_kx_public_key")?;
        validate_text(
            &self.instance_label,
            MAX_INSTANCE_LABEL_CHARS,
            "instance_label",
            false,
        )?;
        let offers = self.app_key_offers();
        for (kind, offer) in &offers {
            offer.validate(*kind)?;
        }
        match &self.app_keys_bind_signature {
            Some(signature) if !offers.is_empty() => {
                decode_b64url_exact(signature, 64, "app_keys_bind_signature")?;
            }
            Some(_) => {
                return Err(ValidationError::new(
                    "app_keys_bind_signature needs at least one offered app key",
                ));
            }
            None if !offers.is_empty() => {
                return Err(ValidationError::new(
                    "offered app keys need app_keys_bind_signature",
                ));
            }
            None => {}
        }
        validate_engine_version(&self.instance_version)
    }

    /// The offered app keys, sorted by kind.
    pub fn app_key_offers(&self) -> Vec<(AppKeyKind, &AppKeyOfferV1)> {
        [
            (AppKeyKind::Chat, &self.chat_key),
            (AppKeyKind::Optin, &self.optin_key),
            (AppKeyKind::TaskPropose, &self.task_propose_key),
        ]
        .into_iter()
        .filter_map(|(kind, offer)| offer.as_ref().map(|offer| (kind, offer)))
        .collect()
    }

    /// The offer member of `kind`.
    pub fn app_key_offer_mut(&mut self, kind: AppKeyKind) -> &mut Option<AppKeyOfferV1> {
        match kind {
            AppKeyKind::Chat => &mut self.chat_key,
            AppKeyKind::Optin => &mut self.optin_key,
            AppKeyKind::TaskPropose => &mut self.task_propose_key,
        }
    }
}

/// Organization reference: the workspace the instance enrolls in.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct OrgRefV1 {
    pub id: String,
    pub name: String,
    /// `personal` | `team` (Cloud C line, additive); older servers omit it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub kind: Option<String>,
    /// The company a team belongs to (Cloud C line, additive).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub company: Option<CompanyRefV1>,
}

/// The company of a team: the business that holds its Enterprise plan.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CompanyRefV1 {
    pub name: String,
}

/// Successful `POST /v1/device/token`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EnrollmentV1 {
    pub schema: String,
    pub instance_id: String,
    pub org: OrgRefV1,
    pub lease: CloudLeaseEnvelopeV1,
    /// Signed by the Cloud root key; verified before the lease. v1 for an
    /// engine below Cloud-Protocol 2.1, v3 from 2.1.
    pub keys: EnrollmentKeySet,
    /// Id of the org salt the engine fetches with `GET /v1/org/salt`.
    pub org_salt_id: String,
    /// 1.3: origin of the LeanCTX Cloud web app (its "Open" link); may equal the API origin.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub web_url: Option<String>,
    /// The name the person gave this computer on the approval page, as the
    /// Cloud stored it (rc4-1). Additive: an older Cloud omits it and the
    /// engine keeps the label it sent in [`DeviceTokenRequestV1`]. Display
    /// only; a value that fails [`EnrollmentV1::chosen_label`] is ignored,
    /// never a reason to refuse the enrollment. `null` reads as absent. The
    /// rule is the Cloud's (`keyset.schema.json` `enrollment_for_2x`
    /// pattern, `vectors/instance_label.vectors.json`): no whitespace at the
    /// start or end (a space, a no-break space or any other Unicode
    /// whitespace), 1–64 characters, no control or [`super::invisible`]
    /// character.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub instance_label: Option<String>,
}

impl EnrollmentV1 {
    /// The name chosen on the approval page when it is 1–64 characters of
    /// printable text without whitespace at either end; `None` when absent
    /// or unusable, so the engine keeps the name it sent.
    pub fn chosen_label(&self) -> Option<&str> {
        let label = self.instance_label.as_deref()?;
        if label.trim() != label {
            return None;
        }
        validate_text(label, MAX_INSTANCE_LABEL_CHARS, "instance_label", false)
            .ok()
            .map(|()| label)
    }

    /// Structural checks; signature checks are the engine's
    /// (`keys` against the root key, then `lease` against `keys`).
    pub fn validate(&self) -> Result<(), ValidationError> {
        require_schema(&self.schema, ENROLLMENT_SCHEMA)?;
        validate_id(&self.instance_id, "instance_id")?;
        validate_id(&self.org.id, "org.id")?;
        validate_text(&self.org.name, 128, "org.name", false)?;
        validate_id(&self.org_salt_id, "org_salt_id")?;
        if let Some(web_url) = &self.web_url {
            super::validate_origin(web_url, "web_url")?;
        }
        self.keys.validate()?;
        self.lease.validate_shape()?;
        if !self.keys.signs_leases_as(&self.lease.kid) {
            return Err(ValidationError::new(
                "the lease kid names no lease key of the enrollment's key set",
            ));
        }
        Ok(())
    }
}

/// `POST /v1/instances/{instance_id}/token`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct InstanceTokenRequestV1 {
    pub schema: String,
    /// Unix seconds; the service accepts ±[`MAX_ASSERTION_SKEW_SECONDS`].
    pub iat: i64,
    /// 16–64 chars of `[A-Za-z0-9_-]`, single use within the skew window.
    pub nonce: String,
    /// Ed25519 signature (base64) over [`token_assertion_input`].
    pub assertion: String,
}

impl InstanceTokenRequestV1 {
    pub fn validate(&self) -> Result<(), ValidationError> {
        require_schema(&self.schema, TOKEN_REQUEST_SCHEMA)?;
        if self.iat <= 0 {
            return Err(ValidationError::new("iat must be positive unix seconds"));
        }
        validate_nonce(&self.nonce)?;
        validate_b64_len(&self.assertion, 64, "assertion")
    }
}

fn validate_nonce(nonce: &str) -> Result<(), ValidationError> {
    if (16..=64).contains(&nonce.len())
        && nonce
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
    {
        Ok(())
    } else {
        Err(ValidationError::new(
            "nonce must be 16-64 characters of [A-Za-z0-9_-]",
        ))
    }
}

/// Bytes the instance key signs: `"leanctx.cloud.token.v1\n" + instance_id +
/// "\n" + iat + "\n" + nonce` (iat in decimal unix seconds).
pub fn token_assertion_input(instance_id: &str, iat: i64, nonce: &str) -> Vec<u8> {
    format!("{TOKEN_ASSERTION_DOMAIN}{instance_id}\n{iat}\n{nonce}").into_bytes()
}

/// Response of `POST /v1/instances/{instance_id}/token`.
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AccessTokenV1 {
    pub schema: String,
    /// Bearer token; never logged, printed or persisted outside `token.json`.
    pub access_token: String,
    /// Seconds, at most [`MAX_ACCESS_TOKEN_SECONDS`].
    pub expires_in: u32,
}

impl fmt::Debug for AccessTokenV1 {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("AccessTokenV1")
            .field("access_token", &"<redacted>")
            .field("expires_in", &self.expires_in)
            .finish_non_exhaustive()
    }
}

impl AccessTokenV1 {
    pub fn validate(&self) -> Result<(), ValidationError> {
        require_schema(&self.schema, ACCESS_TOKEN_SCHEMA)?;
        validate_text(&self.access_token, 4096, "access_token", false)?;
        if !(1..=MAX_ACCESS_TOKEN_SECONDS).contains(&self.expires_in) {
            return Err(ValidationError::new("expires_in must be 1-3600 s"));
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_device_code_label_follows_the_text_rule() {
        let request = |label: Option<&str>| {
            DeviceCodeRequestV1::new("3.12.0", EngineOs::Macos)
                .with_label(label.map(str::to_string))
        };
        assert!(request(None).validate().is_ok());
        assert!(request(Some("build-box")).validate().is_ok());
        let long = "x".repeat(MAX_INSTANCE_LABEL_CHARS + 1);
        for bad in [
            "",
            "line\nbreak",
            "zero\u{200b}width",
            "a\u{202e}b",
            long.as_str(),
        ] {
            assert!(request(Some(bad)).validate().is_err(), "{bad:?}");
        }
        let unlabelled = serde_json::to_value(request(None)).unwrap();
        assert!(
            unlabelled.get("instance_label").is_none(),
            "older services refuse unknown fields"
        );
    }

    /// `cloud connect --trial`: intent and plan travel only on a trial
    /// request; a sign-in sends neither (older Clouds refuse unknown fields).
    #[test]
    fn trial_device_code_request_carries_intent_and_plan() {
        let plain = DeviceCodeRequestV1::new("3.12.0", EngineOs::Macos).with_trial(None);
        let json = serde_json::to_value(&plain).unwrap();
        assert!(json.get("intent").is_none() && json.get("plan").is_none());
        let trial =
            DeviceCodeRequestV1::new("3.12.0", EngineOs::Macos).with_trial(Some(TrialPlan::Team));
        assert!(trial.validate().is_ok());
        let json = serde_json::to_value(&trial).unwrap();
        assert_eq!(json["intent"], "trial");
        assert_eq!(json["plan"], "team");
        assert_eq!(
            serde_json::from_value::<DeviceCodeRequestV1>(json).unwrap(),
            trial
        );
        let personal = DeviceCodeRequestV1::new("3.12.0", EngineOs::Linux)
            .with_trial(Some(TrialPlan::Personal));
        assert_eq!(serde_json::to_value(&personal).unwrap()["plan"], "personal");
        let mut plan_only = plain.clone();
        plan_only.plan = Some(TrialPlan::Personal);
        assert!(plan_only.validate().is_err(), "plan needs intent trial");
        assert_eq!(TrialPlan::parse("team"), Some(TrialPlan::Team));
        assert_eq!(TrialPlan::parse("enterprise"), None);
    }

    /// p37 !134 contract fixtures: the trial request is the engine's own,
    /// byte for byte, and the answer echoes the trial it starts.
    #[test]
    fn trial_device_code_documents_are_the_contract_fixtures() {
        let request: serde_json::Value = serde_json::from_str(include_str!(
            "../../tests/fixtures/cloud/device_code_trial.request.json"
        ))
        .unwrap();
        let ours = DeviceCodeRequestV1::new("3.12.1", EngineOs::Macos)
            .with_trial(Some(TrialPlan::Personal));
        assert_eq!(serde_json::to_value(&ours).unwrap(), request);
        let answer: serde_json::Value = serde_json::from_str(include_str!(
            "../../tests/fixtures/cloud/device_code_trial.response.json"
        ))
        .unwrap();
        let code: DeviceCodeV1 = serde_json::from_value(answer.clone()).unwrap();
        code.validate().unwrap();
        assert_eq!(serde_json::to_value(&code).unwrap(), answer);
        assert!(code.starts_trial(TrialPlan::Personal));
        assert!(!code.starts_trial(TrialPlan::Team));
        assert!(
            code.verification_uri_complete
                .ends_with("&intent=trial&plan=personal")
        );
        let sign_in: DeviceCodeV1 = serde_json::from_str(include_str!(
            "../../tests/fixtures/cloud/device_code.response.json"
        ))
        .unwrap();
        assert!(
            !sign_in.starts_trial(TrialPlan::Personal),
            "no echo, no trial"
        );
    }

    #[test]
    fn assertion_input_is_the_documented_text() {
        assert_eq!(
            token_assertion_input("inst_1", 1_792_500_000, "n0nce-n0nce-n0nce"),
            b"leanctx.cloud.token.v1\ninst_1\n1792500000\nn0nce-n0nce-n0nce".to_vec()
        );
    }

    #[test]
    fn secrets_stay_out_of_debug() {
        let token = AccessTokenV1 {
            schema: ACCESS_TOKEN_SCHEMA.into(),
            access_token: "atl_secret_value".into(),
            expires_in: 3600,
        };
        assert!(!format!("{token:?}").contains("atl_secret_value"));
        let code = DeviceCodeV1 {
            schema: DEVICE_CODE_SCHEMA.into(),
            device_code: "dc_secret_value".into(),
            user_code: "WDJB-MJHT".into(),
            verification_uri: "https://cloud.leanctx.com/device".into(),
            verification_uri_complete: "https://cloud.leanctx.com/device?code=WDJB-MJHT".into(),
            interval: 5,
            expires_in: 900,
            features: Vec::new(),
            intent: None,
            plan: None,
        };
        assert!(!format!("{code:?}").contains("dc_secret_value"));
        assert!(!code.offers_device_setup());
    }

    /// C0 2.1 device setup: the contract fixtures round-trip byte for byte
    /// through the engine's types, and the features list is optional.
    #[test]
    fn device_setup_documents_are_the_contract_fixtures() {
        fn round<T: serde::de::DeserializeOwned + Serialize>(raw: &str) {
            let value: serde_json::Value = serde_json::from_str(raw).unwrap();
            let typed: T = serde_json::from_value(value.clone()).unwrap();
            assert_eq!(serde_json::to_value(typed).unwrap(), value);
        }
        round::<DeviceSetupRequestV1>(include_str!(
            "../../tests/fixtures/cloud-v2/routes/device_setup.request.json"
        ));
        round::<DeviceSetupResultV1>(include_str!(
            "../../tests/fixtures/cloud-v2/routes/device_setup_result.request.json"
        ));
        let mut answer = serde_json::json!({
            "schema": DEVICE_CODE_SCHEMA, "device_code": "dc_x", "user_code": "WDJB-MJHT",
            "verification_uri": "https://cloud.leanctx.com/device",
            "verification_uri_complete": "https://cloud.leanctx.com/device?user_code=WDJB-MJHT",
            "interval": 5, "expires_in": 900,
        });
        let old: DeviceCodeV1 = serde_json::from_value(answer.clone()).unwrap();
        assert!(
            !old.offers_device_setup(),
            "a LeanCTX Cloud server with C0 2.0 lists nothing"
        );
        answer["features"] = serde_json::json!([FEATURE_DEVICE_SETUP, "later"]);
        let new: DeviceCodeV1 = serde_json::from_value(answer).unwrap();
        assert!(new.offers_device_setup());
    }

    /// An enrollment as a Cloud-Protocol 1.x/2.0 engine receives it: key
    /// set v1, the lease signed by a `kid` of it.
    #[test]
    fn an_enrollment_with_key_set_v1_decodes_and_names_its_lease_key() {
        let raw: serde_json::Value = serde_json::from_str(include_str!(
            "../../tests/fixtures/cloud/enrollment.response.json"
        ))
        .unwrap();
        let enrollment: EnrollmentV1 = serde_json::from_value(raw.clone()).unwrap();
        enrollment.validate().unwrap();
        assert!(matches!(enrollment.keys, EnrollmentKeySet::V1(_)));
        assert_eq!(serde_json::to_value(&enrollment).unwrap(), raw);
        let mut other_kid = enrollment;
        other_kid.lease.kid = "k-unknown".into();
        assert!(other_kid.validate().is_err(), "the kid follows the set");
    }

    /// An enrollment as a Cloud-Protocol 2.1+ engine receives it
    /// (`routes/enrollment.for_2x.response.json`): key set v3, the lease of
    /// a 2.x engine signed by the v3 key of purpose `policy` its `kid`
    /// names.
    #[test]
    fn an_enrollment_with_key_set_v3_decodes_and_names_its_policy_key() {
        let raw: serde_json::Value = serde_json::from_str(include_str!(
            "../../tests/fixtures/cloud-v2/routes/enrollment.for_2x.response.json"
        ))
        .unwrap();
        let enrollment: EnrollmentV1 = serde_json::from_value(raw.clone()).unwrap();
        enrollment.validate().unwrap();
        let EnrollmentKeySet::V3(set) = &enrollment.keys else {
            panic!("a v3 set decodes as v3");
        };
        assert_eq!(
            set.lease_key(&enrollment.lease.kid)
                .map(|k| k.key_id.as_str()),
            Some("552e43422b3589fa")
        );
        assert_eq!(serde_json::to_value(&enrollment).unwrap(), raw);
        // The kid of a key without purpose `policy` signs no lease.
        let mut event_kid = enrollment.clone();
        event_kid.lease.kid = "4fc7bebc302357bd".into();
        assert!(event_kid.validate().is_err());
        // A v3 key without its v3 fields is refused, not read as v1.
        let mut broken = raw;
        broken["keys"]["keys"][0]
            .as_object_mut()
            .unwrap()
            .remove("key_id");
        assert!(serde_json::from_value::<EnrollmentV1>(broken).is_err());
    }

    fn fixture(rel: &str) -> serde_json::Value {
        let path = format!(
            "{}/tests/fixtures/cloud-v2/{rel}",
            env!("CARGO_MANIFEST_DIR")
        );
        serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap()
    }

    fn enrollment_from(answer: serde_json::Value) -> EnrollmentV1 {
        let enrollment: EnrollmentV1 = serde_json::from_value(answer).unwrap();
        enrollment.validate().unwrap();
        enrollment
    }

    /// rc4-1: the name typed on the approval page comes back as
    /// `instance_label` (`routes/enrollment.for_2x.response.json`); a Cloud
    /// that stored none sends no member (`….unlabelled.response.json`) or,
    /// tolerated, `null`.
    #[test]
    fn an_enrollment_names_the_label_chosen_on_the_approval_page() {
        let labelled = fixture("routes/enrollment.for_2x.response.json");
        let enrollment = enrollment_from(labelled.clone());
        assert_eq!(enrollment.chosen_label(), Some("Ada's MacBook Air"));
        assert_eq!(serde_json::to_value(&enrollment).unwrap(), labelled);

        let unlabelled = fixture("routes/enrollment.for_2x.unlabelled.response.json");
        let enrollment = enrollment_from(unlabelled.clone());
        assert_eq!(enrollment.instance_label, None);
        assert_eq!(enrollment.chosen_label(), None);
        assert_eq!(serde_json::to_value(&enrollment).unwrap(), unlabelled);

        let mut null = labelled;
        null["instance_label"] = serde_json::Value::Null;
        assert_eq!(enrollment_from(null).chosen_label(), None);
    }

    /// `vectors/instance_label.vectors.json`: the engine takes a name exactly
    /// as the Cloud does (1–64 characters, no control or invisible
    /// character), and a refused one leaves the enrollment valid.
    #[test]
    fn the_chosen_label_follows_the_instance_label_vectors() {
        let vectors = fixture("vectors/instance_label.vectors.json");
        assert_eq!(vectors["max_chars"], MAX_INSTANCE_LABEL_CHARS);
        let base = fixture("routes/enrollment.for_2x.unlabelled.response.json");
        let cases = vectors["cases"].as_array().unwrap();
        assert!(cases.len() >= 40, "only {} vectors", cases.len());
        for case in cases {
            let input = case["input"].as_str().unwrap();
            // The vectors trim what a person types; the stored name the
            // enrollment answer carries has no whitespace at either end
            // (keyset.schema.json pattern), so the engine refuses one.
            let name = if input.trim() == input {
                case["name"].as_str()
            } else {
                None
            };
            let mut answer = base.clone();
            answer["instance_label"] = case["input"].clone();
            let enrollment = enrollment_from(answer);
            assert_eq!(
                enrollment.chosen_label(),
                name,
                "{}: {:?}",
                case["why"],
                case["input"]
            );
        }
    }

    /// p37 !290: whitespace at the start or end, a space or a no-break space,
    /// is refused rather than trimmed.
    #[test]
    fn a_label_with_whitespace_at_either_end_is_ignored() {
        let base = fixture("routes/enrollment.for_2x.unlabelled.response.json");
        let chosen = |label: &str| {
            let mut answer = base.clone();
            answer["instance_label"] = serde_json::Value::from(label);
            enrollment_from(answer).chosen_label().map(str::to_string)
        };
        assert_eq!(chosen("Ada").as_deref(), Some("Ada"));
        assert_eq!(chosen("Ada\u{a0}Mac").as_deref(), Some("Ada\u{a0}Mac"));
        for bad in [
            " Ada",
            "Ada ",
            "\u{a0}Ada",
            "Ada\u{a0}",
            "\u{3000}Ada",
            "Ada\u{2003}",
        ] {
            assert_eq!(chosen(bad), None, "{bad:?}");
        }
    }

    /// The Cloud's schema refuses the `routes/invalid/enrollment_instance_label_*`
    /// answers; the engine reads each as an enrollment without a chosen name
    /// rather than failing the connect.
    #[test]
    fn an_invalid_instance_label_is_ignored_not_fatal() {
        let dir = format!(
            "{}/tests/fixtures/cloud-v2/routes/invalid",
            env!("CARGO_MANIFEST_DIR")
        );
        let mut checked = 0;
        for entry in std::fs::read_dir(&dir).unwrap() {
            let name = entry.unwrap().file_name().to_string_lossy().into_owned();
            if !name.starts_with("enrollment_instance_label_") {
                continue;
            }
            let case = fixture(&format!("routes/invalid/{name}"));
            let mut answer = fixture(case["base"].as_str().unwrap());
            for op in case["patch"].as_array().unwrap() {
                assert_eq!(op["op"], "replace", "{name}");
                let member = op["path"].as_str().unwrap().strip_prefix('/').unwrap();
                answer[member] = op["value"].clone();
            }
            assert_eq!(enrollment_from(answer).chosen_label(), None, "{name}");
            checked += 1;
        }
        assert!(
            checked >= 9,
            "only {checked} invalid instance_label fixtures"
        );
    }

    #[test]
    fn requests_refuse_unknown_fields() {
        let json = r#"{"schema":"leanctx.cloud.device-code-request/v1","client_id":"lean-ctx-engine","instance_version":"3.12.0","os":"macos","extra":true}"#;
        assert!(serde_json::from_str::<DeviceCodeRequestV1>(json).is_err());
    }
}