Opened 3 years ago
Last modified 4 days ago
#59446 accepted defect (bug)
Use script helper functions in admin to enable Content-Security-Policy opt-in
| Reported by: | westonruter | Owned by: | westonruter |
|---|---|---|---|
| Priority: | normal | Milestone: | 7.3 |
| Component: | Administration | Version: | 5.7 |
| Severity: | normal | Keywords: | has-patch has-unit-tests |
| Cc: | Focuses: | javascript |
Description (last modified by )
In #58664 the script helper functions—wp_get_script_tag(), wp_print_inline_script_tag(), wp_get_inline_script_tag()—were leveraged to eliminate manual construction of script tags on the frontend and the login screen. These were introduced in #39941. This made it possible to opt-in (see example plugin) to a Strict Content-Security-Policy (Strict CSP) to guard against any possible XSS exploits. The scope in #58664 was limited to the frontend and the login screen because of the sheer number of inline scripts printed on the wp-admin. Additionally, the site editor and block editors make use of dynamically-constructed script tags in the editor iframe which is a Strict CSP violation.
Much of the work to rework inline scripts to use wp_print_inline_script() in the admin can be seen in an existing PR (now stale) from @enricocarraro.
See also #59444 which is about how to improve the developer experience of working with these JavaScript string literals.
Change History (53)
This ticket was mentioned in Slack in #core-performance by westonruter. View the logs.
3 years ago
#3
in reply to: ↑ 2
;
follow-up:
↓ 4
@
3 years ago
Replying to bedas:
Can I ask a clarification? I am confused on the "version" of this trac
It says 5.7 and the selector only allows up to 5.7.2
Good question. The version field here refers to when the first applicable version of WordPress that the issue is relevant to. Since the functions were introduced in 5.7, that's why this version is used.
The target version for fixing the issue is captured in the "milestone" field, which is still just Future Release. There isn't currently an established way to opt-in to CSP for the backend, so that's what this ticket is for.
#4
in reply to: ↑ 3
;
follow-up:
↓ 5
@
3 years ago
Replying to westonruter:
Thanks! Makes sense now.
I guess then there is some issue with wp_inline_script_attributes, because if it is intended for front end, then it shouldn't run in the backend - but does, and misses the array key type in that case.
I also notice that the documentation for the related wp_get_inline_script_tag is wrongly saying to use wp_script_attributes to filter the tags.
I guess I will open a commit/trac for the latter one and, should I open a trac for the first one? the very least we would need to specify on the doc page that this needs to be hooked explicitly to front end, or that an isset() should be run (which IMO is quite uncommon for filters/hooks, usually they run only where the data is available)
Finally, what about style tag? This is as far I see also not yet implemented (neither in the front nor in the backend)
Is there already a trac for that?
Please stop me if I am wrong. Thanks!
#5
in reply to: ↑ 4
@
3 years ago
Replying to bedas:
Replying to westonruter:
I guess then there is some issue withwp_inline_script_attributes, because if it is intended for front end, then it shouldn't run in the backend - but does, and misses the array keytypein that case. [...] the very least we would need to specify on the doc page that this needs to be hooked explicitly to front end, or that an isset() should be run (which IMO is quite uncommon for filters/hooks, usually they run only where the data is available)
This filter is not specific for the frontend. It is intended to be used in any context, whether frontend or admin. The type array key is only supplied automatically if the page is not HTML5. So yes, an isset() check should always be done for $attributes['type']. If it is not set, then it is assumed to be text/javascript, per the HTML spec.
I also notice that the documentation for the related
wp_get_inline_script_tagis wrongly saying to usewp_script_attributesto filter the tags.
Good catch. The phpdoc for wp_get_inline_script_tag() needs to be updated.
This ticket was mentioned in PR #9416 on WordPress/wordpress-develop by @debarghyabanerjee.
15 months ago
#7
- Keywords has-patch added; needs-patch removed
Trac Ticket: Core-63806
This pull request updates all inline script outputs in the bundled themes to use WordPress’s script helper functions, specifically wp_print_inline_script_tag(), in place of manually constructed <script> tags.
---
## ✅ Why This Matters
As of #59446, WordPress Core has adopted the use of wp_get_script_tag(), wp_get_inline_script_tag(), and wp_print_inline_script_tag() to eliminate manually constructed <script> tags. This change was made to:
However, many default and third-party themes still use raw <script> tags, which prevents them from fully benefiting from these improvements.
---
## 🛠 What’s Changed
- Replaced all instances of echo
'<script>...</script>'with calls towp_print_inline_script_tag().
---
## 🔙 Backward Compatibility
Since these helper functions were introduced in WordPress 5.7+, this PR also includes polyfill definitions in functions.php to ensure compatibility with earlier WordPress versions.
The polyfills conditionally define wp_print_inline_script_tag() and wp_get_inline_script_tag() functions only if they don’t already exist, making it safe for all supported versions.
@westonruter commented on PR #9416:
14 months ago
#9
@Debarghya-Banerjee Hello! Have you seen the latest PR feedback yet?
Also, note the comment I just added to the ticket, related the changes to Core-63887.
@debarghyabanerjee commented on PR #9416:
14 months ago
#10
Hi @westonruter , I have checked the comments and feedback, I am working on it, and will push the changes in sometime by today itself. Thanks.
@debarghyabanerjee commented on PR #9416:
14 months ago
#11
Hi @westonruter , Apologies for the late update. I’ve pushed the changes based on your and @sabernhardt 's feedback. Could you please take a look? Thanks!
@westonruter commented on PR #9416:
14 months ago
#12
@Debarghya-Banerjee Are you planning to address the remaining feedback or should we start pushing up commits to this PR? Thanks!
@debarghyabanerjee commented on PR #9416:
14 months ago
#13
Hi @westonruter , I have addressed the feedback. Sorry for getting back late. Can you please check once? Thanks.
@westonruter commented on PR #9416:
13 months ago
#14
I wrote a script that checked the output of rendered output of the homepages for each of the themes to verify that there were no regressions in the generated markup, and that only the expected changes occur:
<details><summary><code>grab-output.sh</code></summary>
#!/bin/bash
outdir=/tmp/trac-63806-output
mkdir -p "$outdir"
echo '' > "$outdir/report.md"
check_theme() {
theme="$1"
url="$2"
theme_dir="/tmp/trac-63806-output/$1"
echo "# $theme" >> "$outdir/report.md"
mkdir -p "$theme_dir"
npm run env:cli theme activate "$theme"
git checkout trunk
curl -s "$url" > "$theme_dir/before.html"
git checkout fix/63806-update-themes-to-use-wp_print_script_tag
curl -s "$url" > "$theme_dir/after.html"
prettier "$theme_dir/before.html" > "$theme_dir/before.prettier.html"
prettier "$theme_dir/after.html" > "$theme_dir/after.prettier.html"
diff -u "$theme_dir/before.html" "$theme_dir/after.html" > "$theme_dir/raw.diff"
diff -u "$theme_dir/before.prettier.html" "$theme_dir/after.prettier.html" > "$theme_dir/prettier.diff"
{
echo "URL: \`$url\`"
echo
echo 'Prettier Diff:'
echo '{{{diff'
cat "$theme_dir/prettier.diff"
echo '}}}'
echo
echo '<details><summary>Raw Diff</summary>'
echo
echo '{{{diff'
cat "$theme_dir/raw.diff"
echo '}}}'
echo
echo '</details>'
echo
} >> "$outdir/report.md"
}
home_url="http://localhost:8000/?enable_plugins=none"
check_theme twentyfifteen "$home_url"
check_theme twentyseventeen "$home_url"
check_theme twentysixteen "$home_url"
check_theme twentytwenty "$home_url"
check_theme twentytwentyone "$home_url"
cat "$outdir/report.md"
</details>
Here is the output:
# twentyfifteen
URL: http://localhost:8000/?enable_plugins=none
Prettier Diff:
-
/tmp/trac-63806-output/twentyfifteen/
old new 9 9 (function (html) { 10 10 html.className = html.className.replace(/\bno-js\b/, "js"); 11 11 })(document.documentElement); 12 //# sourceURL=twentyfifteen_javascript_detection 12 13 </script> 13 14 <title>WordPress Develop</title> 14 15 <meta name="robots" content="max-image-preview:large" />
<details><summary>Raw Diff</summary>
-
/tmp/trac-63806-output/twentyfifteen/
old new 5 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 6 <link rel="profile" href="https://gmpg.org/xfn/11"> 7 7 <link rel="pingback" href="http://localhost:8000/xmlrpc.php"> 8 <script>(function(html){html.className = html.className.replace(/\bno-js\b/,'js')})(document.documentElement);</script> 8 <script> 9 (function(html){html.className = html.className.replace(/\bno-js\b/,'js')})(document.documentElement); 10 //# sourceURL=twentyfifteen_javascript_detection 11 </script> 9 12 <title>WordPress Develop</title> 10 13 <meta name='robots' content='max-image-preview:large' /> 11 14 <link rel="alternate" type="application/rss+xml" title="WordPress Develop » Feed" href="http://localhost:8000/feed/" />
</details>
# twentyseventeen
URL: http://localhost:8000/?enable_plugins=none
Prettier Diff:
-
/tmp/trac-63806-output/twentyseventeen/
old new 9 9 (function (html) { 10 10 html.className = html.className.replace(/\bno-js\b/, "js"); 11 11 })(document.documentElement); 12 //# sourceURL=twentyseventeen_javascript_detection 12 13 </script> 13 14 <title>WordPress Develop</title> 14 15 <meta name="robots" content="max-image-preview:large" />
<details><summary>Raw Diff</summary>
-
/tmp/trac-63806-output/twentyseventeen/
old new 5 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 6 <link rel="profile" href="https://gmpg.org/xfn/11"> 7 7 8 <script>(function(html){html.className = html.className.replace(/\bno-js\b/,'js')})(document.documentElement);</script> 8 <script> 9 (function(html){html.className = html.className.replace(/\bno-js\b/,'js')})(document.documentElement); 10 //# sourceURL=twentyseventeen_javascript_detection 11 </script> 9 12 <title>WordPress Develop</title> 10 13 <meta name='robots' content='max-image-preview:large' /> 11 14 <link rel="alternate" type="application/rss+xml" title="WordPress Develop » Feed" href="http://localhost:8000/feed/" />
</details>
# twentysixteen
URL: http://localhost:8000/?enable_plugins=none
Prettier Diff:
-
/tmp/trac-63806-output/twentysixteen/
old new 8 8 (function (html) { 9 9 html.className = html.className.replace(/\bno-js\b/, "js"); 10 10 })(document.documentElement); 11 //# sourceURL=twentysixteen_javascript_detection 11 12 </script> 12 13 <title>WordPress Develop</title> 13 14 <meta name="robots" content="max-image-preview:large" />
<details><summary>Raw Diff</summary>
-
/tmp/trac-63806-output/twentysixteen/
old new 4 4 <meta charset="UTF-8"> 5 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 6 <link rel="profile" href="https://gmpg.org/xfn/11"> 7 <script>(function(html){html.className = html.className.replace(/\bno-js\b/,'js')})(document.documentElement);</script> 7 <script> 8 (function(html){html.className = html.className.replace(/\bno-js\b/,'js')})(document.documentElement); 9 //# sourceURL=twentysixteen_javascript_detection 10 </script> 8 11 <title>WordPress Develop</title> 9 12 <meta name='robots' content='max-image-preview:large' /> 10 13 <link rel="alternate" type="application/rss+xml" title="WordPress Develop » Feed" href="http://localhost:8000/feed/" />
</details>
# twentytwenty
URL: http://localhost:8000/?enable_plugins=none
Prettier Diff:
-
/tmp/trac-63806-output/twentytwenty/
old new 618 618 <script> 619 619 document.documentElement.className = 620 620 document.documentElement.className.replace("no-js", "js"); 621 //# sourceURL=twentytwenty_no_js_class 621 622 </script> 622 623 <style id="custom-background-css"> 623 624 body.custom-background {
<details><summary>Raw Diff</summary>
-
/tmp/trac-63806-output/twentytwenty/
old new 78 78 <script src="http://localhost:8000/wp-content/themes/twentytwenty/assets/js/index.js?ver=2.9" id="twentytwenty-js-js" defer data-wp-strategy="defer"></script> 79 79 <link rel="https://api.w.org/" href="http://localhost:8000/wp-json/" /><link rel="EditURI" type="application/rsd+xml" title="RSD" href="http://localhost:8000/xmlrpc.php?rsd" /> 80 80 <meta name="generator" content="WordPress 6.9-alpha-60093-src" /> 81 <script>document.documentElement.className = document.documentElement.className.replace( 'no-js', 'js' );</script> 82 <style id="custom-background-css"> 81 <script> 82 document.documentElement.className = document.documentElement.className.replace( 'no-js', 'js' ); 83 //# sourceURL=twentytwenty_no_js_class 84 </script> 85 <style id="custom-background-css"> 83 86 body.custom-background { background-color: #fff; } 84 87 </style>
</details>
# twentytwentyone
URL: http://localhost:8000/?enable_plugins=none
Prettier Diff:
-
/tmp/trac-63806-output/twentytwentyone/
old new 1524 1524 </script> 1525 1525 <script> 1526 1526 document.body.classList.remove("no-js"); 1527 //# sourceURL=twenty_twenty_one_supports_js 1527 1528 </script> 1528 1529 <button 1529 1530 id="dark-mode-toggler" … … 1622 1623 1623 1624 darkModeInitialLoad(); 1624 1625 darkModeRepositionTogglerOnScroll(); 1626 //# sourceURL=http://localhost:8000/wp-content/themes/twentytwentyone/assets/js/dark-mode-toggler.js 1625 1627 </script> 1626 1628 <script> 1627 1629 if ( … … 1630 1632 ) { 1631 1633 document.body.classList.add("is-IE"); 1632 1634 } 1635 //# sourceURL=twentytwentyone_add_ie_class 1633 1636 </script> 1634 1637 <style id="core-block-supports-inline-css"> 1635 1638 /**
<details><summary>Raw Diff</summary>
-
/tmp/trac-63806-output/twentytwentyone/
old new 470 470 <script type="speculationrules"> 471 471 {"prefetch":[{"source":"document","where":{"and":[{"href_matches":"/*"},{"not":{"href_matches":["/wp-*.php","/wp-admin/*","/wp-content/uploads/*","/wp-content/*","/wp-content/plugins/*","/wp-content/themes/twentytwentyone/*","/*\\?(.+)"]}},{"not":{"selector_matches":"a[rel~=\"nofollow\"]"}},{"not":{"selector_matches":".no-prefetch, .no-prefetch a"}}]},"eagerness":"conservative"}]} 472 472 </script> 473 <script>document.body.classList.remove("no-js");</script><button id="dark-mode-toggler" class="fixed-bottom" aria-pressed="false" onClick="toggleDarkMode()">Dark Mode: <span aria-hidden="true"></span></button> <style> 473 <script> 474 document.body.classList.remove('no-js'); 475 //# sourceURL=twenty_twenty_one_supports_js 476 </script> 477 <button id="dark-mode-toggler" class="fixed-bottom" aria-pressed="false" onClick="toggleDarkMode()">Dark Mode: <span aria-hidden="true"></span></button> <style> 474 478 #dark-mode-toggler > span { 475 479 margin-left: 5px; 476 480 } … … 482 486 } 483 487 </style> 484 488 485 <script>function toggleDarkMode() { // jshint ignore:line 489 <script> 490 function toggleDarkMode() { // jshint ignore:line 486 491 var toggler = document.getElementById( 'dark-mode-toggler' ); 487 492 488 493 if ( 'false' === toggler.getAttribute( 'aria-pressed' ) ) { … … 553 558 554 559 darkModeInitialLoad(); 555 560 darkModeRepositionTogglerOnScroll(); 556 </script> <script> 557 if ( -1 !== navigator.userAgent.indexOf( 'MSIE' ) || -1 !== navigator.appVersion.indexOf( 'Trident/' ) ) { 558 document.body.classList.add( 'is-IE' ); 559 } 560 </script> 561 <style id='core-block-supports-inline-css'> 561 //# sourceURL=http://localhost:8000/wp-content/themes/twentytwentyone/assets/js/dark-mode-toggler.js 562 </script> 563 <script> 564 if ( -1 !== navigator.userAgent.indexOf('MSIE') || -1 !== navigator.appVersion.indexOf('Trident/') ) { 565 document.body.classList.add('is-IE'); 566 } 567 //# sourceURL=twentytwentyone_add_ie_class 568 </script> 569 <style id='core-block-supports-inline-css'> 562 570 /** 563 571 * Core styles: block-supports 564 572 */
</details>
This ticket was mentioned in Slack in #core by jorbin. View the logs.
13 months ago
This ticket was mentioned in Slack in #core by westonruter. View the logs.
12 months ago
#19
@
3 months ago
Hi @westonruter (and committers),
I'd like to help move this ticket forward by taking ownership of a bounded slice.
Proposed slice: migrate the remaining raw <script> blocks in wp-admin/includes/media.php
and wp-admin/admin-header.php to wp_get_inline_script_tag() / wp_print_inline_script_tag(),
matching the patterns established in r60909 and r60913.
Why this slice: every migrated block routes through the wp_inline_script_attributes filter
(script-loader.php:3034 on trunk @ 02778fd6a1), which is the central point a future CSP nonce
will need. That makes this a concrete prerequisite for the report-only CSP rollout discussed on
this ticket, and it is fully verifiable: PHPUnit per touched subsystem plus a before/after
rendered-markup diff (the grab-output.sh approach from PR #9416) showing only expected
<script> attribute changes.
Verification I'll provide with the patch:
PHPUnit coverage for each touched subsystem.
A rendered-output diff proving no functional markup change beyond the added attributes.
Two questions before I start:
Is wp-admin/includes/media.php + admin-header.php the right first slice, or would you prefer a different subsystem first?
Should the per-subsystem migrations be tracked on this ticket, or split into child tickets as the work progresses?
Happy to start as soon as the scope is confirmed.
This ticket was mentioned in PR #13319 on WordPress/wordpress-develop by tinhien11.
3 months ago
#20
## Description
Follows up on the Trac ticket discussion (comment 19): migrates the raw inline
<script> blocks in wp-admin/admin-header.php and wp-admin/includes/media.php to
wp_print_inline_script_tag(), matching the patterns established in r60909 / r60913.
This is a prerequisite slice for the Content Security Policy rollout discussed in Trac #59446:
once all admin inline scripts route through the script tag API, the
wp_inline_script_attributes filter becomes the single point where a per-request nonce can be
attached.
## Changes
wp-admin/admin-header.php: the global admin JS (addLoadEvent, ajaxurl, pagenow, typenow, adminpage, locale separators, isRtl) and theno-js->jsbody-class replacement are now printed viawp_print_inline_script_tag().wp-admin/includes/media.php: 10 of the 11 inline script blocks (send-to-editor handoff, plupload init, preloaded media item lists,wpOnload()trigger, post_id echo) migrated. Thedisable_captionsconditional and the dynamic admin image URLs keep their existing behavior.- Deferred: the
addExtImageraw block (the only remaining<script>in media.php) needs the same treatment but ships separately to keep this slice reviewable.
## Verification
php -lon both files.- The emitted JS is byte-identical to the previous output (same
esc_js()values, same statement order; only the surrounding<script>wrapper newlines differ). - Rendered-markup diff on a live admin page will be attached from the PR test run.
## Next steps
With this in place, the script-loader can attach a per-request nonce via the
wp_inline_script_attributes filter, enabling the report-only CSP discussed in Trac #59446.
Trac ticket: https://core.trac.wordpress.org/ticket/59446 (see comment 19).
tinhien11 commented on PR #13319:
3 months ago
#21
Thanks for the detailed review @westonruter — all points addressed in cfaa362:
- Nowdoc everywhere: the admin-header
no-jsreplacement script, the threepreloadedhandlers in media.php, and the popupaddLoadEvent. - media-upload-popup globals block now mirrors admin-header: unminified, strict-mode-compatible
addLoadEvent, andObject.assign( window, wp_json_encode( ... ) )withJSON_HEX_TAG | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_LINE_TERMINATORS. The popup keeps its original variable subset (ajaxurl,pagenow,adminpage,isRtl). media_send_to_editor()uses the suggestedsprintf()+wp_json_encode()form.- PHP close/reopen pairs removed: the
wp_print_inline_script_tag()calls now sit directly in the surrounding PHP blocks inmedia_send_to_editor(),wp_iframe()(×2),media_upload_form_handler(),media_upload_gallery_form(), and both spots in admin-header.php. isRtlstays(int)as in your suggestion, preserving the previous JS value type.
Coding standards (PHP/JS) and PHP compatibility pass on the new head; the rest of the matrix is running.
@westonruter commented on PR #13319:
2 months ago
#23
🤖 _Comment by Claude Opus 5_
Two behavioral changes in this PR are not apparent from the diff and are worth stating explicitly for review, followed by a note on the scope that was added for consistency and what was verified in a browser.
## 1. Replacing esc_js() with wp_json_encode() changes the emitted values
This is not a pure refactor. esc_js() does two things that JSON encoding does not: it runs the value through _wp_specialchars( $text, ENT_COMPAT ), and it applies stripslashes(). The consequence is that the JavaScript string previously contained HTML entities rather than the literal characters:
| Input | Before (esc_js inside '…') | After (wp_json_encode)
|
|---|---|---|
Tom & Jerry | 'Tom & Jerry' | "Tom & Jerry"
|
a "quoted" value | 'a "quoted" value' | "a \"quoted\" value"
|
back\slash | 'back\slash' (backslash lost) | "back\\slash"
|
| '&nbsp;' | " "
|
Every case above is a correction rather than a regression, since the old output was mangled. The affected values are ajaxurl, pagenow, typenow, adminpage, thousandsSeparator and decimalPoint. The two locale-supplied separators are the ones most likely to contain an affected character in practice, as they come from translations.
## 2. The js_escape filter no longer runs for these values
esc_js() ends with apply_filters( 'js_escape', $safe_text, $text ). Any plugin hooking that filter was previously able to alter the six values listed above. That extension point is gone for them. It is an obscure surface, but it is a removal rather than a change.
## 3. Global property descriptors are no longer identical to before
Because var ajaxurl = … became Object.assign( window, … ), and addLoadEvent = function … became a function declaration, the resulting global properties carry different descriptors. This was measured in a browser rather than inferred:
| Global | Before | After |
|---|---|---|
ajaxurl, pagenow, typenow, adminpage | configurable: false | configurable: true
|
addLoadEvent | configurable: true | configurable: false
|
The flags move in opposite directions because the old globals were created by var (non-configurable) while addLoadEvent was an implicit global assignment (configurable). Values, writability and enumerability are unchanged, and isRtl remains a number. The practical effect is that delete window.ajaxurl now succeeds where it previously could not. No core or bundled code depends on either behavior.
## Scope added for consistency
The same block of global admin JavaScript existed in three places. Only two were covered initially, which would have left Thickbox iframes on the old esc_js() behavior while every other admin screen used the new one — so a thousands_sep containing an ampersand would have arrived as & in an iframe and as & elsewhere. iframe_header() and iframe_footer() in wp-admin/includes/template.php have therefore been migrated as well, which also brings tb_close() across.
iframe_footer() matters most of the three: it holds the script that actually invokes wpOnload, so leaving it as a raw tag would have caused every callback registered through addLoadEvent() on a Thickbox iframe to be silently dropped under a CSP while the surrounding page continued to work.
compression_test() in the same file still emits a raw <script> and has deliberately been left alone, as its removal is intended separately.
## Deliberately not changed
wp_json_encode() can return false, in which case sprintf( 'Object.assign( window, %s );', false ) emits a syntax error. Guarding this was considered and rejected: a filter that renders the data non-encodable is a bug, and a loud SyntaxError surfaces it better than a silent fallback would. The realistic path to false is narrow in any case, since wp_json_encode() retries through _wp_json_sanity_check(), which strips invalid UTF-8.
The JSON flags were also narrowed to JSON_HEX_TAG | JSON_UNESCAPED_SLASHES throughout. JSON_UNESCAPED_UNICODE and JSON_UNESCAPED_LINE_TERMINATORS are only safe when the page is served as UTF-8, which is not guaranteed in the admin, as admin-header.php sends the charset straight from the blog_charset option. WP_Script_Modules::print_script_module_data() gates the same pair behind is_utf8_charset() for this reason. Rather than repeat that gate at several call sites for a marginal saving on very small payloads, the narrower pair is now used everywhere, matching the rest of core.
## Verification
Checked in a browser against the running admin:
- All globals carry their expected values and types on the Dashboard, on
media-upload.phpin both thetypeandtype_urltabs, and on a Thickbox iframe page. wpOnload()is invoked exactly once fromiframe_footer(), and the tag remains positioned after the closing div that wraps the footer hooks.- The
addExtImageblock survivesWP_HTML_Tag_Processorbyte-for-byte, including'</a>',replace(/</g, '<')and'<br />', with none of the Unicode escaping thatescape_javascript_script_contents()would apply to a<scriptor</scriptsequence. It was then driven through its real inline handlers: theonblurpopulated width and height from an actual image, the align radio'sonclicksetaddExtImage.align, andinsert()produced the expected caption shortcode. pluploadinitializes andwindow.uploaderis instantiated.tb_close()resolves the same target and preservesthis.- No console errors on any page. The only console output anywhere was a pre-existing
JQMIGRATEdeprecation notice and a pre-existing<label for>issue, neither touched here.
The "Insert media from another website" tab is still not usable under a strict CSP even with its script tag now able to carry a nonce, because wp_media_insert_url_form() drives addExtImage entirely through inline onclick and onblur attributes, which a nonce cannot cover. That needs a separate change.
#24
@
2 months ago
Following the 7.2 milestone — I'd like to take the follow-up noted in the review of GitHub PR 13319 (https://github.com/WordPress/wordpress-develop/pull/13319): the "Insert media from another website" tab is still unusable under a strict CSP because wp_media_insert_url_form() drives addExtImage through inline onclick/onblur attributes, which a nonce cannot cover. I have a patch ready that binds the same handlers from the existing nonce-eligible script block on DOMContentLoaded, and will open the PR on top of it as soon as it lands.
This ticket was mentioned in PR #13393 on WordPress/wordpress-develop by @thanhtinpk.
2 months ago
#25
## Description
Follows up on the inline script migration in #13319 for the Content Security Policy rollout discussed in Trac #59446: wraps the remaining one-liner raw <script> tags in wp_print_inline_script_tag(), so every script these pages print can carry a per-request nonce.
Under a CSP that only allows nonce'd scripts, each raw tag replaced here was blocked outright: the wpOnload() trigger on every admin screen, the installer's title focus, and the upload-error dismissal.
## Changes
### wp-admin/admin-footer.php
- The
wpOnload()trigger printed at the end of every admin screen now goes throughwp_print_inline_script_tag(), mirroring theiframe_footer()migration in #13319.
### wp-admin/install.php
- The installer's
weblog_titlefocus helper (non-mobile) and thehide-if-no-jsclass-removal block are wrapped the same way. The needless PHP close/reopen pair between them is removed.
### wp-admin/async-upload.php
- The upload-error speak-and-dismiss handler is printed via
wp_print_inline_script_tag()instead of a manually assembledecho '<script>…'. The dismiss button selector is passed throughwp_json_encode()as one whole string, replacing raw string interpolation of the id.
## Behavioral notes
- The emitted JavaScript is semantically identical; only the formatting of the
wpOnloadand installer blocks is normalized. wp_print_inline_script_tag()appends a trailing newline after the closing tag, matching the raw echo it replaces inasync-upload.php.- Hardening aside, the dismiss selector construction now can never break on unusual ids, since the full
button#…string is JSON-encoded rather than the id being interpolated inside quotes.
## Verification
php -lon all three files.- The four emitted script bodies were executed against a simulated DOM:
wpOnloadguard (no-op when undefined, invoked when defined), installer focus,.hide-if-no-jsremoval on ready, and the full dismiss chain (click →parents( 'div.media-item' )→ slideUp → remove →wp.a11y.speak). - Emitted tags were validated through the real
wp_get_inline_script_tag()implementation, including its unsafe-content guard for</script>sequences.
compression_test() in wp-admin/includes/template.php intentionally remains untouched, per #13319.
@westonruter commented on PR #13393:
2 months ago
#27
Please add the AI Disclosure section from the PR template to indicate whether/how AI was used in the construction of this PR.
#29
follow-up:
↓ 30
@
2 months ago
In quite a few places, this now sends JSDoc to the browser, adding extra bytes to the requests. Wouldn't it be sufficient to have have these in the PHP code only?
#30
in reply to: ↑ 29
@
2 months ago
Replying to TobiasBg:
In quite a few places, this now sends JSDoc to the browser, adding extra bytes to the requests. Wouldn't it be sufficient to have have these in the PHP code only?
We should really be moving all such scripts into JS files which get read in via file_get_contents() (as is done for the emoji loader via print_emoji_detection_script()), and in this way the build process can generate the minified versions which we can then inline serve when SCRIPT_DEBUG is turned off. I hinted at that in my PR comment, but it was out of scope for that changeset.
#31
@
2 months ago
A couple notes for getting this to the finish line:
Not all existing <script> tags will be suitable for directly being replaced with wp_print_inline_script_tag(). In some cases, existing <script> tags should be wrapped in ob_start() and ob_get_clean() with the return value of the latter being passed through wp_remove_surrounding_empty_script_tags() which is then passed into wp_print_inline_script_tag(). An example of this is in media_upload_type_url_form() where there are PHP conditionals inline with the JS code that make it more difficult to extract into a NOWDOC. (That said, it would still be ideal to get rid of this, but probably later as part of another effort.)
Non-JS SCRIPT tags will need to be converted as well. Before the TEMPLATE tag existed, core used the SCRIPT tag with a non-JS type. For example, wp_print_community_events_templates() includes this:
<script id="tmpl-community-events-attend-event-near" type="text/template"> <?php printf( /* translators: %s: The name of a city. */ __( 'Attend an upcoming event near %s.' ), '<strong>{{ data.location.description }}</strong>' ); ?> </script>
This doesn't need any NOWDOC at all. It can simply switch to using sprintf():
<?php wp_print_inline_script_tag( sprintf( /* translators: %s: The name of a city. */ __( 'Attend an upcoming event near %s.' ), '<strong>{{ data.location.description }}</strong>' ), array( 'id' => 'tmpl-community-events-attend-event-near', 'type' => 'text/template', ) );
For more complicated HTML templates with nested PHP conditionals where wp_remove_surrounding_empty_script_tags() is needed, it will need to be modified to allow not warn when attributes are included on the <script> tag, so that this can be done (but not with this specific example):
<?php ob_start(); ?> <script id="tmpl-community-events-attend-event-near" type="text/template"> <?php printf( /* translators: %s: The name of a city. */ __( 'Attend an upcoming event near %s.' ), '<strong>{{ data.location.description }}</strong>' ); ?> </script> <?php wp_print_inline_script_tag( wp_remove_surrounding_empty_script_tags( ob_get_clean() ), array( 'id' => 'tmpl-community-events-attend-event-near', 'type' => 'text/template', ) ); ?>
For example, wp_remove_surrounding_empty_script_tags() could be modified as follows:
<?php function wp_remove_surrounding_empty_script_tags( $contents ) { $contents = trim( $contents ); $processor = new WP_HTML_Tag_Processor( $contents ); if ( ! $processor->next_tag( 'SCRIPT' ) ) { // TODO: Use next_token() and also verify that '</script>' is the last token. $error_message = __( 'Expected string to start with script tag and end with script tag, with optional whitespace.' ); _doing_it_wrong( __FUNCTION__, $error_message, '7.2' ); return sprintf( 'console.error(%s)', wp_json_encode( sprintf( /* translators: %s: wp_remove_surrounding_empty_script_tags() */ __( 'Function %s used incorrectly in PHP.' ), 'wp_remove_surrounding_empty_script_tags()' ) . ' ' . $error_message ) ); } return $processor->get_modifiable_text(); }
(Note the TODO comment to make this more robust.)
That said, it would be even better if we could avoid relying on wp_remove_surrounding_empty_script_tags() entirely, as well as moving all of these inline JS snippets to external files which can be included with file_get_contents() per my preceding comment.
This ticket was mentioned in PR #13492 on WordPress/wordpress-develop by @haritpanchal.
2 months ago
#33
- Keywords has-patch added; needs-patch removed
Continues the migration away from manually constructed SCRIPT markup begun in [63481] and [63545]. The four raw one-liner script tags in Bulk_Upgrader_Skin::error(), ::before(), and ::after() now print through wp_print_inline_script_tag(), so wp_inline_script_attributes can attach a per-request nonce to these as well — one more step toward an admin Content-Security-Policy opt-in.
The dynamic jQuery selector is now passed through wp_json_encode() with JSON_HEX_TAG | JSON_UNESCAPED_SLASHES instead of being built via esc_js() string concatenation, consistent with the fix applied to similar call sites in [63481]: esc_js() runs the value through _wp_specialchars(), which isn't needed here since the value lands inside a JS string literal, not an HTML attribute.
Behavior is unchanged — output was compared before/after with a manual smoke test of all three methods.
## Testing instructions
- Go to Plugins → Add New, install/update a plugin, or use Dashboard → Updates to bulk-update plugins/themes.
- Confirm the spinner and progress states still toggle correctly during and after the bulk update.
npm run test:php -- --group upgradepasses (183 tests).vendor/bin/phpcs --standard=phpcs.xml.dist src/wp-admin/includes/class-bulk-upgrader-skin.phpis clean.
Trac ticket: https://core.trac.wordpress.org/ticket/59446
## Use of AI Tools
AI assistance: Yes
Tool(s): Claude Code
Model(s): Claude Sonnet 5
Used for: Identifying the unconverted call sites, drafting the wp_print_inline_script_tag() replacement, and running the coding-standards/PHPUnit/manual smoke checks. I reviewed the diff and test output before opening this PR.
#34
@
2 months ago
Opened a PR continuing the migration from [63481]/[63545]: https://github.com/WordPress/wordpress-develop/pull/13492
Bulk_Upgrader_Skin had four raw one-liner <script> tags (in error(), before(), and after()) that hadn't been converted yet. They now go through wp_print_inline_script_tag(), with the dynamic selector passed via wp_json_encode() instead of esc_js() concatenation, matching the approach used elsewhere in this ticket.
Verified with npm run test:php -- --group upgrade (183/183 passing), phpcs against phpcs.xml.dist (clean), and a manual smoke test of all three methods to confirm identical script output before/after.
Happy to take this further if there are other files in scope that should go in the same PR, or keep it split out — let me know what's preferred.
This ticket was mentioned in PR #13646 on WordPress/wordpress-develop by sjackson0109.
8 weeks ago
#35
- Keywords has-unit-tests added
Description
Continues the inline script migration for the Content Security Policy rollout discussed in Trac #59446.
WP_List_Table::_js_vars() and the WP_Themes_List_Table override each printed a raw one-liner <script> tag built with printf(). Under a CSP that only allows nonce'd scripts, both were blocked outright: raw markup cannot receive attributes through wp_inline_script_attributes.
Both call sites now print through wp_print_inline_script_tag(), so a per-request nonce (or any other attribute) added via wp_inline_script_attributes is attached to the emitted tag.
The base WP_List_Table::_js_vars() fix covers every list table screen that does not override the method (Posts, Users, Comments, Plugins, and so on), since WP_Themes_List_Table::_js_vars() and WP_Theme_Install_List_Table::_js_vars() both call parent::_js_vars().
The emitted JavaScript is unchanged; only the tag construction differs.
Testing instructions
- Start the WordPress Core development environment.
- Apply a nonce through
wp_inline_script_attributes. - Enforce a CSP without
unsafe-inlineonscript-src-attr. - Open any admin list table screen (for example Posts, Users, or Themes).
- Confirm the
list_args/theme_list_argsscript now carries the nonce. - Confirm the affected admin behaviour (bulk actions, screen options JS, and so on) still works.
- Confirm the previous CSP violation for this script is no longer emitted.
Automated checks:
php -lon both changed source files: passed.vendor/bin/phpcsagainstphpcs.xml.dist: 0 errors introduced.npm run test:php(Tests_Admin_WpListTable): 74 tests, 121 assertions, all passing, including two new tests asserting that a nonce added viawp_inline_script_attributesis present in the printed tag.wp eval-filesmoke test against the running dev site confirmed the live output changes from a bare<script>tag to<script nonce="...">for bothWP_List_TableandWP_Themes_List_Table.
AI assistance
AI assistance: Yes
Tool(s): Claude Code
Used for: Repository analysis, implementation support and test execution. All changes were reviewed and submitted by Simon Jackson.
sjackson0109 commented on PR #13646:
8 weeks ago
#36
Thanks for the review. Pushed a follow-up commit applying all four points:
- Added var to the list_args assignment in WP_List_Table::_js_vars() for strict-mode compatibility, matching the existing var theme_list_args declaration in the WP_Themes_List_Table override.
- Switched to WP_Themes_List_Table::class instead of the string class name in the test.
- Dropped the remove_filter() calls in both new tests since WP_UnitTestCase already resets hooks between tests.
- Replaced the substring assertions with WP_HTML_Tag_Processor: locate the SCRIPT tag, then read its nonce attribute and modifiable text directly. I adapted the tag name to SCRIPT rather than TABLE, since _js_vars() only ever prints a script tag.
npm run test:php (Tests_Admin_WpListTable) still passes: 74 tests, 123 assertions.
This ticket was mentioned in PR #13653 on WordPress/wordpress-develop by sjackson0109.
8 weeks ago
#37
Description
Continues the inline script migration for the Content Security Policy rollout discussed in Trac #59446.
WP_Upgrader_Skin::decrement_update_count() printed one of two raw one-liner <script> tags, with the update type concatenated directly into the JavaScript string. Under a CSP that only allows nonce'd scripts, both variants were blocked outright: raw markup cannot receive attributes through wp_inline_script_attributes.
Both variants now print through wp_print_inline_script_tag(), so a per-request nonce (or any other attribute) added via wp_inline_script_attributes is attached to the emitted tag. The update type is now passed through wp_json_encode() rather than being concatenated directly into the script body, matching the convention already used for the sibling Bulk_Upgrader_Skin class in #13492.
This method is inherited by Plugin_Upgrader_Skin, Theme_Upgrader_Skin, Bulk_Plugin_Upgrader_Skin, Bulk_Theme_Upgrader_Skin and Language_Pack_Upgrader_Skin, none of which override it, so the fix covers every plugin, theme and translation update screen that calls it.
The emitted JavaScript is unchanged; only the tag construction and the encoding of the update type differ.
Testing instructions
- Start the WordPress Core development environment.
- Apply a nonce through
wp_inline_script_attributes. - Enforce a CSP without
unsafe-inlineonscript-src-attr. - Update a plugin or theme (or run a bulk update) from wp-admin.
- Confirm the printed script carries the nonce.
- Confirm the update count in the admin menu still decrements as expected.
- Confirm the previous CSP violation for this script is no longer emitted.
Automated checks:
php -lon the changed source file: passed.vendor/bin/phpcsagainstphpcs.xml.dist: 0 errors, 0 warnings.npm run test:php(new fileTests_Admin_WpUpgraderSkin): 5 tests, 10 assertions, all passing, covering the early-return guard, the default branch's nonce attribute, and theIFRAME_REQUESTpostMessage branch's nonce attribute.
AI assistance
AI assistance: Yes
Tool(s): Claude Code
Used for: Repository analysis, implementation support and test execution. All changes were reviewed and submitted by Simon Jackson.
sjackson0109 commented on PR #13653:
8 weeks ago
#38
Hello @westonruter, given your involvement in #13646 as a reviewer, please can I request you also review this item.
Both fixes are relating to the exact same CSP nonce-problem
https://lists.wordpress.org/pipermail/wp-trac/2025-October/550812.html
Given your prior involvement in the email thread, i feel you are likely a good person to offer a constructive review.
Thanks,
Si
sjackson0109 commented on PR #13653:
8 weeks ago
#39
Thanks for the detailed suggestion. Pushed a follow-up commit applying it:
- Both branches now define their JavaScript as a self-contained arrow function via a nowdoc (with the language=JavaScript marker for editor highlighting), invoked immediately with the JSON-encoded update type passed as a call argument, rather than splicing the encoded value into the middle of the script body.
- The data provider in the test now has a return type and the suggested PHPStan array-shape @return tag, and the assertions were updated to match the new output shape.
One note: the IFRAME_REQUEST branch also drops the "window.postMessage && JSON" feature-detection guard, per your comment that both are now universally supported. I want to flag that explicitly: this is a behaviour change that the CSP nonce migration itself does not require, so I have made it specifically because you asked for it as part of this patch, not as something I decided was in scope on my own.
npm run test:php (Tests_Admin_WpUpgraderSkin) passes: 5 tests, 13 assertions.
sjackson0109 commented on PR #13653:
8 weeks ago
#40
Good catch, pushed a fix: dropped the redundant PhpStorm workaround comment on the second nowdoc and renamed its label to JS to match your original suggestion. No behaviour change.
@westonruter commented on PR #13646:
8 weeks ago
#41
@sjackson0109 Please link your GitHub account per https://github.com/WordPress/wordpress-develop/pull/13646#issuecomment-5779791936
I'll presume that this is your profile: https://profiles.wordpress.org/sjackson0109/
sjackson0109 commented on PR #13646:
8 weeks ago
#43
That is one of my Wordpress.org profiles. Except I cannot login/reset that specific profile. My other is ‘VCNS tech’. Happy to use that.On 22 Sep 2026, at 23:03, Weston Ruter *@*.*> wrote:westonruter left a comment (WordPress/wordpress-develop#13646)
@sjackson0109 Please link your GitHub account per #13646 (comment)
I'll presume that this is your profile: https://profiles.wordpress.org/sjackson0109/
—Reply to this email directly, view it on GitHub, or unsubscribe.You are receiving this because you were mentioned.Message ID: *@*.*>
@westonruter commented on PR #13646:
8 weeks ago
#44
OK, if you can't access sjackson0109 anymore, then please connect vcnstech with your GitHub account going forward. Otherwise, please reach out to someone, perhaps in the #meta channel in WordPress Slack to get access again.
sjackson0109 commented on PR #13646:
8 weeks ago
#46
Lets keep this tag @westonruter - I prefer to use @sjackson0109.
I'll see if i can close down my work one.
@sjackson0109 commented on PR #13646:
7 weeks ago
#48
I have access to both now - tag either, i don't mind which.
@westonruter commented on PR #13646:
7 weeks ago
#49
Cool. Just please connect your accounts to streamline this in the future.
This ticket was mentioned in PR #14767 on WordPress/wordpress-develop by aeonframework.
4 weeks ago
#51
The image editor markup printed by wp_image_editor() binds every control with an inline on* attribute: 48 handlers covering crop, scale, rotate and flip, the popup menu keyboard navigation, undo and redo, save and cancel, the help toggles, the numeric crop and selection fields, and the preview image's onload. The "Edit Image" buttons printed by edit_form_image_editor() and get_media_item() open the editor with an inline onclick too.
A site that sends a nonce-based Content Security Policy without 'unsafe-inline' blocks all of these (script-src-attr). Core already supports adding nonces to every script it prints, through wp_script_attributes and wp_inline_script_attributes. Inline event handlers cannot carry a nonce, though. As a result:
- On Media > Edit (
post.php?post=ID&action=edit), "Edit Image" does nothing. - With
&image-editor, the editor is printed with the page, but the crop tool never initializes because the preview'sonloadis blocked.
The image editor is the largest single group of inline handlers left in wp-admin. It had 48 of the 83 on*= attributes in wp-admin/ and wp-includes/ PHP at this base.
Changes
wp-admin/includes/image-edit.php: every inline handler is replaced by adata-imgedit-actionattribute (buttons), adata-imgedit-inputattribute (numeric fields) or adata-imgedit-previewattribute (preview image). Adata-imgedit-valueattribute carries an argument where one is needed (rotation angle, flip axis,scale/restore, ratio axis)..imgedit-wrapgetsdata-postid. The nonce is read from the existing#imgedit-nonce-{id}field, so it is no longer interpolated into JavaScript inside HTML attributes.wp-admin/includes/media.php: both "Edit Image" buttons getdata-imgedit-open,data-postidanddata-nonce.js/_enqueues/lib/image-edit.js: delegated listeners ondocumentcall the sameimageEditmethods with the same arguments as before:- clicks on
[data-imgedit-open]and.imgedit-wrap [data-imgedit-action]; keydown/bluron the rotate menu;keyup bluron[data-imgedit-input].
- clicks on
- The preview image's load event does not bubble, so it is caught in the capture phase. A check on DOM ready catches a preview that finished loading before the footer script ran. The attribute is removed when the image is handled, so
imgLoaded()runs exactly once either way. The images thatrefreshEditor()builds are unaffected. - The
imageEditmethod signatures, element IDs and markup structure are unchanged. Code that triggers clicks on these elements keeps working because the listeners are delegated.
Testing
- New
tests/phpunit/tests/admin/includesImageEdit.php, 3 tests:wp_image_editor()andedit_form_image_editor()output has noon*attribute (checked withWP_HTML_Tag_Processor);- every control exposes its action, the wrapper's
data-postidmatches the attachment, and the nonce fields verify forimage_editor-{id}.
Before the change all 3 tests fail. After it,
vendor/bin/phpunit tests/phpunit/tests/admin/includesImageEdit.phpreports OK (3 tests, 26 assertions).
- Full PHPUnit suite,
vendor/bin/phpunitagainst MySQL 8.0 on PHP 8.3:- before: 30761 tests, 28 failures;
- after: 30764 tests, the same 28 failures;
- in both runs the failures are in
Tests_Template(23),Tests_Dependencies_jQuery(4) andTests_Script_Modules_WpScriptModules(1), and they come from the environment (thesrc/tree was not built).
vendor/bin/phpcson the changed PHP files: no new warnings. The 3 existing warnings inmedia.phpare unchanged.- JSHint 2.13.6 with the repo's
.jshintrconimage-edit.js: nothing new. The only 2 warnings are the existing==at line 1035. - Browser check: headless Chromium against a 7.2-beta1 nightly with the three changed files copied in,
SCRIPT_DEBUGon,CONCATENATE_SCRIPTSoff. A mu-plugin sendsContent-Security-Policy: script-src 'self' 'nonce-…'and adds the nonce throughwp_script_attributesandwp_inline_script_attributes.- Before: "Edit Image" is blocked (
script-src-attr) and the editor never opens. With&image-editorthe crop tool never initializes. Threescript-src-attrviolations came from the editor. - After: all of these work, with 0 violations from the image editor:
- open over Ajax; crop initialized;
- rotate menu, including ArrowDown to move focus;
- rotate 90° left, which adds a history step and enables Save;
- undo and redo;
- scale width 100, which updates the height (480 → 75);
- help toggle;
- Save ("Image saved");
- server-rendered
&image-editor: crop initialized, Cancel closes.
- The violations still left on that screen come from code outside this patch: the raw
<script>tags inwp-admin/includes/misc.php(_wpColorScheme,wp_admin_canonical_url(), the back-forward cache reload) and the TinyMCE init inclass-wp-editor.php.
- Before: "Edit Image" is blocked (
Follow-ups (not in this PR)
misc.php's three admin-head scripts go throughwp_print_inline_script_tag(), the same pattern as r63545.- The remaining inline handlers in the legacy
media-upload.phpscreens (get_media_item()Delete/Cancel andWPSetAsThumbnail, and theaddExtImageform), inmeta-boxes.phpand in the list tables.
Use of AI Tools
AI assistance: Yes
Tool(s): MiniAeon (omp agent harness)
Model(s): Claude Opus 5.5
Used for: finding the remaining inline handlers, drafting the markup and listener changes, the PHPUnit tests and the headless-browser CSP check. The tests and the headless-browser CSP check listed above were run during that work, and the full diff was reviewed by a person before this PR was opened.
aaronjmars commented on PR #14767:
9 days ago
#52
Hi, checking whether this PR needs anything else from me. Happy to address feedback.
Can I ask a clarification? I am confused on the "version" of this trac
It says 5.7 and the selector only allows up to 5.7.2
Yet the trac was opened just 5 weeks ago, during a 6.x WP Version "timeframe". I am confused :)
What I am ultimately wondering is if there are ways already available for the _backend_ to become CSP ready, or if we only yet have https://core.trac.wordpress.org/ticket/39941 which implemented a front end filter allowing us to somewhat filter those script tags and add a nonce...
Thank you for any information!