use base64::engine::general_purpose::STANDARD as B64;
use base64::Engine;
use nostr::prelude::*;
pub use crate::params::NIP98_KIND;
use crate::params::NIP98_WINDOW_SECS;
pub fn nip98_header(keys: &Keys, url: &str, method: &str) -> Result<String, String> {
let tag = |parts: &[&str]| Tag::parse(parts).map_err(|e| format!("could not build tag: {e}"));
let event = EventBuilder::new(
Kind::from(NIP98_KIND as u16),
"",
vec![tag(&["u", url])?, tag(&["method", method])?],
)
.to_event(keys)
.map_err(|e| format!("could not sign the request: {e}"))?;
Ok(format!("Nostr {}", B64.encode(event.as_json())))
}
pub fn verify_nip98(header: &str, expected_url: &str, method: &str) -> Result<PublicKey, String> {
verify_nip98_at(header, expected_url, method, Timestamp::now().as_u64())
}
pub fn verify_nip98_at(
header: &str,
expected_url: &str,
method: &str,
now: u64,
) -> Result<PublicKey, String> {
let encoded = header
.strip_prefix("Nostr ")
.ok_or("the Authorization header is not a Nostr one")?;
let json = B64
.decode(encoded.trim())
.map_err(|_| "the Authorization header is not valid base64")?;
let json = String::from_utf8(json).map_err(|_| "the Authorization event is not UTF-8")?;
let event = Event::from_json(json).map_err(|_| "the Authorization event is malformed")?;
event
.verify()
.map_err(|_| "the Authorization signature does not verify")?;
if event.kind.as_u64() != NIP98_KIND {
return Err("the Authorization event has the wrong kind".to_string());
}
let first = |key: &str| {
event.tags().iter().find_map(|t| {
let v = t.as_vec();
(v.first().map(String::as_str) == Some(key))
.then(|| v.get(1).cloned())
.flatten()
})
};
if first("u").as_deref() != Some(expected_url) {
return Err("the Authorization event is for a different URL".to_string());
}
if !first("method").is_some_and(|m| m.eq_ignore_ascii_case(method)) {
return Err("the Authorization event is for a different method".to_string());
}
if event.created_at.as_u64().abs_diff(now) > NIP98_WINDOW_SECS {
return Err("the Authorization event is too old or too far ahead".to_string());
}
Ok(event.pubkey)
}
#[cfg(test)]
mod tests {
use super::*;
const URL: &str = "https://api.firm.example/api/federation/verifications";
fn header_at(keys: &Keys, url: &str, method: &str, created_at: u64, kind: u64) -> String {
let tag = |p: &[&str]| Tag::parse(p).unwrap();
let ev = EventBuilder::new(
Kind::from(kind as u16),
"",
vec![tag(&["u", url]), tag(&["method", method])],
)
.custom_created_at(Timestamp::from(created_at))
.to_event(keys)
.unwrap();
format!("Nostr {}", B64.encode(ev.as_json()))
}
#[test]
fn nip98_accepts_a_fresh_matching_header() {
let keys = Keys::generate();
let h = nip98_header(&keys, URL, "GET").unwrap();
assert_eq!(verify_nip98(&h, URL, "GET").unwrap(), keys.public_key());
}
#[test]
fn nip98_rejects_each_mismatch() {
let keys = Keys::generate();
let now = 1_700_000_000u64;
let ok = header_at(&keys, URL, "GET", now, NIP98_KIND);
assert!(verify_nip98_at(&ok, URL, "GET", now + 59).is_ok());
assert!(
verify_nip98_at(&ok, URL, "GET", now + 61).is_err(),
"too old"
);
assert!(
verify_nip98_at(&ok, URL, "GET", now - 61).is_err(),
"too new"
);
assert!(verify_nip98_at(&ok, "https://evil.example/x", "GET", now).is_err());
assert!(verify_nip98_at(&ok, URL, "POST", now).is_err());
let wrong_kind = header_at(&keys, URL, "GET", now, 1);
assert!(verify_nip98_at(&wrong_kind, URL, "GET", now).is_err());
assert!(verify_nip98_at("Bearer abc", URL, "GET", now).is_err());
assert!(verify_nip98_at("Nostr !!!", URL, "GET", now).is_err());
let tampered = format!(
"Nostr {}",
B64.encode(
String::from_utf8(B64.decode(ok.trim_start_matches("Nostr ")).unwrap())
.unwrap()
.replace("GET", "PUT")
)
);
assert!(verify_nip98_at(&tampered, URL, "PUT", now).is_err());
}
}