<?php

/**
 * Copyright 2024-2025 Simply.IN Sp. z o.o.
 *
 * NOTICE OF LICENSE
 *
 * Licensed under the EUPL-1.2 or later.
 * You may not use this work except in compliance with the Licence.
 *
 * Copy of the Licence is available at:
 * https://joinup.ec.europa.eu/software/page/eupl
 * It is bundled with this package in the file LICENSE.txt
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the Licence is distributed on an as is basis,
 * without warranties or conditions of any kind, either express or implied.
 * Check the Licence for the specific language governing permissions
 * and limitations under the License.
 *
 * @author   Simply.IN Sp. z o.o.
 * @copyright 2024-2025 Simply.IN Sp. z o.o.
 * @license   https://joinup.ec.europa.eu/software/page/eupl
 */

declare(strict_types=1);

namespace SimplyIn\Auth;

if (!defined('_PS_VERSION_')) {
    exit;
}

/**
 * Inbound payment-webhook HMAC verifier, compatible with the backend and the other shop-plugin
 * receivers. Verifies the `x-simplyin-webhook-signature` header against the request body and the
 * `x-simplyin-webhook-timestamp` header using the per-shop signing secret.
 *
 * This verification method, the header names, and the replay window are a fixed contract shared
 * with the backend and the other Simply.IN plugins — must stay identical everywhere.
 *
 * Pure and side-effect free so it can be unit-tested in isolation.
 */
final class WebhookSignatureVerifier
{
    /** Replay window in seconds (±) around the signed timestamp. */
    private const FRESHNESS_WINDOW_SECONDS = 900;

    /**
     * Verify a webhook signature.
     *
     * @param string $rawBody   exact request body bytes (before json_decode)
     * @param string $timestamp value of the x-simplyin-webhook-timestamp header
     * @param string $signature value of the x-simplyin-webhook-signature header (hex)
     * @param string $secret    decrypted per-shop signing secret
     */
    public function verify(string $rawBody, string $timestamp, string $signature, string $secret): bool
    {
        if ($secret === '' || $signature === '' || $timestamp === '') {
            return false;
        }

        // Signature must be a 64-char SHA-256 hex digest. Normalize case before comparison:
        // hash_equals() is case-sensitive while hash_hmac() emits lowercase.
        if (strlen($signature) !== 64 || !ctype_xdigit($signature)) {
            return false;
        }
        $signature = strtolower($signature);

        // Timestamp must be a plain integer string — the exact bytes the HMAC was computed over.
        if (!ctype_digit($timestamp) || strlen($timestamp) > 20) {
            return false;
        }
        if (abs(time() - (int) $timestamp) > self::FRESHNESS_WINDOW_SECONDS) {
            return false;
        }

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

        return hash_equals($expected, $signature);
    }
}
