use serde_json::json;
use stratum_node_core::{
card_names_owner, profile_acl, profile_card, profile_card_path, DidNostr, NostrSecretKey,
PodPath, PROFILE_CONTENT_TYPE, PROFILE_MAX_BYTES,
};
use crate::error::CliError;
use crate::exit;
use crate::gate::{Buffered, GateClient, Precondition, Request, Route, ANY};
use crate::origin::GateTarget;
use crate::output::{sanitize, Output};
use crate::session::Session;
const CARD_READ_LIMIT: u64 = 16 * 1024 * 1024;
const ACL_READ_LIMIT: u64 = 1024 * 1024;
#[derive(Debug, Clone, Copy, Default)]
pub struct ProfileInitOptions {
pub replace: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Conflicting {
Report,
Replace,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum CardOutcome {
Written,
Kept,
Replaced,
Conflict(String),
}
impl CardOutcome {
fn as_str(&self) -> &'static str {
match self {
Self::Written => "written",
Self::Kept => "kept",
Self::Replaced => "replaced",
Self::Conflict(_) => "conflict",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum AclOutcome {
Written,
Kept { standard: bool },
Skipped,
}
impl AclOutcome {
fn as_str(self) -> &'static str {
match self {
Self::Written => "written",
Self::Kept { .. } => "kept",
Self::Skipped => "skipped",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ProfileOutcome {
pub(crate) card: CardOutcome,
pub(crate) acl: AclOutcome,
}
impl ProfileOutcome {
pub(crate) fn to_json(&self, card: &PodPath, acl: &PodPath) -> serde_json::Value {
let conflict = match &self.card {
CardOutcome::Conflict(why) => Some(why.clone()),
_ => None,
};
let standard = match self.acl {
AclOutcome::Kept { standard } => Some(standard),
AclOutcome::Written => Some(true),
AclOutcome::Skipped => None,
};
json!({
"card": {"path": card, "outcome": self.card.as_str(), "conflict": conflict},
"acl": {"path": acl, "outcome": self.acl.as_str(), "standard": standard},
})
}
pub(crate) fn note(&self, output: Output, card: &PodPath) -> Result<(), CliError> {
let line = match &self.card {
CardOutcome::Written => format!("profile {card}: written"),
CardOutcome::Kept => format!("profile {card}: already there and names you; left as is"),
CardOutcome::Replaced => format!("profile {card}: replaced with the standard card"),
CardOutcome::Conflict(why) => format!("profile {card}: {why}; left as is"),
};
output.note(&line)?;
let line = match self.acl {
AclOutcome::Written => {
"profile ACL: written (you: read, write, control; everyone: read)".to_owned()
}
AclOutcome::Kept { standard: true } => {
"profile ACL: already there; left as is".to_owned()
}
AclOutcome::Kept { standard: false } => "profile ACL: already there and not the \
standard one; left as is, so the card may not be public"
.to_owned(),
AclOutcome::Skipped => {
"profile ACL: not written, because the card is not yours to publish".to_owned()
}
};
output.note(&line)
}
}
pub(crate) fn ensure_profile(
gate: &GateClient,
key: &NostrSecretKey,
conflicting: Conflicting,
) -> Result<ProfileOutcome, CliError> {
let owner = key.public();
let card_path = profile_card_path(&owner);
let acl_path = acl_of_card(&card_path)?;
let card = ensure_card(gate, key, &owner, &card_path, conflicting)?;
if matches!(card, CardOutcome::Conflict(_)) {
return Ok(ProfileOutcome {
card,
acl: AclOutcome::Skipped,
});
}
let acl = ensure_acl(gate, key, &owner, &acl_path)?;
Ok(ProfileOutcome { card, acl })
}
fn acl_of_card(card: &PodPath) -> Result<PodPath, CliError> {
card.acl_path()
.ok_or_else(|| CliError::Local("the profile card has no ACL path".to_owned()))
}
fn ensure_card(
gate: &GateClient,
key: &NostrSecretKey,
owner: &DidNostr,
path: &PodPath,
conflicting: Conflicting,
) -> Result<CardOutcome, CliError> {
let standard = profile_card(owner);
for _attempt in 0..2 {
let existing = gate.fetch(
&Request::new("GET", path.as_str(), ANY),
Some(key),
CARD_READ_LIMIT,
)?;
if existing.head.status == 404 {
let put = put_turtle(gate, key, path, &standard, Precondition::CreateOnly)?;
if put.head.status == 412 {
continue;
}
if !put.head.is_success() {
return Err(put.into_error(Route::Pod));
}
return Ok(CardOutcome::Written);
}
if !existing.head.is_success() {
return Err(existing.into_error(Route::Pod));
}
let Some(why) = card_problem(&existing, owner) else {
return Ok(CardOutcome::Kept);
};
if conflicting == Conflicting::Report {
return Ok(CardOutcome::Conflict(why));
}
let Some(etag) = existing.head.etag.as_deref() else {
return Err(CliError::Refused(format!(
"{path} {why}, and the pod server sent no entity tag, so it cannot be replaced \
without risking a change made meanwhile"
)));
};
let put = put_turtle(gate, key, path, &standard, Precondition::IfMatch(etag))?;
if put.head.status == 412 {
return Err(CliError::Refused(format!(
"{path} changed while it was being replaced; nothing was written, run the \
command again"
)));
}
if !put.head.is_success() {
return Err(put.into_error(Route::Pod));
}
return Ok(CardOutcome::Replaced);
}
Err(CliError::Refused(format!(
"{path} kept appearing and disappearing while it was being created; run the command \
again"
)))
}
fn ensure_acl(
gate: &GateClient,
key: &NostrSecretKey,
owner: &DidNostr,
path: &PodPath,
) -> Result<AclOutcome, CliError> {
let standard = profile_acl(owner);
for _attempt in 0..2 {
let existing = gate.fetch(
&Request::new("GET", path.as_str(), ANY),
Some(key),
ACL_READ_LIMIT,
)?;
if existing.head.status == 404 {
let put = put_turtle(gate, key, path, &standard, Precondition::CreateOnly)?;
if put.head.status == 412 {
continue;
}
if !put.head.is_success() {
return Err(put.into_error(Route::Pod));
}
return Ok(AclOutcome::Written);
}
if !existing.head.is_success() {
return Err(existing.into_error(Route::Pod));
}
return Ok(AclOutcome::Kept {
standard: existing.body == standard.as_bytes(),
});
}
Err(CliError::Refused(format!(
"{path} kept appearing and disappearing while it was being created; run the command \
again"
)))
}
fn put_turtle(
gate: &GateClient,
key: &NostrSecretKey,
path: &PodPath,
text: &str,
precondition: Precondition<'_>,
) -> Result<Buffered, CliError> {
gate.fetch(
&Request::new("PUT", path.as_str(), ANY)
.with_body(text.as_bytes(), PROFILE_CONTENT_TYPE)
.with_precondition(precondition),
Some(key),
crate::client::MAX_RESPONSE_BYTES,
)
}
fn card_problem(card: &Buffered, owner: &DidNostr) -> Option<String> {
let content_type = card.head.content_type.as_deref().unwrap_or("");
if !is_turtle(content_type) {
return Some(format!(
"exists but is stored as {:?}, not {PROFILE_CONTENT_TYPE}, so it is never served \
publicly",
sanitize(content_type)
));
}
if card.body.len() > PROFILE_MAX_BYTES {
return Some(format!(
"exists but is {} bytes, over the {PROFILE_MAX_BYTES} bytes served publicly",
card.body.len()
));
}
if !card_names_owner(&card.body, owner) {
return Some(format!(
"exists but does not name {owner} as its owner (`<#me> owl:sameAs <{owner}>`)"
));
}
None
}
fn is_turtle(content_type: &str) -> bool {
content_type
.split(';')
.next()
.is_some_and(|essence| essence.trim().eq_ignore_ascii_case(PROFILE_CONTENT_TYPE))
}
impl Session {
pub fn profile_init(
&self,
target: &GateTarget,
options: ProfileInitOptions,
) -> Result<u8, CliError> {
let key = self.key()?;
let me = key.public();
let gate = GateClient::new(target.clone()).with_busy_retries(*self.output());
let conflicting = if options.replace {
Conflicting::Replace
} else {
Conflicting::Report
};
let outcome = ensure_profile(&gate, &key, conflicting)?;
let card = profile_card_path(&me);
let acl = acl_of_card(&card)?;
if let CardOutcome::Conflict(why) = &outcome.card {
self.output().json(&outcome.to_json(&card, &acl))?;
return Err(CliError::Refused(format!(
"{card} {why}; nothing was changed. Pass --replace to replace it with the \
standard card"
)));
}
self.output().json(&outcome.to_json(&card, &acl))?;
outcome.note(*self.output(), &card)?;
let url = target.origin().url(card.as_str());
self.output().line(&format!("profile: {url}"))?;
self.output().line(&format!(
"card: {}, acl: {}",
outcome.card.as_str(),
outcome.acl.as_str()
))?;
Ok(exit::OK)
}
pub fn profile_show(&self, target: &GateTarget, member: &DidNostr) -> Result<u8, CliError> {
let path = profile_card_path(member);
let url = target.origin().url(path.as_str());
let gate = GateClient::new(target.clone());
let limit = u64::try_from(PROFILE_MAX_BYTES).unwrap_or(u64::MAX);
let response = gate.fetch(
&Request::new("GET", path.as_str(), PROFILE_CONTENT_TYPE),
None,
limit,
)?;
if response.head.status == 404 {
self.output()
.json(&json!({"did": member, "url": url, "profile": null}))?;
self.output()
.line(&format!("no public profile for {member}"))?;
self.output().note(
"the key is not a member of this node, or the member has not written a \
profile, deleted it or made it private; the node does not say which",
)?;
return Ok(exit::NOT_FOUND);
}
if !response.head.is_success() {
return Err(response.into_error(Route::Pod));
}
let content_type = response.head.content_type.clone().unwrap_or_default();
if !is_turtle(&content_type) {
return Err(CliError::Protocol(format!(
"the profile was served as {:?}, not {PROFILE_CONTENT_TYPE}",
sanitize(&content_type)
)));
}
let text = sanitize(&String::from_utf8_lossy(&response.body));
self.output().json(&json!({
"did": member,
"url": url,
"content_type": PROFILE_CONTENT_TYPE,
"etag": response.head.etag.as_deref().map(sanitize),
"profile": text,
}))?;
self.output().note(&format!("profile of {member}: {url}"))?;
for line in text.lines() {
self.output().line(line)?;
}
Ok(exit::OK)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn turtle_is_recognised_with_parameters_and_in_any_case() {
assert!(is_turtle("text/turtle"));
assert!(is_turtle("text/turtle; charset=utf-8"));
assert!(is_turtle("Text/Turtle"));
assert!(!is_turtle("application/ld+json"));
assert!(!is_turtle("text/turtles"));
assert!(!is_turtle(""));
}
}