Skip to main content

weirdnet_push/server/
apns.rs

1use crate::error::{Error, Result};
2use crate::wake::Payload96;
3use serde::Deserialize;
4use std::path::PathBuf;
5use std::sync::Mutex;
6use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
7
8/// APNs with token-based (`.p8`) authentication.
9#[derive(Debug, Clone, Deserialize)]
10#[serde(deny_unknown_fields)]
11pub struct ApnsConfig {
12    /// The `.p8` signing key from the Apple developer account.
13    pub key: PathBuf,
14    /// Its key id.
15    pub key_id: String,
16    /// The team id.
17    pub team_id: String,
18    /// Bundle ids this server delivers for.
19    pub topics: Vec<String>,
20    /// Override the production endpoint (tests).
21    #[serde(default)]
22    pub endpoint: Option<String>,
23    /// Override the development endpoint (tests).
24    #[serde(default)]
25    pub sandbox_endpoint: Option<String>,
26}
27
28/// An APNs sender.
29pub struct Apns {
30    config: ApnsConfig,
31    key: jsonwebtoken::EncodingKey,
32    http: reqwest::Client,
33    jwt: Mutex<Option<(String, Instant)>>,
34}
35
36impl std::fmt::Debug for Apns {
37    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
38        f.debug_struct("Apns").field("key_id", &self.config.key_id).field("topics", &self.config.topics).finish()
39    }
40}
41
42#[derive(serde::Serialize)]
43struct Claims<'a> {
44    iss: &'a str,
45    iat: u64,
46}
47
48/// The text shown if the Notification Service Extension can't run; the real alert is made
49/// on the device after decrypting.
50pub const PLACEHOLDER_TITLE: &str = "Weirdnet";
51/// See [`PLACEHOLDER_TITLE`].
52pub const PLACEHOLDER_BODY: &str = "New activity";
53
54impl Apns {
55    /// Loads the key.
56    pub fn new(config: &ApnsConfig) -> Result<Self> {
57        let pem = std::fs::read(&config.key)?;
58        let key = jsonwebtoken::EncodingKey::from_ec_pem(&pem).map_err(|e| Error::Invalid(format!("APNs key: {e}")))?;
59        let plain = |e: &Option<String>| e.as_deref().is_some_and(|u| u.starts_with("http://"));
60        let mut b = reqwest::Client::builder().timeout(Duration::from_secs(20)).pool_idle_timeout(Duration::from_secs(3000));
61        if plain(&config.endpoint) || plain(&config.sandbox_endpoint) {
62            b = b.http2_prior_knowledge(); // h2c for tests
63        }
64        Ok(Self { config: config.clone(), key, http: b.build()?, jwt: Mutex::new(None) })
65    }
66
67    pub(crate) fn allows_topic(&self, t: &str) -> bool {
68        self.config.topics.iter().any(|x| x == t)
69    }
70
71    fn token(&self) -> Result<String> {
72        let mut g = self.jwt.lock().unwrap();
73        // Apple: refresh no more than every 20 minutes, and before an hour.
74        if let Some((t, at)) = &*g
75            && at.elapsed() < Duration::from_secs(40 * 60)
76        {
77            return Ok(t.clone());
78        }
79        let mut h = jsonwebtoken::Header::new(jsonwebtoken::Algorithm::ES256);
80        h.kid = Some(self.config.key_id.clone());
81        let iat = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs();
82        let t = jsonwebtoken::encode(&h, &Claims { iss: &self.config.team_id, iat }, &self.key)
83            .map_err(|e| Error::Delivery(format!("APNs token: {e}")))?;
84        *g = Some((t.clone(), Instant::now()));
85        Ok(t)
86    }
87
88    pub(crate) async fn send(&self, device: &str, topic: &str, sandbox: bool, p: &Payload96) -> Result<()> {
89        let base = if sandbox {
90            self.config.sandbox_endpoint.as_deref().unwrap_or("https://api.sandbox.push.apple.com")
91        } else {
92            self.config.endpoint.as_deref().unwrap_or("https://api.push.apple.com")
93        };
94        let exp = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs() + 3600;
95        let body = serde_json::json!({
96            "aps": { "alert": { "title": PLACEHOLDER_TITLE, "body": PLACEHOLDER_BODY }, "mutable-content": 1 },
97            "wn": p.to_b64(),
98        });
99        let r = self
100            .http
101            .post(format!("{base}/3/device/{device}"))
102            .bearer_auth(self.token()?)
103            .header("apns-topic", topic)
104            .header("apns-push-type", "alert")
105            .header("apns-priority", "10")
106            .header("apns-expiration", exp.to_string())
107            .json(&body)
108            .send()
109            .await
110            .map_err(|e| Error::Delivery(format!("APNs: {e}")))?;
111        let status = r.status().as_u16();
112        if status == 200 {
113            return Ok(());
114        }
115        #[derive(Deserialize)]
116        struct Reason {
117            reason: String,
118        }
119        let reason = r.json::<Reason>().await.map(|r| r.reason).unwrap_or_default();
120        match (status, reason.as_str()) {
121            (410, _) | (400, "BadDeviceToken") | (400, "DeviceTokenNotForTopic") => Err(Error::Gone),
122            _ => Err(Error::Delivery(format!("APNs {status} {reason}"))),
123        }
124    }
125}