From b269844bcd1033d02ff3732826c3e7fe7df6d0d2 Mon Sep 17 00:00:00 2001 From: Maxime Rainville Date: Fri, 2 Feb 2024 15:38:25 +1300 Subject: [PATCH] BUG Fix CSP headers by using Requirements API for custom script --- src/Controller.php | 38 ++++++++++++++++++++++++++++++++------ templates/DevTools.ss | 19 +------------------ 2 files changed, 33 insertions(+), 24 deletions(-) diff --git a/src/Controller.php b/src/Controller.php index e501fdc..697cec1 100644 --- a/src/Controller.php +++ b/src/Controller.php @@ -11,6 +11,7 @@ use SilverStripe\Core\Path; use SilverStripe\GraphQL\Schema\Schema; use SilverStripe\Security\SecurityToken; +use SilverStripe\View\Requirements; class Controller extends BaseController { @@ -34,26 +35,51 @@ class Controller extends BaseController public function index(HTTPRequest $request) { $routes = $this->getRoutes(); - $json = null; + $endpoint = sizeof($routes ?? []) === 1 ? $routes[0] : null; + $csrf = SecurityToken::inst()->getValue(); + $tabs = []; if (sizeof($routes ?? []) > 1) { - $tabs = []; foreach ($routes as $route) { $tabs[] = [ 'endpoint' => Director::absoluteURL($route), 'query' => '', 'name' => $route, 'headers' => [ - 'X-CSRF-TOKEN' => SecurityToken::inst()->getValue(), + 'X-CSRF-TOKEN' => $csrf, ] ]; } + } + + $data = [ + 'headers' => [ + 'X-CSRF-TOKEN' => $csrf, + ], + 'endpoint' => $endpoint, + 'settings' => [ + 'request.globalHeaders' => [ + 'X-CSRF-TOKEN' => $csrf, + ], + 'request.credentials' => 'include', + ], + ]; - $json = json_encode($tabs); + if ($tabs) { + $data['tabs'] = $tabs; } + $jsonPayload = json_encode($data); + + Requirements::customScript(<< sizeof($routes ?? []) === 1 ? $routes[0] : null, - 'TabsJSON' => $json, + 'Endpoint' => $endpoint, + 'TabsJSON' => $tabs ? json_encode($tabs): null, ]; } diff --git a/templates/DevTools.ss b/templates/DevTools.ss index bf41d6d..8008f48 100644 --- a/templates/DevTools.ss +++ b/templates/DevTools.ss @@ -7,7 +7,7 @@ GraphQL IDE | Silverstripe CMS <% require javascript('silverstripe/graphql-devtools: client/bundle.js') %> - +