1use std::thread;
4use std::time::{Duration, Instant};
5
6use serde_json::{json, Value as Json};
7use stratum_node_core::{
8 admission_notice_v1_sha256, profile_card_path, AdmissionClaim, AdmissionFields, DidNostr,
9 InvitationId, MemberState, NostrSecretKey, PodPath, Sha256Digest,
10};
11
12use crate::client::{self, MAX_RESPONSE_BYTES};
13use crate::error::CliError;
14use crate::exit;
15use crate::gate::{self, GateClient, Precondition, Request, Route, ANY, JSON};
16use crate::origin::GateTarget;
17use crate::output::sanitize;
18use crate::profile::{self, CardOutcome, Conflicting};
19use crate::session::{to_body, Confirmation, Session};
20use crate::wire::{ConfirmRequest, ConfirmResponse, NoticeResponse, OperationResponse};
21
22const NOTICE: &str = "/api/v1/admission/notice";
24const REDEEM: &str = "/api/v1/admission/redeem";
26const OPERATION: &str = "/api/v1/admission/operation";
28const CONFIRM: &str = "/api/v1/admission/confirm";
30
31pub const DEFAULT_WAIT: Duration = Duration::from_secs(120);
33
34const FIRST_POLL_INTERVAL: Duration = Duration::from_millis(250);
37const MAX_POLL_INTERVAL: Duration = Duration::from_secs(2);
39
40const PROBE_PREFIX: &str = "stratum-join-probe-";
43
44#[derive(Debug, Clone)]
46pub struct JoinOptions {
47 pub invitation: InvitationId,
49 pub node: DidNostr,
52 pub wait: Duration,
54 pub confirmation: Confirmation,
56}
57
58#[derive(Debug, Default)]
60struct Progress {
61 redeemed: bool,
62 resent: bool,
63}
64
65impl Session {
66 pub fn join(&self, target: &GateTarget, options: &JoinOptions) -> Result<u8, CliError> {
118 let key = self.key()?;
119 let me = key.public();
120 let gate = GateClient::new(target.clone());
121 let pod_url = target.origin().url(PodPath::pod_root(&me).as_str());
122 let notice = fetch_notice(&gate, options)?;
123
124 let mut progress = Progress::default();
125 let mut operation = if let Some(operation) = own_operation(&gate, &key)? {
126 self.output().note(&format!(
127 "{me} is already a member of this node ({}); continuing",
128 operation.state
129 ))?;
130 operation
131 } else {
132 self.show_notice(¬ice)?;
133 if !self.confirmed(
134 "join this node, accepting the notice above?",
135 options.confirmation,
136 )? {
137 self.output().json(&json!({"joined": false}))?;
138 return Err(CliError::NotConfirmed);
139 }
140 let operation = self.redeem(&gate, &key, options, &mut progress)?;
141 progress.redeemed = true;
142 operation
143 };
144 check_operation(&operation, me, &pod_url)?;
145 self.output().note(&format!(
146 "operation {}: {}",
147 operation.operation_id, operation.state
148 ))?;
149 if !matches!(
150 operation.state,
151 MemberState::Provisioned | MemberState::Active
152 ) {
153 operation = self.wait_provisioned(&gate, &key, &pod_url, options.wait)?;
154 }
155
156 let (probe, probe_sha256) = self.probe(&gate, &key, &me)?;
157 let profile = profile::ensure_profile(&gate, &key, Conflicting::Report)?;
158 let card_path = profile_card_path(&me);
159 profile.note(*self.output(), &card_path)?;
160 if matches!(profile.card, CardOutcome::Conflict(_)) {
161 self.output().note(
162 "the join continues; run `stratum profile init --replace` to replace that card \
163 with the standard one",
164 )?;
165 }
166 let card_acl = card_path
167 .acl_path()
168 .ok_or_else(|| CliError::Local("the profile card has no ACL path".to_owned()))?;
169 let body = to_body(&ConfirmRequest {
170 node: options.node,
171 operation_id: &operation.operation_id,
172 })?;
173 let (confirmed, _raw): (ConfirmResponse, Json) = gate
174 .fetch(
175 &Request::new("POST", CONFIRM, JSON).with_body(&body, JSON),
176 Some(&key),
177 MAX_RESPONSE_BYTES,
178 )?
179 .into_json(Route::Admission)?;
180 if confirmed.did != me || confirmed.pod_url != pod_url {
181 return Err(CliError::Refused(format!(
182 "the confirmation names {} at {}, not {me} at {pod_url}",
183 confirmed.did,
184 sanitize(&confirmed.pod_url)
185 )));
186 }
187 if confirmed.state != MemberState::Active {
188 return Err(CliError::Refused(format!(
189 "the node reports the member {} after confirming, not active",
190 confirmed.state
191 )));
192 }
193 self.output().json(&json!({
194 "joined": true,
195 "did": me,
196 "node": options.node,
197 "origin": target.origin().as_str(),
198 "invitation": options.invitation,
199 "operation_id": operation.operation_id,
200 "state": confirmed.state,
201 "pod_url": pod_url,
202 "redeemed": progress.redeemed,
203 "resent": progress.resent,
204 "probe": {"path": probe, "sha256": probe_sha256},
205 "profile": profile.to_json(&card_path, &card_acl),
206 }))?;
207 self.output().line(&format!("member: {me}"))?;
208 self.output().line("state: active")?;
209 self.output().line(&format!("pod: {pod_url}"))?;
210 self.output().line(&format!(
211 "profile: {}",
212 target.origin().url(card_path.as_str())
213 ))?;
214 Ok(exit::OK)
215 }
216
217 fn show_notice(&self, notice: &NoticeResponse) -> Result<(), CliError> {
219 self.output().note(&format!(
220 "admission notice from {} (sha256 {}):",
221 notice.node, notice.notice_sha256
222 ))?;
223 self.output().note("")?;
224 self.output().note(&sanitize(¬ice.notice))?;
225 self.output().note("")
226 }
227
228 fn redeem(
231 &self,
232 gate: &GateClient,
233 key: &NostrSecretKey,
234 options: &JoinOptions,
235 progress: &mut Progress,
236 ) -> Result<OperationResponse, CliError> {
237 let claim = AdmissionClaim::new(AdmissionFields {
238 node: options.node,
239 subject: key.public(),
240 invitation: options.invitation,
241 notice_sha256: admission_notice_v1_sha256(),
242 });
243 let request = Request::new("POST", REDEEM, JSON).with_body(claim.as_bytes(), JSON);
244 let authorization = gate.sign(key, &request)?;
245 let response = match gate.fetch_with(&request, Some(&authorization), MAX_RESPONSE_BYTES) {
246 Err(CliError::Unreachable { message, .. }) => {
247 self.output().note(&format!(
248 "the redemption response was lost ({message}); resending the identical \
249 signed request once"
250 ))?;
251 progress.resent = true;
252 gate.fetch_with(&request, Some(&authorization), MAX_RESPONSE_BYTES)?
253 }
254 other => other?,
255 };
256 let (operation, _raw): (OperationResponse, Json) = response.into_json(Route::Admission)?;
257 if operation.state == MemberState::Cancelled {
258 return Err(cancelled());
259 }
260 Ok(operation)
261 }
262
263 fn wait_provisioned(
265 &self,
266 gate: &GateClient,
267 key: &NostrSecretKey,
268 pod_url: &str,
269 wait: Duration,
270 ) -> Result<OperationResponse, CliError> {
271 let deadline = Instant::now() + wait;
272 let mut interval = FIRST_POLL_INTERVAL;
273 let mut shown_error: Option<String> = None;
274 loop {
275 let now = Instant::now();
276 if now >= deadline {
277 let last = shown_error
278 .map(|err| format!("; the node's last error: {err}"))
279 .unwrap_or_default();
280 return Err(CliError::TimedOut(format!(
281 "the pod was not provisioned within {} s{last}; rerun the same join command \
282 to continue",
283 wait.as_secs()
284 )));
285 }
286 thread::sleep(interval.min(deadline - now));
287 interval = (interval * 2).min(MAX_POLL_INTERVAL);
288 let (operation, _raw): (OperationResponse, Json) = gate
289 .fetch(
290 &Request::new("GET", OPERATION, JSON),
291 Some(key),
292 MAX_RESPONSE_BYTES,
293 )?
294 .into_json(Route::Admission)?;
295 check_operation(&operation, key.public(), pod_url)?;
296 if let Some(err) = &operation.last_error {
297 let err = sanitize(err);
298 if shown_error.as_deref() != Some(err.as_str()) {
299 self.output()
300 .note(&format!("the node reports a provisioning error: {err}"))?;
301 shown_error = Some(err);
302 }
303 }
304 match operation.state {
305 MemberState::Provisioned | MemberState::Active => return Ok(operation),
306 MemberState::Cancelled => return Err(cancelled()),
307 MemberState::Suspended => return Err(suspended()),
308 MemberState::Removed => return Err(removed()),
309 _ => {}
310 }
311 }
312 }
313
314 fn probe(
317 &self,
318 gate: &GateClient,
319 key: &NostrSecretKey,
320 me: &DidNostr,
321 ) -> Result<(PodPath, Sha256Digest), CliError> {
322 let random = client::random_32()?;
323 let name = format!("{PROBE_PREFIX}{}", hex::encode(&random[..8]));
324 let path = PodPath::pod_root(me)
325 .join(&name)
326 .map_err(|err| CliError::Local(format!("probe path: {err}")))?;
327 let content = format!("stratum join probe {}\n", hex::encode(&random[8..24]));
328 let written = Sha256Digest::of(content.as_bytes());
329
330 let put = gate.fetch(
331 &Request::new("PUT", path.as_str(), ANY)
332 .with_body(content.as_bytes(), "text/plain")
333 .with_precondition(Precondition::CreateOnly),
334 Some(key),
335 MAX_RESPONSE_BYTES,
336 )?;
337 if !put.head.is_success() {
338 return Err(put.into_error(Route::Pod));
339 }
340 let get = gate.fetch(
341 &Request::new("GET", path.as_str(), ANY),
342 Some(key),
343 MAX_RESPONSE_BYTES,
344 )?;
345 if !get.head.is_success() {
346 return Err(get.into_error(Route::Pod));
347 }
348 if get.body != content.as_bytes() {
349 return Err(CliError::Refused(format!(
350 "the probe {path} read back {} bytes that differ from the {} written",
351 get.body.len(),
352 content.len()
353 )));
354 }
355 let delete = gate.fetch(
356 &Request::new("DELETE", path.as_str(), ANY),
357 Some(key),
358 MAX_RESPONSE_BYTES,
359 )?;
360 if !delete.head.is_success() {
361 return Err(delete.into_error(Route::Pod));
362 }
363 self.output()
364 .note(&format!("probe {path} written, read back and deleted"))?;
365 Ok((path, written))
366 }
367}
368
369fn fetch_notice(gate: &GateClient, options: &JoinOptions) -> Result<NoticeResponse, CliError> {
371 let (notice, _raw): (NoticeResponse, Json) = gate
372 .fetch(&Request::new("GET", NOTICE, JSON), None, MAX_RESPONSE_BYTES)?
373 .into_json(Route::Admission)?;
374 if notice.node != options.node {
375 return Err(CliError::Refused(format!(
376 "the node at this origin is {}, not {} named by the invitation",
377 notice.node, options.node
378 )));
379 }
380 let origin = gate.target().origin().as_str();
381 if notice.origin != origin {
382 return Err(CliError::Refused(format!(
383 "the node reports its origin as {}, not {origin}",
384 sanitize(¬ice.origin)
385 )));
386 }
387 let received = Sha256Digest::of(notice.notice.as_bytes());
388 if received != notice.notice_sha256 {
389 return Err(CliError::Refused(format!(
390 "the notice text hashes to {received}, not to the {} the node reports",
391 notice.notice_sha256
392 )));
393 }
394 let known = admission_notice_v1_sha256();
395 if received != known {
396 return Err(CliError::Refused(format!(
397 "the node's notice (sha256 {received}) is not the admission notice this client \
398 knows (sha256 {known}); nothing was signed"
399 )));
400 }
401 Ok(notice)
402}
403
404fn own_operation(
407 gate: &GateClient,
408 key: &NostrSecretKey,
409) -> Result<Option<OperationResponse>, CliError> {
410 let response = gate.fetch(
411 &Request::new("GET", OPERATION, JSON),
412 Some(key),
413 MAX_RESPONSE_BYTES,
414 )?;
415 if response.head.status == 403
418 && gate::envelope_code(&response.body).as_deref() == Some(gate::SUSPENDED)
419 {
420 return Err(response.into_error(Route::Admission));
421 }
422 if matches!(response.head.status, 403 | 404) {
426 return Ok(None);
427 }
428 let (operation, _raw): (OperationResponse, Json) = response.into_json(Route::Admission)?;
429 match operation.state {
430 MemberState::Suspended => Err(suspended()),
431 MemberState::Cancelled | MemberState::Removed => Ok(None),
436 _ => Ok(Some(operation)),
437 }
438}
439
440fn check_operation(
443 operation: &OperationResponse,
444 me: DidNostr,
445 pod_url: &str,
446) -> Result<(), CliError> {
447 if operation.did != me {
448 return Err(CliError::Refused(format!(
449 "the node answered with the operation of {}, not of {me}",
450 operation.did
451 )));
452 }
453 let pending = operation.state == MemberState::Reserved && operation.pod_url.is_empty();
456 if operation.pod_url != pod_url && !pending {
457 return Err(CliError::Refused(format!(
458 "the node reports pod url {}, not {pod_url}",
459 sanitize(&operation.pod_url)
460 )));
461 }
462 Ok(())
463}
464
465fn suspended() -> CliError {
467 CliError::Refused(
468 "the administrator has suspended this membership; nothing can be done with this key on \
469 this node until they resume it"
470 .to_owned(),
471 )
472}
473
474fn removed() -> CliError {
476 CliError::Refused(
477 "the administrator removed this membership; ask them for a new invitation, which they \
478 can issue once the old pod data has been purged"
479 .to_owned(),
480 )
481}
482
483fn cancelled() -> CliError {
485 CliError::Refused(
486 "the administrator cancelled this membership; ask them for a new invitation".to_owned(),
487 )
488}