stratum-node-cli 0.1.0-alpha.4

The `stratum` client for Stratum pod nodes: operator key files, bootstrap, config, backup, invitations and members over the loopback API; join, pod access and export for tenants through the gate
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
913
914
//! The `stratum` commands, run against one node with one operator key.

use std::path::{Path, PathBuf};
use std::time::Duration;

use serde::{Deserialize as _, Serialize};
use serde_json::{json, Value as Json};
use stratum_node_config::Change;
use stratum_node_core::{ClaimBody, DidNostr, NostrSecretKey, OperationId, SignedEvent};

use crate::changes::parse_changes;
use crate::client::{self, Client, Response};
use crate::error::CliError;
use crate::exit;
use crate::key::{generate_key_file, load_key_file};
use crate::output::{sanitize, Output};
use crate::private_file::{self, ModePolicy};
use crate::url::LoopbackUrl;
use crate::wire::{
    ApplyRequest, ApplyResponse, BackupManifest, BackupRequest, BackupResponse, CheckpointResponse,
    ConfigResponse, PreviewRequest, PreviewResponse, Readyz, BACKUP_FILES, BACKUP_FILES_SEALED,
    BACKUP_FORMAT, BACKUP_FORMAT_VERSION, BACKUP_FORMAT_VERSION_PODS, BACKUP_FORMAT_VERSION_SEALED,
    BACKUP_POD_ARCHIVE,
};

/// `GET` route: readiness.
pub(crate) const READYZ: &str = "/readyz";
/// `GET` route: the configuration schema.
const SCHEMA: &str = "/api/v1/config/schema";
/// `GET` route: the effective configuration.
const CONFIG: &str = "/api/v1/config";
/// `POST` route: preview a change.
pub(crate) const PREVIEW: &str = "/api/v1/config/preview";
/// `POST` route: apply a change.
const APPLY: &str = "/api/v1/config/apply";
/// `GET` route: the audit checkpoint.
const CHECKPOINT: &str = "/api/v1/audit/checkpoint";
/// `POST` route: take a backup.
const BACKUP: &str = "/api/v1/backup";

/// How long `backup` waits for the node's answer. A node with pods may wait
/// 90 seconds for the gate to drain before it answers `gate_unavailable`
/// (E2.23), then snapshots the store and archives every pod; the usual
/// 30-second request timeout would report a node still working as
/// unreachable.
const BACKUP_TIMEOUT: Duration = Duration::from_secs(15 * 60);
/// `POST` route: request a bootstrap challenge.
pub(crate) const CHALLENGE: &str = "/api/v1/bootstrap/challenge";
/// `POST` route: claim the node.
pub(crate) const CLAIM: &str = "/api/v1/bootstrap/claim";

/// The only HTTP API version this client speaks.
const API_VERSION: u64 = 1;

/// The NIP-78 application-data event kind the backup manifest is signed as.
const MANIFEST_KIND: u16 = 30078;

/// The largest claim body file `sign-challenge` reads.
const CLAIM_BODY_FILE_LIMIT: usize = 64 * 1024;

/// Whether a command that changes the node may proceed without asking.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum Confirmation {
    /// Ask on the terminal; refuse when standard input is not a terminal.
    #[default]
    Prompt,
    /// Proceed without asking (`--yes`).
    Assumed,
}

/// Options for [`Session::config_apply`].
#[derive(Debug, Clone, Default)]
pub struct ApplyOptions {
    /// The `--set path=value` arguments; see [`parse_changes`](crate::parse_changes).
    pub sets: Vec<String>,
    /// The revision the change is based on; the node's head revision when
    /// `None`.
    pub base_revision: Option<u64>,
    /// The operation ID; a random one is generated and printed when `None`.
    pub operation_id: Option<String>,
    /// Whether to ask before applying.
    pub confirmation: Confirmation,
}

/// Options for [`Session::setup`].
#[derive(Debug, Clone, Default)]
pub struct SetupOptions {
    /// The node's bootstrap token file, `<state_dir>/bootstrap-token`.
    pub token_file: PathBuf,
    /// The `--set path=value` arguments for the initial configuration.
    pub sets: Vec<String>,
    /// Where the signed claim request is saved before it is sent;
    /// `<key file>.setup-resume` when `None`.
    pub resume_file: Option<PathBuf>,
    /// Whether to ask before claiming.
    pub confirmation: Confirmation,
    /// The node DID the operator expects (`--expect-node`), as `stratumd`
    /// printed it at start. When given, the bootstrap token is sent only if
    /// `/readyz` reports this DID and the claim body names it. When `None`,
    /// setup trusts whatever answers on the loopback port.
    pub expect_node: Option<DidNostr>,
    /// Also print the full configuration text whose SHA-256 the claim
    /// binds (`--show-text`).
    pub show_text: bool,
}

/// One node, one optional operator key file and one output format: the
/// context every `stratum` command runs in.
///
/// Each command method writes its results through [`Output`] and returns
/// the process exit code on success (see [`exit`](crate::exit)); failures
/// are returned as [`CliError`], whose
/// [`exit_code`](CliError::exit_code) gives theirs. Every authenticated
/// request is signed with [`NostrSecretKey::sign_request_with_nonce`] over
/// the exact URL, method and body bytes sent, with a fresh random nonce and
/// fresh auxiliary randomness.
///
/// # Examples
///
/// ```
/// use stratum_node_cli::{CliError, Output, OutputFormat, Session};
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let session = Session::new("http://127.0.0.1:7460".parse()?, None, Output::new(OutputFormat::Json));
/// // Commands that need the operator key say so before touching the network.
/// assert!(matches!(session.audit_checkpoint(), Err(CliError::MissingKeyFile)));
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct Session {
    url: LoopbackUrl,
    key_file: Option<PathBuf>,
    output: Output,
}

impl Session {
    /// Creates a session for the node at `url`, signing with the key in
    /// `key_file` when a command needs it.
    pub fn new(url: LoopbackUrl, key_file: Option<PathBuf>, output: Output) -> Self {
        Self {
            url,
            key_file,
            output,
        }
    }

    /// `stratum key generate --out <file>`: creates a new operator key file
    /// and prints the operator's DID and `npub`.
    ///
    /// # Errors
    ///
    /// [`CliError::KeyFile`] when the file exists or cannot be created.
    pub fn key_generate(&self, out: &Path) -> Result<u8, CliError> {
        let key = generate_key_file(out).map_err(|source| CliError::KeyFile {
            path: out.to_owned(),
            source,
        })?;
        self.print_identity(&key.public(), out)
    }

    /// `stratum key show`: prints the DID and `npub` of the operator key.
    ///
    /// # Errors
    ///
    /// [`CliError::MissingKeyFile`] or [`CliError::KeyFile`].
    pub fn key_show(&self) -> Result<u8, CliError> {
        let path = self.key_path()?;
        let key = self.key()?;
        self.print_identity(&key.public(), path)
    }

    /// `stratum status`: reads `/readyz` and returns [`exit::OK`] when the
    /// node is ready, [`exit::UNCONFIGURED`] or [`exit::DEGRADED`].
    ///
    /// # Errors
    ///
    /// [`CliError::Unreachable`] (exit 2) or [`CliError::Protocol`].
    pub fn status(&self) -> Result<u8, CliError> {
        let client = self.client()?;
        let response = client.get(READYZ, None)?;
        let status = response.status;
        let (readyz, raw): (Readyz, Json) = response.parse()?;
        let code = match (status, readyz.status.as_str()) {
            (200, "ready") => exit::OK,
            (200, "unconfigured") => exit::UNCONFIGURED,
            (503, "degraded") => exit::DEGRADED,
            _ => {
                return Err(CliError::Protocol(format!(
                    "readyz answered HTTP {status} with status {:?}",
                    sanitize(&readyz.status)
                )))
            }
        };
        self.output.json(&raw)?;
        self.output.line(&format!("status: {}", readyz.status))?;
        self.output.line(&format!("node: {}", readyz.node_did))?;
        self.output
            .line(&format!("version: {}", sanitize(&readyz.version)))?;
        self.output
            .line(&format!("api version: {}", readyz.api_version))?;
        self.output.line(&format!(
            "revision: head {}, active {}",
            readyz.head_revision, readyz.active_revision
        ))?;
        self.output.line(&format!(
            "public config hash: {}",
            readyz
                .public_config_hash
                .as_deref()
                .map_or_else(|| "none".to_owned(), sanitize)
        ))?;
        Ok(code)
    }

    /// `stratum config schema`: prints the node's configuration schema.
    ///
    /// # Errors
    ///
    /// Transport, protocol and server errors.
    pub fn config_schema(&self) -> Result<u8, CliError> {
        let client = self.client()?;
        let (schema, raw): (Json, Json) = client.get(SCHEMA, None)?.into_json()?;
        self.output.json(&raw)?;
        if let Some(version) = schema.get("schema_version") {
            self.output.line(&format!("schema version {version}"))?;
        }
        let fields = schema
            .get("fields")
            .and_then(Json::as_array)
            .ok_or_else(|| CliError::Protocol("schema has no fields list".to_owned()))?;
        for field in fields {
            let text = |name: &str| field.get(name).map_or_else(String::new, compact);
            let kind = field
                .get("type")
                .and_then(|t| t.get("kind"))
                .map_or_else(String::new, compact);
            self.output.line(&sanitize(&format!(
                "\n{}  ({kind}, {}, default {})\n  {}",
                text("path").trim_matches('"'),
                text("apply_class").trim_matches('"'),
                text("default"),
                text("description").trim_matches('"'),
            )))?;
        }
        Ok(exit::OK)
    }

    /// `stratum config show`: prints the node's effective configuration,
    /// revisions and public-config hash. Signed.
    ///
    /// # Errors
    ///
    /// Key, transport, protocol and server errors.
    pub fn config_show(&self) -> Result<u8, CliError> {
        let key = self.key()?;
        let client = self.client()?;
        let (config, raw): (ConfigResponse, Json) = client.get(CONFIG, Some(&key))?.into_json()?;
        self.output.json(&raw)?;
        self.output.line(&format!(
            "revision: head {}, active {}",
            config.head_revision, config.active_revision
        ))?;
        self.output.line(&format!(
            "public config hash: {}",
            config.public_config_hash
        ))?;
        self.output.line("")?;
        self.output.line(sanitize(&config.text).trim_end())?;
        Ok(exit::OK)
    }

    /// `stratum config preview --set path=value …`: shows what the change
    /// would do, without changing anything. Signed when a key file is
    /// given (the node requires it once an administrator is bound).
    ///
    /// # Errors
    ///
    /// [`CliError::Usage`] for bad `--set` arguments,
    /// [`CliError::InvalidPreview`] when the result would be invalid, and
    /// key, transport, protocol and server errors.
    pub fn config_preview(
        &self,
        sets: &[String],
        base_revision: Option<u64>,
    ) -> Result<u8, CliError> {
        let changes = changes_from(sets)?;
        let key = match self.key_file {
            Some(_) => Some(self.key()?),
            None => None,
        };
        let client = self.client()?;
        let base = match base_revision {
            Some(base) => base,
            None => readyz(&client)?.head_revision,
        };
        let (preview, raw) = request_preview(&client, base, &changes, key.as_ref())?;
        self.output.json(&raw)?;
        self.show_preview(&preview)?;
        if preview.errors.is_empty() {
            Ok(exit::OK)
        } else {
            Err(invalid_preview(&preview))
        }
    }

    /// `stratum config apply --set path=value …`: previews the change,
    /// prints the diff and the strictest apply class, and after
    /// confirmation applies it on the same base revision. Signed.
    ///
    /// The operation ID is printed before the apply request is sent, so a
    /// retry after a lost response can pass it with `--operation-id`.
    ///
    /// # Errors
    ///
    /// [`CliError::NotConfirmed`] when not confirmed,
    /// [`CliError::InvalidPreview`], [`CliError::Usage`], and key,
    /// transport, protocol and server errors (`conflict` for a stale base
    /// revision, `invalid` for a rejected configuration).
    pub fn config_apply(&self, options: &ApplyOptions) -> Result<u8, CliError> {
        let changes = changes_from(&options.sets)?;
        let operation_id = operation_id(options.operation_id.as_deref())?;
        let key = self.key()?;
        let client = self.client()?;
        let ready = readyz(&client)?;
        let base = options.base_revision.unwrap_or(ready.head_revision);
        let (preview, preview_raw) = request_preview(&client, base, &changes, Some(&key))?;
        self.show_preview(&preview)?;
        let mut report = json!({
            "operation_id": operation_id.as_str(),
            "base_revision": base,
            "preview": preview_raw,
            "applied": false,
        });
        if !preview.errors.is_empty() {
            self.output.json(&report)?;
            return Err(invalid_preview(&preview));
        }
        if preview.changes.is_empty() {
            self.output.json(&report)?;
            self.output
                .line("nothing to apply: the change leaves the configuration as it is")?;
            return Ok(exit::OK);
        }
        if !self.confirmed("apply these changes?", options.confirmation)? {
            self.output.json(&report)?;
            return Err(CliError::NotConfirmed);
        }
        self.output.note(&format!(
            "operation id: {operation_id} (to retry after a lost response, pass --operation-id {operation_id})"
        ))?;
        let body = to_body(&ApplyRequest {
            node: ready.node_did,
            operation_id: &operation_id,
            base_revision: base,
            changes: &changes,
        })?;
        let (applied, applied_raw): (ApplyResponse, Json) =
            client.post(APPLY, &body, Some(&key))?.into_json()?;
        report["applied"] = Json::Bool(true);
        report["result"] = applied_raw;
        self.output.json(&report)?;
        self.output
            .line(&format!("applied: revision {}", applied.revision))?;
        self.output.line(&format!(
            "public config hash: {}",
            applied.public_config_hash
        ))?;
        self.output.line(&format!(
            "strictest apply class: {}",
            applied
                .strictest_apply_class
                .as_deref()
                .map_or_else(|| "none".to_owned(), sanitize)
        ))?;
        if applied.restart_required {
            self.output
                .line("restart required: the change takes effect after the controller restarts")?;
        }
        Ok(exit::OK)
    }

    /// `stratum audit checkpoint`: prints the audit checkpoint `<seq>:<hex>`
    /// and the node DID. Keep the checkpoint somewhere the node cannot
    /// write: it is what truncation of the audit log is detected against.
    /// Signed.
    ///
    /// # Errors
    ///
    /// Key, transport, protocol and server errors.
    pub fn audit_checkpoint(&self) -> Result<u8, CliError> {
        let key = self.key()?;
        let client = self.client()?;
        let (checkpoint, raw): (CheckpointResponse, Json) =
            client.get(CHECKPOINT, Some(&key))?.into_json()?;
        let expected = format!("{}:{}", checkpoint.sequence, checkpoint.tail_hash);
        if checkpoint.checkpoint != expected {
            return Err(CliError::Protocol(
                "checkpoint text does not match its sequence and tail hash".to_owned(),
            ));
        }
        self.output.json(&raw)?;
        self.output.line(&expected)?;
        self.output
            .line(&format!("node: {}", checkpoint.node_did))?;
        Ok(exit::OK)
    }

    /// `stratum backup [--expect-node <did>]`: asks the node for a backup
    /// and prints its directory, checkpoint and configuration revision.
    /// Signed.
    ///
    /// Before anything is printed, the returned manifest event must verify
    /// (ID and signature), be of kind 30078 and be authored by the node DID
    /// reported by `/readyz`; its content must be a `stratum-backup`
    /// version 1 manifest naming that node and listing the three backup
    /// files in order; and its signed `audit_checkpoint` must equal the
    /// response's `checkpoint`. Every printed fact except the backup directory therefore
    /// comes from the signed manifest; the directory is the node's unsigned
    /// statement of where it wrote the files. When `expect_node` is given, `/readyz` must report
    /// it before any request is signed.
    ///
    /// # Errors
    ///
    /// [`CliError::Refused`] for a manifest that fails verification or a
    /// node other than `expect_node`, `backup_refused` when the node has no
    /// backup recipient, and key, transport, protocol and server errors.
    pub fn backup(
        &self,
        operation_id_arg: Option<&str>,
        expect_node: Option<&DidNostr>,
    ) -> Result<u8, CliError> {
        let operation_id = operation_id(operation_id_arg)?;
        let key = self.key()?;
        let client = self.client()?;
        let ready = readyz(&client)?;
        check_expected_node(ready.node_did, expect_node)?;
        self.output.note(&format!(
            "operation id: {operation_id} (to retry after a lost response, pass --operation-id {operation_id})"
        ))?;
        let body = to_body(&BackupRequest {
            node: ready.node_did,
            operation_id: &operation_id,
        })?;
        let (backup, raw): (BackupResponse, Json) = client
            .post_with_timeout(BACKUP, &body, &key, BACKUP_TIMEOUT)?
            .into_json()?;
        let manifest = SignedEvent::deserialize(&backup.manifest).map_err(|_| {
            CliError::Refused("the backup manifest is not a validly signed nostr event".to_owned())
        })?;
        if manifest.author() != ready.node_did {
            return Err(CliError::Refused(format!(
                "the backup manifest is signed by {}, not by the node {}",
                manifest.author(),
                ready.node_did
            )));
        }
        if manifest.kind() != MANIFEST_KIND {
            return Err(CliError::Refused(format!(
                "the backup manifest is kind {}, not the NIP-78 kind {MANIFEST_KIND}",
                manifest.kind()
            )));
        }
        if !is_checkpoint(&backup.checkpoint) {
            return Err(CliError::Protocol(
                "backup checkpoint is not of the form <seq>:<64 hex>".to_owned(),
            ));
        }
        let content =
            check_manifest_content(manifest.content(), ready.node_did, &backup.checkpoint)?;
        let report = json!({
            "operation_id": operation_id.as_str(),
            "node_did": ready.node_did,
            "config_revision": content.config_revision,
            "created_at": content.created_at,
            "pod_archive": content.pod_archive,
            "keystore_recipients": content.keystore_recipients,
            "backup": raw,
        });
        self.output.json(&report)?;
        self.output
            .line(&format!("directory: {}", sanitize(&backup.directory)))?;
        self.output
            .line(&format!("checkpoint: {}", backup.checkpoint))?;
        self.output
            .line(&format!("config revision: {}", content.config_revision))?;
        if let Some(pods) = content.pod_archive {
            self.output.line(&format!(
                "pod archive: {} entries, {} bytes",
                pods.entries, pods.bytes
            ))?;
        }
        if !content.keystore_recipients.is_empty() {
            self.output.line(&format!(
                "keystore sealed to {} signer recipient(s)",
                content.keystore_recipients.len()
            ))?;
        }
        self.output.line(&format!(
            "manifest: event {} signed by the node {}",
            manifest.id(),
            manifest.author()
        ))?;
        Ok(exit::OK)
    }

    /// `stratum sign-challenge --claim-body-file <file> --expect-node <did>`:
    /// signs a claim body offline and prints the `Authorization` header
    /// value for it. No network.
    ///
    /// Before signing, the body must name this key as claimant and
    /// `expect_node` as the node, and must not have expired. The expected
    /// node comes from the operator (`stratumd` prints its node DID at
    /// start), never from the file, so a substituted claim file for another
    /// node is refused. The configuration hash and base revision in the body
    /// cannot be checked offline: they are signed as the node issued them.
    /// `stratum setup` checks them against its own derivation; prefer it
    /// when the node is reachable.
    ///
    /// The URL is the session URL: a bare origin gets
    /// `/api/v1/bootstrap/claim` appended, and a URL with a path must end in
    /// exactly that path, so no other route can be signed. It must equal
    /// the `url` the challenge response named. The file's bytes are signed
    /// exactly as they are, so a trailing newline added by an editor makes
    /// the signature fail at the node; a warning is printed if one is
    /// present.
    ///
    /// # Errors
    ///
    /// [`CliError::Usage`] for a URL with another path,
    /// [`CliError::Refused`] when the body names another claimant or node or
    /// has expired, [`CliError::FileContents`] when it is not a claim body,
    /// and key and file errors.
    pub fn sign_challenge(
        &self,
        claim_body_file: &Path,
        expect_node: &DidNostr,
    ) -> Result<u8, CliError> {
        let key = self.key()?;
        let url = if self.url.is_origin() {
            self.url.join(CLAIM)
        } else if self.url.path() == CLAIM {
            self.url.to_url_string()
        } else {
            return Err(CliError::Usage(format!(
                "sign-challenge signs only for the claim route: --url must be an origin or end in {CLAIM}"
            )));
        };
        let bytes = private_file::read(claim_body_file, CLAIM_BODY_FILE_LIMIT, ModePolicy::Any)
            .map_err(|source| CliError::File {
                path: claim_body_file.to_owned(),
                source,
            })?;
        let body = ClaimBody::parse(&bytes).map_err(|err| CliError::FileContents {
            path: claim_body_file.to_owned(),
            message: format!("not a claim body: {err}"),
        })?;
        if bytes.last().is_some_and(u8::is_ascii_whitespace) {
            self.output.note(
                "warning: the claim body file ends in whitespace; the node compares the exact bytes it issued",
            )?;
        }
        if body.claimant() != key.public() {
            return Err(CliError::Refused(format!(
                "the claim body names claimant {}, but this key is {}",
                body.claimant(),
                key.public()
            )));
        }
        body.check(client::now()?, expect_node, &key.public())
            .map_err(|err| CliError::Refused(err.to_string()))?;
        let authorization = client::sign(&key, "POST", &url, Some(body.as_bytes()))?;
        if self.output.is_json() {
            self.output.json(&json!({
                "url": url,
                "method": "POST",
                "authorization": authorization,
                "claim": claim_json(&body),
            }))?;
        } else {
            self.show_claim(&body)?;
            self.output.note(&format!("signed for POST {url}"))?;
            self.output.value_line(&authorization)?;
        }
        Ok(exit::OK)
    }

    /// Returns a client for the session URL, which must be a bare origin.
    pub(crate) fn client(&self) -> Result<Client, CliError> {
        if !self.url.is_origin() {
            return Err(CliError::Usage(
                "--url must be an origin such as http://127.0.0.1:7460 for this command".to_owned(),
            ));
        }
        Ok(Client::new(self.url.clone()))
    }

    /// Returns the key file path.
    pub(crate) fn key_path(&self) -> Result<&Path, CliError> {
        self.key_file.as_deref().ok_or(CliError::MissingKeyFile)
    }

    /// Loads the operator key.
    pub(crate) fn key(&self) -> Result<NostrSecretKey, CliError> {
        let path = self.key_path()?;
        load_key_file(path).map_err(|source| CliError::KeyFile {
            path: path.to_owned(),
            source,
        })
    }

    /// Returns the output writer.
    pub(crate) fn output(&self) -> &Output {
        &self.output
    }

    /// Asks for confirmation unless it is assumed.
    pub(crate) fn confirmed(
        &self,
        question: &str,
        confirmation: Confirmation,
    ) -> Result<bool, CliError> {
        match confirmation {
            Confirmation::Assumed => Ok(true),
            Confirmation::Prompt => {
                if let Some(answer) = self.output.confirm(question)? {
                    return Ok(answer);
                }
                self.output
                    .note("standard input is not a terminal: pass --yes to confirm")?;
                Ok(false)
            }
        }
    }

    /// Prints a preview in human form.
    pub(crate) fn show_preview(&self, preview: &PreviewResponse) -> Result<(), CliError> {
        self.output.line(&format!(
            "preview against revision {}:",
            preview.base_revision
        ))?;
        if preview.diff.is_empty() {
            self.output.line("(no textual change)")?;
        } else {
            self.output.line(sanitize(&preview.diff).trim_end())?;
        }
        if !preview.changes.is_empty() {
            self.output.line("changes:")?;
            for change in &preview.changes {
                let old = change
                    .old
                    .as_ref()
                    .map_or_else(|| "unset".to_owned(), compact);
                self.output.line(&sanitize(&format!(
                    "  {}: {old} -> {} ({})",
                    change.path,
                    compact(&change.new),
                    change.apply_class
                )))?;
            }
        }
        self.output.line(&format!(
            "strictest apply class: {}",
            preview
                .strictest_apply_class
                .as_deref()
                .map_or_else(|| "none".to_owned(), sanitize)
        ))?;
        for error in &preview.errors {
            self.output
                .line(&format!("invalid: {}", validation_line(error)))?;
        }
        Ok(())
    }

    /// Prints a claim body's fields in human form, to standard error.
    pub(crate) fn show_claim(&self, body: &ClaimBody) -> Result<(), CliError> {
        let fields = [
            ("node", body.node().to_string()),
            ("claimant", body.claimant().to_string()),
            ("nonce", body.nonce().to_string()),
            ("expires at", body.expires_at().to_string()),
            ("base revision", body.base_revision().to_string()),
            ("config sha256", body.config_sha256().to_string()),
        ];
        self.output.note("claim body:")?;
        for (name, value) in fields {
            self.output.note(&format!("  {name}: {value}"))?;
        }
        Ok(())
    }

    /// Prints a principal's DID and `npub`.
    fn print_identity(&self, did: &DidNostr, path: &Path) -> Result<u8, CliError> {
        self.output.json(&json!({
            "did": did,
            "npub": did.to_npub(),
            "key_file": path.display().to_string(),
        }))?;
        self.output.line(&did.to_string())?;
        self.output.line(&did.to_npub())?;
        Ok(exit::OK)
    }
}

/// Reads `/readyz` and checks the API version.
pub(crate) fn readyz(client: &Client) -> Result<Readyz, CliError> {
    let response: Response = client.get(READYZ, None)?;
    let (ready, _raw): (Readyz, Json) = match response.status {
        200 | 503 => response.parse()?,
        _ => return Err(response.into_error()),
    };
    if ready.api_version != API_VERSION {
        return Err(CliError::Protocol(format!(
            "the node speaks API version {}; this client speaks {API_VERSION}",
            ready.api_version
        )));
    }
    Ok(ready)
}

/// Refuses `actual` unless it is the node DID the operator expects, when
/// one was given.
pub(crate) fn check_expected_node(
    actual: DidNostr,
    expected: Option<&DidNostr>,
) -> Result<(), CliError> {
    match expected {
        Some(expected) if *expected != actual => Err(CliError::Refused(format!(
            "the node at this url reports {actual}, not the expected {expected}"
        ))),
        _ => Ok(()),
    }
}

/// Checks the content of a validly signed backup manifest event against
/// the node and the response's checkpoint, and returns it.
fn check_manifest_content(
    content: &str,
    node: DidNostr,
    checkpoint: &str,
) -> Result<BackupManifest, CliError> {
    let not_manifest =
        || CliError::Refused("the signed event is not a stratum backup manifest".to_owned());
    let value: Json = serde_json::from_str(content).map_err(|_| not_manifest())?;
    if value.get("format").and_then(Json::as_str) != Some(BACKUP_FORMAT) {
        return Err(not_manifest());
    }
    let version = value.get("format_version").and_then(Json::as_u64);
    // Whether the format requires the pod archive (`Some(true)`), forbids it
    // (`Some(false)`) or leaves it to the node (`None`, format 3), and the
    // files listed before it.
    let (pods_rule, files) = match version {
        Some(BACKUP_FORMAT_VERSION) => (Some(false), BACKUP_FILES),
        Some(BACKUP_FORMAT_VERSION_PODS) => (Some(true), BACKUP_FILES),
        Some(BACKUP_FORMAT_VERSION_SEALED) => (None, BACKUP_FILES_SEALED),
        _ => {
            return Err(CliError::Refused(format!(
                "the backup manifest has format version {}; this client reads versions \
                 {BACKUP_FORMAT_VERSION}, {BACKUP_FORMAT_VERSION_PODS} and \
                 {BACKUP_FORMAT_VERSION_SEALED}",
                version.map_or_else(|| "none".to_owned(), |v| v.to_string())
            )));
        }
    };
    let manifest = BackupManifest::deserialize(&value).map_err(|_| not_manifest())?;
    let pods = manifest.pod_archive.is_some();
    if manifest.format != BACKUP_FORMAT
        || Some(manifest.format_version) != version
        || pods_rule.is_some_and(|required| required != pods)
    {
        return Err(not_manifest());
    }
    if manifest.node_did != node {
        return Err(CliError::Refused(format!(
            "the backup manifest is for node {}, not {node}",
            manifest.node_did
        )));
    }
    if manifest.audit_checkpoint != checkpoint {
        return Err(CliError::Refused(format!(
            "the signed manifest's audit checkpoint {} differs from the reported {checkpoint}",
            sanitize(&manifest.audit_checkpoint)
        )));
    }
    let mut expected = files.to_vec();
    if pods {
        expected.push(BACKUP_POD_ARCHIVE);
    }
    if !manifest
        .files
        .iter()
        .map(|file| file.name.as_str())
        .eq(expected.iter().copied())
    {
        return Err(CliError::Refused(format!(
            "the backup manifest does not list exactly {}",
            expected.join(", ")
        )));
    }
    Ok(manifest)
}

/// Sends a preview request.
pub(crate) fn request_preview(
    client: &Client,
    base_revision: u64,
    changes: &[Change],
    key: Option<&NostrSecretKey>,
) -> Result<(PreviewResponse, Json), CliError> {
    let body = to_body(&PreviewRequest {
        base_revision,
        changes,
    })?;
    let (preview, raw): (PreviewResponse, Json) = client.post(PREVIEW, &body, key)?.into_json()?;
    if preview.base_revision != base_revision {
        return Err(CliError::Protocol(format!(
            "preview is against revision {}, not the requested {base_revision}",
            preview.base_revision
        )));
    }
    Ok((preview, raw))
}

/// Parses `--set` arguments, requiring at least one.
pub(crate) fn changes_from(sets: &[String]) -> Result<Vec<Change>, CliError> {
    let changes = parse_changes(sets).map_err(|err| CliError::Usage(err.to_string()))?;
    if changes.is_empty() {
        return Err(CliError::Usage(
            "give at least one --set path=value".to_owned(),
        ));
    }
    Ok(changes)
}

/// Serialises a request body once; these bytes are signed and sent.
pub(crate) fn to_body<T: Serialize>(request: &T) -> Result<Vec<u8>, CliError> {
    serde_json::to_vec(request)
        .map_err(|err| CliError::Local(format!("encoding the request failed: {err}")))
}

/// Parses a given operation ID or generates a random one.
pub(crate) fn operation_id(given: Option<&str>) -> Result<OperationId, CliError> {
    if let Some(text) = given {
        return text
            .parse()
            .map_err(|err| CliError::Usage(format!("--operation-id: {err}")));
    }
    let random = client::random_32()?;
    let text = format!("op-{}", hex::encode(&random[..16]));
    text.parse()
        .map_err(|err| CliError::Local(format!("generated operation id: {err}")))
}

/// Builds the error for a preview that reports validation errors.
pub(crate) fn invalid_preview(preview: &PreviewResponse) -> CliError {
    CliError::InvalidPreview {
        details: preview.errors.iter().map(validation_line).collect(),
    }
}

/// Formats one validation error as `path: message`.
fn validation_line(error: &crate::wire::ValidationEntry) -> String {
    match &error.path {
        Some(path) => sanitize(&format!("{path}: {}", error.message)),
        None => sanitize(&error.message),
    }
}

/// Renders a JSON value compactly.
fn compact(value: &Json) -> String {
    value.to_string()
}

/// Returns the claim body's fields as JSON.
pub(crate) fn claim_json(body: &ClaimBody) -> Json {
    json!({
        "nonce": body.nonce(),
        "node": body.node(),
        "claimant": body.claimant(),
        "expires_at": body.expires_at(),
        "base_revision": body.base_revision(),
        "config_sha256": body.config_sha256(),
    })
}

/// Returns `true` for `<decimal>:<64 lowercase hex>`.
fn is_checkpoint(text: &str) -> bool {
    text.split_once(':').is_some_and(|(seq, hash)| {
        !seq.is_empty()
            && seq.bytes().all(|b| b.is_ascii_digit())
            && hash.len() == 64
            && hash.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
    })
}

#[cfg(test)]
mod tests {
    use std::time::Duration;

    use super::BACKUP_TIMEOUT;

    /// The node answers a backup it cannot quiesce only after waiting 90 s
    /// for the gate (E2.23); the client must still be listening then, or it
    /// reports a working node as unreachable. Found by the end-to-end run.
    #[test]
    fn backup_outwaits_the_nodes_drain_bound() {
        assert!(
            BACKUP_TIMEOUT > Duration::from_secs(90 + 60),
            "the drain bound plus time to snapshot and archive"
        );
    }
}