| 1 | 1 |
new file mode 100644 |
| ... | ... |
@@ -0,0 +1,62 @@ |
| 1 |
+<?php |
|
| 2 |
+ |
|
| 3 |
+namespace Telnyx; |
|
| 4 |
+ |
|
| 5 |
+abstract class WebhookSignature |
|
| 6 |
+{
|
|
| 7 |
+ /** |
|
| 8 |
+ * Verifies the signature header sent by Telnyx. Throws an |
|
| 9 |
+ * Exception\SignatureVerificationException exception if the verification fails for |
|
| 10 |
+ * any reason. |
|
| 11 |
+ * |
|
| 12 |
+ * @param string $payload the payload sent by Telnyx |
|
| 13 |
+ * @param string $header the contents of the signature header sent by |
|
| 14 |
+ * Telnyx |
|
| 15 |
+ * @param string $public_key secret used to generate the signature |
|
| 16 |
+ * @param int $tolerance maximum difference allowed between the header's |
|
| 17 |
+ * timestamp and the current time |
|
| 18 |
+ * |
|
| 19 |
+ * @throws Exception\SignatureVerificationException if the verification fails |
|
| 20 |
+ * |
|
| 21 |
+ * @return bool |
|
| 22 |
+ */ |
|
| 23 |
+ public static function verifyHeader($payload, $signature_header, $timestamp, $public_key = '', $tolerance = null) |
|
| 24 |
+ {
|
|
| 25 |
+ // Typecast timestamp to int for comparisons |
|
| 26 |
+ $timestamp = (int)$timestamp; |
|
| 27 |
+ |
|
| 28 |
+ // If it is empty, then maybe we need to get the $public_key from the Telnyx object. |
|
| 29 |
+ if (empty($public_key)) {
|
|
| 30 |
+ $my_public_key = Telnyx::$publicKey; |
|
| 31 |
+ } |
|
| 32 |
+ else {
|
|
| 33 |
+ $my_public_key = $public_key; |
|
| 34 |
+ } |
|
| 35 |
+ |
|
| 36 |
+ // Check if timestamp is within tolerance |
|
| 37 |
+ if (($tolerance > 0) && (\abs(\time() - $timestamp) > $tolerance)) {
|
|
| 38 |
+ throw Exception\SignatureVerificationException::factory( |
|
| 39 |
+ 'Timestamp outside the tolerance zone', |
|
| 40 |
+ $payload, |
|
| 41 |
+ $signature_header |
|
| 42 |
+ ); |
|
| 43 |
+ } |
|
| 44 |
+ |
|
| 45 |
+ // Convert base64 string to bytes for sodium crypto functions |
|
| 46 |
+ $public_key_bytes = base64_decode($my_public_key); |
|
| 47 |
+ $signature_header_bytes = base64_decode($signature_header); |
|
| 48 |
+ |
|
| 49 |
+ // Construct a message to test against the signature header using the timestamp and payload |
|
| 50 |
+ $signed_payload = $timestamp . '|' . $payload; |
|
| 51 |
+ |
|
| 52 |
+ if (!\sodium_crypto_sign_verify_detached($signature_header_bytes, $signed_payload, $public_key_bytes)) {
|
|
| 53 |
+ throw Exception\SignatureVerificationException::factory( |
|
| 54 |
+ 'Signature is invalid and does not match the payload', |
|
| 55 |
+ $payload, |
|
| 56 |
+ $signature_header |
|
| 57 |
+ ); |
|
| 58 |
+ } |
|
| 59 |
+ |
|
| 60 |
+ return true; |
|
| 61 |
+ } |
|
| 62 |
+} |