CSP script-src settings reject inline-scripts in wordpress

Presently i have: function add_csp_header() { $csp = "script-src 'nonce-".custom_nonce_value()."'"; //and some more header("X-Content-Type-Options: nosniff"); header("Referrer-Policy: strict-origin-when-cross-origin"); header("Content-Security-Policy: $csp"); } add_action('send_headers', 'add_csp_header'); In the console i get several error messages saying: Content-Security-Policy: the settings of the page have blocked loading a ressource on inline ("script-src"). The inline scripts are enqueued with wp_localize_script() like this: wp_register_script( 'dibujos', get_stylesheet_directory_uri() . '/js/dibujos.js', array('jquery'),'1.0.0', true); wp_localize_script( 'dibujos', 'archVar', array( 'url' => get_bloginfo('url') ) ); wp_enqueue_script('dibujos'); To add nonces to inline-scripts i tried the following approaches: function toa_inline_script_nonce( array $attr ): array { if ( empty( $attr['id'] ) ) { return $attr; } if ( 'dibujos' === $attr['id'] ) { $attr['nonce'] = custom_nonce_value(); } return $attr; } add_filter( 'wp_script_attributes', 'toa_inline_script_nonce', 10, 1 ); does nothing, or... //nonce for specific scripts function toa_script_tag_nonce( $tag, $handle ) { if ( $handle === 'jquery' OR $handle === 'admin-bar' OR $handle === 'dibujos' ) { $nonce = custom_nonce_value(); $tag = str_replace( '<script ', '<script nonce="'.$nonce.'"', $tag ); } return $tag; } add_filter( 'script_loader_tag', 'toa_script_tag_nonce', 10, 2 ); This adds nonces for the $handle 'jquery' and 'admin-bar', but ignores 'dibujos'. and lastly... add_filter( 'script_loader_tag', 'add_nonce_to_script_tag', 10, 3 ); function add_nonce_to_script_tag( $tag, $handle, $src ) { // Check the $handle and respond accordingly if ( $handle === 'dibujos' ) { $nonce_value = custom_nonce_value(); $replace = sprintf("javascript' nonce='%s'>", $nonce_value ); $tag = str_replace( "javascript'>", $replace, $tag); } return $tag; } // Then... $data is the inline JS from wherever wp_add_inline_script('dibujos', $data, 'before'); This throws errors: $data is undefined and wp_add_inline_script() shouldn’t be called prior to wp_enqueue_scripts(). Conclusion: All my attempts to catch the script tag and add a nonce attribute failed. Somehow it appears that inline scripts are out of reach...(at least with these approaches) In this post someone says: Since these are echoed and is hard coded you cannot add an attribute to the HTML script elements of wp_localize_script(). According to this statement inline-scripts are a dead-end for a save script-src CSP in wordpress. Despite of this saying, i wonder if this is really the case and if not, how can i add nonces to all inline scripts?

Comment (0)

You’ll be in good company