bibby 0.1.0

The official Rust SDK for Bytebury — typed clients, smart .env initialization, and ergonomic macros for Geo, Images, PDF, Mailer, Uploader, Cron, Forms, Webhooks, Monitors, and Vault.
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
//! Client, types, and signature verification for **Bytebury Webhooks**
//! (`https://api.bytebury.com/webhooks/v1`).
//!
//! Manage webhook endpoints, rotate signing secrets, publish custom events,
//! inspect delivery attempts, replay failed deliveries, and verify incoming
//! `X-Bytebury-Signature` headers in constant time.

use std::collections::BTreeMap;
use std::time::{SystemTime, UNIX_EPOCH};

use hmac::{Hmac, Mac};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use sha2::Sha256;
use subtle::ConstantTimeEq;

use crate::client::Bibby;
use crate::error::{Error, Result};
use crate::pagination::Page;

const PRODUCT: &str = "webhooks";

/// Default maximum allowed clock skew / signature age in seconds (5 minutes).
pub const DEFAULT_SIGNATURE_TOLERANCE_SECS: i64 = 300;

/// HTTP header carrying the event type on outgoing Bytebury webhooks.
pub const HEADER_EVENT: &str = "X-Bytebury-Event";
/// HTTP header carrying the stable event ID (`evt_...`).
pub const HEADER_EVENT_ID: &str = "X-Bytebury-Event-Id";
/// HTTP header carrying the stable delivery ID (`del_...`).
pub const HEADER_DELIVERY_ID: &str = "X-Bytebury-Delivery-Id";
/// HTTP header carrying the Unix timestamp (seconds).
pub const HEADER_TIMESTAMP: &str = "X-Bytebury-Timestamp";
/// HTTP header carrying the signature (`t=<timestamp>,v1=<hex>`).
pub const HEADER_SIGNATURE: &str = "X-Bytebury-Signature";

/// Client for **Bytebury Webhooks**.
///
/// Obtained via [`Bibby::webhooks`].
#[derive(Debug, Clone, Copy)]
pub struct WebhooksClient<'a> {
    client: &'a Bibby,
}

impl<'a> WebhooksClient<'a> {
    pub(crate) fn new(client: &'a Bibby) -> Self {
        Self { client }
    }

    /// Lists webhook endpoints in your account (newest first).
    ///
    /// Calls `GET /webhooks/v1/endpoints`.
    pub async fn list_endpoints(&self, params: &ListEndpointsParams) -> Result<Page<Endpoint>> {
        self.client
            .get_json_query(PRODUCT, "endpoints", params)
            .await
    }

    /// Creates a new webhook endpoint.
    ///
    /// Calls `POST /webhooks/v1/endpoints`.
    pub async fn create_endpoint(&self, request: &CreateEndpointRequest) -> Result<Endpoint> {
        self.client.post_json(PRODUCT, "endpoints", request).await
    }

    /// Fetches a single webhook endpoint by ID.
    ///
    /// Calls `GET /webhooks/v1/endpoints/{id}`.
    pub async fn get_endpoint(&self, id: i64) -> Result<Endpoint> {
        self.client
            .get_json(PRODUCT, &format!("endpoints/{id}"))
            .await
    }

    /// Updates an existing webhook endpoint.
    ///
    /// Calls `PATCH /webhooks/v1/endpoints/{id}`.
    pub async fn update_endpoint(
        &self,
        id: i64,
        changes: &UpdateEndpointRequest,
    ) -> Result<Endpoint> {
        self.client
            .patch_json(PRODUCT, &format!("endpoints/{id}"), changes)
            .await
    }

    /// Permanently deletes a webhook endpoint.
    ///
    /// Calls `DELETE /webhooks/v1/endpoints/{id}`.
    pub async fn delete_endpoint(&self, id: i64) -> Result<Endpoint> {
        self.client
            .delete_json(PRODUCT, &format!("endpoints/{id}"))
            .await
    }

    /// Rotates the signing secret (`whsec_...`) for an endpoint and returns the updated endpoint.
    ///
    /// Calls `POST /webhooks/v1/endpoints/{id}/rotate-secret`.
    pub async fn rotate_secret(&self, id: i64) -> Result<Endpoint> {
        self.client
            .post_empty(PRODUCT, &format!("endpoints/{id}/rotate-secret"))
            .await
    }

    /// Publishes an event to all matching subscribed endpoints.
    ///
    /// Use [`crate::webhook_event!`] for concise inline JSON payloads.
    ///
    /// Calls `POST /webhooks/v1/events`.
    pub async fn publish_event(&self, request: &PublishEventRequest) -> Result<PublishedEvent> {
        self.client.post_json(PRODUCT, "events", request).await
    }

    /// Lists webhook deliveries with optional endpoint, event type, and status filters.
    ///
    /// Calls `GET /webhooks/v1/deliveries`.
    pub async fn list_deliveries(&self, params: &ListDeliveriesParams) -> Result<Page<Delivery>> {
        self.client
            .get_json_query(PRODUCT, "deliveries", params)
            .await
    }

    /// Fetches full details for a delivery, including payload and all attempts.
    ///
    /// Calls `GET /webhooks/v1/deliveries/{id}`.
    pub async fn get_delivery(&self, id: i64) -> Result<DeliveryDetail> {
        self.client
            .get_json(PRODUCT, &format!("deliveries/{id}"))
            .await
    }

    /// Queues a delivery to be replayed immediately.
    ///
    /// Calls `POST /webhooks/v1/deliveries/{id}/replay`.
    pub async fn replay_delivery(&self, id: i64) -> Result<Delivery> {
        self.client
            .post_empty(PRODUCT, &format!("deliveries/{id}/replay"))
            .await
    }

    /// Replays all failed deliveries from the last `since_hours` hours.
    ///
    /// Calls `POST /webhooks/v1/deliveries/replay-failed`.
    pub async fn replay_failed(&self, since_hours: i64) -> Result<ReplayFailedResult> {
        #[derive(Serialize)]
        struct Body {
            since_hours: i64,
        }
        self.client
            .post_json(PRODUCT, "deliveries/replay-failed", &Body { since_hours })
            .await
    }
}

/// Verifies an incoming Bytebury webhook `X-Bytebury-Signature` header against
/// the raw request body using the endpoint's full `whsec_...` secret and the
/// default 5-minute ([`DEFAULT_SIGNATURE_TOLERANCE_SECS`]) timestamp tolerance.
///
/// # Example
///
/// ```no_run
/// use bibby::webhooks;
///
/// # fn handle(secret: &str, sig_header: &str, raw_body: &[u8]) -> bibby::Result<()> {
/// webhooks::verify_signature(secret, sig_header, raw_body)?;
/// # Ok(())
/// # }
/// ```
pub fn verify_signature(secret: &str, signature_header: &str, raw_body: &[u8]) -> Result<()> {
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_err(|_| Error::WebhookSignature("system clock is before UNIX_EPOCH".into()))?
        .as_secs() as i64;
    verify_signature_at(
        secret,
        signature_header,
        raw_body,
        now,
        DEFAULT_SIGNATURE_TOLERANCE_SECS,
    )
}

/// Verifies an incoming `X-Bytebury-Signature` header with a custom timestamp
/// tolerance in seconds.
pub fn verify_signature_with_tolerance(
    secret: &str,
    signature_header: &str,
    raw_body: &[u8],
    tolerance_secs: i64,
) -> Result<()> {
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_err(|_| Error::WebhookSignature("system clock is before UNIX_EPOCH".into()))?
        .as_secs() as i64;
    verify_signature_at(secret, signature_header, raw_body, now, tolerance_secs)
}

/// Deterministic signature verification against an explicit `now_unix_secs` timestamp
/// (useful for unit tests and replay checks).
pub fn verify_signature_at(
    secret: &str,
    signature_header: &str,
    raw_body: &[u8],
    now_unix_secs: i64,
    tolerance_secs: i64,
) -> Result<()> {
    let mut timestamp: Option<i64> = None;
    let mut provided_v1: Option<&str> = None;

    for part in signature_header.split(',') {
        let part = part.trim();
        if let Some(t) = part.strip_prefix("t=") {
            timestamp = Some(t.parse::<i64>().map_err(|_| {
                Error::WebhookSignature("invalid timestamp in signature header".into())
            })?);
        } else if let Some(v1) = part.strip_prefix("v1=") {
            provided_v1 = Some(v1);
        }
    }

    let ts = timestamp
        .ok_or_else(|| Error::WebhookSignature("missing `t=` timestamp in signature".into()))?;
    let v1_hex = provided_v1
        .ok_or_else(|| Error::WebhookSignature("missing `v1=` digest in signature".into()))?;

    if (now_unix_secs - ts).abs() > tolerance_secs {
        return Err(Error::WebhookSignature(format!(
            "signature timestamp {ts} is outside tolerance of {tolerance_secs}s"
        )));
    }

    let provided_bytes = hex::decode(v1_hex)
        .map_err(|_| Error::WebhookSignature("invalid hex in `v1=` digest".into()))?;

    let mut mac = Hmac::<Sha256>::new_from_slice(secret.as_bytes())
        .map_err(|_| Error::WebhookSignature("invalid signing secret".into()))?;
    mac.update(format!("{ts}.").as_bytes());
    mac.update(raw_body);
    let expected = mac.finalize().into_bytes();

    if provided_bytes.len() == expected.len()
        && bool::from(provided_bytes.ct_eq(expected.as_slice()))
    {
        Ok(())
    } else {
        Err(Error::WebhookSignature("signature mismatch".into()))
    }
}

/// Computes an `X-Bytebury-Signature` header value (`t=<ts>,v1=<hex>`) for
/// testing webhook handlers locally.
pub fn sign_payload(secret: &str, timestamp_unix_secs: i64, raw_body: &[u8]) -> String {
    let mut mac =
        Hmac::<Sha256>::new_from_slice(secret.as_bytes()).expect("HMAC accepts any key length");
    mac.update(format!("{timestamp_unix_secs}.").as_bytes());
    mac.update(raw_body);
    let digest = hex::encode(mac.finalize().into_bytes());
    format!("t={timestamp_unix_secs},v1={digest}")
}

/// Query parameters for [`WebhooksClient::list_endpoints`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct ListEndpointsParams {
    /// Substring filter.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub q: Option<String>,
    /// 1-based page number.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub page: Option<i64>,
    /// Items per page (`1..=100`, default `25`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub page_size: Option<i64>,
}

/// Request body for [`WebhooksClient::create_endpoint`].
#[derive(Debug, Clone, Serialize)]
pub struct CreateEndpointRequest {
    /// Endpoint name (max 100 chars).
    pub name: String,
    /// Public `http://` or `https://` target URL.
    pub url: String,
    /// Event patterns to subscribe to (exact or `prefix.*`; empty receives all).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub event_types: Option<Vec<String>>,
    /// Extra HTTP headers (max 20; supports [`crate::vault_ref!`] placeholders).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub headers: Option<BTreeMap<String, String>>,
    /// Whether the endpoint starts enabled (default `true`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enabled: Option<bool>,
}

impl CreateEndpointRequest {
    /// Creates a new webhook endpoint request with `name` and `url`.
    pub fn new(name: impl Into<String>, url: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            url: url.into(),
            event_types: None,
            headers: None,
            enabled: None,
        }
    }

    /// Subscribes to specific event type patterns.
    pub fn event_types(mut self, types: Vec<String>) -> Self {
        self.event_types = Some(types);
        self
    }

    /// Sets custom HTTP headers.
    pub fn headers(mut self, headers: BTreeMap<String, String>) -> Self {
        self.headers = Some(headers);
        self
    }

    /// Sets whether the endpoint is enabled.
    pub fn enabled(mut self, enabled: bool) -> Self {
        self.enabled = Some(enabled);
        self
    }
}

/// Request body for [`WebhooksClient::update_endpoint`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct UpdateEndpointRequest {
    /// Updated name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Updated target URL.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
    /// Replaces subscribed event type patterns.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub event_types: Option<Vec<String>>,
    /// Replaces custom HTTP headers.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub headers: Option<BTreeMap<String, String>>,
    /// Enable or pause the endpoint.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enabled: Option<bool>,
}

/// Request body for [`WebhooksClient::publish_event`].
#[derive(Debug, Clone, Serialize)]
pub struct PublishEventRequest {
    /// Event type name (e.g. `"order.created"`).
    pub event_type: String,
    /// Arbitrary JSON object payload.
    pub payload: Value,
    /// Optional idempotency key to deduplicate repeated publishes.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub idempotency_key: Option<String>,
}

/// Delivery lifecycle status.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum DeliveryStatus {
    /// Queued or awaiting retry.
    Pending,
    /// Successfully delivered (2xx response).
    Delivered,
    /// Exhausted retries without success.
    Failed,
}

/// Query parameters for [`WebhooksClient::list_deliveries`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct ListDeliveriesParams {
    /// Filter by endpoint ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub endpoint_id: Option<i64>,
    /// Filter by exact event type.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub event_type: Option<String>,
    /// Filter by delivery status.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<DeliveryStatus>,
    /// 1-based page number.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub page: Option<i64>,
    /// Items per page (`1..=100`, default `25`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub page_size: Option<i64>,
}

/// A configured webhook endpoint.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Endpoint {
    /// Endpoint ID.
    pub id: i64,
    /// Display name.
    pub name: String,
    /// Target URL.
    pub url: String,
    /// Subscribed event patterns (empty = all events).
    #[serde(default)]
    pub event_types: Vec<String>,
    /// Extra HTTP headers sent on delivery.
    #[serde(default)]
    pub headers: BTreeMap<String, String>,
    /// Signing secret (`whsec_...`) used with [`verify_signature`].
    pub secret: String,
    /// Whether the endpoint is active.
    pub enabled: bool,
    /// RFC 3339 creation timestamp.
    pub created_at: String,
    /// RFC 3339 last-update timestamp.
    pub updated_at: String,
}

/// Response returned by [`WebhooksClient::publish_event`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PublishedEvent {
    /// Generated event ID (`evt_...`).
    pub event_id: String,
    /// Number of endpoint deliveries queued.
    pub deliveries_queued: i64,
}

/// Summary of a webhook delivery.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Delivery {
    /// Delivery ID.
    pub id: i64,
    /// Target endpoint ID, if still present.
    #[serde(default)]
    pub endpoint_id: Option<i64>,
    /// Event type delivered.
    pub event_type: String,
    /// Target URL.
    pub url: String,
    /// Current delivery status.
    pub status: DeliveryStatus,
    /// Number of delivery attempts so far.
    pub attempt_count: i32,
    /// HTTP status code of the most recent attempt, if any.
    pub last_status_code: Option<i32>,
    /// Error message of the most recent attempt, if any.
    pub last_error: Option<String>,
    /// RFC 3339 creation timestamp.
    pub created_at: String,
}

/// A single HTTP attempt for a webhook delivery.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DeliveryAttempt {
    /// Attempt ID.
    pub id: i64,
    /// 1-based attempt number.
    pub attempt_number: i32,
    /// HTTP status code received, if any.
    pub status_code: Option<i32>,
    /// Request duration in milliseconds.
    pub duration_ms: i32,
    /// Transport or status error, if any.
    pub error: Option<String>,
    /// Truncated response body, if any.
    pub response_body: Option<String>,
    /// RFC 3339 timestamp of the attempt.
    pub attempted_at: String,
}

/// Full delivery record returned by [`WebhooksClient::get_delivery`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DeliveryDetail {
    /// Core delivery metadata.
    pub delivery: Delivery,
    /// Public event ID (`evt_...`).
    #[serde(default)]
    pub event_public_id: String,
    /// Original JSON event payload.
    pub payload: Value,
    /// Chronological delivery attempts.
    #[serde(default)]
    pub attempts: Vec<DeliveryAttempt>,
}

/// Response from [`WebhooksClient::replay_failed`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct ReplayFailedResult {
    /// Number of failed deliveries queued for replay.
    pub replayed: u64,
}