verifyWebhook function

Map<String, dynamic>? verifyWebhook(
  1. String secret,
  2. String rawBody,
  3. String? signature, {
  4. Duration tolerance = const Duration(minutes: 5),
})

Check a webhook delivery. Pass the RAW body (not re-serialized JSON) and the X-SfuKit-Signature header. secret is WEBHOOK_SECRET (or ADMIN_API_KEY if none was set). Returns the event, or null if the signature is wrong or older than tolerance.

Implementation

Map<String, dynamic>? verifyWebhook(String secret, String rawBody, String? signature,
    {Duration tolerance = const Duration(minutes: 5)}) {
  if (secret.isEmpty || signature == null || signature.isEmpty) return null;
  final parts = <String, String>{};
  for (final p in signature.split(',')) {
    final i = p.indexOf('=');
    if (i > 0) parts[p.substring(0, i).trim()] = p.substring(i + 1).trim();
  }
  final t = int.tryParse(parts['t'] ?? '');
  final v1 = parts['v1'] ?? '';
  if (t == null || !_hex64.hasMatch(v1)) return null;
  final now = DateTime.now().millisecondsSinceEpoch ~/ 1000;
  if ((now - t).abs() > tolerance.inSeconds) return null;
  if (!_equal(_hmacHex(secret, '$t.$rawBody'), v1)) return null;
  try {
    final event = jsonDecode(rawBody);
    return event is Map<String, dynamic> ? event : null;
  } on FormatException {
    return null;
  }
}