<?php
// apidata.one: verifying a webhook's signature in PHP (7.4 or later, no extensions beyond hash).
// The page that explains it: docs/concepts/webhooks.md. Test vectors: vectors.json.
//
// Use it:      require 'verify.php';  apidata_verify_webhook($secret, $header, $body);
// Try it:      echo '{"secret":"…","header":"…","body":"…","now":1794322803}' | php verify.php
//              prints true or false.

// docs:begin
/**
 * True when $header is a valid ApiData-Signature for $body under $secret.
 *
 * $secret  the endpoint's secret, exactly as it was shown when the endpoint was created
 * $header  the value of the ApiData-Signature header: $_SERVER['HTTP_APIDATA_SIGNATURE']
 * $body    the request body exactly as received: file_get_contents('php://input')
 * $now     the current time in Unix seconds (left out: the clock)
 */
function apidata_verify_webhook(string $secret, string $header, string $body, ?int $now = null): bool
{
    if ($secret === '') {
        return false;
    }
    $now = $now ?? time();
    $timestamp = null;
    $signatures = [];
    foreach (explode(',', $header) as $part) {
        $at = strpos($part, '=');
        if ($at === false) {
            continue;
        }
        $name = substr($part, 0, $at);
        $value = (string) substr($part, $at + 1);
        if ($name === 't') {
            $timestamp = $value;
        } elseif ($name === 'v1') {
            $signatures[] = $value;
        }
    }
    if ($timestamp === null || preg_match('/^[0-9]{1,15}$/D', $timestamp) !== 1) {
        return false;
    }
    // Refuse a timestamp more than five minutes from now, in either direction.
    if (abs($now - (int) $timestamp) > 300) {
        return false;
    }
    $expected = hash_hmac('sha256', $timestamp . '.' . $body, $secret);
    $valid = false;
    foreach ($signatures as $signature) {
        // Constant time: never compare signatures with == or === .
        if (hash_equals($expected, $signature)) {
            $valid = true;
        }
    }
    return $valid;
}
// docs:end

// Command line: {"secret","header","body","now"} as JSON on standard input; prints true or
// false. `now` is Unix seconds (a number or digits) or an ISO-8601 time; left out, the clock.
if (PHP_SAPI === 'cli' && isset($argv[0]) && realpath($argv[0]) === realpath(__FILE__)) {
    $answer = false;
    $given = json_decode((string) stream_get_contents(STDIN), true);
    if (is_array($given) && is_string($given['secret'] ?? null) && is_string($given['header'] ?? null)
        && is_string($given['body'] ?? null)) {
        $now = $given['now'] ?? null;
        $ok = true;
        if (is_int($now) || is_float($now)) {
            $now = (int) $now;
        } elseif (is_string($now) && preg_match('/^[0-9]+$/D', $now) === 1) {
            $now = (int) $now;
        } elseif (is_string($now)) {
            $parsed = strtotime($now);
            $ok = $parsed !== false;
            $now = $ok ? $parsed : null;
        } elseif ($now !== null) {
            $ok = false;
        }
        if ($ok) {
            $answer = apidata_verify_webhook($given['secret'], $given['header'], $given['body'], $now);
        }
    }
    echo $answer ? "true\n" : "false\n";
}
