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