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, AdmissionClaim, AdmissionFields, DidNostr, InvitationId,
9 MemberState, NostrSecretKey, PodPath, Sha256Digest,
10};
11
12use crate::client::{self, MAX_RESPONSE_BYTES};
13use crate::error::CliError;
14use crate::exit;
15use crate::gate::{GateClient, Precondition, Request, Route, ANY, JSON};
16use crate::origin::GateTarget;
17use crate::output::sanitize;
18use crate::session::{to_body, Confirmation, Session};
19use crate::wire::{ConfirmRequest, ConfirmResponse, NoticeResponse, OperationResponse};
20
21const NOTICE: &str = "/api/v1/admission/notice";
23const REDEEM: &str = "/api/v1/admission/redeem";
25const OPERATION: &str = "/api/v1/admission/operation";
27const CONFIRM: &str = "/api/v1/admission/confirm";
29
30pub const DEFAULT_WAIT: Duration = Duration::from_secs(120);
32
33const FIRST_POLL_INTERVAL: Duration = Duration::from_millis(250);
36const MAX_POLL_INTERVAL: Duration = Duration::from_secs(2);
38
39const PROBE_PREFIX: &str = "stratum-join-probe-";
42
43#[derive(Debug, Clone)]
45pub struct JoinOptions {
46 pub invitation: InvitationId,
48 pub node: DidNostr,
51 pub wait: Duration,
53 pub confirmation: Confirmation,
55}
56
57#[derive(Debug, Default)]
59struct Progress {
60 redeemed: bool,
61 resent: bool,
62}
63
64impl Session {
65 pub fn join(&self, target: &GateTarget, options: &JoinOptions) -> Result<u8, CliError> {
104 let key = self.key()?;
105 let me = key.public();
106 let gate = GateClient::new(target.clone());
107 let pod_url = target.origin().url(PodPath::pod_root(&me).as_str());
108 let notice = fetch_notice(&gate, options)?;
109
110 let mut progress = Progress::default();
111 let mut operation = if let Some(operation) = own_operation(&gate, &key)? {
112 self.output().note(&format!(
113 "{me} is already a member of this node ({}); continuing",
114 operation.state
115 ))?;
116 operation
117 } else {
118 self.show_notice(¬ice)?;
119 if !self.confirmed(
120 "join this node, accepting the notice above?",
121 options.confirmation,
122 )? {
123 self.output().json(&json!({"joined": false}))?;
124 return Err(CliError::NotConfirmed);
125 }
126 let operation = self.redeem(&gate, &key, options, &mut progress)?;
127 progress.redeemed = true;
128 operation
129 };
130 check_operation(&operation, me, &pod_url)?;
131 self.output().note(&format!(
132 "operation {}: {}",
133 operation.operation_id, operation.state
134 ))?;
135 if !matches!(
136 operation.state,
137 MemberState::Provisioned | MemberState::Active
138 ) {
139 operation = self.wait_provisioned(&gate, &key, &pod_url, options.wait)?;
140 }
141
142 let (probe, probe_sha256) = self.probe(&gate, &key, &me)?;
143 let body = to_body(&ConfirmRequest {
144 node: options.node,
145 operation_id: &operation.operation_id,
146 })?;
147 let (confirmed, _raw): (ConfirmResponse, Json) = gate
148 .fetch(
149 &Request::new("POST", CONFIRM, JSON).with_body(&body, JSON),
150 Some(&key),
151 MAX_RESPONSE_BYTES,
152 )?
153 .into_json(Route::Admission)?;
154 if confirmed.did != me || confirmed.pod_url != pod_url {
155 return Err(CliError::Refused(format!(
156 "the confirmation names {} at {}, not {me} at {pod_url}",
157 confirmed.did,
158 sanitize(&confirmed.pod_url)
159 )));
160 }
161 if confirmed.state != MemberState::Active {
162 return Err(CliError::Refused(format!(
163 "the node reports the member {} after confirming, not active",
164 confirmed.state
165 )));
166 }
167 self.output().json(&json!({
168 "joined": true,
169 "did": me,
170 "node": options.node,
171 "origin": target.origin().as_str(),
172 "invitation": options.invitation,
173 "operation_id": operation.operation_id,
174 "state": confirmed.state,
175 "pod_url": pod_url,
176 "redeemed": progress.redeemed,
177 "resent": progress.resent,
178 "probe": {"path": probe, "sha256": probe_sha256},
179 }))?;
180 self.output().line(&format!("member: {me}"))?;
181 self.output().line("state: active")?;
182 self.output().line(&format!("pod: {pod_url}"))?;
183 Ok(exit::OK)
184 }
185
186 fn show_notice(&self, notice: &NoticeResponse) -> Result<(), CliError> {
188 self.output().note(&format!(
189 "admission notice from {} (sha256 {}):",
190 notice.node, notice.notice_sha256
191 ))?;
192 self.output().note("")?;
193 self.output().note(&sanitize(¬ice.notice))?;
194 self.output().note("")
195 }
196
197 fn redeem(
200 &self,
201 gate: &GateClient,
202 key: &NostrSecretKey,
203 options: &JoinOptions,
204 progress: &mut Progress,
205 ) -> Result<OperationResponse, CliError> {
206 let claim = AdmissionClaim::new(AdmissionFields {
207 node: options.node,
208 subject: key.public(),
209 invitation: options.invitation,
210 notice_sha256: admission_notice_v1_sha256(),
211 });
212 let request = Request::new("POST", REDEEM, JSON).with_body(claim.as_bytes(), JSON);
213 let authorization = gate.sign(key, &request)?;
214 let response = match gate.fetch_with(&request, Some(&authorization), MAX_RESPONSE_BYTES) {
215 Err(CliError::Unreachable { message, .. }) => {
216 self.output().note(&format!(
217 "the redemption response was lost ({message}); resending the identical \
218 signed request once"
219 ))?;
220 progress.resent = true;
221 gate.fetch_with(&request, Some(&authorization), MAX_RESPONSE_BYTES)?
222 }
223 other => other?,
224 };
225 let (operation, _raw): (OperationResponse, Json) = response.into_json(Route::Admission)?;
226 if operation.state == MemberState::Cancelled {
227 return Err(cancelled());
228 }
229 Ok(operation)
230 }
231
232 fn wait_provisioned(
234 &self,
235 gate: &GateClient,
236 key: &NostrSecretKey,
237 pod_url: &str,
238 wait: Duration,
239 ) -> Result<OperationResponse, CliError> {
240 let deadline = Instant::now() + wait;
241 let mut interval = FIRST_POLL_INTERVAL;
242 let mut shown_error: Option<String> = None;
243 loop {
244 let now = Instant::now();
245 if now >= deadline {
246 let last = shown_error
247 .map(|err| format!("; the node's last error: {err}"))
248 .unwrap_or_default();
249 return Err(CliError::TimedOut(format!(
250 "the pod was not provisioned within {} s{last}; rerun the same join command \
251 to continue",
252 wait.as_secs()
253 )));
254 }
255 thread::sleep(interval.min(deadline - now));
256 interval = (interval * 2).min(MAX_POLL_INTERVAL);
257 let (operation, _raw): (OperationResponse, Json) = gate
258 .fetch(
259 &Request::new("GET", OPERATION, JSON),
260 Some(key),
261 MAX_RESPONSE_BYTES,
262 )?
263 .into_json(Route::Admission)?;
264 check_operation(&operation, key.public(), pod_url)?;
265 if let Some(err) = &operation.last_error {
266 let err = sanitize(err);
267 if shown_error.as_deref() != Some(err.as_str()) {
268 self.output()
269 .note(&format!("the node reports a provisioning error: {err}"))?;
270 shown_error = Some(err);
271 }
272 }
273 match operation.state {
274 MemberState::Provisioned | MemberState::Active => return Ok(operation),
275 MemberState::Cancelled => return Err(cancelled()),
276 _ => {}
277 }
278 }
279 }
280
281 fn probe(
284 &self,
285 gate: &GateClient,
286 key: &NostrSecretKey,
287 me: &DidNostr,
288 ) -> Result<(PodPath, Sha256Digest), CliError> {
289 let random = client::random_32()?;
290 let name = format!("{PROBE_PREFIX}{}", hex::encode(&random[..8]));
291 let path = PodPath::pod_root(me)
292 .join(&name)
293 .map_err(|err| CliError::Local(format!("probe path: {err}")))?;
294 let content = format!("stratum join probe {}\n", hex::encode(&random[8..24]));
295 let written = Sha256Digest::of(content.as_bytes());
296
297 let put = gate.fetch(
298 &Request::new("PUT", path.as_str(), ANY)
299 .with_body(content.as_bytes(), "text/plain")
300 .with_precondition(Precondition::CreateOnly),
301 Some(key),
302 MAX_RESPONSE_BYTES,
303 )?;
304 if !put.head.is_success() {
305 return Err(put.into_error(Route::Pod));
306 }
307 let get = gate.fetch(
308 &Request::new("GET", path.as_str(), ANY),
309 Some(key),
310 MAX_RESPONSE_BYTES,
311 )?;
312 if !get.head.is_success() {
313 return Err(get.into_error(Route::Pod));
314 }
315 if get.body != content.as_bytes() {
316 return Err(CliError::Refused(format!(
317 "the probe {path} read back {} bytes that differ from the {} written",
318 get.body.len(),
319 content.len()
320 )));
321 }
322 let delete = gate.fetch(
323 &Request::new("DELETE", path.as_str(), ANY),
324 Some(key),
325 MAX_RESPONSE_BYTES,
326 )?;
327 if !delete.head.is_success() {
328 return Err(delete.into_error(Route::Pod));
329 }
330 self.output()
331 .note(&format!("probe {path} written, read back and deleted"))?;
332 Ok((path, written))
333 }
334}
335
336fn fetch_notice(gate: &GateClient, options: &JoinOptions) -> Result<NoticeResponse, CliError> {
338 let (notice, _raw): (NoticeResponse, Json) = gate
339 .fetch(&Request::new("GET", NOTICE, JSON), None, MAX_RESPONSE_BYTES)?
340 .into_json(Route::Admission)?;
341 if notice.node != options.node {
342 return Err(CliError::Refused(format!(
343 "the node at this origin is {}, not {} named by the invitation",
344 notice.node, options.node
345 )));
346 }
347 let origin = gate.target().origin().as_str();
348 if notice.origin != origin {
349 return Err(CliError::Refused(format!(
350 "the node reports its origin as {}, not {origin}",
351 sanitize(¬ice.origin)
352 )));
353 }
354 let received = Sha256Digest::of(notice.notice.as_bytes());
355 if received != notice.notice_sha256 {
356 return Err(CliError::Refused(format!(
357 "the notice text hashes to {received}, not to the {} the node reports",
358 notice.notice_sha256
359 )));
360 }
361 let known = admission_notice_v1_sha256();
362 if received != known {
363 return Err(CliError::Refused(format!(
364 "the node's notice (sha256 {received}) is not the admission notice this client \
365 knows (sha256 {known}); nothing was signed"
366 )));
367 }
368 Ok(notice)
369}
370
371fn own_operation(
374 gate: &GateClient,
375 key: &NostrSecretKey,
376) -> Result<Option<OperationResponse>, CliError> {
377 let response = gate.fetch(
378 &Request::new("GET", OPERATION, JSON),
379 Some(key),
380 MAX_RESPONSE_BYTES,
381 )?;
382 if matches!(response.head.status, 403 | 404) {
386 return Ok(None);
387 }
388 let (operation, _raw): (OperationResponse, Json) = response.into_json(Route::Admission)?;
389 if operation.state == MemberState::Cancelled {
390 return Err(cancelled());
391 }
392 Ok(Some(operation))
393}
394
395fn check_operation(
398 operation: &OperationResponse,
399 me: DidNostr,
400 pod_url: &str,
401) -> Result<(), CliError> {
402 if operation.did != me {
403 return Err(CliError::Refused(format!(
404 "the node answered with the operation of {}, not of {me}",
405 operation.did
406 )));
407 }
408 let pending = operation.state == MemberState::Reserved && operation.pod_url.is_empty();
411 if operation.pod_url != pod_url && !pending {
412 return Err(CliError::Refused(format!(
413 "the node reports pod url {}, not {pod_url}",
414 sanitize(&operation.pod_url)
415 )));
416 }
417 Ok(())
418}
419
420fn cancelled() -> CliError {
422 CliError::Refused(
423 "the administrator cancelled this membership; ask them for a new invitation".to_owned(),
424 )
425}