use crate::crypto::primitives::{constant_time_equal, hmac_sha256};
use crate::encoding::{from_hex, to_hex};
pub const DEFAULT_TOLERANCE_SECONDS: i64 = 300;
pub fn webhook_signature_header(secret: &str, raw_body: &[u8], timestamp: i64) -> String {
let mut message = timestamp.to_string().into_bytes();
message.push(b'.');
message.extend_from_slice(raw_body);
format!("t={timestamp},v1={}", to_hex(&hmac_sha256(secret.as_bytes(), &message)))
}
pub fn verify_webhook_signature(
secret: &str,
raw_body: &[u8],
header: Option<&str>,
tolerance_seconds: i64,
now: i64,
) -> bool {
let Some(header) = header else { return false };
let mut timestamp: Option<i64> = None;
let mut given: Option<&str> = None;
for part in header.split(',') {
if let Some((name, value)) = part.split_once('=') {
match name.trim() {
"t" => timestamp = value.trim().parse().ok(),
"v1" => given = Some(value.trim()),
_ => {}
}
}
}
let (Some(timestamp), Some(given)) = (timestamp, given) else { return false };
if (now - timestamp).abs() > tolerance_seconds {
return false;
}
if given.len() != 64 {
return false;
}
let Some(signature) = from_hex(given) else { return false };
let mut message = timestamp.to_string().into_bytes();
message.push(b'.');
message.extend_from_slice(raw_body);
constant_time_equal(&hmac_sha256(secret.as_bytes(), &message), &signature)
}
pub fn verify_webhook_signature_now(secret: &str, raw_body: &[u8], header: Option<&str>) -> bool {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0);
verify_webhook_signature(secret, raw_body, header, DEFAULT_TOLERANCE_SECONDS, now)
}