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