Skip to content

Commit

Permalink
feat: add origins whitelist
Browse files Browse the repository at this point in the history
  • Loading branch information
chipslays committed Feb 17, 2023
1 parent ec94158 commit bd1f431
Showing 1 changed file with 28 additions and 5 deletions.
33 changes: 28 additions & 5 deletions src/Server.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,13 @@ class Server
*/
protected array $events = [];

/**
* Origins whitelist.
*
* @var array
*/
protected array $whitelist = [];

/**
* Set worker.
*
Expand Down Expand Up @@ -116,6 +123,7 @@ public function create(string $address, array $context = []): self
$this->boot($worker);

// Register required events.
$this->onWebsocketConnected();
$this->onDisconnected();
$this->onError();

Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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;
}
}

0 comments on commit bd1f431

Please sign in to comment.