<?php
class SS_Security {
    public static function init() {}

    // HMAC-SHA256 verification
    public static function verify_hmac_signature(string $method, string $path, int $ts, string $nonce, string $dataJson, string $sigB64Url, string $secret): bool {
        if ($secret === '' || $sigB64Url === '' || $dataJson === '') return false;

        $base = $method . ':' . $path . ':' . $ts . ':' . $nonce . ':' . $dataJson;
        $raw  = hash_hmac('sha256', $base, $secret, true);
        $calc = rtrim(strtr(base64_encode($raw), '+/', '-_'), '=');

        return function_exists('hash_equals') ? hash_equals($calc, $sigB64Url) : $calc === $sigB64Url;
    }

    // Ed25519 (optional)
    public static function verify_signature($payload_json, $signature_b64, $pubkey_b64){
        if (!$payload_json || !$signature_b64 || !$pubkey_b64) return false;
        if (function_exists('sodium_crypto_sign_verify_detached')){
            $sig = base64_decode($signature_b64, true);
            $pk  = base64_decode($pubkey_b64, true);
            if ($sig && $pk) {
                return sodium_crypto_sign_verify_detached($sig, $payload_json, $pk);
            }
            return false;
        }
        if (function_exists('openssl_verify')){
            $pem = base64_decode($pubkey_b64, true);
            $sig = base64_decode($signature_b64, true);
            if ($pem && $sig) {
                $algo = defined('OPENSSL_ALGO_SHA256') ? OPENSSL_ALGO_SHA256 : 0;
                return openssl_verify($payload_json, $sig, $pem, $algo) === 1;
            }
        }
        return false;
    }
}
