sendly 3.30.0

Official Rust SDK for the Sendly SMS API
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
//! Sendly Webhook Helpers
//!
//! Utilities for verifying and parsing webhook events from Sendly.
//!
//! # Example
//!
//! ```rust
//! use sendly::webhooks::{Webhooks, WebhookEvent};
//!
//! // In your webhook handler (e.g., Actix-web)
//! async fn handle_webhook(
//!     body: String,
//!     signature: &str,
//!     timestamp: &str,
//! ) -> Result<WebhookEvent, &'static str> {
//!     let secret = std::env::var("WEBHOOK_SECRET").unwrap();
//!
//!     match Webhooks::parse_event(&body, signature, &secret, Some(timestamp)) {
//!         Ok(event) => {
//!             println!("Received event: {:?}", event.event_type);
//!             Ok(event)
//!         }
//!         Err(_) => Err("Invalid signature"),
//!     }
//! }
//! ```

use hmac::{Hmac, Mac};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use sha2::Sha256;
use std::time::{SystemTime, UNIX_EPOCH};
use thiserror::Error;

type HmacSha256 = Hmac<Sha256>;

const SIGNATURE_TOLERANCE_SECONDS: u64 = 300;

/// Webhook event types
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum WebhookEventType {
    #[serde(rename = "message.queued")]
    MessageQueued,
    #[serde(rename = "message.sent")]
    MessageSent,
    #[serde(rename = "message.delivered")]
    MessageDelivered,
    #[serde(rename = "message.failed")]
    MessageFailed,
    #[serde(rename = "message.bounced")]
    MessageBounced,
    #[serde(rename = "message.retrying")]
    MessageRetrying,
    #[serde(rename = "message.received")]
    MessageReceived,
    #[serde(rename = "message.opt_out")]
    MessageOptOut,
    #[serde(rename = "message.opt_in")]
    MessageOptIn,
    #[serde(rename = "message.undelivered")]
    MessageUndelivered,
    #[serde(rename = "verification.created")]
    VerificationCreated,
    #[serde(rename = "verification.delivered")]
    VerificationDelivered,
    #[serde(rename = "verification.verified")]
    VerificationVerified,
    #[serde(rename = "verification.expired")]
    VerificationExpired,
    #[serde(rename = "verification.failed")]
    VerificationFailed,
    #[serde(rename = "verification.resent")]
    VerificationResent,
    #[serde(rename = "verification.delivery_failed")]
    VerificationDeliveryFailed,
    #[serde(rename = "contact.auto_flagged")]
    ContactAutoFlagged,
    #[serde(rename = "contact.marked_valid")]
    ContactMarkedValid,
    #[serde(rename = "contacts.lookup_completed")]
    ContactsLookupCompleted,
    #[serde(rename = "contacts.bulk_marked_valid")]
    ContactsBulkMarkedValid,
}

/// Source of a list-health event. Frozen enum — new values will be
/// added in minor SDK versions, never removed.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum ListHealthEventSource {
    #[serde(rename = "send_failure")]
    SendFailure,
    #[serde(rename = "carrier_lookup")]
    CarrierLookup,
    #[serde(rename = "user_action")]
    UserAction,
    #[serde(rename = "bulk_mark_valid")]
    BulkMarkValid,
}

/// Message status in webhook events
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum WebhookMessageStatus {
    Queued,
    Sent,
    Delivered,
    Failed,
    Bounced,
    Retrying,
    Received,
    Undelivered,
}

/// Data payload for message webhook events
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WebhookMessageData {
    /// The message ID
    pub id: String,
    /// Current message status
    pub status: WebhookMessageStatus,
    /// Recipient phone number
    pub to: String,
    /// Sender ID or phone number
    pub from: String,
    /// Message direction
    #[serde(default = "default_direction")]
    pub direction: String,
    /// Organization ID
    #[serde(skip_serializing_if = "Option::is_none")]
    pub organization_id: Option<String>,
    /// Message text
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,
    /// Error message if status is 'failed' or 'undelivered'
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    /// Error code if available
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error_code: Option<String>,
    /// When the message was delivered
    #[serde(skip_serializing_if = "Option::is_none")]
    pub delivered_at: Option<Value>,
    /// When the message failed
    #[serde(skip_serializing_if = "Option::is_none")]
    pub failed_at: Option<Value>,
    /// When the message was created
    #[serde(skip_serializing_if = "Option::is_none")]
    pub created_at: Option<Value>,
    /// Number of SMS segments
    #[serde(default = "default_segments")]
    pub segments: i32,
    /// Credits charged
    #[serde(default)]
    pub credits_used: i32,
    /// Message format (sms or mms)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message_format: Option<String>,
    /// Media URLs for MMS
    #[serde(skip_serializing_if = "Option::is_none")]
    pub media_urls: Option<Vec<String>>,
    #[serde(default)]
    pub retry_count: Option<i32>,
    #[serde(default)]
    pub metadata: Option<serde_json::Map<String, serde_json::Value>>,
    /// Batch ID if message was sent as part of a batch.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub batch_id: Option<String>,
}

impl WebhookMessageData {
    /// Backwards-compatible alias for id
    pub fn message_id(&self) -> &str {
        &self.id
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WebhookVerificationData {
    pub id: String,
    #[serde(default)]
    pub organization_id: Option<String>,
    pub phone: String,
    pub status: String,
    #[serde(default = "default_delivery_status")]
    pub delivery_status: String,
    #[serde(default)]
    pub attempts: i32,
    #[serde(default = "default_max_attempts")]
    pub max_attempts: i32,
    #[serde(default)]
    pub expires_at: Option<serde_json::Value>,
    #[serde(default)]
    pub verified_at: Option<serde_json::Value>,
    #[serde(default)]
    pub created_at: Option<serde_json::Value>,
    #[serde(default)]
    pub app_name: Option<String>,
    #[serde(default)]
    pub template_id: Option<String>,
    #[serde(default)]
    pub profile_id: Option<String>,
    #[serde(default)]
    pub metadata: Option<serde_json::Map<String, serde_json::Value>>,
}

fn default_delivery_status() -> String {
    "queued".to_string()
}

fn default_max_attempts() -> i32 {
    3
}

fn default_direction() -> String {
    "outbound".to_string()
}

fn default_segments() -> i32 {
    1
}

/// Webhook event from Sendly
#[derive(Debug, Clone, Serialize)]
pub struct WebhookEvent {
    /// Unique event ID
    pub id: String,
    /// Event type
    #[serde(rename = "type")]
    pub event_type: WebhookEventType,
    /// Event data
    #[serde(skip_serializing)]
    pub data: WebhookMessageData,
    /// When the event was created (unix timestamp)
    #[serde(default)]
    pub created: Value,
    /// API version
    #[serde(default = "default_api_version")]
    pub api_version: String,
    /// Whether this is a live (production) event
    #[serde(default)]
    pub livemode: bool,
}

fn default_api_version() -> String {
    "2024-01".to_string()
}

/// Error type for webhook signature verification failures
#[derive(Error, Debug)]
pub enum WebhookError {
    #[error("Invalid webhook signature")]
    InvalidSignature,
    #[error("Failed to parse webhook payload: {0}")]
    ParseError(String),
    #[error("Invalid event structure")]
    InvalidStructure,
}

/// Webhook utilities for verifying and parsing Sendly webhook events
pub struct Webhooks;

impl Webhooks {
    /// Verify webhook signature from Sendly.
    /// Pass `None` for timestamp to skip timestamp verification (backwards compat).
    pub fn verify_signature(
        payload: &str,
        signature: &str,
        secret: &str,
        timestamp: Option<&str>,
    ) -> bool {
        if payload.is_empty() || signature.is_empty() || secret.is_empty() {
            return false;
        }

        let signed_payload = match timestamp {
            Some(ts) if !ts.is_empty() => {
                if let Ok(ts_val) = ts.parse::<u64>() {
                    let now = SystemTime::now()
                        .duration_since(UNIX_EPOCH)
                        .unwrap_or_default()
                        .as_secs();
                    if now.abs_diff(ts_val) > SIGNATURE_TOLERANCE_SECONDS {
                        return false;
                    }
                }
                format!("{}.{}", ts, payload)
            }
            _ => payload.to_string(),
        };

        let mut mac = match HmacSha256::new_from_slice(secret.as_bytes()) {
            Ok(mac) => mac,
            Err(_) => return false,
        };

        mac.update(signed_payload.as_bytes());
        let result = mac.finalize();
        let expected = format!("sha256={}", hex::encode(result.into_bytes()));

        constant_time_compare(signature, &expected)
    }

    /// Parse and validate a webhook event.
    /// Pass `None` for timestamp to skip timestamp verification.
    pub fn parse_event(
        payload: &str,
        signature: &str,
        secret: &str,
        timestamp: Option<&str>,
    ) -> Result<WebhookEvent, WebhookError> {
        if !Self::verify_signature(payload, signature, secret, timestamp) {
            return Err(WebhookError::InvalidSignature);
        }

        let raw: Value =
            serde_json::from_str(payload).map_err(|e| WebhookError::ParseError(e.to_string()))?;

        let id = raw["id"]
            .as_str()
            .ok_or(WebhookError::InvalidStructure)?
            .to_string();
        let event_type: WebhookEventType = serde_json::from_value(raw["type"].clone())
            .map_err(|e| WebhookError::ParseError(e.to_string()))?;

        let data_val = &raw["data"];
        let obj_val = if data_val["object"].is_object() {
            &data_val["object"]
        } else {
            data_val
        };

        let mut msg_data: WebhookMessageData = serde_json::from_value(obj_val.clone())
            .map_err(|e| WebhookError::ParseError(e.to_string()))?;

        if msg_data.id.is_empty() {
            if let Some(mid) = obj_val["message_id"].as_str() {
                msg_data.id = mid.to_string();
            }
        }

        let created = if !raw["created"].is_null() {
            raw["created"].clone()
        } else {
            raw["created_at"].clone()
        };

        Ok(WebhookEvent {
            id,
            event_type,
            data: msg_data,
            created,
            api_version: raw["api_version"]
                .as_str()
                .unwrap_or("2024-01")
                .to_string(),
            livemode: raw["livemode"].as_bool().unwrap_or(false),
        })
    }

    /// Generate a webhook signature for testing purposes.
    /// Pass `None` for timestamp to skip timestamp in signature.
    pub fn generate_signature(payload: &str, secret: &str, timestamp: Option<&str>) -> String {
        let signed_payload = match timestamp {
            Some(ts) if !ts.is_empty() => format!("{}.{}", ts, payload),
            _ => payload.to_string(),
        };

        let mut mac =
            HmacSha256::new_from_slice(secret.as_bytes()).expect("HMAC can take key of any size");
        mac.update(signed_payload.as_bytes());
        let result = mac.finalize();
        format!("sha256={}", hex::encode(result.into_bytes()))
    }
}

/// Constant-time string comparison to prevent timing attacks
fn constant_time_compare(a: &str, b: &str) -> bool {
    if a.len() != b.len() {
        return false;
    }

    let mut result = 0u8;
    for (x, y) in a.bytes().zip(b.bytes()) {
        result |= x ^ y;
    }
    result == 0
}

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

    #[test]
    fn test_verify_signature_with_timestamp() {
        let payload = r#"{"id":"evt_123","type":"message.delivered"}"#;
        let secret = "test_secret";
        let ts = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs()
            .to_string();
        let signature = Webhooks::generate_signature(payload, secret, Some(&ts));

        assert!(Webhooks::verify_signature(payload, &signature, secret, Some(&ts)));
        assert!(!Webhooks::verify_signature(payload, "invalid", secret, Some(&ts)));
    }

    #[test]
    fn test_verify_signature_without_timestamp() {
        let payload = r#"{"id":"evt_123","type":"message.delivered"}"#;
        let secret = "test_secret";
        let signature = Webhooks::generate_signature(payload, secret, None);

        assert!(Webhooks::verify_signature(payload, &signature, secret, None));
    }

    #[test]
    fn test_generate_signature() {
        let payload = "test";
        let secret = "secret";
        let signature = Webhooks::generate_signature(payload, secret, None);

        assert!(signature.starts_with("sha256="));
        assert_eq!(signature.len(), 71); // "sha256=" + 64 hex chars
    }
}