styleNonce)) { throw new RuntimeException('No nonce set for CSS'); } $response->setHeader('Content-Security-Policy', "style-src 'self' 'nonce-$csp->styleNonce';", true); } /** * Set/recreate nonce for dynamic CSS * * Should always be called upon initial page loads or page reloads, * as it sets/recreates a nonce for CSS and writes it to a window-aware session. */ public static function createNonce(): void { $csp = static::getInstance(); $csp->styleNonce = base64_encode(random_bytes(16)); Window::getInstance()->getSessionNamespace('csp')->set('style_nonce', $csp->styleNonce); } /** * Get nonce for dynamic CSS * * @return ?string */ public static function getStyleNonce(): ?string { return static::getInstance()->styleNonce; } /** * Get the CSP instance * * @return self */ protected static function getInstance(): self { if (static::$instance === null) { $csp = new static(); $nonce = Window::getInstance()->getSessionNamespace('csp')->get('style_nonce'); if ($nonce !== null && ! is_string($nonce)) { throw new RuntimeException( sprintf( 'Nonce value is expected to be string, got %s instead', get_php_type($nonce) ) ); } $csp->styleNonce = $nonce; static::$instance = $csp; } return static::$instance; } }