use alloc::borrow::Cow;
use alloc::string::{String, ToString};
use alloc::vec;
use alloc::vec::Vec;
use core::fmt;
use core::str::FromStr;
use crate::{Kind, PublicKey, Tags, Timestamp, UnsignedEvent};
use serde::{Deserialize, Serialize};
use url::Url;
use url::form_urlencoded::Serializer;
#[non_exhaustive]
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("invalid URI")]
InvalidUri {
#[source]
source: url::ParseError,
},
#[error("expected a {expected}: URI")]
UnexpectedScheme {
expected: &'static str,
},
#[error("invalid public key in URI")]
InvalidPublicKey,
#[error("missing secret in URI")]
MissingSecret,
#[error("missing relays in URI")]
MissingRelays,
#[error("invalid NIP-46 JSON")]
InvalidJson {
#[source]
source: crate::JsonError,
},
}
fn authority_or_path(url: &Url) -> &str {
match url.host_str() {
Some(host) if !host.is_empty() => host,
_ => url.path().trim_start_matches('/'),
}
}
fn query_get<'a>(pairs: &'a [(Cow<'a, str>, Cow<'a, str>)], name: &str) -> Option<&'a str> {
pairs
.iter()
.find(|(key, _)| key == name)
.map(|(_, value)| value.as_ref())
}
fn query_get_all<'a>(pairs: &[(Cow<'a, str>, Cow<'a, str>)], name: &str) -> Vec<String> {
pairs
.iter()
.filter(|(key, _)| key == name)
.map(|(_, value)| value.to_string())
.collect()
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct BunkerUri {
pub remote_signer: PublicKey,
pub relays: Vec<String>,
pub secret: Option<String>,
}
impl FromStr for BunkerUri {
type Err = Error;
fn from_str(input: &str) -> Result<Self, Error> {
let url = Url::parse(input.trim_ascii()).map_err(|e| Error::InvalidUri { source: e })?;
if url.scheme() != "bunker" {
return Err(Error::UnexpectedScheme { expected: "bunker" });
}
let remote_signer = PublicKey::from_wire_hex(authority_or_path(&url))
.map_err(|_| Error::InvalidPublicKey)?;
let pairs: Vec<(Cow<'_, str>, Cow<'_, str>)> = url.query_pairs().collect();
Ok(Self {
remote_signer,
relays: query_get_all(&pairs, "relay"),
secret: query_get(&pairs, "secret").map(String::from),
})
}
}
impl fmt::Display for BunkerUri {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut serializer = Serializer::new(String::new());
for relay in &self.relays {
serializer.append_pair("relay", relay);
}
if let Some(secret) = self.secret.as_deref().filter(|s| !s.is_empty()) {
serializer.append_pair("secret", secret);
}
let query = serializer.finish();
if query.is_empty() {
write!(f, "bunker://{}", self.remote_signer)
} else {
write!(f, "bunker://{}?{query}", self.remote_signer)
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct NostrConnectUri {
client: PublicKey,
relays: Vec<String>,
secret: String,
perms: Vec<String>,
name: Option<String>,
url: Option<String>,
image: Option<String>,
}
impl NostrConnectUri {
pub fn new(client: PublicKey, relays: Vec<String>, secret: String) -> Result<Self, Error> {
if secret.is_empty() {
return Err(Error::MissingSecret);
}
if relays.is_empty() {
return Err(Error::MissingRelays);
}
Ok(Self {
client,
relays,
secret,
perms: Vec::new(),
name: None,
url: None,
image: None,
})
}
#[must_use]
pub fn with_perms<I, S>(mut self, perms: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.perms = perms.into_iter().map(Into::into).collect();
self
}
#[must_use]
pub fn with_name(mut self, name: impl Into<String>) -> Self {
self.name = Some(name.into());
self
}
#[must_use]
pub fn with_url(mut self, url: impl Into<String>) -> Self {
self.url = Some(url.into());
self
}
#[must_use]
pub fn with_image(mut self, image: impl Into<String>) -> Self {
self.image = Some(image.into());
self
}
#[must_use]
pub const fn client(&self) -> PublicKey {
self.client
}
#[must_use]
pub fn relays(&self) -> &[String] {
&self.relays
}
#[must_use]
pub fn secret(&self) -> &str {
&self.secret
}
#[must_use]
pub fn perms(&self) -> &[String] {
&self.perms
}
#[must_use]
pub fn name(&self) -> Option<&str> {
self.name.as_deref()
}
#[must_use]
pub fn url(&self) -> Option<&str> {
self.url.as_deref()
}
#[must_use]
pub fn image(&self) -> Option<&str> {
self.image.as_deref()
}
}
impl FromStr for NostrConnectUri {
type Err = Error;
fn from_str(uri: &str) -> Result<Self, Error> {
let url = Url::parse(uri).map_err(|e| Error::InvalidUri { source: e })?;
if url.scheme() != "nostrconnect" {
return Err(Error::UnexpectedScheme {
expected: "nostrconnect",
});
}
let client = PublicKey::from_wire_hex(authority_or_path(&url))
.map_err(|_| Error::InvalidPublicKey)?;
let pairs: Vec<(Cow<'_, str>, Cow<'_, str>)> = url.query_pairs().collect();
let secret = query_get(&pairs, "secret")
.filter(|s| !s.is_empty())
.ok_or(Error::MissingSecret)?;
let relays = query_get_all(&pairs, "relay");
if relays.is_empty() {
return Err(Error::MissingRelays);
}
let perms = match query_get(&pairs, "perms") {
Some(raw) if !raw.is_empty() => raw
.split(',')
.filter(|perm| !perm.is_empty())
.map(String::from)
.collect(),
_ => Vec::new(),
};
Ok(Self {
client,
relays,
secret: String::from(secret),
perms,
name: query_get(&pairs, "name").map(String::from),
url: query_get(&pairs, "url").map(String::from),
image: query_get(&pairs, "image").map(String::from),
})
}
}
impl fmt::Display for NostrConnectUri {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut serializer = Serializer::new(String::new());
for relay in &self.relays {
serializer.append_pair("relay", relay);
}
serializer.append_pair("secret", &self.secret);
if !self.perms.is_empty() {
serializer.append_pair("perms", &self.perms.join(","));
}
for (key, value) in [
("name", self.name.as_deref()),
("url", self.url.as_deref()),
("image", self.image.as_deref()),
] {
if let Some(value) = value.filter(|v| !v.is_empty()) {
serializer.append_pair(key, value);
}
}
write!(f, "nostrconnect://{}?{}", self.client, serializer.finish())
}
}
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum Method {
Connect,
GetPublicKey,
SignEvent,
Ping,
Nip04Encrypt,
Nip04Decrypt,
Nip44Encrypt,
Nip44Decrypt,
SwitchRelays,
Logout,
Other(String),
}
impl Method {
#[must_use]
pub fn as_str(&self) -> &str {
match self {
Self::Connect => "connect",
Self::GetPublicKey => "get_public_key",
Self::SignEvent => "sign_event",
Self::Ping => "ping",
Self::Nip04Encrypt => "nip04_encrypt",
Self::Nip04Decrypt => "nip04_decrypt",
Self::Nip44Encrypt => "nip44_encrypt",
Self::Nip44Decrypt => "nip44_decrypt",
Self::SwitchRelays => "switch_relays",
Self::Logout => "logout",
Self::Other(name) => name,
}
}
}
impl From<String> for Method {
fn from(name: String) -> Self {
match name.as_str() {
"connect" => Self::Connect,
"get_public_key" => Self::GetPublicKey,
"sign_event" => Self::SignEvent,
"ping" => Self::Ping,
"nip04_encrypt" => Self::Nip04Encrypt,
"nip04_decrypt" => Self::Nip04Decrypt,
"nip44_encrypt" => Self::Nip44Encrypt,
"nip44_decrypt" => Self::Nip44Decrypt,
"switch_relays" => Self::SwitchRelays,
"logout" => Self::Logout,
_ => Self::Other(name),
}
}
}
impl Serialize for Method {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(self.as_str())
}
}
impl<'de> Deserialize<'de> for Method {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
String::deserialize(deserializer).map(Self::from)
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Request {
pub id: String,
pub method: Method,
pub params: Vec<String>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize)]
pub struct ClientMetadata {
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub url: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub image: Option<String>,
}
impl ClientMetadata {
#[must_use]
pub fn to_json(&self) -> String {
serde_json::to_string(self).unwrap_or_default()
}
}
impl Request {
#[must_use]
pub fn connect(
id: impl Into<String>,
remote_signer: &PublicKey,
secret: Option<&str>,
perms: &[String],
metadata: Option<&ClientMetadata>,
) -> Self {
let mut params = vec![remote_signer.to_hex(), String::from(secret.unwrap_or(""))];
if !perms.is_empty() || metadata.is_some() {
params.push(perms.join(","));
}
if let Some(metadata) = metadata {
params.push(metadata.to_json());
}
Self {
id: id.into(),
method: Method::Connect,
params,
}
}
#[must_use]
pub fn sign_event(id: impl Into<String>, unsigned: &UnsignedEvent) -> Self {
#[derive(Serialize)]
struct Template<'a> {
kind: Kind,
content: &'a str,
tags: &'a Tags,
created_at: Timestamp,
}
let template = Template {
kind: unsigned.kind(),
content: unsigned.content(),
tags: unsigned.tags(),
created_at: unsigned.created_at(),
};
Self {
id: id.into(),
method: Method::SignEvent,
params: vec![serde_json::to_string(&template).unwrap_or_default()],
}
}
pub fn from_json(json: &str) -> Result<Self, Error> {
serde_json::from_str(json).map_err(|e| Error::InvalidJson { source: e.into() })
}
#[must_use]
pub fn to_json(&self) -> String {
serde_json::to_string(self).unwrap_or_default()
}
}
pub fn parse_switch_relays(result: &str) -> Result<Option<Vec<String>>, Error> {
let parsed: Option<Vec<String>> =
serde_json::from_str(result).map_err(|e| Error::InvalidJson { source: e.into() })?;
match parsed {
None => Ok(None),
Some(urls) if urls.is_empty() => Err(Error::MissingRelays),
Some(urls) => Ok(Some(urls)),
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Response {
pub id: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub result: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
}
impl Response {
pub fn from_json(json: &str) -> Result<Self, Error> {
serde_json::from_str(json).map_err(|e| Error::InvalidJson { source: e.into() })
}
#[must_use]
pub fn to_json(&self) -> String {
serde_json::to_string(self).unwrap_or_default()
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::panic, reason = "tests fail by panicking")]
use alloc::format;
use alloc::vec;
use core::error::Error as _;
use super::*;
const PK: &str = "3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d";
fn pubkey() -> PublicKey {
PublicKey::from_hex(PK).unwrap()
}
#[test]
fn bunker_uri_round_trip() {
let uri = BunkerUri {
remote_signer: pubkey(),
relays: vec![
String::from("wss://relay.one"),
String::from("wss://relay.two/path?x=1"),
],
secret: Some(String::from("s e c r e t")),
};
let encoded = uri.to_string();
assert_eq!(
encoded,
"bunker://3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d?\
relay=wss%3A%2F%2Frelay.one&relay=wss%3A%2F%2Frelay.two%2Fpath%3Fx%3D1&secret=s+e+c+r+e+t"
);
assert_eq!(encoded.parse::<BunkerUri>().unwrap(), uri);
}
#[test]
fn bunker_parse_variants() {
let parsed = format!(" bunker://{PK}?secret= ")
.parse::<BunkerUri>()
.unwrap();
assert_eq!(
parsed,
BunkerUri {
remote_signer: pubkey(),
relays: Vec::new(),
secret: Some(String::new()),
}
);
assert!(matches!(
format!("bunker://{}", PK.to_uppercase()).parse::<BunkerUri>(),
Err(Error::InvalidPublicKey)
));
assert!(matches!(
"nostrconnect://x".parse::<BunkerUri>(),
Err(Error::UnexpectedScheme { expected: "bunker" })
));
assert!(matches!(
"alice@example.com".parse::<BunkerUri>(),
Err(Error::InvalidUri { .. })
));
assert!(matches!(
format!("bunker://{PK}@evil").parse::<BunkerUri>(),
Err(Error::InvalidPublicKey)
));
let path_form = format!("bunker:{PK}");
assert!(path_form.parse::<BunkerUri>().is_ok());
}
#[test]
fn nostrconnect_uri_round_trip() {
let uri = NostrConnectUri::new(
pubkey(),
vec![String::from("wss://relay.damus.io")],
String::from("hunter2"),
)
.unwrap()
.with_perms([String::from("nip44_encrypt"), String::from("sign_event")])
.with_name("My App")
.with_url("https://my.app/");
let encoded = uri.to_string();
assert_eq!(
encoded,
"nostrconnect://3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d?\
relay=wss%3A%2F%2Frelay.damus.io&secret=hunter2&perms=nip44_encrypt%2Csign_event&name=My+App&url=https%3A%2F%2Fmy.app%2F"
);
let parsed = encoded.parse::<NostrConnectUri>().unwrap();
assert_eq!(parsed, uri);
assert_eq!(parsed.client(), pubkey());
assert_eq!(parsed.secret(), "hunter2");
assert_eq!(parsed.name(), Some("My App"));
assert_eq!(parsed.url(), Some("https://my.app/"));
assert_eq!(parsed.image(), None);
}
#[test]
fn nostrconnect_new_rejects_empty_invariants() {
assert!(matches!(
NostrConnectUri::new(pubkey(), vec![String::from("wss://r")], String::new()),
Err(Error::MissingSecret)
));
assert!(matches!(
NostrConnectUri::new(pubkey(), Vec::new(), String::from("s")),
Err(Error::MissingRelays)
));
}
#[test]
fn nostrconnect_parse_errors() {
let base = |tail: &str| format!("nostrconnect://{PK}?{tail}");
let inputs = [
"not a uri",
"https://x",
"nostrconnect://xyz?secret=s&relay=r",
&base("relay=r"),
&base("secret=&relay=r"),
&base("secret=s"),
];
let checks: [fn(&Error) -> bool; 6] = [
|e| matches!(e, Error::InvalidUri { .. }),
|e| {
matches!(
e,
Error::UnexpectedScheme {
expected: "nostrconnect"
}
)
},
|e| matches!(e, Error::InvalidPublicKey),
|e| matches!(e, Error::MissingSecret),
|e| matches!(e, Error::MissingSecret),
|e| matches!(e, Error::MissingRelays),
];
for (input, check) in inputs.iter().zip(checks) {
let err = input.parse::<NostrConnectUri>().unwrap_err();
assert!(check(&err), "{input}: {err}");
let text = err.to_string();
assert!(
!text.contains("not a uri") && !text.contains("hunter"),
"{input} leaked into the error"
);
}
let err = "not a uri".parse::<NostrConnectUri>().unwrap_err();
assert!(err.source().is_some());
}
#[test]
fn nostrconnect_perms_and_metadata() {
let uri: NostrConnectUri =
format!("nostrconnect://{PK}?relay=r&secret=s&perms=a%2C%2Cb&name=")
.parse()
.unwrap();
assert_eq!(uri.perms(), ["a", "b"]);
assert_eq!(uri.name(), Some(""));
assert_eq!(uri.url(), None);
assert_eq!(uri.image(), None);
let empty: NostrConnectUri = format!("nostrconnect://{PK}?relay=r&secret=s&perms=%2C")
.parse()
.unwrap();
assert_eq!(empty.perms(), Vec::<String>::new());
}
#[test]
fn method_wire_strings() {
let cases = [
(Method::Connect, "connect"),
(Method::GetPublicKey, "get_public_key"),
(Method::SignEvent, "sign_event"),
(Method::Ping, "ping"),
(Method::Nip04Encrypt, "nip04_encrypt"),
(Method::Nip04Decrypt, "nip04_decrypt"),
(Method::Nip44Encrypt, "nip44_encrypt"),
(Method::Nip44Decrypt, "nip44_decrypt"),
(Method::SwitchRelays, "switch_relays"),
(Method::Logout, "logout"),
];
for (method, name) in cases {
assert_eq!(method.as_str(), name);
let json = serde_json::to_string(&method).unwrap();
assert_eq!(json, format!("\"{name}\""));
let decoded: Method = serde_json::from_str(&json).unwrap();
assert_eq!(decoded, method);
}
let decoded: Method = serde_json::from_str("\"weird\"").unwrap();
assert_eq!(decoded, Method::Other(String::from("weird")));
assert_eq!(
serde_json::to_string(&Method::Other(String::from("weird"))).unwrap(),
"\"weird\""
);
}
#[test]
fn request_json_round_trip() {
let request = Request {
id: String::from("1"),
method: Method::SignEvent,
params: vec![String::from("{\"kind\":1}")],
};
let json = request.to_json();
assert_eq!(
json,
r#"{"id":"1","method":"sign_event","params":["{\"kind\":1}"]}"#
);
assert_eq!(Request::from_json(&json).unwrap(), request);
let weird = Request::from_json(r#"{"id":"2","method":"weird","params":[]}"#).unwrap();
assert_eq!(weird.method, Method::Other(String::from("weird")));
}
#[test]
fn request_json_errors() {
let cases = [
"{",
r#"{"id":"\ud800","method":"m","params":[]}"#,
"[]",
r#"{"id":1,"method":"m","params":[]}"#,
r#"{"id":"i","method":"m"}"#,
r#"{"id":"i","method":"m","params":[1]}"#,
];
for input in cases {
let err = Request::from_json(input).unwrap_err();
assert!(matches!(err, Error::InvalidJson { .. }), "{input}");
assert!(err.source().is_some(), "{input}");
}
}
#[test]
fn response_json_round_trip_and_nulls() {
let response = Response::from_json(r#"{"id":"r","result":null,"error":null}"#).unwrap();
assert_eq!(
response,
Response {
id: String::from("r"),
result: None,
error: None,
}
);
assert_eq!(response.to_json(), r#"{"id":"r"}"#);
let err = Response::from_json(r#"{"id":"r","error":"denied"}"#).unwrap();
assert_eq!(err.to_json(), r#"{"id":"r","error":"denied"}"#);
let ok = Response::from_json(r#"{"id":"r","result":"sig"}"#).unwrap();
assert_eq!(ok.to_json(), r#"{"id":"r","result":"sig"}"#);
}
#[test]
fn connect_param_shapes() {
let remote = pubkey();
let bare = Request::connect("a", &remote, None, &[], None);
assert_eq!(bare.method, Method::Connect);
assert_eq!(bare.params, [PK, ""]);
let secret = Request::connect("b", &remote, Some("s3cr3t"), &[], None);
assert_eq!(secret.params, [PK, "s3cr3t"]);
let perms = Request::connect("c", &remote, None, &[String::from("sign_event")], None);
assert_eq!(perms.params, [PK, "", "sign_event"]);
let metadata = ClientMetadata {
name: Some(String::from("My App")),
..ClientMetadata::default()
};
let meta_only = Request::connect("d", &remote, None, &[], Some(&metadata));
assert_eq!(meta_only.params, [PK, "", "", r#"{"name":"My App"}"#]);
let both = Request::connect(
"e",
&remote,
Some("s"),
&[String::from("ping"), String::from("sign_event")],
Some(&metadata),
);
assert_eq!(
both.params,
[PK, "s", "ping,sign_event", r#"{"name":"My App"}"#]
);
}
#[test]
fn sign_event_sends_bare_template() {
let unsigned = UnsignedEvent::new(
pubkey(),
Timestamp::from_secs(1_700_000_000),
Kind::new(1),
Tags::new(),
"hello",
);
let request = Request::sign_event("s1", &unsigned);
assert_eq!(request.method, Method::SignEvent);
assert_eq!(
request.params,
[r#"{"kind":1,"content":"hello","tags":[],"created_at":1700000000}"#]
);
}
#[test]
fn parse_switch_relays_cases() {
assert_eq!(parse_switch_relays("null").unwrap(), None);
assert_eq!(
parse_switch_relays(r#"["wss://a","wss://b"]"#).unwrap(),
Some(vec![String::from("wss://a"), String::from("wss://b")])
);
assert!(matches!(
parse_switch_relays("[]"),
Err(Error::MissingRelays)
));
for bad in ["{", "42", r#""wss://a""#, r#"["wss://a",7]"#, r#"{"a":1}"#] {
assert!(
matches!(parse_switch_relays(bad), Err(Error::InvalidJson { .. })),
"{bad}"
);
}
}
#[test]
fn response_json_errors() {
let cases = [
"{",
r#"{"id":"\udfffr"}"#,
"42",
r#"{"id":1}"#,
r#"{"id":"r","result":{}}"#,
r#"{"id":"r","error":true}"#,
];
for input in cases {
let err = Response::from_json(input).unwrap_err();
assert!(matches!(err, Error::InvalidJson { .. }), "{input}");
assert!(err.source().is_some(), "{input}");
}
}
}