1use 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
23const CARD_READ_LIMIT: u64 = 16 * 1024 * 1024;
27
28const ACL_READ_LIMIT: u64 = 1024 * 1024;
31
32#[derive(Debug, Clone, Copy, Default)]
46pub struct ProfileInitOptions {
47 pub replace: bool,
51}
52
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55pub(crate) enum Conflicting {
56 Report,
58 Replace,
60}
61
62#[derive(Debug, Clone, PartialEq, Eq)]
64pub(crate) enum CardOutcome {
65 Written,
67 Kept,
70 Replaced,
73 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
91pub(crate) enum AclOutcome {
92 Written,
94 Kept { standard: bool },
97 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#[derive(Debug, Clone, PartialEq, Eq)]
114pub(crate) struct ProfileOutcome {
115 pub(crate) card: CardOutcome,
116 pub(crate) acl: AclOutcome,
117}
118
119impl ProfileOutcome {
120 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 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
164pub(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
199fn 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
205fn 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
263fn 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
300fn 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
317fn 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
343fn 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 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 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}