nylas-types 0.1.1

Type definitions for Nylas API v3
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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
//! Webhook types for Nylas API v3
//!
//! Webhooks allow you to receive real-time notifications about changes to your Nylas data.
//! This module provides types for webhook configuration, notifications, and signature verification.

use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::common::WebhookId;

/// A webhook configuration.
///
/// Webhooks send HTTP POST requests to your specified callback URL when events occur.
///
/// # Example
///
/// ```
/// # use nylas_types::{Webhook, WebhookId, WebhookTrigger};
/// let webhook = Webhook {
///     id: WebhookId::new("webhook_123"),
///     description: Some("Production webhook for message events".to_string()),
///     trigger_types: vec![WebhookTrigger::MessageCreated, WebhookTrigger::MessageUpdated],
///     webhook_url: "https://api.example.com/webhooks".to_string(),
///     webhook_secret: Some("secret_key_xyz".to_string()),
///     notification_email_addresses: vec!["admin@example.com".to_string()],
///     privacy_mode: None,
/// };
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Webhook {
    /// Unique identifier for the webhook.
    pub id: WebhookId,

    /// Description of the webhook.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// List of trigger types this webhook listens for.
    pub trigger_types: Vec<WebhookTrigger>,

    /// URL where webhook notifications will be sent.
    pub webhook_url: String,

    /// Secret key for webhook signature verification.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub webhook_secret: Option<String>,

    /// Email addresses to notify when webhook fails.
    #[serde(default)]
    pub notification_email_addresses: Vec<String>,

    /// Privacy mode settings (NEW in 2025)
    ///
    /// When enabled, sensitive information is redacted from webhook
    /// payloads and server logs.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub privacy_mode: Option<PrivacyMode>,
}

/// Privacy mode configuration.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct PrivacyMode {
    /// Enable privacy mode
    pub enabled: bool,

    /// Redact email addresses
    #[serde(default)]
    pub redact_emails: bool,

    /// Redact message bodies
    #[serde(default)]
    pub redact_bodies: bool,

    /// Redact participant names
    #[serde(default)]
    pub redact_names: bool,
}

/// Webhook trigger types.
///
/// Specifies which events will trigger webhook notifications.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum WebhookTrigger {
    /// Message created
    MessageCreated,
    /// Message updated
    MessageUpdated,
    /// Message deleted (not sent)
    MessageDeleted,

    /// Thread created
    ThreadCreated,
    /// Thread updated
    ThreadUpdated,

    /// Draft created
    DraftCreated,
    /// Draft updated
    DraftUpdated,
    /// Draft deleted (not sent)
    DraftDeleted,

    /// Event created
    EventCreated,
    /// Event updated
    EventUpdated,
    /// Event deleted
    EventDeleted,

    /// Calendar created
    CalendarCreated,
    /// Calendar updated
    CalendarUpdated,
    /// Calendar deleted
    CalendarDeleted,

    /// Contact created
    ContactCreated,
    /// Contact updated
    ContactUpdated,
    /// Contact deleted
    ContactDeleted,

    /// Folder created
    FolderCreated,
    /// Folder updated
    FolderUpdated,
    /// Folder deleted
    FolderDeleted,

    /// Grant created
    GrantCreated,
    /// Grant updated
    GrantUpdated,
    /// Grant deleted
    GrantDeleted,
    /// Grant expired
    GrantExpired,
}

/// Webhook notification payload.
///
/// This is the payload sent by Nylas to your webhook URL when an event occurs.
///
/// # Example
///
/// ```
/// # use nylas_types::WebhookNotification;
/// # use serde_json::json;
/// let payload = r#"{
///     "id": "notif_123",
///     "grant_id": "grant_456",
///     "application_id": "app_789",
///     "trigger": "message.created",
///     "timestamp": 1609459200,
///     "data": {"id": "msg_abc", "subject": "Hello"}
/// }"#;
///
/// let notification: WebhookNotification = serde_json::from_str(payload).unwrap();
/// assert_eq!(notification.trigger, "message.created");
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WebhookNotification {
    /// Unique notification ID.
    pub id: String,

    /// Grant ID that triggered this notification.
    pub grant_id: String,

    /// Application ID.
    pub application_id: String,

    /// Trigger type (e.g., "message.created").
    pub trigger: String,

    /// Unix timestamp when event occurred.
    pub timestamp: i64,

    /// Event data payload.
    pub data: Value,

    /// Calendar ID (for calendar/event triggers).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub calendar_id: Option<String>,

    /// Master event ID (for recurring event triggers).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub master_event_id: Option<String>,
}

/// Request to create a new webhook.
///
/// # Example
///
/// ```
/// # use nylas_types::{CreateWebhookRequest, WebhookTrigger};
/// let request = CreateWebhookRequest::builder()
///     .description("My webhook")
///     .webhook_url("https://api.example.com/webhooks")
///     .trigger_types(vec![WebhookTrigger::MessageCreated])
///     .webhook_secret("my_secret_key")
///     .build();
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CreateWebhookRequest {
    /// Description of the webhook.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// URL where webhook notifications will be sent.
    pub webhook_url: String,

    /// List of trigger types this webhook listens for.
    pub trigger_types: Vec<WebhookTrigger>,

    /// Secret key for webhook signature verification.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub webhook_secret: Option<String>,

    /// Email addresses to notify when webhook fails.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub notification_email_addresses: Option<Vec<String>>,

    /// Privacy mode settings
    #[serde(skip_serializing_if = "Option::is_none")]
    pub privacy_mode: Option<PrivacyMode>,
}

impl CreateWebhookRequest {
    /// Create a builder for CreateWebhookRequest.
    pub fn builder() -> CreateWebhookRequestBuilder {
        CreateWebhookRequestBuilder::default()
    }
}

/// Builder for CreateWebhookRequest.
#[derive(Debug, Clone, Default)]
pub struct CreateWebhookRequestBuilder {
    description: Option<String>,
    webhook_url: Option<String>,
    trigger_types: Option<Vec<WebhookTrigger>>,
    webhook_secret: Option<String>,
    notification_email_addresses: Option<Vec<String>>,
    privacy_mode: Option<PrivacyMode>,
}

impl CreateWebhookRequestBuilder {
    /// Set webhook description.
    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }

    /// Set webhook URL.
    pub fn webhook_url(mut self, url: impl Into<String>) -> Self {
        self.webhook_url = Some(url.into());
        self
    }

    /// Set trigger types.
    pub fn trigger_types(mut self, triggers: Vec<WebhookTrigger>) -> Self {
        self.trigger_types = Some(triggers);
        self
    }

    /// Set webhook secret for signature verification.
    pub fn webhook_secret(mut self, secret: impl Into<String>) -> Self {
        self.webhook_secret = Some(secret.into());
        self
    }

    /// Set notification email addresses.
    pub fn notification_email_addresses(mut self, emails: Vec<String>) -> Self {
        self.notification_email_addresses = Some(emails);
        self
    }

    /// Set privacy mode.
    ///
    /// # Example
    ///
    /// ```
    /// use nylas_types::{CreateWebhookRequest, PrivacyMode, WebhookTrigger};
    ///
    /// let privacy = PrivacyMode {
    ///     enabled: true,
    ///     redact_emails: true,
    ///     redact_bodies: true,
    ///     redact_names: false,
    /// };
    ///
    /// let request = CreateWebhookRequest::builder()
    ///     .webhook_url("https://example.com/webhook")
    ///     .trigger_types(vec![WebhookTrigger::MessageCreated])
    ///     .privacy_mode(privacy)
    ///     .build();
    /// ```
    pub fn privacy_mode(mut self, mode: PrivacyMode) -> Self {
        self.privacy_mode = Some(mode);
        self
    }

    /// Build the CreateWebhookRequest.
    ///
    /// # Panics
    ///
    /// Panics if webhook_url or trigger_types are not set.
    pub fn build(self) -> CreateWebhookRequest {
        CreateWebhookRequest {
            description: self.description,
            webhook_url: self.webhook_url.expect("webhook_url is required"),
            trigger_types: self.trigger_types.expect("trigger_types is required"),
            webhook_secret: self.webhook_secret,
            notification_email_addresses: self.notification_email_addresses,
            privacy_mode: self.privacy_mode,
        }
    }
}

/// Request to update a webhook.
///
/// All fields are optional - only provide the fields you want to update.
///
/// # Example
///
/// ```
/// # use nylas_types::{UpdateWebhookRequest, WebhookTrigger};
/// let update = UpdateWebhookRequest::builder()
///     .description("Updated description")
///     .trigger_types(vec![WebhookTrigger::MessageCreated, WebhookTrigger::MessageUpdated])
///     .build();
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct UpdateWebhookRequest {
    /// Update webhook description.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// Update webhook URL.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub webhook_url: Option<String>,

    /// Update trigger types.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trigger_types: Option<Vec<WebhookTrigger>>,

    /// Update webhook secret.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub webhook_secret: Option<String>,

    /// Update notification email addresses.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub notification_email_addresses: Option<Vec<String>>,
}

impl UpdateWebhookRequest {
    /// Create a builder for UpdateWebhookRequest.
    pub fn builder() -> UpdateWebhookRequestBuilder {
        UpdateWebhookRequestBuilder::default()
    }
}

/// Builder for UpdateWebhookRequest.
#[derive(Debug, Clone, Default)]
pub struct UpdateWebhookRequestBuilder {
    description: Option<String>,
    webhook_url: Option<String>,
    trigger_types: Option<Vec<WebhookTrigger>>,
    webhook_secret: Option<String>,
    notification_email_addresses: Option<Vec<String>>,
}

impl UpdateWebhookRequestBuilder {
    /// Set webhook description.
    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }

    /// Set webhook URL.
    pub fn webhook_url(mut self, url: impl Into<String>) -> Self {
        self.webhook_url = Some(url.into());
        self
    }

    /// Set trigger types.
    pub fn trigger_types(mut self, triggers: Vec<WebhookTrigger>) -> Self {
        self.trigger_types = Some(triggers);
        self
    }

    /// Set webhook secret.
    pub fn webhook_secret(mut self, secret: impl Into<String>) -> Self {
        self.webhook_secret = Some(secret.into());
        self
    }

    /// Set notification email addresses.
    pub fn notification_email_addresses(mut self, emails: Vec<String>) -> Self {
        self.notification_email_addresses = Some(emails);
        self
    }

    /// Build the UpdateWebhookRequest.
    pub fn build(self) -> UpdateWebhookRequest {
        UpdateWebhookRequest {
            description: self.description,
            webhook_url: self.webhook_url,
            trigger_types: self.trigger_types,
            webhook_secret: self.webhook_secret,
            notification_email_addresses: self.notification_email_addresses,
        }
    }
}

/// Verifies the HMAC signature of a webhook payload.
///
/// Use this to verify that a webhook notification actually came from Nylas.
///
/// # Arguments
///
/// * `payload` - The raw webhook payload bytes
/// * `signature` - The signature from the X-Nylas-Signature header
/// * `secret` - Your webhook secret key
///
/// # Returns
///
/// Returns `true` if the signature is valid, `false` otherwise.
///
/// # Example
///
/// ```
/// # use nylas_types::verify_webhook_signature;
/// let payload = b"{\"id\":\"123\",\"trigger\":\"message.created\"}";
/// let signature = "abc123def456...";
/// let secret = "my_webhook_secret";
///
/// if verify_webhook_signature(payload, signature, secret) {
///     println!("Webhook signature is valid!");
/// } else {
///     println!("Invalid webhook signature!");
/// }
/// ```
pub fn verify_webhook_signature(payload: &[u8], signature: &str, secret: &str) -> bool {
    use hmac::{Hmac, Mac};
    use sha2::Sha256;

    type HmacSha256 = Hmac<Sha256>;

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

    mac.update(payload);

    let result = mac.finalize();
    let expected = hex::encode(result.into_bytes());

    signature == expected
}

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

    #[test]
    fn test_webhook_serialization() {
        let webhook = Webhook {
            id: WebhookId::new("webhook_123"),
            description: Some("Test webhook".to_string()),
            trigger_types: vec![WebhookTrigger::MessageCreated],
            webhook_url: "https://example.com/webhook".to_string(),
            webhook_secret: Some("secret".to_string()),
            notification_email_addresses: vec!["admin@example.com".to_string()],
            privacy_mode: None,
        };

        let json = serde_json::to_string(&webhook).unwrap();
        assert!(json.contains("webhook_123"));
        assert!(json.contains("https://example.com/webhook"));
    }

    #[test]
    fn test_webhook_notification_deserialization() {
        let json = r#"{
            "id": "notif_123",
            "grant_id": "grant_456",
            "application_id": "app_789",
            "trigger": "message.created",
            "timestamp": 1609459200,
            "data": {"id": "msg_abc", "subject": "Test"}
        }"#;

        let notification: WebhookNotification = serde_json::from_str(json).unwrap();
        assert_eq!(notification.id, "notif_123");
        assert_eq!(notification.trigger, "message.created");
        assert_eq!(notification.timestamp, 1609459200);
    }

    #[test]
    fn test_webhook_trigger_serialization() {
        let trigger = WebhookTrigger::MessageCreated;
        let json = serde_json::to_string(&trigger).unwrap();
        assert_eq!(json, "\"message-created\"");

        let trigger = WebhookTrigger::EventUpdated;
        let json = serde_json::to_string(&trigger).unwrap();
        assert_eq!(json, "\"event-updated\"");
    }

    #[test]
    fn test_create_webhook_request_builder() {
        let request = CreateWebhookRequest::builder()
            .description("My webhook")
            .webhook_url("https://api.example.com/webhooks")
            .trigger_types(vec![WebhookTrigger::MessageCreated])
            .webhook_secret("secret_key")
            .notification_email_addresses(vec!["admin@example.com".to_string()])
            .build();

        assert_eq!(request.description, Some("My webhook".to_string()));
        assert_eq!(request.webhook_url, "https://api.example.com/webhooks");
        assert_eq!(request.trigger_types.len(), 1);
        assert_eq!(request.webhook_secret, Some("secret_key".to_string()));
    }

    #[test]
    fn test_update_webhook_request_builder() {
        let update = UpdateWebhookRequest::builder()
            .description("Updated")
            .trigger_types(vec![
                WebhookTrigger::MessageCreated,
                WebhookTrigger::MessageUpdated,
            ])
            .build();

        assert_eq!(update.description, Some("Updated".to_string()));
        assert_eq!(update.trigger_types.as_ref().unwrap().len(), 2);
        assert!(update.webhook_url.is_none());
    }

    #[test]
    fn test_verify_webhook_signature() {
        let payload = b"test payload";
        let secret = "test_secret";

        // Generate a valid signature
        use hmac::{Hmac, Mac};
        use sha2::Sha256;
        type HmacSha256 = Hmac<Sha256>;

        let mut mac = HmacSha256::new_from_slice(secret.as_bytes()).unwrap();
        mac.update(payload);
        let result = mac.finalize();
        let signature = hex::encode(result.into_bytes());

        // Verify it
        assert!(verify_webhook_signature(payload, &signature, secret));

        // Verify wrong signature fails
        assert!(!verify_webhook_signature(
            payload,
            "wrong_signature",
            secret
        ));

        // Verify wrong secret fails
        assert!(!verify_webhook_signature(
            payload,
            &signature,
            "wrong_secret"
        ));
    }

    #[test]
    fn test_privacy_mode_default() {
        let mode = PrivacyMode::default();
        assert!(!mode.enabled);
        assert!(!mode.redact_emails);
    }

    #[test]
    fn test_privacy_mode_enabled() {
        let mode = PrivacyMode {
            enabled: true,
            redact_emails: true,
            redact_bodies: true,
            redact_names: true,
        };

        let json = serde_json::to_string(&mode).unwrap();
        assert!(json.contains("\"enabled\":true"));
        assert!(json.contains("\"redact_emails\":true"));
    }

    #[test]
    fn test_webhook_with_privacy_mode() {
        let privacy = PrivacyMode {
            enabled: true,
            redact_emails: true,
            redact_bodies: false,
            redact_names: false,
        };

        let request = CreateWebhookRequest::builder()
            .webhook_url("https://example.com")
            .trigger_types(vec![WebhookTrigger::MessageCreated])
            .privacy_mode(privacy.clone())
            .build();

        assert!(request.privacy_mode.is_some());
        let mode = request.privacy_mode.unwrap();
        assert!(mode.enabled);
        assert!(mode.redact_emails);
    }
}