1use nostr::nips::nip44::{self, Version};
9use nostr::prelude::{Keys, PublicKey, SecretKey};
10use serde::{Deserialize, Serialize};
11
12use crate::{Error, Result};
13
14#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
15pub struct Ticket {
16 pub id: String,
18 pub pusher: String,
20 pub relays: Vec<String>,
21 pub sealed: String,
22 pub p256dh: String,
24 pub auth: String,
25 pub origin: String,
27 pub h: String,
29 pub mk: String,
30}
31
32impl Ticket {
33 pub fn validate(&self) -> Result<()> {
35 PublicKey::from_hex(&self.pusher).map_err(|_| Error::Key("bad pusher key"))?;
36 if self.relays.is_empty() || self.relays.iter().any(|r| !r.starts_with("wss://") && !r.starts_with("ws://")) {
37 return Err(Error::Format("bad pusher relays".into()));
38 }
39 if crate::unb64url(&self.p256dh)?.len() != 65 || crate::unb64url(&self.auth)?.len() != 16 {
40 return Err(Error::Key("bad subscription keys"));
41 }
42 if crate::unhex(&self.mk)?.len() != 32 || crate::unhex(&self.h)?.len() != 8 {
43 return Err(Error::Key("bad contact keys"));
44 }
45 if !self.origin.starts_with("https://") && !self.origin.starts_with("http://localhost") && !self.origin.starts_with("http://127.0.0.1") {
46 return Err(Error::Format("bad origin".into()));
47 }
48 if self.id.is_empty() || self.id.len() > 64 || self.sealed.len() > 4096 {
49 return Err(Error::Format("bad ticket".into()));
50 }
51 Ok(())
52 }
53
54 pub fn request(&self, notice: &crate::Notice, ttl: u32) -> Result<nostr::prelude::Event> {
57 let notice = crate::Notice { h: self.h.clone(), ..notice.clone() };
58 let plain = notice.message(&self.origin, &self.mk)?;
59 let body = crate::webpush::encrypt(&crate::unb64url(&self.p256dh)?, &crate::unb64url(&self.auth)?, &plain)?;
60 let pusher = PublicKey::from_hex(&self.pusher).map_err(|_| Error::Key("bad pusher key"))?;
61 crate::Request::new(&self.sealed, &body, ttl).event(&pusher)
62 }
63}
64
65#[derive(Debug, Clone, Default, Serialize, Deserialize)]
67pub struct TicketList {
68 pub v: u8,
69 #[serde(default)]
70 pub tickets: Vec<Ticket>,
71 #[serde(default)]
73 pub revoked: Vec<String>,
74}
75
76#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
78pub struct Capability {
79 #[serde(rename = "e")]
80 pub endpoint: String,
81 #[serde(rename = "k")]
83 pub vapid: String,
84 #[serde(rename = "c")]
86 pub cap: String,
87}
88
89const SEALED_PLAINTEXT: usize = 1000;
92
93pub fn seal(pusher: &PublicKey, cap: &Capability) -> Result<String> {
94 let mut json = serde_json::to_value(cap).map_err(|e| Error::Format(e.to_string()))?;
95 let len = json.to_string().len();
96 if len + 7 < SEALED_PLAINTEXT {
98 json["p"] = serde_json::Value::String("0".repeat(SEALED_PLAINTEXT - len - 7));
99 }
100 let eph = Keys::generate();
101 let ct = nip44::encrypt(eph.secret_key(), pusher, json.to_string(), Version::V2)
102 .map_err(|_| Error::Crypto("seal failed"))?;
103 Ok(format!("{}:{ct}", eph.public_key().to_hex()))
104}
105
106pub fn unseal(pusher: &SecretKey, sealed: &str) -> Result<Capability> {
107 let (eph, ct) = sealed.split_once(':').ok_or(Error::Format("bad sealed capability".into()))?;
108 let eph = PublicKey::from_hex(eph).map_err(|_| Error::Key("bad sealing key"))?;
109 let plain = nip44::decrypt(pusher, &eph, ct).map_err(|_| Error::Crypto("unseal failed"))?;
110 serde_json::from_str(&plain).map_err(|e| Error::Format(e.to_string()))
111}
112
113#[cfg(test)]
114mod tests {
115 use super::*;
116
117 #[test]
118 fn only_the_pusher_opens_a_seal_and_every_seal_is_the_same_size() {
119 let pusher = Keys::generate();
120 let short = Capability { endpoint: "https://web.push.apple.com/abc".into(), vapid: "k".into(), cap: "c".into() };
121 let long = Capability { endpoint: format!("https://fcm.googleapis.com/fcm/send/{}", "x".repeat(400)), ..short.clone() };
122 let a = seal(&pusher.public_key(), &short).unwrap();
123 let b = seal(&pusher.public_key(), &long).unwrap();
124 assert_eq!(a.len(), b.len());
125 assert_eq!(unseal(pusher.secret_key(), &a).unwrap(), short);
126 assert_eq!(unseal(pusher.secret_key(), &b).unwrap(), long);
127 assert!(unseal(Keys::generate().secret_key(), &a).is_err());
128 assert_ne!(a, seal(&pusher.public_key(), &short).unwrap());
130 }
131
132 #[test]
133 fn a_ticket_carries_a_notice_only_the_device_reads() {
134 use p256::elliptic_curve::sec1::ToEncodedPoint;
135 let pusher = Keys::generate();
136 let device = p256::SecretKey::random(&mut rand::rngs::OsRng);
137 let auth = crate::random::<16>();
138 let vapid = crate::b64url(&crate::random::<32>());
139 let cap = Capability { endpoint: "https://web.push.apple.com/abc".into(), vapid, cap: "c1".into() };
140 let t = Ticket {
141 id: "dev".into(),
142 pusher: pusher.public_key().to_hex(),
143 relays: vec!["wss://relay.example".into()],
144 sealed: seal(&pusher.public_key(), &cap).unwrap(),
145 p256dh: crate::b64url(device.public_key().to_encoded_point(false).as_bytes()),
146 auth: crate::b64url(&auth),
147 origin: "https://web.vectorapp.io".into(),
148 h: crate::hex(&[1; 8]),
149 mk: crate::hex(&[2; 32]),
150 };
151 t.validate().unwrap();
152 let notice = crate::Notice { h: String::new(), kind: "dm".into(), msg: "m".into(), ts: 5, text: "hi".into() };
153 let ev = t.request(¬ice, 60).unwrap();
154 let req = crate::Request::open(&pusher, &ev).unwrap();
155 assert_eq!(unseal(pusher.secret_key(), &req.s).unwrap(), cap);
156 let plain = crate::webpush::decrypt(&device, &auth, &req.body().unwrap()).unwrap();
157 let v: serde_json::Value = serde_json::from_slice(&plain).unwrap();
158 let data = &v["notification"]["data"];
159 assert_eq!(data["x"], "hi");
160 assert_eq!(data["h"], t.h);
161 let signed = crate::Notice { h: t.h.clone(), ..notice };
162 assert_eq!(data["a"], signed.mac(&[2; 32]).unwrap());
163 }
164}
165