dpl/app/Services/MailFlow/WebhookSignature.php

25 lines
856 B
PHP

<?php
namespace App\Services\MailFlow;
class WebhookSignature
{
public function valid(string $body, string $id, string $timestamp, string $signatures, string $secret): bool
{
if (!$id || !ctype_digit($timestamp) || abs(time() - (int) $timestamp) > 300 || !str_starts_with($secret, 'whsec_')) {
return false;
}
$key = base64_decode(substr($secret, 6), true);
if ($key === false || strlen($key) < 16) {
return false;
}
$expected = base64_encode(hash_hmac('sha256', $id . '.' . $timestamp . '.' . $body, $key, true));
foreach (preg_split('/\s+/', trim($signatures)) as $signature) {
if (str_starts_with($signature, 'v1,') && hash_equals($expected, substr($signature, 3))) {
return true;
}
}
return false;
}
}