| 1: | <?php |
| 2: | |
| 3: | declare(strict_types=1); |
| 4: | |
| 5: | |
| 6: | |
| 7: | |
| 8: | |
| 9: | |
| 10: | |
| 11: | |
| 12: | |
| 13: | |
| 14: | namespace Nexus\Mcp\Server; |
| 15: | |
| 16: | use Nexus\Assert\Assert; |
| 17: | |
| 18: | |
| 19: | |
| 20: | |
| 21: | |
| 22: | |
| 23: | |
| 24: | |
| 25: | |
| 26: | final readonly class RequestStateSigner |
| 27: | { |
| 28: | |
| 29: | |
| 30: | |
| 31: | |
| 32: | private const string SEPARATOR = '.'; |
| 33: | |
| 34: | |
| 35: | |
| 36: | |
| 37: | private const int SECRET_BYTES = 32; |
| 38: | |
| 39: | |
| 40: | |
| 41: | |
| 42: | public function __construct(private string $secret, private string $algorithm = 'sha256') |
| 43: | { |
| 44: | Assert::that($secret)->isNonEmptyString('The request-state signing secret must be a non-empty string.'); |
| 45: | Assert::that(\in_array($algorithm, hash_hmac_algos(), true))->isTrue( |
| 46: | \sprintf('The request-state signing algorithm "%s" is not available.', $algorithm), |
| 47: | ); |
| 48: | } |
| 49: | |
| 50: | |
| 51: | |
| 52: | |
| 53: | |
| 54: | public static function generate(): self |
| 55: | { |
| 56: | return new self(bin2hex(random_bytes(self::SECRET_BYTES))); |
| 57: | } |
| 58: | |
| 59: | public function sign(string $payload): string |
| 60: | { |
| 61: | return $payload.self::SEPARATOR.hash_hmac($this->algorithm, $payload, $this->secret); |
| 62: | } |
| 63: | |
| 64: | |
| 65: | |
| 66: | |
| 67: | |
| 68: | public function verify(string $state): ?string |
| 69: | { |
| 70: | $split = strrpos($state, self::SEPARATOR); |
| 71: | |
| 72: | if (false === $split) { |
| 73: | return null; |
| 74: | } |
| 75: | |
| 76: | $payload = substr($state, 0, $split); |
| 77: | |
| 78: | return hash_equals($this->sign($payload), $state) ? $payload : null; |
| 79: | } |
| 80: | } |
| 81: | |