1use 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
24pub(crate) const READYZ: &str = "/readyz";
26const SCHEMA: &str = "/api/v1/config/schema";
28const CONFIG: &str = "/api/v1/config";
30pub(crate) const PREVIEW: &str = "/api/v1/config/preview";
32const APPLY: &str = "/api/v1/config/apply";
34const CHECKPOINT: &str = "/api/v1/audit/checkpoint";
36const BACKUP: &str = "/api/v1/backup";
38pub(crate) const CHALLENGE: &str = "/api/v1/bootstrap/challenge";
40pub(crate) const CLAIM: &str = "/api/v1/bootstrap/claim";
42
43const API_VERSION: u64 = 1;
45
46const MANIFEST_KIND: u16 = 30078;
48
49const CLAIM_BODY_FILE_LIMIT: usize = 64 * 1024;
51
52#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
54#[non_exhaustive]
55pub enum Confirmation {
56 #[default]
58 Prompt,
59 Assumed,
61}
62
63#[derive(Debug, Clone, Default)]
65pub struct ApplyOptions {
66 pub sets: Vec<String>,
68 pub base_revision: Option<u64>,
71 pub operation_id: Option<String>,
73 pub confirmation: Confirmation,
75}
76
77#[derive(Debug, Clone, Default)]
79pub struct SetupOptions {
80 pub token_file: PathBuf,
82 pub sets: Vec<String>,
84 pub resume_file: Option<PathBuf>,
87 pub confirmation: Confirmation,
89 pub expect_node: Option<DidNostr>,
94 pub show_text: bool,
97}
98
99#[derive(Debug, Clone)]
122pub struct Session {
123 url: LoopbackUrl,
124 key_file: Option<PathBuf>,
125 output: Output,
126}
127
128impl Session {
129 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 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 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 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 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 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 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 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 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 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 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 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 pub(crate) fn key_path(&self) -> Result<&Path, CliError> {
576 self.key_file.as_deref().ok_or(CliError::MissingKeyFile)
577 }
578
579 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 pub(crate) fn output(&self) -> &Output {
590 &self.output
591 }
592
593 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 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 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 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
682pub(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
698pub(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
712fn 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
762pub(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
783pub(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
794pub(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
800fn 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
813pub(crate) fn invalid_preview(preview: &PreviewResponse) -> CliError {
815 CliError::InvalidPreview {
816 details: preview.errors.iter().map(validation_line).collect(),
817 }
818}
819
820fn 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
828fn compact(value: &Json) -> String {
830 value.to_string()
831}
832
833pub(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
845fn 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}