2020-10-19 21:43:33 +00:00
|
|
|
<?php
|
|
|
|
|
2020-10-20 21:13:48 +00:00
|
|
|
namespace Alltube\Middleware;
|
2020-10-19 21:43:33 +00:00
|
|
|
|
2020-10-20 21:13:48 +00:00
|
|
|
use Alltube\Config;
|
2020-10-19 21:43:33 +00:00
|
|
|
use ParagonIE\CSPBuilder\CSPBuilder;
|
|
|
|
use Psr\Container\ContainerInterface;
|
|
|
|
use Psr\Http\Message\MessageInterface;
|
|
|
|
use Slim\Http\Request;
|
|
|
|
use Slim\Http\Response;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Class CspMiddleware
|
|
|
|
* @package Alltube
|
|
|
|
*/
|
|
|
|
class CspMiddleware
|
|
|
|
{
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @var Config
|
|
|
|
*/
|
|
|
|
private $config;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* CspMiddleware constructor.
|
|
|
|
* @param ContainerInterface $container
|
|
|
|
*/
|
|
|
|
public function __construct(ContainerInterface $container)
|
|
|
|
{
|
|
|
|
$this->config = $container->get('config');
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param Response $response
|
|
|
|
* @return MessageInterface
|
|
|
|
*/
|
|
|
|
public function applyHeader(Response $response)
|
|
|
|
{
|
|
|
|
$csp = new CSPBuilder();
|
|
|
|
$csp->addDirective('default-src', [])
|
|
|
|
->addDirective('font-src', ['self' => true])
|
|
|
|
->addDirective('style-src', ['self' => true])
|
2020-10-20 21:32:16 +00:00
|
|
|
->addDirective('manifest-src', ['self' => true])
|
2020-10-19 22:57:26 +00:00
|
|
|
->addDirective('base-uri', [])
|
|
|
|
->addDirective('frame-ancestors', [])
|
2020-11-04 22:03:39 +00:00
|
|
|
->addSource('form-action', '*')
|
2020-10-19 21:43:33 +00:00
|
|
|
->addSource('img-src', '*');
|
|
|
|
|
|
|
|
if ($this->config->debug) {
|
|
|
|
// So symfony/debug and symfony/error-handler can work.
|
|
|
|
$csp->setDirective('script-src', ['unsafe-inline' => true])
|
|
|
|
->setDirective('style-src', ['self' => true, 'unsafe-inline' => true]);
|
|
|
|
}
|
|
|
|
|
|
|
|
return $csp->injectCSPHeader($response);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param Request $request
|
|
|
|
* @param Response $response
|
|
|
|
* @param callable $next
|
|
|
|
* @return mixed
|
|
|
|
*/
|
|
|
|
public function __invoke(Request $request, Response $response, callable $next)
|
|
|
|
{
|
|
|
|
$response = $this->applyHeader($response);
|
|
|
|
|
|
|
|
return $next($request, $response);
|
|
|
|
}
|
|
|
|
}
|