diff --git a/src/Server.php b/src/Server.php index 55c2de2..5103afa 100644 --- a/src/Server.php +++ b/src/Server.php @@ -53,6 +53,13 @@ class Server */ protected array $events = []; + /** + * Origins whitelist. + * + * @var array + */ + protected array $whitelist = []; + /** * Set worker. * @@ -116,6 +123,7 @@ public function create(string $address, array $context = []): self $this->boot($worker); // Register required events. + $this->onWebsocketConnected(); $this->onDisconnected(); $this->onError(); @@ -153,12 +161,14 @@ public function onConnected(?callable $handler = null): self */ public function onWebsocketConnected(?callable $handler = null): self { - if (!$handler) { - return $this; - } - $this->getWorker()->onWebSocketConnect = function (TcpConnection $connection, string $header) use ($handler) { - call_user_func_array($handler, [new Connection($connection), $header]); + if (count($this->whitelist) > 0 && !in_array($_SERVER['HTTP_ORIGIN'], $this->whitelist)) { + $connection->destroy(); + } + + if ($handler) { + call_user_func_array($handler, [new Connection($connection), $header]); + } }; return $this; @@ -531,4 +541,17 @@ public function log(string|array $text): self return $this; } + + /** + * Add array of origins to whitelist. + * + * @param array $origins + * @return self + */ + public function whitelist(array $origins): self + { + $this->whitelist = $origins; + + return $this; + } } \ No newline at end of file