web.dev icon indicating copy to clipboard operation
web.dev copied to clipboard

Fix inline scripts in patterns

Open beaufortfrancois opened this issue 2 years ago • 5 comments

An inline <script> in web.dev patterns requires using {% set script %} to avoid CSP issues such as ones in https://web.dev/new-patterns-july-2022/

image

Here's a quick way to fix it for instance:


diff --git a/src/site/content/en/patterns/layout/gentle-flex/demo.njk b/src/site/content/en/patterns/layout/gentle-flex/demo.njk
index a8978a8fd..003bf4445 100644
--- a/src/site/content/en/patterns/layout/gentle-flex/demo.njk
+++ b/src/site/content/en/patterns/layout/gentle-flex/demo.njk
@@ -93,7 +93,7 @@ patternId: layout/gentle-flex
       <div>Resize ⤴</div>
     </footer>
 
-    <script>
+    {% set script %}
       const examples = ['Sibling', 'Sibling with a long name', 'Maybe a whole paragraph of content, you never know!', 'Short']
       let position = 0
 
@@ -103,6 +103,7 @@ patternId: layout/gentle-flex
 
         document.querySelector('article').appendChild(newNode)
       }
-    </script>
+    {% endset %}
+    <script>{{ script | minifyJs | cspHash | safe }}</script>
   </body>
 </html>

A more complicated problem is the inability to create CSP hashes (using cspHash) for import * from ... inside {% set script %}. It happens at least for https://cdn.skypack.dev/blingblingjs and https://cdn.skypack.dev/roving-ux at least from what I can see.

image

beaufortfrancois avatar Aug 01 '22 13:08 beaufortfrancois

oh snap, so i need to go update each example with these additions?

argyleink avatar Aug 08 '22 21:08 argyleink

Yes, the use of inline scripts is documented in the Full HTML demo page: https://web.dev/patterns/example-set/full-html-demo/demo.html

devnook avatar Aug 09 '22 06:08 devnook

@devnook See https://github.com/GoogleChrome/web.dev/pull/8480#issuecomment-1208953649

beaufortfrancois avatar Aug 09 '22 07:08 beaufortfrancois

i'll go through the remaining demo's that were type=module and had imports, and bundle them so they dont have imports. sounds like inlining it all without imports will resolve the current csp limitations

seems like it'd be nice to allow these for the future tho?

argyleink avatar Aug 10 '22 17:08 argyleink

patch PR here https://github.com/GoogleChrome/web.dev/pull/8499

argyleink avatar Aug 10 '22 22:08 argyleink

Fixed in #8499

devnook avatar Aug 15 '22 07:08 devnook