| 1 |
<?php |
| 2 |
|
| 3 |
namespace IvyForms\Services\Payment; |
| 4 |
|
| 5 |
/** |
| 6 |
* Appends payment-provider hosts to an existing Content-Security-Policy. |
| 7 |
* |
| 8 |
* A plugin must not emit a standalone CSP — that would lock the rest of the site. |
| 9 |
*/ |
| 10 |
class PaymentCspHeaders |
| 11 |
{ |
| 12 |
private const SOURCES = [ |
| 13 |
'https://web.squarecdn.com', |
| 14 |
'https://sandbox.web.squarecdn.com', |
| 15 |
'https://pci-connect.squareup.com', |
| 16 |
'https://pci-connect.squareupsandbox.com', |
| 17 |
'https://connect.squareup.com', |
| 18 |
'https://connect.squareupsandbox.com', |
| 19 |
'https://js.stripe.com', |
| 20 |
'https://hooks.stripe.com', |
| 21 |
'https://api.stripe.com', |
| 22 |
'https://www.paypal.com', |
| 23 |
'https://www.sandbox.paypal.com', |
| 24 |
'https://www.paypalobjects.com', |
| 25 |
]; |
| 26 |
|
| 27 |
public static function register(): void |
| 28 |
{ |
| 29 |
add_filter('wp_headers', [self::class, 'appendSources']); |
| 30 |
} |
| 31 |
|
| 32 |
/** |
| 33 |
* @param array<string, mixed> $headers |
| 34 |
* @return array<string, mixed> |
| 35 |
*/ |
| 36 |
public static function appendSources(array $headers): array |
| 37 |
{ |
| 38 |
$extra = implode(' ', self::SOURCES); |
| 39 |
|
| 40 |
foreach (['Content-Security-Policy', 'Content-Security-Policy-Report-Only'] as $name) { |
| 41 |
if (empty($headers[$name]) || !is_string($headers[$name])) { |
| 42 |
continue; |
| 43 |
} |
| 44 |
$headers[$name] = self::appendToPolicy($headers[$name], $extra); |
| 45 |
} |
| 46 |
|
| 47 |
return $headers; |
| 48 |
} |
| 49 |
|
| 50 |
private static function appendToPolicy(string $policy, string $extra): string |
| 51 |
{ |
| 52 |
foreach (['script-src', 'frame-src', 'connect-src', 'child-src'] as $directive) { |
| 53 |
if (!preg_match('/' . preg_quote($directive, '/') . '\s/i', $policy)) { |
| 54 |
continue; |
| 55 |
} |
| 56 |
$policy = preg_replace( |
| 57 |
'/' . preg_quote($directive, '/') . '\s([^;]*)/i', |
| 58 |
$directive . ' $1 ' . $extra, |
| 59 |
$policy, |
| 60 |
1 |
| 61 |
) ?? $policy; |
| 62 |
} |
| 63 |
|
| 64 |
return $policy; |
| 65 |
} |
| 66 |
} |
| 67 |
|