Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 30 additions & 3 deletions src/Webhook.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,42 @@ final class Webhook
* @param string $rawBody Corpo bruto EXATO da requisição (não re-serialize o JSON).
* @param string|null $signatureHeader Valor do header `X-SMSGo-Signature`.
* @param string $secret Segredo do webhook (retornado por `setWebhook`/`getWebhook`).
* @param int|null $toleranceSeconds Se informado, além da assinatura exige que o
* `sentAt` do corpo esteja dentro desta janela (anti-replay). Sem ele, o
* comportamento é idêntico ao anterior (só assinatura). Deduplicar pelo `id`
* do corpo continua a cargo do receptor.
*/
public static function verifySignature(string $rawBody, ?string $signatureHeader, string $secret): bool
{
public static function verifySignature(
string $rawBody,
?string $signatureHeader,
string $secret,
?int $toleranceSeconds = null
): bool {
if ($signatureHeader === null || $signatureHeader === '') {
return false;
}

$expected = 'sha256=' . hash_hmac('sha256', $rawBody, $secret);

return hash_equals($expected, $signatureHeader);
if (!hash_equals($expected, $signatureHeader)) {
return false;
}

if ($toleranceSeconds !== null) {
$payload = json_decode($rawBody, true);
$sentAt = is_array($payload) && isset($payload['sentAt']) ? $payload['sentAt'] : null;
if (!is_string($sentAt)) {
return false;
}
$ts = strtotime($sentAt);
if ($ts === false) {
return false;
}
if (abs(time() - $ts) > $toleranceSeconds) {
return false;
}
}

return true;
}
}
Loading