| 1 |
<?php |
| 2 |
|
| 3 |
namespace IvyForms\Services\Integrations; |
| 4 |
|
| 5 |
/** |
| 6 |
* Signs outbound requests from WordPress to ivyforms-middleware. |
| 7 |
* |
| 8 |
* Canonical HMAC matches MiddlewareAuthService: timestamp, nonce, method, path, body. |
| 9 |
*/ |
| 10 |
class MiddlewareRequestAuthService |
| 11 |
{ |
| 12 |
public function signRequestBody(string $body): string |
| 13 |
{ |
| 14 |
$secret = $this->sharedSecret(); |
| 15 |
if ($secret === '') { |
| 16 |
return ''; |
| 17 |
} |
| 18 |
|
| 19 |
return hash_hmac('sha256', $body, $secret); |
| 20 |
} |
| 21 |
|
| 22 |
/** |
| 23 |
* @return array<string, string> |
| 24 |
*/ |
| 25 |
public function buildSignedHeaders(string $body, string $url = '', string $method = 'POST'): array |
| 26 |
{ |
| 27 |
$secret = $this->sharedSecret(); |
| 28 |
$path = $this->requestPath($url); |
| 29 |
if ($secret === '' || $path === '') { |
| 30 |
return ['Content-Type' => 'application/json']; |
| 31 |
} |
| 32 |
|
| 33 |
$timestamp = (string) time(); |
| 34 |
$nonce = wp_generate_password(32, false, false); |
| 35 |
$canonicalRequest = implode( |
| 36 |
"\n", |
| 37 |
[ |
| 38 |
$timestamp, |
| 39 |
$nonce, |
| 40 |
strtoupper($method), |
| 41 |
$path, |
| 42 |
$body, |
| 43 |
] |
| 44 |
); |
| 45 |
|
| 46 |
return [ |
| 47 |
'Content-Type' => 'application/json', |
| 48 |
'X-IvyForms-Signature' => hash_hmac('sha256', $canonicalRequest, $secret), |
| 49 |
'X-IvyForms-Timestamp' => $timestamp, |
| 50 |
'X-IvyForms-Nonce' => $nonce, |
| 51 |
]; |
| 52 |
} |
| 53 |
|
| 54 |
private function sharedSecret(): string |
| 55 |
{ |
| 56 |
return defined('IVYFORMS_MIDDLEWARE_SHARED_SECRET') |
| 57 |
? trim((string) IVYFORMS_MIDDLEWARE_SHARED_SECRET) |
| 58 |
: ''; |
| 59 |
} |
| 60 |
|
| 61 |
private function requestPath(string $url): string |
| 62 |
{ |
| 63 |
$path = parse_url($url, PHP_URL_PATH); |
| 64 |
|
| 65 |
return is_string($path) && $path !== '' ? $path : ''; |
| 66 |
} |
| 67 |
} |
| 68 |
|