use alloc::collections::BTreeSet;
use alloc::string::{String, ToString as _};
use alloc::vec::Vec;
use core::fmt;
use core::str::FromStr;
use base64ct::{Base64UrlUnpadded, Encoding};
use serde_json::Value;
use sha2::Digest;
use crate::event::{Event, EventBuilder, Kind, Tag, Tags};
use crate::hex;
use crate::{JsonError, Timestamp};
#[non_exhaustive]
#[derive(Debug, thiserror::Error)]
#[allow(
variant_size_differences,
reason = "the JsonError source is a cold error path"
)]
pub enum Error {
#[error("invalid blob sha256")]
InvalidHash,
#[error("invalid blossom server URL")]
InvalidServer,
#[error("blossom auth message must not be empty")]
EmptyMessage,
#[error("server list requires at least one valid http(s) URL")]
NoServers,
#[error("expected kind {expected}, got {found}")]
WrongKind {
expected: u16,
found: u16,
},
#[error("invalid blossom JSON")]
InvalidJson {
#[source]
source: JsonError,
},
#[error("invalid blob descriptor")]
NotAnObject,
#[error("blob descriptor missing url")]
MissingUrl,
#[error("blob descriptor missing sha256")]
MissingHash,
#[error("blob descriptor missing size")]
MissingSize,
#[error("blossom list response must be a JSON array")]
NotAnArray,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct BlobHash([u8; 32]);
impl BlobHash {
#[must_use]
pub fn of(data: &[u8]) -> Self {
Self(sha2::Sha256::digest(data).into())
}
#[must_use]
pub const fn as_bytes(&self) -> &[u8; 32] {
&self.0
}
#[must_use]
pub fn from_url(url: &str) -> Option<Self> {
let parsed = url::Url::parse(url).ok()?;
let mut last = None;
for run in parsed
.path()
.split(|b: char| !matches!(b, '0'..='9' | 'a'..='f'))
{
let Some(last_block) = (run.len() / 64).checked_sub(1).map(|n| n * 64) else {
continue;
};
if let Some(hash) = run
.get(last_block..last_block + 64)
.and_then(|block| hex::decode_wire(block).ok())
{
last = Some(Self(hash));
}
}
last
}
}
impl FromStr for BlobHash {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Error> {
Ok(Self(hex::decode_caller(s).map_err(|_| Error::InvalidHash)?))
}
}
impl fmt::Display for BlobHash {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&hex::encode(&self.0))
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Server(String);
impl Server {
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
#[must_use]
pub fn endpoint(&self, path: &str) -> String {
alloc::format!("{}/{}", self.0, path.strip_prefix('/').unwrap_or(path))
}
#[must_use]
pub fn blob_url(&self, hash: &BlobHash, extension: &str) -> String {
alloc::format!("{}/{}{}", self.0, hash, extension)
}
}
impl FromStr for Server {
type Err = Error;
fn from_str(raw: &str) -> Result<Self, Error> {
let url = url::Url::parse(raw).map_err(|_| Error::InvalidServer)?;
if !matches!(url.scheme(), "http" | "https") {
return Err(Error::InvalidServer);
}
let mut base = url.origin().ascii_serialization();
base.push_str(url.path().trim_end_matches('/'));
Ok(Self(base))
}
}
impl fmt::Display for Server {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum AuthVerb {
Upload,
Delete,
List,
Get,
Media,
}
impl AuthVerb {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Upload => "upload",
Self::Delete => "delete",
Self::List => "list",
Self::Get => "get",
Self::Media => "media",
}
}
#[must_use]
pub const fn default_message(self) -> &'static str {
match self {
Self::Upload => "Upload Blob",
Self::Delete => "Delete Blob",
Self::List => "List Blobs",
Self::Get => "Get Blob",
Self::Media => "Upload Media",
}
}
}
#[derive(Clone, Debug)]
pub struct Authorization {
verb: AuthVerb,
expiration: Timestamp,
blob: Option<BlobHash>,
message: Option<String>,
servers: Vec<String>,
}
fn server_hostname(raw: &str) -> Option<String> {
let owned;
let raw = if raw.contains("://") {
raw
} else {
owned = alloc::format!("https://{raw}");
owned.as_str()
};
let url = url::Url::parse(raw).ok()?;
if !matches!(url.scheme(), "http" | "https") {
return None;
}
let hostname = String::from(url.host_str()?);
if hostname.is_empty() {
None
} else {
Some(hostname)
}
}
impl Authorization {
#[must_use]
pub const fn new(verb: AuthVerb, expiration: Timestamp) -> Self {
Self {
verb,
expiration,
blob: None,
message: None,
servers: Vec::new(),
}
}
#[must_use]
pub const fn blob(mut self, hash: BlobHash) -> Self {
self.blob = Some(hash);
self
}
pub fn message(mut self, message: impl Into<String>) -> Result<Self, Error> {
let message = message.into();
if message.trim_ascii().is_empty() {
return Err(Error::EmptyMessage);
}
self.message = Some(message);
Ok(self)
}
#[must_use]
pub fn servers<S: AsRef<str>>(mut self, servers: impl IntoIterator<Item = S>) -> Self {
let mut seen: BTreeSet<String> = self.servers.iter().cloned().collect();
for raw in servers {
if let Some(hostname) = server_hostname(raw.as_ref())
&& seen.insert(hostname.clone())
{
self.servers.push(hostname);
}
}
self
}
}
impl From<Authorization> for EventBuilder {
fn from(auth: Authorization) -> Self {
let mut tags = alloc::vec![
Tag::custom("t", [auth.verb.as_str()]),
Tag::custom("expiration", [auth.expiration.as_secs().to_string()]),
];
if let Some(hash) = auth.blob {
tags.push(Tag::custom("x", [hash.to_string()]));
}
for server in &auth.servers {
tags.push(Tag::custom("server", [server.as_str()]));
}
let content = auth
.message
.unwrap_or_else(|| String::from(auth.verb.default_message()));
Self::new(Kind::BLOBS_AUTH, content).tags(tags)
}
}
#[must_use]
pub fn authorization_header(event: &Event) -> String {
alloc::format!(
"Nostr {}",
Base64UrlUnpadded::encode_string(event.to_json().as_bytes())
)
}
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BlobDescriptor {
pub url: String,
pub sha256: BlobHash,
pub size: u64,
pub mime_type: Option<String>,
pub uploaded: Option<Timestamp>,
pub nip94: Option<Tags>,
}
impl BlobDescriptor {
pub fn from_json(json: &str) -> Result<Self, Error> {
let value: Value =
serde_json::from_str(json).map_err(|e| Error::InvalidJson { source: e.into() })?;
Self::from_value(&value)
}
pub fn list_from_json(json: &str) -> Result<Vec<Self>, Error> {
let value: Value =
serde_json::from_str(json).map_err(|e| Error::InvalidJson { source: e.into() })?;
let items = value.as_array().ok_or(Error::NotAnArray)?;
items.iter().map(Self::from_value).collect()
}
#[must_use]
pub fn mirror_body(&self) -> String {
serde_json::json!({ "url": self.url }).to_string()
}
fn from_value(value: &Value) -> Result<Self, Error> {
let object = value.as_object().ok_or(Error::NotAnObject)?;
let url = object
.get("url")
.and_then(Value::as_str)
.filter(|s| !s.is_empty())
.ok_or(Error::MissingUrl)?;
let sha256 = object
.get("sha256")
.and_then(Value::as_str)
.and_then(|s| hex::decode_wire(s).ok().map(BlobHash))
.ok_or(Error::MissingHash)?;
let size = object
.get("size")
.and_then(Value::as_u64)
.ok_or(Error::MissingSize)?;
let mime_type = object.get("type").and_then(Value::as_str).map(String::from);
let uploaded = object
.get("uploaded")
.and_then(Value::as_u64)
.map(Timestamp::from_secs);
let nip94 = object.get("nip94").and_then(nip94_tags);
Ok(Self {
url: String::from(url),
sha256,
size,
mime_type,
uploaded,
nip94,
})
}
}
fn nip94_tags(value: &Value) -> Option<Tags> {
let array = value.as_array()?;
let mut tags = Vec::with_capacity(array.len());
for element in array {
let items: Option<Vec<String>> = element
.as_array()?
.iter()
.map(|v| v.as_str().map(String::from))
.collect();
tags.push(Tag::new(items?).ok()?);
}
Some(tags.into_iter().collect())
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct ServerList {
servers: Vec<Server>,
}
impl ServerList {
pub fn new<S: AsRef<str>>(servers: impl IntoIterator<Item = S>) -> Result<Self, Error> {
let mut list = Self::default();
for raw in servers {
if let Ok(server) = Server::from_str(raw.as_ref())
&& !list.servers.contains(&server)
{
list.servers.push(server);
}
}
if list.servers.is_empty() {
return Err(Error::NoServers);
}
Ok(list)
}
#[must_use]
pub fn servers(&self) -> &[Server] {
&self.servers
}
}
impl TryFrom<&Event> for ServerList {
type Error = Error;
fn try_from(event: &Event) -> Result<Self, Error> {
if event.kind() != Kind::BLOSSOM_SERVER_LIST {
return Err(Error::WrongKind {
expected: Kind::BLOSSOM_SERVER_LIST.as_u16(),
found: event.kind().as_u16(),
});
}
let mut list = Self::default();
for tag in event.tags() {
let Some(value) = tag
.value()
.filter(|v| tag.name() == "server" && !v.is_empty())
else {
continue;
};
if let Ok(server) = Server::from_str(value)
&& !list.servers.contains(&server)
{
list.servers.push(server);
}
}
Ok(list)
}
}
impl From<ServerList> for EventBuilder {
fn from(list: ServerList) -> Self {
let tags: Tags = list
.servers
.iter()
.map(|s| Tag::custom("server", [s.as_str()]))
.collect();
Self::new(Kind::BLOSSOM_SERVER_LIST, "").tags(tags)
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::panic, reason = "tests fail by panicking")]
use super::*;
const PK: &str = "3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d";
#[test]
fn hash_display_round_trips() {
let hash = BlobHash::from_str(&PK.to_uppercase()).unwrap();
assert_eq!(hash.to_string(), PK);
assert_eq!(
BlobHash::of(b"").to_string(),
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
);
}
#[test]
fn from_url_last_run_wins() {
let hash = BlobHash::from_url(&alloc::format!("https://x/aaa/{PK}.png")).unwrap();
assert_eq!(hash.to_string(), PK);
assert!(BlobHash::from_url("not a url").is_none());
assert!(BlobHash::from_url("https://x/nohash").is_none());
}
#[test]
fn server_normalizes() {
let server = "https://cdn.example.com/api/".parse::<Server>().unwrap();
assert_eq!(server.as_str(), "https://cdn.example.com/api");
assert_eq!(
server.endpoint("/upload"),
"https://cdn.example.com/api/upload"
);
assert!("wss://x.example".parse::<Server>().is_err());
}
#[test]
fn auth_template_ts_order() {
let auth = Authorization::new(AuthVerb::Upload, Timestamp::from_secs(1_700_000_000))
.blob(BlobHash::from_str(PK).unwrap())
.servers(["https://a.example.com", "A.EXAMPLE.COM", "ftp://b.com"]);
let template = EventBuilder::from(auth);
let unsigned = template.build_at(
crate::PublicKey::from_hex(PK).unwrap(),
Timestamp::from_secs(1_700_000_000),
);
let names: Vec<&str> = unsigned.tags().iter().map(Tag::name).collect();
assert_eq!(names, ["t", "expiration", "x", "server"]);
}
#[test]
fn auth_message_validation() {
let auth = Authorization::new(AuthVerb::Get, Timestamp::from_secs(0));
assert!(matches!(
auth.clone().message(" "),
Err(Error::EmptyMessage)
));
assert!(auth.message("hey").is_ok());
}
}