verifyWebhook function

void verifyWebhook({
  1. required String secret,
  2. required String timestamp,
  3. required String eventId,
  4. required String signature,
  5. required String rawBody,
  6. int toleranceSeconds = 300,
  7. int? nowSeconds,
})

Throws WebhookSignatureException unless the request is validly signed and recent. timestamp, eventId and signature are the X-OpenRoam-Timestamp, X-OpenRoam-Event-Id and X-OpenRoam-Signature headers; rawBody is the request body exactly as received.

Implementation

void verifyWebhook({
  required String secret,
  required String timestamp,
  required String eventId,
  required String signature,
  required String rawBody,
  int toleranceSeconds = 300,
  int? nowSeconds,
}) {
  final sentAt = double.tryParse(timestamp);
  if (sentAt == null) throw WebhookSignatureException('Invalid X-OpenRoam-Timestamp.');
  final now = nowSeconds ?? DateTime.now().millisecondsSinceEpoch ~/ 1000;
  if ((now - sentAt).abs() > toleranceSeconds) {
    throw WebhookSignatureException('The timestamp is outside the tolerance.');
  }

  final mac = Hmac(sha256, utf8.encode(secret)).convert(utf8.encode('$timestamp.$eventId.$rawBody'));
  final expected = mac.toString();
  final given = signature.toLowerCase();
  if (!_constantTimeEqual(expected, given)) throw WebhookSignatureException('Signature mismatch.');
}