1use std::fs;
4use std::path::{Path, PathBuf};
5
6use serde::Deserialize as _;
7use serde_json::{json, Value as Json};
8use stratum_node_config::{schema, Change};
9use stratum_node_core::{ClaimBody, DidNostr, Sha256Digest};
10
11use crate::changes::parse_changes;
12use crate::client::{self, Client};
13use crate::error::CliError;
14use crate::exit;
15use crate::output::sanitize;
16use crate::private_file;
17use crate::resume::ResumeRecord;
18use crate::session::{
19 check_expected_node, claim_json, invalid_preview, readyz, request_preview, to_body, Session,
20 SetupOptions, CHALLENGE, CLAIM,
21};
22use crate::token::BootstrapToken;
23use crate::wire::{ChallengeRequest, ChallengeResponse, ClaimResponse, PreviewResponse};
24
25const RESUME_SUFFIX: &str = ".setup-resume";
27
28impl Session {
29 pub fn setup(&self, options: &SetupOptions) -> Result<u8, CliError> {
78 let key_path = self.key_path()?;
79 let resume_path = options
80 .resume_file
81 .clone()
82 .unwrap_or_else(|| default_resume_path(key_path));
83 let client = self.client()?;
84 if fs::symlink_metadata(&resume_path).is_ok() {
85 return self.resume_setup(&client, &resume_path, options);
86 }
87 self.fresh_setup(&client, &resume_path, options)
88 }
89
90 fn fresh_setup(
92 &self,
93 client: &Client,
94 resume_path: &Path,
95 options: &SetupOptions,
96 ) -> Result<u8, CliError> {
97 let key = self.key()?;
98 let claimant = key.public();
99 let token = BootstrapToken::read_file(&options.token_file).map_err(|source| {
100 CliError::TokenFile {
101 path: options.token_file.clone(),
102 source,
103 }
104 })?;
105 let changes =
108 parse_changes(&options.sets).map_err(|err| CliError::Usage(err.to_string()))?;
109
110 let ready = readyz(client)?;
111 check_expected_node(ready.node_did, options.expect_node.as_ref())?;
112 if ready.status != "unconfigured" {
113 return Err(CliError::Refused(format!(
114 "the node reports status {:?}, not \"unconfigured\": it has already been set up",
115 sanitize(&ready.status)
116 )));
117 }
118 if ready.head_revision != SEED_REVISION {
119 return Err(CliError::Refused(format!(
120 "the node reports itself unconfigured at revision {}, not {SEED_REVISION}",
121 ready.head_revision
122 )));
123 }
124 let node = ready.node_did;
125 let base = SEED_REVISION;
126
127 let (preview, preview_raw) = derive_initial(&changes)?;
128 let (remote, _remote_raw) = request_preview(client, base, &changes, None)?;
129 if remote.text != preview.text || remote.diff != preview.diff {
130 return Err(CliError::Refused(
131 "the node's preview of the initial configuration differs from the one this client \
132 derives from its own stratum-node-config seed; the node and the client may be \
133 built on different versions; nothing was signed"
134 .to_owned(),
135 ));
136 }
137 self.show_preview(&preview)?;
138 if options.show_text {
139 self.output().line(&format!(
140 "configuration text (sha256 {}), exactly as the claim binds it:",
141 Sha256Digest::of(preview.text.as_bytes())
142 ))?;
143 self.output().line(sanitize(&preview.text).trim_end())?;
144 }
145 if !preview.errors.is_empty() {
146 self.output()
147 .json(&json!({ "preview": preview_raw, "claimed": false }))?;
148 return Err(invalid_preview(&preview));
149 }
150
151 let request = to_body(&ChallengeRequest {
152 did: claimant,
153 base_revision: base,
154 changes: &changes,
155 })?;
156 let (challenge, _raw): (ChallengeResponse, Json) =
157 client.post(CHALLENGE, &request, None)?.into_json()?;
158 let claim_url = client.url(CLAIM);
159 let body = check_challenge(&challenge, &claim_url, node, claimant, base, &preview.text)?;
160 self.show_claim(&body)?;
161 self.output().note(&format!(
162 "the claim binds {claimant} as the administrator of {node}"
163 ))?;
164 let mut report = json!({
165 "preview": preview_raw,
166 "claim": claim_json(&body),
167 "claimed": false,
168 });
169 if !self.confirmed("claim this node?", options.confirmation)? {
170 self.output().json(&report)?;
171 return Err(CliError::NotConfirmed);
172 }
173
174 let authorization = client::sign(&key, "POST", &claim_url, Some(body.as_bytes()))?;
175 let record = ResumeRecord {
176 url: claim_url,
177 authorization,
178 token,
179 claim_body: challenge.claim_body,
180 };
181 record.save(resume_path)?;
182 self.output().note(&format!(
183 "saved the signed claim to {}; if the response is lost, rerun the same command to resend it",
184 resume_path.display()
185 ))?;
186 let result = self.send_claim(client, &record, resume_path, node, claimant)?;
187 report["claimed"] = Json::Bool(true);
188 report["result"] = result;
189 self.output().json(&report)?;
190 Ok(exit::OK)
191 }
192
193 fn resume_setup(
195 &self,
196 client: &Client,
197 resume_path: &Path,
198 options: &SetupOptions,
199 ) -> Result<u8, CliError> {
200 let key = self.key()?;
201 let record = ResumeRecord::load(resume_path)?;
202 let claim_url = client.url(CLAIM);
203 if record.url != claim_url {
204 return Err(CliError::Usage(format!(
205 "the saved claim in {} is for {}, not {claim_url}; pass the matching --url",
206 resume_path.display(),
207 sanitize(&record.url)
208 )));
209 }
210 let body = ClaimBody::parse(record.claim_body.as_bytes()).map_err(|err| {
211 CliError::FileContents {
212 path: resume_path.to_owned(),
213 message: format!("the saved claim body is malformed: {err}"),
214 }
215 })?;
216 if body.claimant() != key.public() {
217 return Err(CliError::Refused(format!(
218 "the saved claim names claimant {}, but this key is {}",
219 body.claimant(),
220 key.public()
221 )));
222 }
223 if let Some(expected) = &options.expect_node {
224 if body.node() != *expected {
225 return Err(CliError::Refused(format!(
226 "the saved claim is for node {}, not the expected {expected}",
227 body.node()
228 )));
229 }
230 check_expected_node(readyz(client)?.node_did, Some(expected))?;
231 }
232 if !options.sets.is_empty() {
233 self.output().note(
234 "note: --set is ignored: resending the saved claim, whose configuration is already fixed",
235 )?;
236 }
237 self.output().note(&format!(
238 "resending the saved claim from {}",
239 resume_path.display()
240 ))?;
241 self.show_claim(&body)?;
242 let result = self.send_claim(client, &record, resume_path, body.node(), body.claimant())?;
243 self.output().json(&json!({
244 "claim": claim_json(&body),
245 "claimed": true,
246 "resumed": true,
247 "result": result,
248 }))?;
249 Ok(exit::OK)
250 }
251
252 fn send_claim(
254 &self,
255 client: &Client,
256 record: &ResumeRecord,
257 resume_path: &Path,
258 node: DidNostr,
259 claimant: DidNostr,
260 ) -> Result<Json, CliError> {
261 let sent = client.post_raw(
262 &record.url,
263 record.claim_body.as_bytes(),
264 Some(&record.authorization),
265 Some(record.token.expose()),
266 );
267 let response = match sent {
268 Ok(response) => response,
269 Err(err) => {
270 self.keep_note(resume_path)?;
271 return Err(err);
272 }
273 };
274 if (400..500).contains(&response.status) {
275 discard(resume_path)?;
276 return Err(response.into_error());
277 }
278 let parsed = response.into_json::<ClaimResponse>();
279 let (claimed, _raw) = match parsed {
280 Ok(ok) => ok,
281 Err(err) => {
282 self.keep_note(resume_path)?;
283 return Err(err);
284 }
285 };
286 discard(resume_path)?;
287 if claimed.administrator != claimant || claimed.node_did != node {
288 return Err(CliError::Refused(format!(
289 "the node reports administrator {} of {}, not {claimant} of {node}",
290 claimed.administrator, claimed.node_did
291 )));
292 }
293 self.output()
294 .line(&format!("administrator: {}", claimed.administrator))?;
295 self.output().line(&format!("node: {}", claimed.node_did))?;
296 self.output()
297 .line(&format!("revision: {}", claimed.revision))?;
298 self.output().line(&format!(
299 "public config hash: {}",
300 claimed.public_config_hash
301 ))?;
302 Ok(json!({
305 "administrator": claimed.administrator,
306 "node_did": claimed.node_did,
307 "revision": claimed.revision,
308 "public_config_hash": claimed.public_config_hash,
309 }))
310 }
311
312 fn keep_note(&self, resume_path: &Path) -> Result<(), CliError> {
314 self.output().note(&format!(
315 "the signed claim is kept in {}; rerun the same command to resend it",
316 resume_path.display()
317 ))
318 }
319}
320
321const SEED_REVISION: u64 = 0;
324
325fn derive_initial(changes: &[Change]) -> Result<(PreviewResponse, Json), CliError> {
329 let preview = stratum_node_config::preview(&schema().seed_text(), changes)
330 .map_err(|err| CliError::Usage(format!("the initial configuration: {err}")))?;
331 let mut value = serde_json::to_value(&preview)
332 .map_err(|err| CliError::Local(format!("encoding the preview failed: {err}")))?;
333 value["base_revision"] = json!(SEED_REVISION);
334 let typed = PreviewResponse::deserialize(&value)
335 .map_err(|err| CliError::Local(format!("reading the local preview failed: {err}")))?;
336 Ok((typed, value))
337}
338
339fn discard(resume_path: &Path) -> Result<(), CliError> {
341 private_file::remove(resume_path).map_err(|source| CliError::File {
342 path: resume_path.to_owned(),
343 source,
344 })
345}
346
347fn default_resume_path(key_path: &Path) -> PathBuf {
349 let mut path = key_path.as_os_str().to_owned();
350 path.push(RESUME_SUFFIX);
351 PathBuf::from(path)
352}
353
354fn check_challenge(
357 challenge: &ChallengeResponse,
358 claim_url: &str,
359 node: DidNostr,
360 claimant: DidNostr,
361 base_revision: u64,
362 previewed_text: &str,
363) -> Result<ClaimBody, CliError> {
364 if challenge.method != "POST" {
365 return Err(CliError::Refused(
366 "the challenge names a claim method other than POST".to_owned(),
367 ));
368 }
369 if challenge.url != claim_url {
370 return Err(CliError::Refused(format!(
371 "the challenge names claim url {}, not {claim_url}",
372 sanitize(&challenge.url)
373 )));
374 }
375 let body = ClaimBody::parse(challenge.claim_body.as_bytes())
376 .map_err(|err| CliError::Refused(format!("the claim body is not acceptable: {err}")))?;
377 body.check(client::now()?, &node, &claimant)
378 .map_err(|err| CliError::Refused(err.to_string()))?;
379 if body.nonce() != challenge.challenge_id {
380 return Err(CliError::Refused(
381 "the claim body's nonce is not the challenge id".to_owned(),
382 ));
383 }
384 if body.expires_at() != challenge.expires_at {
385 return Err(CliError::Refused(
386 "the claim body's expiry differs from the challenge's".to_owned(),
387 ));
388 }
389 if body.base_revision().get() != base_revision {
390 return Err(CliError::Refused(format!(
391 "the claim body is based on revision {}, not {base_revision}",
392 body.base_revision()
393 )));
394 }
395 if body.config_sha256() != Sha256Digest::of(previewed_text.as_bytes()) {
396 return Err(CliError::Refused(
397 "the claim body's config_sha256 is not the hash of the previewed configuration"
398 .to_owned(),
399 ));
400 }
401 Ok(body)
402}