Skip to main content

stratum_node_cli/
session.rs

1//! The `stratum` commands, run against one node with one operator key.
2
3use std::path::{Path, PathBuf};
4use std::time::Duration;
5
6use serde::{Deserialize as _, Serialize};
7use serde_json::{json, Value as Json};
8use stratum_node_config::Change;
9use stratum_node_core::{ClaimBody, DidNostr, NostrSecretKey, OperationId, SignedEvent};
10
11use crate::changes::parse_changes;
12use crate::client::{self, Client, Response};
13use crate::error::CliError;
14use crate::exit;
15use crate::key::{generate_key_file, load_key_file};
16use crate::output::{sanitize, Output};
17use crate::private_file::{self, ModePolicy};
18use crate::url::LoopbackUrl;
19use crate::wire::{
20    ApplyRequest, ApplyResponse, BackupManifest, BackupRequest, BackupResponse, CheckpointResponse,
21    ConfigResponse, PreviewRequest, PreviewResponse, Readyz, BACKUP_FILES, BACKUP_FORMAT,
22    BACKUP_FORMAT_VERSION, BACKUP_FORMAT_VERSION_PODS, BACKUP_POD_ARCHIVE,
23};
24
25/// `GET` route: readiness.
26pub(crate) const READYZ: &str = "/readyz";
27/// `GET` route: the configuration schema.
28const SCHEMA: &str = "/api/v1/config/schema";
29/// `GET` route: the effective configuration.
30const CONFIG: &str = "/api/v1/config";
31/// `POST` route: preview a change.
32pub(crate) const PREVIEW: &str = "/api/v1/config/preview";
33/// `POST` route: apply a change.
34const APPLY: &str = "/api/v1/config/apply";
35/// `GET` route: the audit checkpoint.
36const CHECKPOINT: &str = "/api/v1/audit/checkpoint";
37/// `POST` route: take a backup.
38const BACKUP: &str = "/api/v1/backup";
39
40/// How long `backup` waits for the node's answer. A node with pods may wait
41/// 90 seconds for the gate to drain before it answers `gate_unavailable`
42/// (E2.23), then snapshots the store and archives every pod; the usual
43/// 30-second request timeout would report a node still working as
44/// unreachable.
45const BACKUP_TIMEOUT: Duration = Duration::from_secs(15 * 60);
46/// `POST` route: request a bootstrap challenge.
47pub(crate) const CHALLENGE: &str = "/api/v1/bootstrap/challenge";
48/// `POST` route: claim the node.
49pub(crate) const CLAIM: &str = "/api/v1/bootstrap/claim";
50
51/// The only HTTP API version this client speaks.
52const API_VERSION: u64 = 1;
53
54/// The NIP-78 application-data event kind the backup manifest is signed as.
55const MANIFEST_KIND: u16 = 30078;
56
57/// The largest claim body file `sign-challenge` reads.
58const CLAIM_BODY_FILE_LIMIT: usize = 64 * 1024;
59
60/// Whether a command that changes the node may proceed without asking.
61#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
62#[non_exhaustive]
63pub enum Confirmation {
64    /// Ask on the terminal; refuse when standard input is not a terminal.
65    #[default]
66    Prompt,
67    /// Proceed without asking (`--yes`).
68    Assumed,
69}
70
71/// Options for [`Session::config_apply`].
72#[derive(Debug, Clone, Default)]
73pub struct ApplyOptions {
74    /// The `--set path=value` arguments; see [`parse_changes`](crate::parse_changes).
75    pub sets: Vec<String>,
76    /// The revision the change is based on; the node's head revision when
77    /// `None`.
78    pub base_revision: Option<u64>,
79    /// The operation ID; a random one is generated and printed when `None`.
80    pub operation_id: Option<String>,
81    /// Whether to ask before applying.
82    pub confirmation: Confirmation,
83}
84
85/// Options for [`Session::setup`].
86#[derive(Debug, Clone, Default)]
87pub struct SetupOptions {
88    /// The node's bootstrap token file, `<state_dir>/bootstrap-token`.
89    pub token_file: PathBuf,
90    /// The `--set path=value` arguments for the initial configuration.
91    pub sets: Vec<String>,
92    /// Where the signed claim request is saved before it is sent;
93    /// `<key file>.setup-resume` when `None`.
94    pub resume_file: Option<PathBuf>,
95    /// Whether to ask before claiming.
96    pub confirmation: Confirmation,
97    /// The node DID the operator expects (`--expect-node`), as `stratumd`
98    /// printed it at start. When given, the bootstrap token is sent only if
99    /// `/readyz` reports this DID and the claim body names it. When `None`,
100    /// setup trusts whatever answers on the loopback port.
101    pub expect_node: Option<DidNostr>,
102    /// Also print the full configuration text whose SHA-256 the claim
103    /// binds (`--show-text`).
104    pub show_text: bool,
105}
106
107/// One node, one optional operator key file and one output format: the
108/// context every `stratum` command runs in.
109///
110/// Each command method writes its results through [`Output`] and returns
111/// the process exit code on success (see [`exit`](crate::exit)); failures
112/// are returned as [`CliError`], whose
113/// [`exit_code`](CliError::exit_code) gives theirs. Every authenticated
114/// request is signed with [`NostrSecretKey::sign_request_with_nonce`] over
115/// the exact URL, method and body bytes sent, with a fresh random nonce and
116/// fresh auxiliary randomness.
117///
118/// # Examples
119///
120/// ```
121/// use stratum_node_cli::{CliError, Output, OutputFormat, Session};
122///
123/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
124/// let session = Session::new("http://127.0.0.1:7460".parse()?, None, Output::new(OutputFormat::Json));
125/// // Commands that need the operator key say so before touching the network.
126/// assert!(matches!(session.audit_checkpoint(), Err(CliError::MissingKeyFile)));
127/// # Ok(())
128/// # }
129/// ```
130#[derive(Debug, Clone)]
131pub struct Session {
132    url: LoopbackUrl,
133    key_file: Option<PathBuf>,
134    output: Output,
135}
136
137impl Session {
138    /// Creates a session for the node at `url`, signing with the key in
139    /// `key_file` when a command needs it.
140    pub fn new(url: LoopbackUrl, key_file: Option<PathBuf>, output: Output) -> Self {
141        Self {
142            url,
143            key_file,
144            output,
145        }
146    }
147
148    /// `stratum key generate --out <file>`: creates a new operator key file
149    /// and prints the operator's DID and `npub`.
150    ///
151    /// # Errors
152    ///
153    /// [`CliError::KeyFile`] when the file exists or cannot be created.
154    pub fn key_generate(&self, out: &Path) -> Result<u8, CliError> {
155        let key = generate_key_file(out).map_err(|source| CliError::KeyFile {
156            path: out.to_owned(),
157            source,
158        })?;
159        self.print_identity(&key.public(), out)
160    }
161
162    /// `stratum key show`: prints the DID and `npub` of the operator key.
163    ///
164    /// # Errors
165    ///
166    /// [`CliError::MissingKeyFile`] or [`CliError::KeyFile`].
167    pub fn key_show(&self) -> Result<u8, CliError> {
168        let path = self.key_path()?;
169        let key = self.key()?;
170        self.print_identity(&key.public(), path)
171    }
172
173    /// `stratum status`: reads `/readyz` and returns [`exit::OK`] when the
174    /// node is ready, [`exit::UNCONFIGURED`] or [`exit::DEGRADED`].
175    ///
176    /// # Errors
177    ///
178    /// [`CliError::Unreachable`] (exit 2) or [`CliError::Protocol`].
179    pub fn status(&self) -> Result<u8, CliError> {
180        let client = self.client()?;
181        let response = client.get(READYZ, None)?;
182        let status = response.status;
183        let (readyz, raw): (Readyz, Json) = response.parse()?;
184        let code = match (status, readyz.status.as_str()) {
185            (200, "ready") => exit::OK,
186            (200, "unconfigured") => exit::UNCONFIGURED,
187            (503, "degraded") => exit::DEGRADED,
188            _ => {
189                return Err(CliError::Protocol(format!(
190                    "readyz answered HTTP {status} with status {:?}",
191                    sanitize(&readyz.status)
192                )))
193            }
194        };
195        self.output.json(&raw)?;
196        self.output.line(&format!("status: {}", readyz.status))?;
197        self.output.line(&format!("node: {}", readyz.node_did))?;
198        self.output
199            .line(&format!("version: {}", sanitize(&readyz.version)))?;
200        self.output
201            .line(&format!("api version: {}", readyz.api_version))?;
202        self.output.line(&format!(
203            "revision: head {}, active {}",
204            readyz.head_revision, readyz.active_revision
205        ))?;
206        self.output.line(&format!(
207            "public config hash: {}",
208            readyz
209                .public_config_hash
210                .as_deref()
211                .map_or_else(|| "none".to_owned(), sanitize)
212        ))?;
213        Ok(code)
214    }
215
216    /// `stratum config schema`: prints the node's configuration schema.
217    ///
218    /// # Errors
219    ///
220    /// Transport, protocol and server errors.
221    pub fn config_schema(&self) -> Result<u8, CliError> {
222        let client = self.client()?;
223        let (schema, raw): (Json, Json) = client.get(SCHEMA, None)?.into_json()?;
224        self.output.json(&raw)?;
225        if let Some(version) = schema.get("schema_version") {
226            self.output.line(&format!("schema version {version}"))?;
227        }
228        let fields = schema
229            .get("fields")
230            .and_then(Json::as_array)
231            .ok_or_else(|| CliError::Protocol("schema has no fields list".to_owned()))?;
232        for field in fields {
233            let text = |name: &str| field.get(name).map_or_else(String::new, compact);
234            let kind = field
235                .get("type")
236                .and_then(|t| t.get("kind"))
237                .map_or_else(String::new, compact);
238            self.output.line(&sanitize(&format!(
239                "\n{}  ({kind}, {}, default {})\n  {}",
240                text("path").trim_matches('"'),
241                text("apply_class").trim_matches('"'),
242                text("default"),
243                text("description").trim_matches('"'),
244            )))?;
245        }
246        Ok(exit::OK)
247    }
248
249    /// `stratum config show`: prints the node's effective configuration,
250    /// revisions and public-config hash. Signed.
251    ///
252    /// # Errors
253    ///
254    /// Key, transport, protocol and server errors.
255    pub fn config_show(&self) -> Result<u8, CliError> {
256        let key = self.key()?;
257        let client = self.client()?;
258        let (config, raw): (ConfigResponse, Json) = client.get(CONFIG, Some(&key))?.into_json()?;
259        self.output.json(&raw)?;
260        self.output.line(&format!(
261            "revision: head {}, active {}",
262            config.head_revision, config.active_revision
263        ))?;
264        self.output.line(&format!(
265            "public config hash: {}",
266            config.public_config_hash
267        ))?;
268        self.output.line("")?;
269        self.output.line(sanitize(&config.text).trim_end())?;
270        Ok(exit::OK)
271    }
272
273    /// `stratum config preview --set path=value …`: shows what the change
274    /// would do, without changing anything. Signed when a key file is
275    /// given (the node requires it once an administrator is bound).
276    ///
277    /// # Errors
278    ///
279    /// [`CliError::Usage`] for bad `--set` arguments,
280    /// [`CliError::InvalidPreview`] when the result would be invalid, and
281    /// key, transport, protocol and server errors.
282    pub fn config_preview(
283        &self,
284        sets: &[String],
285        base_revision: Option<u64>,
286    ) -> Result<u8, CliError> {
287        let changes = changes_from(sets)?;
288        let key = match self.key_file {
289            Some(_) => Some(self.key()?),
290            None => None,
291        };
292        let client = self.client()?;
293        let base = match base_revision {
294            Some(base) => base,
295            None => readyz(&client)?.head_revision,
296        };
297        let (preview, raw) = request_preview(&client, base, &changes, key.as_ref())?;
298        self.output.json(&raw)?;
299        self.show_preview(&preview)?;
300        if preview.errors.is_empty() {
301            Ok(exit::OK)
302        } else {
303            Err(invalid_preview(&preview))
304        }
305    }
306
307    /// `stratum config apply --set path=value …`: previews the change,
308    /// prints the diff and the strictest apply class, and after
309    /// confirmation applies it on the same base revision. Signed.
310    ///
311    /// The operation ID is printed before the apply request is sent, so a
312    /// retry after a lost response can pass it with `--operation-id`.
313    ///
314    /// # Errors
315    ///
316    /// [`CliError::NotConfirmed`] when not confirmed,
317    /// [`CliError::InvalidPreview`], [`CliError::Usage`], and key,
318    /// transport, protocol and server errors (`conflict` for a stale base
319    /// revision, `invalid` for a rejected configuration).
320    pub fn config_apply(&self, options: &ApplyOptions) -> Result<u8, CliError> {
321        let changes = changes_from(&options.sets)?;
322        let operation_id = operation_id(options.operation_id.as_deref())?;
323        let key = self.key()?;
324        let client = self.client()?;
325        let ready = readyz(&client)?;
326        let base = options.base_revision.unwrap_or(ready.head_revision);
327        let (preview, preview_raw) = request_preview(&client, base, &changes, Some(&key))?;
328        self.show_preview(&preview)?;
329        let mut report = json!({
330            "operation_id": operation_id.as_str(),
331            "base_revision": base,
332            "preview": preview_raw,
333            "applied": false,
334        });
335        if !preview.errors.is_empty() {
336            self.output.json(&report)?;
337            return Err(invalid_preview(&preview));
338        }
339        if preview.changes.is_empty() {
340            self.output.json(&report)?;
341            self.output
342                .line("nothing to apply: the change leaves the configuration as it is")?;
343            return Ok(exit::OK);
344        }
345        if !self.confirmed("apply these changes?", options.confirmation)? {
346            self.output.json(&report)?;
347            return Err(CliError::NotConfirmed);
348        }
349        self.output.note(&format!(
350            "operation id: {operation_id} (to retry after a lost response, pass --operation-id {operation_id})"
351        ))?;
352        let body = to_body(&ApplyRequest {
353            node: ready.node_did,
354            operation_id: &operation_id,
355            base_revision: base,
356            changes: &changes,
357        })?;
358        let (applied, applied_raw): (ApplyResponse, Json) =
359            client.post(APPLY, &body, Some(&key))?.into_json()?;
360        report["applied"] = Json::Bool(true);
361        report["result"] = applied_raw;
362        self.output.json(&report)?;
363        self.output
364            .line(&format!("applied: revision {}", applied.revision))?;
365        self.output.line(&format!(
366            "public config hash: {}",
367            applied.public_config_hash
368        ))?;
369        self.output.line(&format!(
370            "strictest apply class: {}",
371            applied
372                .strictest_apply_class
373                .as_deref()
374                .map_or_else(|| "none".to_owned(), sanitize)
375        ))?;
376        if applied.restart_required {
377            self.output
378                .line("restart required: the change takes effect after the controller restarts")?;
379        }
380        Ok(exit::OK)
381    }
382
383    /// `stratum audit checkpoint`: prints the audit checkpoint `<seq>:<hex>`
384    /// and the node DID. Keep the checkpoint somewhere the node cannot
385    /// write: it is what truncation of the audit log is detected against.
386    /// Signed.
387    ///
388    /// # Errors
389    ///
390    /// Key, transport, protocol and server errors.
391    pub fn audit_checkpoint(&self) -> Result<u8, CliError> {
392        let key = self.key()?;
393        let client = self.client()?;
394        let (checkpoint, raw): (CheckpointResponse, Json) =
395            client.get(CHECKPOINT, Some(&key))?.into_json()?;
396        let expected = format!("{}:{}", checkpoint.sequence, checkpoint.tail_hash);
397        if checkpoint.checkpoint != expected {
398            return Err(CliError::Protocol(
399                "checkpoint text does not match its sequence and tail hash".to_owned(),
400            ));
401        }
402        self.output.json(&raw)?;
403        self.output.line(&expected)?;
404        self.output
405            .line(&format!("node: {}", checkpoint.node_did))?;
406        Ok(exit::OK)
407    }
408
409    /// `stratum backup [--expect-node <did>]`: asks the node for a backup
410    /// and prints its directory, checkpoint and configuration revision.
411    /// Signed.
412    ///
413    /// Before anything is printed, the returned manifest event must verify
414    /// (ID and signature), be of kind 30078 and be authored by the node DID
415    /// reported by `/readyz`; its content must be a `stratum-backup`
416    /// version 1 manifest naming that node and listing the three backup
417    /// files in order; and its signed `audit_checkpoint` must equal the
418    /// response's `checkpoint`. Every printed fact except the backup directory therefore
419    /// comes from the signed manifest; the directory is the node's unsigned
420    /// statement of where it wrote the files. When `expect_node` is given, `/readyz` must report
421    /// it before any request is signed.
422    ///
423    /// # Errors
424    ///
425    /// [`CliError::Refused`] for a manifest that fails verification or a
426    /// node other than `expect_node`, `backup_refused` when the node has no
427    /// backup recipient, and key, transport, protocol and server errors.
428    pub fn backup(
429        &self,
430        operation_id_arg: Option<&str>,
431        expect_node: Option<&DidNostr>,
432    ) -> Result<u8, CliError> {
433        let operation_id = operation_id(operation_id_arg)?;
434        let key = self.key()?;
435        let client = self.client()?;
436        let ready = readyz(&client)?;
437        check_expected_node(ready.node_did, expect_node)?;
438        self.output.note(&format!(
439            "operation id: {operation_id} (to retry after a lost response, pass --operation-id {operation_id})"
440        ))?;
441        let body = to_body(&BackupRequest {
442            node: ready.node_did,
443            operation_id: &operation_id,
444        })?;
445        let (backup, raw): (BackupResponse, Json) = client
446            .post_with_timeout(BACKUP, &body, &key, BACKUP_TIMEOUT)?
447            .into_json()?;
448        let manifest = SignedEvent::deserialize(&backup.manifest).map_err(|_| {
449            CliError::Refused("the backup manifest is not a validly signed nostr event".to_owned())
450        })?;
451        if manifest.author() != ready.node_did {
452            return Err(CliError::Refused(format!(
453                "the backup manifest is signed by {}, not by the node {}",
454                manifest.author(),
455                ready.node_did
456            )));
457        }
458        if manifest.kind() != MANIFEST_KIND {
459            return Err(CliError::Refused(format!(
460                "the backup manifest is kind {}, not the NIP-78 kind {MANIFEST_KIND}",
461                manifest.kind()
462            )));
463        }
464        if !is_checkpoint(&backup.checkpoint) {
465            return Err(CliError::Protocol(
466                "backup checkpoint is not of the form <seq>:<64 hex>".to_owned(),
467            ));
468        }
469        let content =
470            check_manifest_content(manifest.content(), ready.node_did, &backup.checkpoint)?;
471        let report = json!({
472            "operation_id": operation_id.as_str(),
473            "node_did": ready.node_did,
474            "config_revision": content.config_revision,
475            "created_at": content.created_at,
476            "pod_archive": content.pod_archive,
477            "backup": raw,
478        });
479        self.output.json(&report)?;
480        self.output
481            .line(&format!("directory: {}", sanitize(&backup.directory)))?;
482        self.output
483            .line(&format!("checkpoint: {}", backup.checkpoint))?;
484        self.output
485            .line(&format!("config revision: {}", content.config_revision))?;
486        if let Some(pods) = content.pod_archive {
487            self.output.line(&format!(
488                "pod archive: {} entries, {} bytes",
489                pods.entries, pods.bytes
490            ))?;
491        }
492        self.output.line(&format!(
493            "manifest: event {} signed by the node {}",
494            manifest.id(),
495            manifest.author()
496        ))?;
497        Ok(exit::OK)
498    }
499
500    /// `stratum sign-challenge --claim-body-file <file> --expect-node <did>`:
501    /// signs a claim body offline and prints the `Authorization` header
502    /// value for it. No network.
503    ///
504    /// Before signing, the body must name this key as claimant and
505    /// `expect_node` as the node, and must not have expired. The expected
506    /// node comes from the operator (`stratumd` prints its node DID at
507    /// start), never from the file, so a substituted claim file for another
508    /// node is refused. The configuration hash and base revision in the body
509    /// cannot be checked offline: they are signed as the node issued them.
510    /// `stratum setup` checks them against its own derivation; prefer it
511    /// when the node is reachable.
512    ///
513    /// The URL is the session URL: a bare origin gets
514    /// `/api/v1/bootstrap/claim` appended, and a URL with a path must end in
515    /// exactly that path, so no other route can be signed. It must equal
516    /// the `url` the challenge response named. The file's bytes are signed
517    /// exactly as they are, so a trailing newline added by an editor makes
518    /// the signature fail at the node; a warning is printed if one is
519    /// present.
520    ///
521    /// # Errors
522    ///
523    /// [`CliError::Usage`] for a URL with another path,
524    /// [`CliError::Refused`] when the body names another claimant or node or
525    /// has expired, [`CliError::FileContents`] when it is not a claim body,
526    /// and key and file errors.
527    pub fn sign_challenge(
528        &self,
529        claim_body_file: &Path,
530        expect_node: &DidNostr,
531    ) -> Result<u8, CliError> {
532        let key = self.key()?;
533        let url = if self.url.is_origin() {
534            self.url.join(CLAIM)
535        } else if self.url.path() == CLAIM {
536            self.url.to_url_string()
537        } else {
538            return Err(CliError::Usage(format!(
539                "sign-challenge signs only for the claim route: --url must be an origin or end in {CLAIM}"
540            )));
541        };
542        let bytes = private_file::read(claim_body_file, CLAIM_BODY_FILE_LIMIT, ModePolicy::Any)
543            .map_err(|source| CliError::File {
544                path: claim_body_file.to_owned(),
545                source,
546            })?;
547        let body = ClaimBody::parse(&bytes).map_err(|err| CliError::FileContents {
548            path: claim_body_file.to_owned(),
549            message: format!("not a claim body: {err}"),
550        })?;
551        if bytes.last().is_some_and(u8::is_ascii_whitespace) {
552            self.output.note(
553                "warning: the claim body file ends in whitespace; the node compares the exact bytes it issued",
554            )?;
555        }
556        if body.claimant() != key.public() {
557            return Err(CliError::Refused(format!(
558                "the claim body names claimant {}, but this key is {}",
559                body.claimant(),
560                key.public()
561            )));
562        }
563        body.check(client::now()?, expect_node, &key.public())
564            .map_err(|err| CliError::Refused(err.to_string()))?;
565        let authorization = client::sign(&key, "POST", &url, Some(body.as_bytes()))?;
566        if self.output.is_json() {
567            self.output.json(&json!({
568                "url": url,
569                "method": "POST",
570                "authorization": authorization,
571                "claim": claim_json(&body),
572            }))?;
573        } else {
574            self.show_claim(&body)?;
575            self.output.note(&format!("signed for POST {url}"))?;
576            self.output.value_line(&authorization)?;
577        }
578        Ok(exit::OK)
579    }
580
581    /// Returns a client for the session URL, which must be a bare origin.
582    pub(crate) fn client(&self) -> Result<Client, CliError> {
583        if !self.url.is_origin() {
584            return Err(CliError::Usage(
585                "--url must be an origin such as http://127.0.0.1:7460 for this command".to_owned(),
586            ));
587        }
588        Ok(Client::new(self.url.clone()))
589    }
590
591    /// Returns the key file path.
592    pub(crate) fn key_path(&self) -> Result<&Path, CliError> {
593        self.key_file.as_deref().ok_or(CliError::MissingKeyFile)
594    }
595
596    /// Loads the operator key.
597    pub(crate) fn key(&self) -> Result<NostrSecretKey, CliError> {
598        let path = self.key_path()?;
599        load_key_file(path).map_err(|source| CliError::KeyFile {
600            path: path.to_owned(),
601            source,
602        })
603    }
604
605    /// Returns the output writer.
606    pub(crate) fn output(&self) -> &Output {
607        &self.output
608    }
609
610    /// Asks for confirmation unless it is assumed.
611    pub(crate) fn confirmed(
612        &self,
613        question: &str,
614        confirmation: Confirmation,
615    ) -> Result<bool, CliError> {
616        match confirmation {
617            Confirmation::Assumed => Ok(true),
618            Confirmation::Prompt => {
619                if let Some(answer) = self.output.confirm(question)? {
620                    return Ok(answer);
621                }
622                self.output
623                    .note("standard input is not a terminal: pass --yes to confirm")?;
624                Ok(false)
625            }
626        }
627    }
628
629    /// Prints a preview in human form.
630    pub(crate) fn show_preview(&self, preview: &PreviewResponse) -> Result<(), CliError> {
631        self.output.line(&format!(
632            "preview against revision {}:",
633            preview.base_revision
634        ))?;
635        if preview.diff.is_empty() {
636            self.output.line("(no textual change)")?;
637        } else {
638            self.output.line(sanitize(&preview.diff).trim_end())?;
639        }
640        if !preview.changes.is_empty() {
641            self.output.line("changes:")?;
642            for change in &preview.changes {
643                let old = change
644                    .old
645                    .as_ref()
646                    .map_or_else(|| "unset".to_owned(), compact);
647                self.output.line(&sanitize(&format!(
648                    "  {}: {old} -> {} ({})",
649                    change.path,
650                    compact(&change.new),
651                    change.apply_class
652                )))?;
653            }
654        }
655        self.output.line(&format!(
656            "strictest apply class: {}",
657            preview
658                .strictest_apply_class
659                .as_deref()
660                .map_or_else(|| "none".to_owned(), sanitize)
661        ))?;
662        for error in &preview.errors {
663            self.output
664                .line(&format!("invalid: {}", validation_line(error)))?;
665        }
666        Ok(())
667    }
668
669    /// Prints a claim body's fields in human form, to standard error.
670    pub(crate) fn show_claim(&self, body: &ClaimBody) -> Result<(), CliError> {
671        let fields = [
672            ("node", body.node().to_string()),
673            ("claimant", body.claimant().to_string()),
674            ("nonce", body.nonce().to_string()),
675            ("expires at", body.expires_at().to_string()),
676            ("base revision", body.base_revision().to_string()),
677            ("config sha256", body.config_sha256().to_string()),
678        ];
679        self.output.note("claim body:")?;
680        for (name, value) in fields {
681            self.output.note(&format!("  {name}: {value}"))?;
682        }
683        Ok(())
684    }
685
686    /// Prints a principal's DID and `npub`.
687    fn print_identity(&self, did: &DidNostr, path: &Path) -> Result<u8, CliError> {
688        self.output.json(&json!({
689            "did": did,
690            "npub": did.to_npub(),
691            "key_file": path.display().to_string(),
692        }))?;
693        self.output.line(&did.to_string())?;
694        self.output.line(&did.to_npub())?;
695        Ok(exit::OK)
696    }
697}
698
699/// Reads `/readyz` and checks the API version.
700pub(crate) fn readyz(client: &Client) -> Result<Readyz, CliError> {
701    let response: Response = client.get(READYZ, None)?;
702    let (ready, _raw): (Readyz, Json) = match response.status {
703        200 | 503 => response.parse()?,
704        _ => return Err(response.into_error()),
705    };
706    if ready.api_version != API_VERSION {
707        return Err(CliError::Protocol(format!(
708            "the node speaks API version {}; this client speaks {API_VERSION}",
709            ready.api_version
710        )));
711    }
712    Ok(ready)
713}
714
715/// Refuses `actual` unless it is the node DID the operator expects, when
716/// one was given.
717pub(crate) fn check_expected_node(
718    actual: DidNostr,
719    expected: Option<&DidNostr>,
720) -> Result<(), CliError> {
721    match expected {
722        Some(expected) if *expected != actual => Err(CliError::Refused(format!(
723            "the node at this url reports {actual}, not the expected {expected}"
724        ))),
725        _ => Ok(()),
726    }
727}
728
729/// Checks the content of a validly signed backup manifest event against
730/// the node and the response's checkpoint, and returns it.
731fn check_manifest_content(
732    content: &str,
733    node: DidNostr,
734    checkpoint: &str,
735) -> Result<BackupManifest, CliError> {
736    let not_manifest =
737        || CliError::Refused("the signed event is not a stratum backup manifest".to_owned());
738    let value: Json = serde_json::from_str(content).map_err(|_| not_manifest())?;
739    if value.get("format").and_then(Json::as_str) != Some(BACKUP_FORMAT) {
740        return Err(not_manifest());
741    }
742    let version = value.get("format_version").and_then(Json::as_u64);
743    let pods = match version {
744        Some(BACKUP_FORMAT_VERSION) => false,
745        Some(BACKUP_FORMAT_VERSION_PODS) => true,
746        _ => {
747            return Err(CliError::Refused(format!(
748                "the backup manifest has format version {}; this client reads versions \
749                 {BACKUP_FORMAT_VERSION} and {BACKUP_FORMAT_VERSION_PODS}",
750                version.map_or_else(|| "none".to_owned(), |v| v.to_string())
751            )));
752        }
753    };
754    let manifest = BackupManifest::deserialize(&value).map_err(|_| not_manifest())?;
755    if manifest.format != BACKUP_FORMAT
756        || Some(manifest.format_version) != version
757        || manifest.pod_archive.is_some() != pods
758    {
759        return Err(not_manifest());
760    }
761    if manifest.node_did != node {
762        return Err(CliError::Refused(format!(
763            "the backup manifest is for node {}, not {node}",
764            manifest.node_did
765        )));
766    }
767    if manifest.audit_checkpoint != checkpoint {
768        return Err(CliError::Refused(format!(
769            "the signed manifest's audit checkpoint {} differs from the reported {checkpoint}",
770            sanitize(&manifest.audit_checkpoint)
771        )));
772    }
773    let mut expected = BACKUP_FILES.to_vec();
774    if pods {
775        expected.push(BACKUP_POD_ARCHIVE);
776    }
777    if !manifest
778        .files
779        .iter()
780        .map(|file| file.name.as_str())
781        .eq(expected.iter().copied())
782    {
783        return Err(CliError::Refused(format!(
784            "the backup manifest does not list exactly {}",
785            expected.join(", ")
786        )));
787    }
788    Ok(manifest)
789}
790
791/// Sends a preview request.
792pub(crate) fn request_preview(
793    client: &Client,
794    base_revision: u64,
795    changes: &[Change],
796    key: Option<&NostrSecretKey>,
797) -> Result<(PreviewResponse, Json), CliError> {
798    let body = to_body(&PreviewRequest {
799        base_revision,
800        changes,
801    })?;
802    let (preview, raw): (PreviewResponse, Json) = client.post(PREVIEW, &body, key)?.into_json()?;
803    if preview.base_revision != base_revision {
804        return Err(CliError::Protocol(format!(
805            "preview is against revision {}, not the requested {base_revision}",
806            preview.base_revision
807        )));
808    }
809    Ok((preview, raw))
810}
811
812/// Parses `--set` arguments, requiring at least one.
813pub(crate) fn changes_from(sets: &[String]) -> Result<Vec<Change>, CliError> {
814    let changes = parse_changes(sets).map_err(|err| CliError::Usage(err.to_string()))?;
815    if changes.is_empty() {
816        return Err(CliError::Usage(
817            "give at least one --set path=value".to_owned(),
818        ));
819    }
820    Ok(changes)
821}
822
823/// Serialises a request body once; these bytes are signed and sent.
824pub(crate) fn to_body<T: Serialize>(request: &T) -> Result<Vec<u8>, CliError> {
825    serde_json::to_vec(request)
826        .map_err(|err| CliError::Local(format!("encoding the request failed: {err}")))
827}
828
829/// Parses a given operation ID or generates a random one.
830pub(crate) fn operation_id(given: Option<&str>) -> Result<OperationId, CliError> {
831    if let Some(text) = given {
832        return text
833            .parse()
834            .map_err(|err| CliError::Usage(format!("--operation-id: {err}")));
835    }
836    let random = client::random_32()?;
837    let text = format!("op-{}", hex::encode(&random[..16]));
838    text.parse()
839        .map_err(|err| CliError::Local(format!("generated operation id: {err}")))
840}
841
842/// Builds the error for a preview that reports validation errors.
843pub(crate) fn invalid_preview(preview: &PreviewResponse) -> CliError {
844    CliError::InvalidPreview {
845        details: preview.errors.iter().map(validation_line).collect(),
846    }
847}
848
849/// Formats one validation error as `path: message`.
850fn validation_line(error: &crate::wire::ValidationEntry) -> String {
851    match &error.path {
852        Some(path) => sanitize(&format!("{path}: {}", error.message)),
853        None => sanitize(&error.message),
854    }
855}
856
857/// Renders a JSON value compactly.
858fn compact(value: &Json) -> String {
859    value.to_string()
860}
861
862/// Returns the claim body's fields as JSON.
863pub(crate) fn claim_json(body: &ClaimBody) -> Json {
864    json!({
865        "nonce": body.nonce(),
866        "node": body.node(),
867        "claimant": body.claimant(),
868        "expires_at": body.expires_at(),
869        "base_revision": body.base_revision(),
870        "config_sha256": body.config_sha256(),
871    })
872}
873
874/// Returns `true` for `<decimal>:<64 lowercase hex>`.
875fn is_checkpoint(text: &str) -> bool {
876    text.split_once(':').is_some_and(|(seq, hash)| {
877        !seq.is_empty()
878            && seq.bytes().all(|b| b.is_ascii_digit())
879            && hash.len() == 64
880            && hash.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
881    })
882}
883
884#[cfg(test)]
885mod tests {
886    use std::time::Duration;
887
888    use super::BACKUP_TIMEOUT;
889
890    /// The node answers a backup it cannot quiesce only after waiting 90 s
891    /// for the gate (E2.23); the client must still be listening then, or it
892    /// reports a working node as unreachable. Found by the end-to-end run.
893    #[test]
894    fn backup_outwaits_the_nodes_drain_bound() {
895        assert!(
896            BACKUP_TIMEOUT > Duration::from_secs(90 + 60),
897            "the drain bound plus time to snapshot and archive"
898        );
899    }
900}