bark-apns 0.1.0

Direct APNs client for sending Bark notifications.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
use std::{
    collections::{BTreeMap, BTreeSet},
    sync::Mutex,
    time::{Duration, SystemTime, UNIX_EPOCH},
};

use jsonwebtoken::{Algorithm, EncodingKey, Header, encode};
use reqwest::{
    StatusCode,
    header::{AUTHORIZATION, HeaderMap, HeaderValue},
};
use serde::{Deserialize, Serialize};

use crate::{
    error::{Error, Result},
    message::Message,
};

const TOKEN_REFRESH_AFTER: u64 = 45 * 60;
const DEFAULT_TEAM_ID: &str = "5U8LBRXG3A";
const DEFAULT_AUTH_KEY_ID: &str = "LH4T9V5U4R";
const DEFAULT_TOPIC: &str = "me.fin.bark";
const DEFAULT_PRIVATE_KEY: &str = "-----BEGIN PRIVATE KEY-----\n\
MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQg4vtC3g5L5HgKGJ2+\n\
T1eA0tOivREvEAY2g+juRXJkYL2gCgYIKoZIzj0DAQehRANCAASmOs3JkSyoGEWZ\n\
sUGxFs/4pw1rIlSV2IC19M8u3G5kq36upOwyFWj9Gi3Ejc9d3sC7+SHRqXrEAJow\n\
8/7tRpV+\n\
-----END PRIVATE KEY-----\n";

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum Environment {
    Production,
    Sandbox,
}

impl Environment {
    pub const fn host(self) -> &'static str {
        match self {
            Self::Production => "api.push.apple.com",
            Self::Sandbox => "api.sandbox.push.apple.com",
        }
    }
}

#[derive(Clone)]
struct Credentials {
    team_id: String,
    auth_key_id: String,
    topic: String,
    encoding_key: EncodingKey,
}

impl Credentials {
    fn new<T, K, O, P>(team_id: T, auth_key_id: K, topic: O, private_key_pem: P) -> Result<Self>
    where
        T: Into<String>,
        K: Into<String>,
        O: Into<String>,
        P: Into<String>,
    {
        let private_key_pem = private_key_pem.into();
        let encoding_key = EncodingKey::from_ec_pem(private_key_pem.as_bytes())?;

        Ok(Self {
            team_id: team_id.into(),
            auth_key_id: auth_key_id.into(),
            topic: topic.into(),
            encoding_key,
        })
    }

    fn team_id(&self) -> &str {
        &self.team_id
    }

    fn auth_key_id(&self) -> &str {
        &self.auth_key_id
    }

    fn topic(&self) -> &str {
        &self.topic
    }

    fn token(&self, issued_at: u64) -> Result<String> {
        let mut header = Header::new(Algorithm::ES256);
        header.kid = Some(self.auth_key_id.clone());

        let claims = ApnsClaims {
            iss: &self.team_id,
            iat: issued_at,
        };

        Ok(encode(&header, &claims, &self.encoding_key)?)
    }
}

/// Direct APNs client for Bark notifications.
///
/// `Bark` signs APNs provider tokens with Bark's default credentials by default
/// and sends serialized [`Message`] payloads to iOS device tokens. It talks to
/// APNs directly; no Bark server is contacted.
///
/// Device tokens are normalized before sending: surrounding angle brackets and
/// ASCII whitespace are removed, and duplicate tokens are sent once.
///
/// [`Message`]: crate::Message
pub struct Bark {
    credentials: Credentials,
    environment: Environment,
    async_http: reqwest::Client,
    blocking_http: reqwest::blocking::Client,
    token: Mutex<Option<CachedToken>>,
}

impl Bark {
    /// Creates a client using Bark's default APNs team id, key id, topic, and
    /// private key.
    ///
    /// This matches the public Bark app topic `me.fin.bark`.
    ///
    /// # Errors
    ///
    /// Returns an error if the built-in APNs key cannot be parsed or the HTTP
    /// clients cannot be constructed.
    pub fn new() -> Result<Self> {
        Self::with_credentials(
            DEFAULT_TEAM_ID,
            DEFAULT_AUTH_KEY_ID,
            DEFAULT_TOPIC,
            DEFAULT_PRIVATE_KEY,
        )
    }

    /// Creates a client with custom APNs credentials.
    ///
    /// Use this for a forked Bark app or a private APNs topic. The private key
    /// must be an APNs Auth Key in PEM format for ES256 signing.
    ///
    /// # Errors
    ///
    /// Returns an error if the private key cannot be parsed or the HTTP clients
    /// cannot be constructed.
    pub fn with_credentials<T, K, O, P>(
        team_id: T,
        auth_key_id: K,
        topic: O,
        private_key_pem: P,
    ) -> Result<Self>
    where
        T: Into<String>,
        K: Into<String>,
        O: Into<String>,
        P: Into<String>,
    {
        let credentials = Credentials::new(team_id, auth_key_id, topic, private_key_pem)?;
        Ok(Self {
            credentials,
            environment: Environment::Production,
            async_http: reqwest::ClientBuilder::new()
                .http2_adaptive_window(true)
                .build()
                .map_err(Error::HttpClient)?,
            blocking_http: reqwest::blocking::ClientBuilder::new()
                .http2_adaptive_window(true)
                .build()
                .map_err(Error::HttpClient)?,
            token: Mutex::new(None),
        })
    }

    /// Selects APNs production.
    ///
    /// This is the default and sends to `api.push.apple.com`.
    pub fn production(mut self) -> Self {
        self.environment = Environment::Production;
        self
    }

    /// Selects APNs sandbox.
    ///
    /// This sends to `api.sandbox.push.apple.com`, useful for development builds
    /// whose device tokens belong to the sandbox environment.
    pub fn sandbox(mut self) -> Self {
        self.environment = Environment::Sandbox;
        self
    }

    /// Returns the APNs team id used for provider-token signing.
    pub fn team_id(&self) -> &str {
        self.credentials.team_id()
    }

    /// Returns the APNs auth key id used in the JWT header.
    pub fn auth_key_id(&self) -> &str {
        self.credentials.auth_key_id()
    }

    /// Returns the APNs topic, normally Bark's bundle id.
    pub fn topic(&self) -> &str {
        self.credentials.topic()
    }

    /// Sends a message synchronously to one or more device tokens.
    ///
    /// The same serialized APNs payload is sent to each unique normalized token.
    /// For delete messages this method uses APNs `background` push type and
    /// priority `5`; otherwise it uses `alert` push type and priority `10`.
    ///
    /// # Errors
    ///
    /// Returns [`Error::ApnsFailures`] if any device fails. The error message
    /// includes the normalized device token and reason for each failed device.
    /// Validation, serialization, encryption, token-signing, and HTTP client
    /// errors are returned directly.
    ///
    /// [`Error::ApnsFailures`]: crate::Error::ApnsFailures
    pub fn send<I, D>(&self, message: &Message, devices: I) -> Result<()>
    where
        I: IntoIterator<Item = D>,
        D: Into<String>,
    {
        let body = message.payload_bytes()?;
        let headers = self.headers(message)?;
        let devices = collect_devices(devices);
        let mut failures = BTreeMap::new();

        for device in devices {
            let response = self
                .blocking_http
                .post(self.device_url(&device))
                .headers(headers.clone())
                .body(body.clone())
                .send();

            match response {
                Ok(response) => {
                    if !response.status().is_success() {
                        let status = response.status();
                        let reason = blocking_apns_reason(response);
                        failures.insert(device, format!("{status}: {reason}"));
                    }
                }
                Err(error) => {
                    failures.insert(device, error.to_string());
                }
            }
        }

        if failures.is_empty() {
            Ok(())
        } else {
            Err(Error::ApnsFailures(format_apns_failures(&failures)))
        }
    }

    /// Sends a message asynchronously to one or more device tokens.
    ///
    /// This has the same payload and error semantics as [`Bark::send`], but uses
    /// the asynchronous `reqwest` client.
    ///
    /// # Errors
    ///
    /// Returns [`Error::ApnsFailures`] if any device fails. The error message
    /// includes the normalized device token and reason for each failed device.
    /// Validation, serialization, encryption, token-signing, and HTTP client
    /// errors are returned directly.
    ///
    /// [`Error::ApnsFailures`]: crate::Error::ApnsFailures
    pub async fn send_async<I, D>(&self, message: &Message, devices: I) -> Result<()>
    where
        I: IntoIterator<Item = D>,
        D: Into<String>,
    {
        let body = message.payload_bytes()?;
        let headers = self.headers(message)?;
        let devices = collect_devices(devices);
        let mut failures = BTreeMap::new();

        for device in devices {
            let response = self
                .async_http
                .post(self.device_url(&device))
                .headers(headers.clone())
                .body(body.clone())
                .send()
                .await;

            match response {
                Ok(response) => {
                    if !response.status().is_success() {
                        let status = response.status();
                        let reason = async_apns_reason(response).await;
                        failures.insert(device, format!("{status}: {reason}"));
                    }
                }
                Err(error) => {
                    failures.insert(device, error.to_string());
                }
            }
        }

        if failures.is_empty() {
            Ok(())
        } else {
            Err(Error::ApnsFailures(format_apns_failures(&failures)))
        }
    }

    fn headers(&self, message: &Message) -> Result<HeaderMap> {
        message.validate_headers()?;

        let mut headers = HeaderMap::new();
        let authorization = format!("bearer {}", self.apns_token()?);
        headers.insert(
            AUTHORIZATION,
            HeaderValue::from_str(&authorization).map_err(|source| Error::InvalidHeaderValue {
                name: "authorization",
                source,
            })?,
        );
        headers.insert(
            "apns-topic",
            HeaderValue::from_str(self.credentials.topic()).map_err(|source| {
                Error::InvalidHeaderValue {
                    name: "apns-topic",
                    source,
                }
            })?,
        );
        headers.insert(
            "apns-push-type",
            HeaderValue::from_static(if message.is_delete() {
                "background"
            } else {
                "alert"
            }),
        );
        headers.insert(
            "apns-priority",
            HeaderValue::from_static(if message.is_delete() { "5" } else { "10" }),
        );

        if let Some(id) = message.id_value() {
            headers.insert(
                "apns-collapse-id",
                HeaderValue::from_str(id).map_err(|source| Error::InvalidHeaderValue {
                    name: "apns-collapse-id",
                    source,
                })?,
            );
        }

        Ok(headers)
    }

    fn apns_token(&self) -> Result<String> {
        let now = unix_timestamp();
        let mut cached = self.token.lock().expect("APNs token cache poisoned");

        if let Some(cached) = cached.as_ref()
            && cached.issued_at + TOKEN_REFRESH_AFTER > now
        {
            return Ok(cached.value.clone());
        }

        let value = self.credentials.token(now)?;
        *cached = Some(CachedToken {
            issued_at: now,
            value: value.clone(),
        });
        Ok(value)
    }

    fn device_url(&self, device: &str) -> String {
        format!("https://{}/3/device/{device}", self.environment.host())
    }
}

#[derive(Clone, Debug)]
struct CachedToken {
    issued_at: u64,
    value: String,
}

#[derive(Debug, Serialize)]
struct ApnsClaims<'a> {
    iss: &'a str,
    iat: u64,
}

#[derive(Debug, Deserialize)]
struct ApnsErrorBody {
    reason: Option<String>,
}

fn collect_devices<I, D>(devices: I) -> Vec<String>
where
    I: IntoIterator<Item = D>,
    D: Into<String>,
{
    devices
        .into_iter()
        .filter_map(|device| {
            let normalized = normalize_device_token(device.into());
            (!normalized.is_empty()).then_some(normalized)
        })
        .collect::<BTreeSet<_>>()
        .into_iter()
        .collect()
}

fn normalize_device_token(device: String) -> String {
    device
        .trim()
        .trim_start_matches('<')
        .trim_end_matches('>')
        .chars()
        .filter(|ch| !ch.is_ascii_whitespace())
        .collect()
}

async fn async_apns_reason(response: reqwest::Response) -> String {
    let status = response.status();
    match response.text().await {
        Ok(text) => apns_reason_from_text(status, &text),
        Err(error) => error.to_string(),
    }
}

fn blocking_apns_reason(response: reqwest::blocking::Response) -> String {
    let status = response.status();
    match response.text() {
        Ok(text) => apns_reason_from_text(status, &text),
        Err(error) => error.to_string(),
    }
}

fn apns_reason_from_text(status: StatusCode, text: &str) -> String {
    if text.trim().is_empty() {
        return status.to_string();
    }

    serde_json::from_str::<ApnsErrorBody>(text)
        .ok()
        .and_then(|body| body.reason)
        .unwrap_or_else(|| text.to_owned())
}

fn format_apns_failures(failures: &BTreeMap<String, String>) -> String {
    failures
        .iter()
        .map(|(device, reason)| format!("{device}: {reason}"))
        .collect::<Vec<_>>()
        .join("; ")
}

fn unix_timestamp() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_else(|_| Duration::from_secs(0))
        .as_secs()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn credentials_accept_str_and_string() {
        let credentials = Credentials::new(
            String::from(DEFAULT_TEAM_ID),
            DEFAULT_AUTH_KEY_ID,
            DEFAULT_TOPIC,
            DEFAULT_PRIVATE_KEY,
        )
        .unwrap();

        assert_eq!(credentials.team_id(), DEFAULT_TEAM_ID);
        assert_eq!(credentials.auth_key_id(), DEFAULT_AUTH_KEY_ID);
        assert_eq!(credentials.topic(), DEFAULT_TOPIC);
    }

    #[test]
    fn device_tokens_are_normalized_and_deduped() {
        let devices = collect_devices(["<aa bb>", "aabb", "  ", "cc"]);

        assert_eq!(devices, vec!["aabb", "cc"]);
    }
}