1use nostr::nips::nip44::{self, Version};
5use nostr::prelude::*;
6use serde::{Deserialize, Serialize};
7
8use crate::{Error, Result};
9
10pub const KIND: u16 = 24590;
12
13#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
14pub struct Request {
15 pub v: u8,
16 pub s: String,
18 pub b: String,
20 pub t: u32,
22}
23
24impl Request {
25 pub fn new(sealed: &str, body: &[u8], ttl: u32) -> Self {
26 Request { v: 1, s: sealed.to_string(), b: crate::b64url(body), t: ttl }
27 }
28
29 pub fn body(&self) -> Result<Vec<u8>> {
30 crate::unb64url(&self.b)
31 }
32
33 pub fn event(&self, pusher: &PublicKey) -> Result<Event> {
34 let json = serde_json::to_string(self).map_err(|e| Error::Format(e.to_string()))?;
35 seal_event(pusher, &json)
36 }
37
38 pub fn open(pusher: &Keys, event: &Event) -> Result<Self> {
39 if event.kind != Kind::Custom(KIND) {
40 return Err(Error::Format("not a push request".into()));
41 }
42 let json = nip44::decrypt(pusher.secret_key(), &event.pubkey, &event.content)
43 .map_err(|_| Error::Crypto("request decryption failed"))?;
44 let req: Request = serde_json::from_str(&json).map_err(|e| Error::Format(e.to_string()))?;
45 if req.v != 1 {
46 return Err(Error::Format(format!("request version {}", req.v)));
47 }
48 Ok(req)
49 }
50}
51
52#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
55pub struct Control {
56 pub v: u8,
57 pub ctl: Vec<Hold>,
58 #[serde(default, skip_serializing_if = "String::is_empty")]
60 pub p: String,
61}
62
63#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
64pub struct Hold {
65 pub c: String,
67 pub until: u64,
69}
70
71pub const HOLD_FOREVER: u64 = u64::MAX;
72
73const MESSAGE_PLAINTEXT: usize = 5600;
75
76impl Control {
77 pub fn new(ctl: Vec<Hold>) -> Self {
78 Control { v: 1, ctl, p: String::new() }
79 }
80
81 pub fn event(&self, pusher: &PublicKey) -> Result<Event> {
82 let mut padded = self.clone();
83 let len = serde_json::to_string(&padded).map_err(|e| Error::Format(e.to_string()))?.len();
84 if len + 8 < MESSAGE_PLAINTEXT {
85 padded.p = "0".repeat(MESSAGE_PLAINTEXT - len - 8);
86 }
87 seal_event(pusher, &serde_json::to_string(&padded).map_err(|e| Error::Format(e.to_string()))?)
88 }
89}
90
91#[derive(Debug, Clone, PartialEq, Eq)]
93pub enum Incoming {
94 Push(Request),
95 Control(Control),
96}
97
98impl Incoming {
99 pub fn open(pusher: &Keys, event: &Event) -> Result<Self> {
100 if event.kind != Kind::Custom(KIND) {
101 return Err(Error::Format("not a push request".into()));
102 }
103 let json = nip44::decrypt(pusher.secret_key(), &event.pubkey, &event.content)
104 .map_err(|_| Error::Crypto("request decryption failed"))?;
105 let value: serde_json::Value = serde_json::from_str(&json).map_err(|e| Error::Format(e.to_string()))?;
106 if value.get("v").and_then(|v| v.as_u64()) != Some(1) {
107 return Err(Error::Format("unknown message version".into()));
108 }
109 if value.get("ctl").is_some() {
110 return serde_json::from_value(value).map(Incoming::Control).map_err(|e| Error::Format(e.to_string()));
111 }
112 serde_json::from_value(value).map(Incoming::Push).map_err(|e| Error::Format(e.to_string()))
113 }
114}
115
116fn seal_event(pusher: &PublicKey, json: &str) -> Result<Event> {
117 let keys = Keys::generate();
118 let content = nip44::encrypt(keys.secret_key(), pusher, json, Version::V2)
119 .map_err(|_| Error::Crypto("request encryption failed"))?;
120 EventBuilder::new(Kind::Custom(KIND), content)
121 .tag(Tag::public_key(*pusher))
122 .finalize(&keys)
123 .map_err(|e| Error::Format(e.to_string()))
124}
125
126#[cfg(test)]
127mod tests {
128 use super::*;
129
130 #[test]
131 fn a_request_round_trips_and_names_nobody() {
132 let pusher = Keys::generate();
133 let req = Request::new("sealed", &[7; 3000], 86_400);
134 let ev = req.event(&pusher.public_key()).unwrap();
135 ev.verify().unwrap();
136 assert_eq!(ev.tags.len(), 1);
137 assert_eq!(Request::open(&pusher, &ev).unwrap(), req);
138 assert_ne!(ev.pubkey, req.event(&pusher.public_key()).unwrap().pubkey);
139 assert!(Request::open(&Keys::generate(), &ev).is_err());
140 }
141
142 #[test]
143 fn a_control_looks_like_a_push_to_the_relay() {
144 let pusher = Keys::generate();
145 let sealed = crate::ticket::seal(&pusher.public_key(), &crate::Capability { endpoint: "https://web.push.apple.com/x".into(), vapid: "k".repeat(43), cap: "c".repeat(32) }).unwrap();
146 let push = Request::new(&sealed, &[7; crate::webpush::BODY_LEN], 172_800).event(&pusher.public_key()).unwrap();
147 let ctl = Control::new(vec![Hold { c: "ab".repeat(16), until: HOLD_FOREVER }, Hold { c: "cd".repeat(16), until: 0 }]);
148 let ev = ctl.event(&pusher.public_key()).unwrap();
149 assert_eq!(ev.content.len(), push.content.len(), "same NIP-44 bucket");
150 match Incoming::open(&pusher, &ev).unwrap() {
151 Incoming::Control(c) => assert_eq!(c.ctl, ctl.ctl),
152 other => panic!("{other:?}"),
153 }
154 assert!(matches!(Incoming::open(&pusher, &push).unwrap(), Incoming::Push(_)));
155 }
156}