Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
97.73% |
43 / 44 |
|
80.00% |
4 / 5 |
CRAP | |
0.00% |
0 / 1 |
| Webhooks | |
97.73% |
43 / 44 |
|
80.00% |
4 / 5 |
22 | |
0.00% |
0 / 1 |
| __construct | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| fromConfig | |
100.00% |
10 / 10 |
|
100.00% |
1 / 1 |
3 | |||
| record | |
100.00% |
18 / 18 |
|
100.00% |
1 / 1 |
4 | |||
| subscribes | |
100.00% |
7 / 7 |
|
100.00% |
1 / 1 |
6 | |||
| hook | |
87.50% |
7 / 8 |
|
0.00% |
0 / 1 |
8.12 | |||
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace Cosray; |
| 6 | |
| 7 | use Celema\Quma\Database; |
| 8 | use Closure; |
| 9 | use Cosray\Exception\RuntimeException; |
| 10 | use Cosray\Webhooks\Delivery; |
| 11 | |
| 12 | /** |
| 13 | * Tells other systems that content changed, such as a static site build or a |
| 14 | * cache in front of the API. Each event queues one delivery job per hook, |
| 15 | * which retries a failed POST. The jobs are pushed inside the write's |
| 16 | * transaction, so they exist only if the write commits, whether it happens |
| 17 | * in a request, a job or a command. |
| 18 | * |
| 19 | * 'webhooks' => [ |
| 20 | * ['url' => 'https://build.example.com/hook', 'secret' => $secret, 'events' => ['node.*']], |
| 21 | * ], |
| 22 | * |
| 23 | * Events are `node.created`, `node.updated` (a live write, publishing and |
| 24 | * unpublishing included), `node.draft` (a working copy saved or dropped) and |
| 25 | * `node.deleted`. The body holds `id`, `event`, `at` and the node's `uid` and |
| 26 | * `type`; with a secret, `X-Cosray-Signature` carries `sha256=` and the |
| 27 | * HMAC-SHA256 of the body. |
| 28 | */ |
| 29 | final class Webhooks |
| 30 | { |
| 31 | public const string USER_AGENT = 'cosray-webhooks'; |
| 32 | |
| 33 | /** @var list<array{url: string, secret: ?string, events: list<string>}> */ |
| 34 | private readonly array $hooks; |
| 35 | |
| 36 | /** |
| 37 | * @param list<array{url: string, secret?: ?string, events?: list<string>}> $hooks |
| 38 | * @param Closure(array{url: string, headers: array<string, string>, body: string}): void $queue |
| 39 | * queues the delivery of one request |
| 40 | */ |
| 41 | public function __construct( |
| 42 | array $hooks, |
| 43 | private readonly Closure $queue, |
| 44 | ) { |
| 45 | $this->hooks = array_map(self::hook(...), $hooks); |
| 46 | } |
| 47 | |
| 48 | public static function fromConfig(Config $config, Database $db): self |
| 49 | { |
| 50 | $hooks = $config->get('webhooks', []); |
| 51 | |
| 52 | if (!is_array($hooks) || !array_is_list($hooks)) { |
| 53 | throw new RuntimeException('`webhooks` takes a list of hooks.'); |
| 54 | } |
| 55 | |
| 56 | $queue = new Queue($db); |
| 57 | |
| 58 | /** @var list<array{url: string, secret?: ?string, events?: list<string>}> $hooks */ |
| 59 | return new self( |
| 60 | $hooks, |
| 61 | static function (array $request) use ($queue): void { |
| 62 | $queue->push(Delivery::class, $request, queue: 'webhooks'); |
| 63 | }, |
| 64 | ); |
| 65 | } |
| 66 | |
| 67 | /** |
| 68 | * Queues the deliveries of an event on the write's connection. |
| 69 | * |
| 70 | * @param array<string, mixed> $data |
| 71 | */ |
| 72 | public function record(string $event, array $data): void |
| 73 | { |
| 74 | $id = bin2hex(random_bytes(16)); |
| 75 | $body = null; |
| 76 | |
| 77 | foreach ($this->hooks as $hook) { |
| 78 | if (!self::subscribes($hook['events'], $event)) { |
| 79 | continue; |
| 80 | } |
| 81 | |
| 82 | $body ??= json_encode( |
| 83 | ['id' => $id, 'event' => $event, 'at' => gmdate('Y-m-d\TH:i:s\Z'), ...$data], |
| 84 | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR, |
| 85 | ); |
| 86 | $headers = [ |
| 87 | 'Content-Type' => 'application/json', |
| 88 | 'User-Agent' => self::USER_AGENT, |
| 89 | 'X-Cosray-Event' => $event, |
| 90 | 'X-Cosray-Delivery' => $id, |
| 91 | ]; |
| 92 | |
| 93 | if ($hook['secret'] !== null) { |
| 94 | $headers['X-Cosray-Signature'] = 'sha256=' . hash_hmac('sha256', $body, $hook['secret']); |
| 95 | } |
| 96 | |
| 97 | ($this->queue)(['url' => $hook['url'], 'headers' => $headers, 'body' => $body]); |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | /** @param list<string> $patterns */ |
| 102 | private static function subscribes(array $patterns, string $event): bool |
| 103 | { |
| 104 | foreach ($patterns as $pattern) { |
| 105 | if ( |
| 106 | $pattern === '*' |
| 107 | || $pattern === $event |
| 108 | || str_ends_with($pattern, '.*') |
| 109 | && str_starts_with($event, substr($pattern, 0, -1)) |
| 110 | ) { |
| 111 | return true; |
| 112 | } |
| 113 | } |
| 114 | |
| 115 | return false; |
| 116 | } |
| 117 | |
| 118 | /** @return array{url: string, secret: ?string, events: list<string>} */ |
| 119 | private static function hook(mixed $hook): array |
| 120 | { |
| 121 | $url = is_array($hook) ? $hook['url'] ?? null : null; |
| 122 | |
| 123 | if (!is_string($url) || preg_match('#^https?://#i', $url) !== 1) { |
| 124 | throw new RuntimeException('A webhook needs an http or https `url`.'); |
| 125 | } |
| 126 | |
| 127 | $secret = $hook['secret'] ?? null; |
| 128 | $events = $hook['events'] ?? ['*']; |
| 129 | |
| 130 | if ($secret !== null && !is_string($secret) || !is_array($events) || !array_is_list($events)) { |
| 131 | throw new RuntimeException("The webhook for {$url} takes a string `secret` and a list of `events`."); |
| 132 | } |
| 133 | |
| 134 | return ['url' => $url, 'secret' => $secret, 'events' => array_values(array_filter($events, is_string(...)))]; |
| 135 | } |
| 136 | } |