bitmomo 0.1.0

BitMomo merchant SDK: accept crypto payments and verify webhooks in Rust
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
//! Verify BitMomo webhook deliveries.
//!
//! Pass the raw request body exactly as received to [`verify_event`]:
//!
//! ```
//! use bitmomo::webhooks::{verify_event, DeliveryDedupeCache, VerifyOptions, WebhookSecret};
//!
//! # fn handle(body: &[u8], signature: &str, timestamp: Option<&str>, key_version: Option<&str>) -> u16 {
//! # let dedupe = DeliveryDedupeCache::default();
//! let opts = VerifyOptions::new(vec![WebhookSecret::new(1, "whsec-from-your-config")])
//!     .timestamp(timestamp)
//!     .key_version(key_version);
//! match verify_event(body, signature, &opts) {
//!     Ok(envelope) if dedupe.seen(&envelope.delivery_id) => 200, // already handled
//!     Ok(envelope) => { /* process envelope.event */ 200 }
//!     Err(reason) => { eprintln!("rejected: {reason}"); 400 }
//! }
//! # }
//! ```
//!
//! Checks, in order: a secret exists for the delivery's key version; the
//! signature is 64 hex characters; HMAC-SHA256 of the raw body matches; the
//! signed `_meta.sent_at` is within the tolerance (default 300 seconds); the
//! unsigned headers equal the signed envelope; the envelope is complete.
//! Deliveries arrive at least once, so dedupe on `delivery_id`.

use std::collections::HashMap;
use std::fmt;
use std::sync::Mutex;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

use hmac::{Hmac, Mac};
use serde_json::{Map, Value};
use sha2::Sha256;

/// The default freshness window.
pub const DEFAULT_TOLERANCE: Duration = Duration::from_secs(300);

const MAX_SAFE_INT: f64 = 9_007_199_254_740_991.0;

/// Why a delivery was refused. The `Display` form matches every BitMomo SDK.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RejectReason {
    MissingSecret,
    UnknownKeyVersion,
    MalformedSignature,
    BadSignature,
    MissingTimestamp,
    StaleTimestamp,
    FutureTimestamp,
    TimestampMismatch,
    VersionMismatch,
    MalformedEnvelope,
}

impl RejectReason {
    /// The shared reason code, such as `"stale-timestamp"`.
    pub fn as_str(&self) -> &'static str {
        match self {
            RejectReason::MissingSecret => "missing-secret",
            RejectReason::UnknownKeyVersion => "unknown-key-version",
            RejectReason::MalformedSignature => "malformed-signature",
            RejectReason::BadSignature => "bad-signature",
            RejectReason::MissingTimestamp => "missing-timestamp",
            RejectReason::StaleTimestamp => "stale-timestamp",
            RejectReason::FutureTimestamp => "future-timestamp",
            RejectReason::TimestampMismatch => "timestamp-mismatch",
            RejectReason::VersionMismatch => "version-mismatch",
            RejectReason::MalformedEnvelope => "malformed-envelope",
        }
    }
}

impl fmt::Display for RejectReason {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl std::error::Error for RejectReason {}

/// One signing secret and its version (the `X-Webhook-Key-Version` header).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WebhookSecret {
    pub version: i64,
    pub secret: String,
}

impl WebhookSecret {
    pub fn new(version: i64, secret: impl Into<String>) -> Self {
        WebhookSecret {
            version,
            secret: secret.into(),
        }
    }
}

/// Everything [`verify_event`] needs besides the body and signature.
#[derive(Debug, Clone)]
pub struct VerifyOptions {
    /// Candidate secrets. Keep the old and new one during the 24 hours after a rotation.
    pub secrets: Vec<WebhookSecret>,
    /// The `X-Webhook-Timestamp` header, if present.
    pub timestamp: Option<String>,
    /// The `X-Webhook-Key-Version` header, if present.
    pub key_version: Option<String>,
    /// The freshness window, in seconds. Must be finite and not negative.
    pub tolerance_secs: f64,
    /// The current time; `None` means now.
    pub now: Option<SystemTime>,
}

impl VerifyOptions {
    pub fn new(secrets: Vec<WebhookSecret>) -> Self {
        VerifyOptions {
            secrets,
            timestamp: None,
            key_version: None,
            tolerance_secs: DEFAULT_TOLERANCE.as_secs_f64(),
            now: None,
        }
    }

    /// Set the `X-Webhook-Timestamp` header value.
    pub fn timestamp(mut self, value: Option<&str>) -> Self {
        self.timestamp = value.map(str::to_string);
        self
    }

    /// Set the `X-Webhook-Key-Version` header value.
    pub fn key_version(mut self, value: Option<&str>) -> Self {
        self.key_version = value.map(str::to_string);
        self
    }

    /// Set the freshness window in seconds.
    pub fn tolerance_secs(mut self, secs: f64) -> Self {
        self.tolerance_secs = secs;
        self
    }

    /// Set the current time (for tests).
    pub fn now(mut self, now: SystemTime) -> Self {
        self.now = Some(now);
        self
    }
}

/// The signed delivery coordinates from `_meta`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Envelope {
    pub delivery_id: String,
    pub event: String,
    pub attempt: i64,
    pub sent_at: String,
    /// `None` when an older sender left it out.
    pub occurred_at: Option<String>,
    pub sequence: i64,
    pub key_version: i64,
}

fn is_hex64(s: &str) -> bool {
    s.len() == 64 && s.bytes().all(|b| b.is_ascii_hexdigit())
}

/// Constant-time check that `signature` (64 hex characters) is the HMAC-SHA256
/// of the raw `payload` with `secret`.
pub fn verify_signature(payload: &[u8], signature: &str, secret: &str) -> bool {
    if secret.is_empty() || !is_hex64(signature) {
        return false;
    }
    let Ok(expected) = hex::decode(signature) else {
        return false;
    };
    let Ok(mut mac) = Hmac::<Sha256>::new_from_slice(secret.as_bytes()) else {
        return false;
    };
    mac.update(payload);
    mac.verify_slice(&expected).is_ok()
}

fn parse_int(s: &str) -> Option<i64> {
    let t = s.trim();
    let digits = t
        .strip_prefix('+')
        .or_else(|| t.strip_prefix('-'))
        .unwrap_or(t);
    if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
        return None;
    }
    t.trim_start_matches('+').parse().ok()
}

/// Parse an RFC 3339 timestamp as the API sends it (for example
/// `"2026-11-15T22:57:30.123456789+00:00"`). Returns `None` when it is not one.
pub fn parse_timestamp(s: &str) -> Option<SystemTime> {
    let secs = parse_rfc3339(s)?;
    if secs >= 0.0 {
        UNIX_EPOCH.checked_add(Duration::from_secs_f64(secs))
    } else {
        UNIX_EPOCH.checked_sub(Duration::from_secs_f64(-secs))
    }
}

/// Seconds since the Unix epoch for an RFC 3339 timestamp, or `None`.
fn parse_rfc3339(s: &str) -> Option<f64> {
    let b = s.as_bytes();
    if b.len() < 20 {
        return None;
    }
    let num = |range: std::ops::Range<usize>| -> Option<i64> {
        let part = s.get(range)?;
        if part.bytes().all(|c| c.is_ascii_digit()) {
            part.parse().ok()
        } else {
            None
        }
    };
    let (year, month, day) = (num(0..4)?, num(5..7)?, num(8..10)?);
    let (hour, minute, second) = (num(11..13)?, num(14..16)?, num(17..19)?);
    if b[4] != b'-'
        || b[7] != b'-'
        || !matches!(b[10], b'T' | b't')
        || b[13] != b':'
        || b[16] != b':'
    {
        return None;
    }
    let mut i = 19;
    let mut nanos = 0f64;
    if b[i] == b'.' {
        let start = i + 1;
        let mut end = start;
        while end < b.len() && b[end].is_ascii_digit() {
            end += 1;
        }
        if end == start {
            return None;
        }
        nanos = format!("0.{}", &s[start..end.min(start + 9)])
            .parse()
            .ok()?;
        i = end;
    }
    let offset_secs = match b.get(i)? {
        b'Z' | b'z' if i + 1 == b.len() => 0,
        sign @ (b'+' | b'-') if i + 6 == b.len() && b[i + 3] == b':' => {
            let (oh, om) = (num(i + 1..i + 3)?, num(i + 4..i + 6)?);
            if oh > 23 || om > 59 {
                return None;
            }
            let total = oh * 3600 + om * 60;
            if *sign == b'+' {
                total
            } else {
                -total
            }
        }
        _ => return None,
    };
    let leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
    let days_in_month = match month {
        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
        4 | 6 | 9 | 11 => 30,
        2 if leap => 29,
        2 => 28,
        _ => return None,
    };
    if !(1..=days_in_month).contains(&day) || hour > 23 || minute > 59 || second > 59 {
        return None;
    }
    // Days from civil (Howard Hinnant's algorithm).
    let y = if month <= 2 { year - 1 } else { year };
    let era = (if y >= 0 { y } else { y - 399 }) / 400;
    let yoe = y - era * 400;
    let mp = (month + 9) % 12;
    let doy = (153 * mp + 2) / 5 + day - 1;
    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
    let days = era * 146_097 + doe - 719_468;
    let secs = days * 86_400 + hour * 3600 + minute * 60 + second - offset_secs;
    Some(secs as f64 + nanos)
}

fn number(value: Option<&Value>) -> Option<&serde_json::Number> {
    match value? {
        Value::Number(n) => Some(n),
        _ => None,
    }
}

fn safe_int(value: Option<&Value>) -> Option<i64> {
    let n = number(value)?;
    if let Some(i) = n.as_i64() {
        return (i.unsigned_abs() as f64 <= MAX_SAFE_INT).then_some(i);
    }
    let f = n.as_f64()?;
    (f.is_finite() && f.fract() == 0.0 && f.abs() <= MAX_SAFE_INT).then_some(f as i64)
}

fn non_blank(value: Option<&Value>) -> bool {
    value
        .and_then(Value::as_str)
        .is_some_and(|s| !s.trim().is_empty())
}

/// Fully verify one delivery. See the [module docs](self) for the order of checks.
pub fn verify_event(
    raw_body: &[u8],
    signature: &str,
    opts: &VerifyOptions,
) -> Result<Envelope, RejectReason> {
    if opts.secrets.is_empty() {
        return Err(RejectReason::MissingSecret);
    }
    let version = match opts.key_version.as_deref() {
        Some(header) if !header.is_empty() => {
            parse_int(header).ok_or(RejectReason::UnknownKeyVersion)?
        }
        _ if opts.secrets.len() == 1 => opts.secrets[0].version,
        _ => return Err(RejectReason::UnknownKeyVersion),
    };
    let secret = opts
        .secrets
        .iter()
        .find(|s| s.version == version)
        .filter(|s| !s.secret.is_empty())
        .ok_or(RejectReason::UnknownKeyVersion)?;

    if !is_hex64(signature) {
        return Err(RejectReason::MalformedSignature);
    }
    if !verify_signature(raw_body, signature, &secret.secret) {
        return Err(RejectReason::BadSignature);
    }

    let text = String::from_utf8_lossy(raw_body);
    let doc: Value = serde_json::from_str(&text).map_err(|_| RejectReason::MissingTimestamp)?;
    let empty = Map::new();
    let top = doc.as_object();
    let meta = top
        .and_then(|o| o.get("_meta"))
        .and_then(Value::as_object)
        .unwrap_or(&empty);
    let sent_at = match meta.get("sent_at").and_then(Value::as_str) {
        Some(s) if !s.is_empty() => s,
        _ => return Err(RejectReason::MissingTimestamp),
    };

    let tolerance = opts.tolerance_secs;
    if !tolerance.is_finite() || tolerance < 0.0 {
        return Err(RejectReason::MalformedEnvelope);
    }
    let sent = parse_rfc3339(sent_at).ok_or(RejectReason::MissingTimestamp)?;
    let now = opts.now.unwrap_or_else(SystemTime::now);
    let now_secs = match now.duration_since(UNIX_EPOCH) {
        Ok(d) => d.as_secs_f64(),
        Err(e) => -e.duration().as_secs_f64(),
    };
    let skew = now_secs - sent;
    if skew > tolerance {
        return Err(RejectReason::StaleTimestamp);
    }
    if skew < -tolerance {
        return Err(RejectReason::FutureTimestamp);
    }

    if let Some(header) = opts.timestamp.as_deref() {
        if header != sent_at {
            return Err(RejectReason::TimestampMismatch);
        }
    }
    if let Some(n) = number(meta.get("key_version")) {
        if n.as_f64() != Some(version as f64) {
            return Err(RejectReason::VersionMismatch);
        }
    }

    let attempt = safe_int(meta.get("attempt"));
    let sequence = safe_int(meta.get("sequence"));
    let signed_version = safe_int(meta.get("key_version"));
    if !non_blank(meta.get("delivery_id"))
        || !non_blank(meta.get("event"))
        || attempt.is_none_or(|a| a < 1)
        || sequence.is_none_or(|s| s < 1)
        || signed_version.is_none_or(|v| v < 1)
    {
        return Err(RejectReason::MalformedEnvelope);
    }
    let event = meta
        .get("event")
        .and_then(Value::as_str)
        .unwrap_or_default();
    if let Some(top_event) = top.and_then(|o| o.get("event")) {
        if top_event.as_str() != Some(event) {
            return Err(RejectReason::MalformedEnvelope);
        }
    }
    let occurred_at = match meta.get("occurred_at") {
        None => None,
        Some(Value::String(s)) if parse_rfc3339(s).is_some() => Some(s.clone()),
        Some(_) => return Err(RejectReason::MalformedEnvelope),
    };

    Ok(Envelope {
        delivery_id: meta
            .get("delivery_id")
            .and_then(Value::as_str)
            .unwrap_or_default()
            .to_string(),
        event: event.to_string(),
        attempt: attempt.unwrap_or_default(),
        sent_at: sent_at.to_string(),
        occurred_at,
        sequence: sequence.unwrap_or_default(),
        key_version: version,
    })
}

/// An in-memory, thread-safe record of processed delivery IDs. Use durable
/// storage instead when processing a delivery twice would cause a second effect.
#[derive(Debug)]
pub struct DeliveryDedupeCache {
    ttl: Duration,
    seen: Mutex<HashMap<String, Instant>>,
}

impl Default for DeliveryDedupeCache {
    /// Entries expire after 24 hours, past the retry window.
    fn default() -> Self {
        DeliveryDedupeCache::new(Duration::from_secs(24 * 60 * 60))
    }
}

impl DeliveryDedupeCache {
    pub fn new(ttl: Duration) -> Self {
        DeliveryDedupeCache {
            ttl,
            seen: Mutex::new(HashMap::new()),
        }
    }

    /// True when `delivery_id` was already recorded (skip it); records it otherwise.
    pub fn seen(&self, delivery_id: &str) -> bool {
        self.seen_at(delivery_id, Instant::now())
    }

    pub(crate) fn seen_at(&self, delivery_id: &str, now: Instant) -> bool {
        let mut map = self
            .seen
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        if map.get(delivery_id).is_some_and(|expires| *expires > now) {
            return true;
        }
        if map.len() >= 1024 {
            map.retain(|_, expires| *expires > now);
        }
        map.insert(delivery_id.to_string(), now + self.ttl);
        false
    }

    /// The number of recorded deliveries.
    pub fn len(&self) -> usize {
        self.seen
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .len()
    }

    /// True when nothing is recorded.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

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

    #[test]
    fn parses_rfc3339() {
        assert_eq!(parse_rfc3339("1970-01-01T00:00:00Z"), Some(0.0));
        assert_eq!(
            parse_rfc3339("2026-11-15T22:57:30+00:00"),
            Some(1_794_783_450.0)
        );
        assert_eq!(
            parse_rfc3339("2026-11-15T23:57:30+01:00"),
            Some(1_794_783_450.0)
        );
        let nanos = parse_rfc3339("2026-11-15T22:57:30.123456789+00:00").unwrap();
        assert!((nanos - 1_794_783_450.123).abs() < 1e-3);
        for bad in [
            "yesterday",
            "2026-11-15",
            "2026-11-15 22:57:30Z",
            "2026-02-30T00:00:00Z",
            "2026-11-15T24:00:00Z",
            "2026-11-15T22:57:30",
            "2026-11-15T22:57:30.Z",
            "2026-11-15T22:57:30+0000",
            "2026-11-15T22:57:30+24:00",
        ] {
            assert_eq!(parse_rfc3339(bad), None, "{bad}");
        }
    }

    #[test]
    fn dedupe_cache_expires_and_prunes() {
        let cache = DeliveryDedupeCache::new(Duration::from_secs(10));
        let t0 = Instant::now();
        assert!(!cache.seen_at("d-1", t0));
        assert!(cache.seen_at("d-1", t0));
        assert!(!cache.seen_at("d-2", t0));
        assert_eq!(cache.len(), 2);
        assert!(!cache.seen_at("d-1", t0 + Duration::from_secs(11)));

        let big = DeliveryDedupeCache::new(Duration::from_secs(1));
        for i in 0..1024 {
            big.seen_at(&format!("old-{i}"), t0);
        }
        big.seen_at("fresh", t0 + Duration::from_secs(5));
        assert_eq!(big.len(), 1);
    }
}