Skip to main content

stratum_node_cli/
profile.rs

1//! The public profile document: writing it during `stratum join` and with
2//! `stratum profile init`, and reading anyone's with `stratum profile show`.
3//!
4//! The card is `/pods/<pk>/profile/card`, Turtle, with exactly the text
5//! [`profile_card`] gives; its ACL, `/pods/<pk>/profile/card.acl`, has
6//! exactly the two rules [`profile_acl`] gives: the owner with read, write
7//! and control, and everyone with read. Both come from `stratum-node-core`,
8//! so the client and the node share one definition.
9
10use serde_json::json;
11use stratum_node_core::{
12    card_names_owner, profile_acl, profile_card, profile_card_path, DidNostr, NostrSecretKey,
13    PodPath, PROFILE_CONTENT_TYPE, PROFILE_MAX_BYTES,
14};
15
16use crate::error::CliError;
17use crate::exit;
18use crate::gate::{Buffered, GateClient, Precondition, Request, Route, ANY};
19use crate::origin::GateTarget;
20use crate::output::{sanitize, Output};
21use crate::session::Session;
22
23/// The most read of an existing card when deciding whether it names its
24/// owner. A card larger than [`PROFILE_MAX_BYTES`] is never served
25/// unsigned, so anything over that is reported, not parsed.
26const CARD_READ_LIMIT: u64 = 16 * 1024 * 1024;
27
28/// The most read of an existing ACL; it is only compared with the standard
29/// text.
30const ACL_READ_LIMIT: u64 = 1024 * 1024;
31
32/// Options for [`Session::profile_init`].
33///
34/// # Examples
35///
36/// ```
37/// use stratum_node_cli::ProfileInitOptions;
38///
39/// // `stratum profile init`: report a card that does not name the owner.
40/// assert!(!ProfileInitOptions::default().replace);
41/// // `stratum profile init --replace`.
42/// let replace = ProfileInitOptions { replace: true };
43/// assert!(replace.replace);
44/// ```
45#[derive(Debug, Clone, Copy, Default)]
46pub struct ProfileInitOptions {
47    /// `--replace`: replace an existing card that does not name the owner,
48    /// conditionally on the version read, instead of reporting the
49    /// conflict.
50    pub replace: bool,
51}
52
53/// What to do with an existing card that does not qualify.
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55pub(crate) enum Conflicting {
56    /// Report it and change nothing.
57    Report,
58    /// Replace it, conditionally on the version read (`--replace`).
59    Replace,
60}
61
62/// What happened to the card.
63#[derive(Debug, Clone, PartialEq, Eq)]
64pub(crate) enum CardOutcome {
65    /// There was none; the standard card was created.
66    Written,
67    /// One exists, is Turtle within the size limit and names the owner; it
68    /// was left alone.
69    Kept,
70    /// One existed that did not name the owner; it was replaced (only with
71    /// `--replace`).
72    Replaced,
73    /// One exists that does not qualify; nothing was written. The text
74    /// says why.
75    Conflict(String),
76}
77
78impl CardOutcome {
79    fn as_str(&self) -> &'static str {
80        match self {
81            Self::Written => "written",
82            Self::Kept => "kept",
83            Self::Replaced => "replaced",
84            Self::Conflict(_) => "conflict",
85        }
86    }
87}
88
89/// What happened to the card's ACL.
90#[derive(Debug, Clone, Copy, PartialEq, Eq)]
91pub(crate) enum AclOutcome {
92    /// There was none; the standard ACL was created.
93    Written,
94    /// One exists and was left alone; `standard` says whether its bytes are
95    /// the standard ACL's.
96    Kept { standard: bool },
97    /// Not looked at, because the card is in conflict: making an unknown
98    /// card public is not this command's to decide.
99    Skipped,
100}
101
102impl AclOutcome {
103    fn as_str(self) -> &'static str {
104        match self {
105            Self::Written => "written",
106            Self::Kept { .. } => "kept",
107            Self::Skipped => "skipped",
108        }
109    }
110}
111
112/// The result of [`ensure_profile`].
113#[derive(Debug, Clone, PartialEq, Eq)]
114pub(crate) struct ProfileOutcome {
115    pub(crate) card: CardOutcome,
116    pub(crate) acl: AclOutcome,
117}
118
119impl ProfileOutcome {
120    /// The report under `--json`.
121    pub(crate) fn to_json(&self, card: &PodPath, acl: &PodPath) -> serde_json::Value {
122        let conflict = match &self.card {
123            CardOutcome::Conflict(why) => Some(why.clone()),
124            _ => None,
125        };
126        let standard = match self.acl {
127            AclOutcome::Kept { standard } => Some(standard),
128            AclOutcome::Written => Some(true),
129            AclOutcome::Skipped => None,
130        };
131        json!({
132            "card": {"path": card, "outcome": self.card.as_str(), "conflict": conflict},
133            "acl": {"path": acl, "outcome": self.acl.as_str(), "standard": standard},
134        })
135    }
136
137    /// Notes what was done, on standard error.
138    pub(crate) fn note(&self, output: Output, card: &PodPath) -> Result<(), CliError> {
139        let line = match &self.card {
140            CardOutcome::Written => format!("profile {card}: written"),
141            CardOutcome::Kept => format!("profile {card}: already there and names you; left as is"),
142            CardOutcome::Replaced => format!("profile {card}: replaced with the standard card"),
143            CardOutcome::Conflict(why) => format!("profile {card}: {why}; left as is"),
144        };
145        output.note(&line)?;
146        let line = match self.acl {
147            AclOutcome::Written => {
148                "profile ACL: written (you: read, write, control; everyone: read)".to_owned()
149            }
150            AclOutcome::Kept { standard: true } => {
151                "profile ACL: already there; left as is".to_owned()
152            }
153            AclOutcome::Kept { standard: false } => "profile ACL: already there and not the \
154                 standard one; left as is, so the card may not be public"
155                .to_owned(),
156            AclOutcome::Skipped => {
157                "profile ACL: not written, because the card is not yours to publish".to_owned()
158            }
159        };
160        output.note(&line)
161    }
162}
163
164/// Makes sure the caller's pod holds the standard profile card and an ACL
165/// beside it, changing nothing that is already right.
166///
167/// Reads before it writes, so a repeat sends no write at all:
168///
169/// 1. `GET` the card. On 404, `PUT` the standard card with
170///    `If-None-Match: *`. On 200, the card is kept if it is `text/turtle`,
171///    at most [`PROFILE_MAX_BYTES`] and names the owner
172///    ([`card_names_owner`]); otherwise it is a conflict, which with
173///    [`Conflicting::Replace`] is resolved by a `PUT` with `If-Match: <etag read>`.
174/// 2. Unless the card is in conflict, `GET` the ACL beside it. On 404,
175///    `PUT` the standard ACL with `If-None-Match: *`. An existing ACL is
176///    left alone.
177///
178/// A create that answers 412 lost a race with another writer, and is read
179/// again once.
180pub(crate) fn ensure_profile(
181    gate: &GateClient,
182    key: &NostrSecretKey,
183    conflicting: Conflicting,
184) -> Result<ProfileOutcome, CliError> {
185    let owner = key.public();
186    let card_path = profile_card_path(&owner);
187    let acl_path = acl_of_card(&card_path)?;
188    let card = ensure_card(gate, key, &owner, &card_path, conflicting)?;
189    if matches!(card, CardOutcome::Conflict(_)) {
190        return Ok(ProfileOutcome {
191            card,
192            acl: AclOutcome::Skipped,
193        });
194    }
195    let acl = ensure_acl(gate, key, &owner, &acl_path)?;
196    Ok(ProfileOutcome { card, acl })
197}
198
199/// The ACL path beside the card.
200fn acl_of_card(card: &PodPath) -> Result<PodPath, CliError> {
201    card.acl_path()
202        .ok_or_else(|| CliError::Local("the profile card has no ACL path".to_owned()))
203}
204
205/// Step 1 of [`ensure_profile`].
206fn ensure_card(
207    gate: &GateClient,
208    key: &NostrSecretKey,
209    owner: &DidNostr,
210    path: &PodPath,
211    conflicting: Conflicting,
212) -> Result<CardOutcome, CliError> {
213    let standard = profile_card(owner);
214    for _attempt in 0..2 {
215        let existing = gate.fetch(
216            &Request::new("GET", path.as_str(), ANY),
217            Some(key),
218            CARD_READ_LIMIT,
219        )?;
220        if existing.head.status == 404 {
221            let put = put_turtle(gate, key, path, &standard, Precondition::CreateOnly)?;
222            if put.head.status == 412 {
223                continue;
224            }
225            if !put.head.is_success() {
226                return Err(put.into_error(Route::Pod));
227            }
228            return Ok(CardOutcome::Written);
229        }
230        if !existing.head.is_success() {
231            return Err(existing.into_error(Route::Pod));
232        }
233        let Some(why) = card_problem(&existing, owner) else {
234            return Ok(CardOutcome::Kept);
235        };
236        if conflicting == Conflicting::Report {
237            return Ok(CardOutcome::Conflict(why));
238        }
239        let Some(etag) = existing.head.etag.as_deref() else {
240            return Err(CliError::Refused(format!(
241                "{path} {why}, and the pod server sent no entity tag, so it cannot be replaced \
242                 without risking a change made meanwhile"
243            )));
244        };
245        let put = put_turtle(gate, key, path, &standard, Precondition::IfMatch(etag))?;
246        if put.head.status == 412 {
247            return Err(CliError::Refused(format!(
248                "{path} changed while it was being replaced; nothing was written, run the \
249                 command again"
250            )));
251        }
252        if !put.head.is_success() {
253            return Err(put.into_error(Route::Pod));
254        }
255        return Ok(CardOutcome::Replaced);
256    }
257    Err(CliError::Refused(format!(
258        "{path} kept appearing and disappearing while it was being created; run the command \
259         again"
260    )))
261}
262
263/// Step 2 of [`ensure_profile`].
264fn ensure_acl(
265    gate: &GateClient,
266    key: &NostrSecretKey,
267    owner: &DidNostr,
268    path: &PodPath,
269) -> Result<AclOutcome, CliError> {
270    let standard = profile_acl(owner);
271    for _attempt in 0..2 {
272        let existing = gate.fetch(
273            &Request::new("GET", path.as_str(), ANY),
274            Some(key),
275            ACL_READ_LIMIT,
276        )?;
277        if existing.head.status == 404 {
278            let put = put_turtle(gate, key, path, &standard, Precondition::CreateOnly)?;
279            if put.head.status == 412 {
280                continue;
281            }
282            if !put.head.is_success() {
283                return Err(put.into_error(Route::Pod));
284            }
285            return Ok(AclOutcome::Written);
286        }
287        if !existing.head.is_success() {
288            return Err(existing.into_error(Route::Pod));
289        }
290        return Ok(AclOutcome::Kept {
291            standard: existing.body == standard.as_bytes(),
292        });
293    }
294    Err(CliError::Refused(format!(
295        "{path} kept appearing and disappearing while it was being created; run the command \
296         again"
297    )))
298}
299
300/// `PUT`s Turtle text under a precondition.
301fn put_turtle(
302    gate: &GateClient,
303    key: &NostrSecretKey,
304    path: &PodPath,
305    text: &str,
306    precondition: Precondition<'_>,
307) -> Result<Buffered, CliError> {
308    gate.fetch(
309        &Request::new("PUT", path.as_str(), ANY)
310            .with_body(text.as_bytes(), PROFILE_CONTENT_TYPE)
311            .with_precondition(precondition),
312        Some(key),
313        crate::client::MAX_RESPONSE_BYTES,
314    )
315}
316
317/// Why an existing card does not qualify, or `None` when it does: it must
318/// be stored as `text/turtle` (what the gate serves unsigned), within
319/// [`PROFILE_MAX_BYTES`], and name its owner.
320fn card_problem(card: &Buffered, owner: &DidNostr) -> Option<String> {
321    let content_type = card.head.content_type.as_deref().unwrap_or("");
322    if !is_turtle(content_type) {
323        return Some(format!(
324            "exists but is stored as {:?}, not {PROFILE_CONTENT_TYPE}, so it is never served \
325             publicly",
326            sanitize(content_type)
327        ));
328    }
329    if card.body.len() > PROFILE_MAX_BYTES {
330        return Some(format!(
331            "exists but is {} bytes, over the {PROFILE_MAX_BYTES} bytes served publicly",
332            card.body.len()
333        ));
334    }
335    if !card_names_owner(&card.body, owner) {
336        return Some(format!(
337            "exists but does not name {owner} as its owner (`<#me> owl:sameAs <{owner}>`)"
338        ));
339    }
340    None
341}
342
343/// Returns `true` when a `Content-Type` value's media type is
344/// `text/turtle`, whatever its parameters.
345fn is_turtle(content_type: &str) -> bool {
346    content_type
347        .split(';')
348        .next()
349        .is_some_and(|essence| essence.trim().eq_ignore_ascii_case(PROFILE_CONTENT_TYPE))
350}
351
352impl Session {
353    /// `stratum profile init [--replace] --origin … [--connect …]`: writes
354    /// the public profile document into the caller's own pod, for a member
355    /// admitted before `join` wrote one. Signed by the caller's key.
356    ///
357    /// It never overwrites what is already right, and a repeat sends no
358    /// write:
359    ///
360    /// - With no card, it writes the standard card
361    ///   (`PUT /pods/<pk>/profile/card`, `If-None-Match: *`, `text/turtle`)
362    ///   and then the ACL beside it if that is missing.
363    /// - With a card that names the owner, it leaves the card and writes
364    ///   only a missing ACL (`PUT /pods/<pk>/profile/card.acl`,
365    ///   `If-None-Match: *`). An existing ACL is never changed; the output
366    ///   says when it is not the standard one.
367    /// - With a card that does not name the owner, or that the gate would
368    ///   not serve (another content type, over 64 KiB), it reports the
369    ///   conflict and changes nothing, unless `--replace` is given; then
370    ///   the card is replaced with `If-Match: <etag read>` and a missing
371    ///   ACL is written.
372    ///
373    /// # Errors
374    ///
375    /// [`CliError::Refused`] for a card in conflict without `--replace`, or
376    /// one that changed while being replaced; and key, transport and server
377    /// errors (`suspended`, `insufficient_storage` among them).
378    ///
379    /// # Examples
380    ///
381    /// ```no_run
382    /// use stratum_node_cli::{GateTarget, Output, OutputFormat, Session, ProfileInitOptions};
383    ///
384    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
385    /// let session = Session::new(
386    ///     stratum_node_cli::DEFAULT_URL.parse()?,
387    ///     Some("me.nsec".into()),
388    ///     Output::new(OutputFormat::Human),
389    /// );
390    /// let target = GateTarget::new(
391    ///     "https://stratum.example".parse()?,
392    ///     Some("127.0.0.1:7461".parse()?),
393    /// )?;
394    /// session.profile_init(&target, ProfileInitOptions::default())?;
395    /// # Ok(())
396    /// # }
397    /// ```
398    pub fn profile_init(
399        &self,
400        target: &GateTarget,
401        options: ProfileInitOptions,
402    ) -> Result<u8, CliError> {
403        let key = self.key()?;
404        let me = key.public();
405        let gate = GateClient::new(target.clone()).with_busy_retries(*self.output());
406        let conflicting = if options.replace {
407            Conflicting::Replace
408        } else {
409            Conflicting::Report
410        };
411        let outcome = ensure_profile(&gate, &key, conflicting)?;
412        let card = profile_card_path(&me);
413        let acl = acl_of_card(&card)?;
414        if let CardOutcome::Conflict(why) = &outcome.card {
415            self.output().json(&outcome.to_json(&card, &acl))?;
416            return Err(CliError::Refused(format!(
417                "{card} {why}; nothing was changed. Pass --replace to replace it with the \
418                 standard card"
419            )));
420        }
421        self.output().json(&outcome.to_json(&card, &acl))?;
422        outcome.note(*self.output(), &card)?;
423        let url = target.origin().url(card.as_str());
424        self.output().line(&format!("profile: {url}"))?;
425        self.output().line(&format!(
426            "card: {}, acl: {}",
427            outcome.card.as_str(),
428            outcome.acl.as_str()
429        ))?;
430        Ok(exit::OK)
431    }
432
433    /// `stratum profile show <did> --origin … [--connect …]`: reads any
434    /// member's public profile, without a key.
435    ///
436    /// Sends an unsigned `GET /pods/<pk>/profile/card` with
437    /// `Accept: text/turtle` to the gate, the one request the gate forwards
438    /// without a signature. A 200 must be `text/turtle` and at most
439    /// [`PROFILE_MAX_BYTES`]; its text is printed with control characters
440    /// escaped (under `--json`: the DID, URL, content type, entity tag and
441    /// text). A 404 is reported as "no public profile" with exit code
442    /// [`exit::NOT_FOUND`]: the key is not a member, or the member never
443    /// wrote one, deleted it or made it private; the gate does not say
444    /// which.
445    ///
446    /// No key file is read, even when one is configured.
447    ///
448    /// # Errors
449    ///
450    /// [`CliError::Protocol`] for an answer of another content type or
451    /// size, and transport and server errors (`pod_unavailable`, busy).
452    ///
453    /// # Examples
454    ///
455    /// ```no_run
456    /// use stratum_node_cli::{GateTarget, Output, OutputFormat, Session};
457    ///
458    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
459    /// let session = Session::new(
460    ///     stratum_node_cli::DEFAULT_URL.parse()?,
461    ///     None,
462    ///     Output::new(OutputFormat::Human),
463    /// );
464    /// let target = GateTarget::new(
465    ///     "https://stratum.example".parse()?,
466    ///     Some("127.0.0.1:7461".parse()?),
467    /// )?;
468    /// let member = "did:nostr:79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798".parse()?;
469    /// let code = session.profile_show(&target, &member)?; // 13: no public profile
470    /// # let _ = code;
471    /// # Ok(())
472    /// # }
473    /// ```
474    pub fn profile_show(&self, target: &GateTarget, member: &DidNostr) -> Result<u8, CliError> {
475        let path = profile_card_path(member);
476        let url = target.origin().url(path.as_str());
477        let gate = GateClient::new(target.clone());
478        let limit = u64::try_from(PROFILE_MAX_BYTES).unwrap_or(u64::MAX);
479        let response = gate.fetch(
480            &Request::new("GET", path.as_str(), PROFILE_CONTENT_TYPE),
481            None,
482            limit,
483        )?;
484        if response.head.status == 404 {
485            self.output()
486                .json(&json!({"did": member, "url": url, "profile": null}))?;
487            self.output()
488                .line(&format!("no public profile for {member}"))?;
489            self.output().note(
490                "the key is not a member of this node, or the member has not written a \
491                 profile, deleted it or made it private; the node does not say which",
492            )?;
493            return Ok(exit::NOT_FOUND);
494        }
495        if !response.head.is_success() {
496            return Err(response.into_error(Route::Pod));
497        }
498        let content_type = response.head.content_type.clone().unwrap_or_default();
499        if !is_turtle(&content_type) {
500            return Err(CliError::Protocol(format!(
501                "the profile was served as {:?}, not {PROFILE_CONTENT_TYPE}",
502                sanitize(&content_type)
503            )));
504        }
505        let text = sanitize(&String::from_utf8_lossy(&response.body));
506        self.output().json(&json!({
507            "did": member,
508            "url": url,
509            "content_type": PROFILE_CONTENT_TYPE,
510            "etag": response.head.etag.as_deref().map(sanitize),
511            "profile": text,
512        }))?;
513        self.output().note(&format!("profile of {member}: {url}"))?;
514        for line in text.lines() {
515            self.output().line(line)?;
516        }
517        Ok(exit::OK)
518    }
519}
520
521#[cfg(test)]
522mod tests {
523    use super::*;
524
525    #[test]
526    fn turtle_is_recognised_with_parameters_and_in_any_case() {
527        assert!(is_turtle("text/turtle"));
528        assert!(is_turtle("text/turtle; charset=utf-8"));
529        assert!(is_turtle("Text/Turtle"));
530        assert!(!is_turtle("application/ld+json"));
531        assert!(!is_turtle("text/turtles"));
532        assert!(!is_turtle(""));
533    }
534}