From b3dcfbc369dad987cc4870fb64c0ddd4310526f1 Mon Sep 17 00:00:00 2001 From: Siebe Vanden Eynden Date: Wed, 13 Mar 2024 11:43:25 +0100 Subject: [PATCH] Add API for caddy domain check --- app/Server/Factory.php | 13 +++- .../Controllers/ValidateTunnelController.php | 63 +++++++++++++++++++ 2 files changed, 75 insertions(+), 1 deletion(-) create mode 100644 app/Server/Http/Controllers/ValidateTunnelController.php diff --git a/app/Server/Factory.php b/app/Server/Factory.php index 35e3e3b..f3e0fee 100644 --- a/app/Server/Factory.php +++ b/app/Server/Factory.php @@ -38,6 +38,7 @@ use App\Server\Http\Controllers\Admin\StoreUsersController; use App\Server\Http\Controllers\ControlMessageController; use App\Server\Http\Controllers\TunnelMessageController; +use App\Server\Http\Controllers\ValidateTunnelController; use App\Server\Http\Router; use App\Server\LoggerRepository\NullLogger; use App\Server\StatisticsCollector\DatabaseStatisticsCollector; @@ -166,6 +167,15 @@ protected function addAdminRoutes() $this->router->get('/api/tcp', GetTcpConnectionsController::class, $adminCondition); $this->router->delete('/api/tcp/{id}', DisconnectTcpConnectionController::class, $adminCondition); + + return $this; + } + + protected function addValidateTunnel() + { + $this->router->get('/validate-tunnel', ValidateTunnelController::class); + + return $this; } protected function bindConfiguration() @@ -209,7 +219,8 @@ public function createServer() ->ensureDatabaseIsInitialized() ->registerStatisticsCollector() ->bindConnectionManager() - ->addAdminRoutes(); + ->addAdminRoutes() + ->addValidateTunnel(); $controlConnection = $this->addControlConnectionRoute(); diff --git a/app/Server/Http/Controllers/ValidateTunnelController.php b/app/Server/Http/Controllers/ValidateTunnelController.php new file mode 100644 index 0000000..d29ed91 --- /dev/null +++ b/app/Server/Http/Controllers/ValidateTunnelController.php @@ -0,0 +1,63 @@ +connectionManager = $connectionManager; + } + + public function handle(Request $request, ConnectionInterface $httpConnection) + { + $domain = $request->get('domain'); + if ($domain === null) { + $httpConnection->send( + respond_json(['exists' => false, 'error' => 'invalid_domain'], 404), + ); + + return; + } + + /** @var Collection $sites */ + $sites = collect($this->connectionManager->getConnections()) + ->filter(function ($site) use ($domain) { + $isControlConnection = get_class($site) === ControlConnection::class; + if (! $isControlConnection) { + return false; + } + + + $fqdn = sprintf( + '%s.%s', + $site->subdomain, + $site->serverHost, + ); + return $fqdn === $domain; + }) + ->map(function (ControlConnection $site) { + return sprintf( + '%s.%s', + $site->host, + $site->subdomain, + ); + }); + + $response = $sites->count() === 0 + ? respond_json(['exists' => false, 'error' => 'no_tunnel_found'], 404) + : respond_json(['exists' => true, 'sites' => $sites->toArray()]); + + $httpConnection->send($response); + } +}