Search code examples
javascriptgoogle-chromecontent-security-policytrusted-types

How to use new Trusted Types header and reCAPTCHA?


I'm trying to use the new require-trusted-types-for 'script' header available in Chrome 83, and it poses a problem for a reCAPTCHA form in my site.

For testing, I'm using this version of the header, which helpfully logs problems to the console:

Content-Security-Policy-Report-Only: require-trusted-types-for 'script';

When I navigate to the page in my site that has reCAPTCHA, I can provide the URL https://www.google.com/recaptcha/api.js wrapped in a TrustedType object as a TrustedScriptURL without an issue. That's no problem.

However, the api.js file itself contains a src assignment that triggers this error:

This document requires 'TrustedScriptURL' assignment.
(anonymous) @ api.js:1
(anonymous) @ api.js:1

The code in api.js that triggers the error is:

po.src = 'https://www.gstatic.com/recaptcha/releases/ADnAC3ZykfbIOflWgrKNsVVT/recaptcha__en.js';

The recaptcha__en.js code itself also triggers the same type of error, but this time a trusted html object is needed:

recaptcha__en.js:formatted:2690 [Report Only] This document requires 'TrustedHTML' assignment.
(anonymous) @ recaptcha__en.js:formatted:2662
(anonymous) @ recaptcha__en.js:formatted:2180
Ph.bottomright.border-radius.render @ recaptcha__en.js:formatted:14714
(anonymous) @ recaptcha__en.js:formatted:599
(anonymous) @ recaptcha__en.js:formatted:5386
(anonymous) @ recaptcha__en.js:formatted:2879
ZI @ recaptcha__en.js:formatted:10647
(anonymous) @ recaptcha__en.js:formatted:4051
(anonymous) @ recaptcha__en.js:formatted:696
(anonymous) @ recaptcha__en.js:formatted:696
(anonymous) @ recaptcha__en.js:formatted:4202
(anonymous) @ recaptcha__en.js:formatted:536
(anonymous) @ recaptcha__en.js:formatted:5151
(anonymous) @ recaptcha__en.js:formatted:536
(anonymous) @ recaptcha__en.js:formatted:14832
(anonymous) @ recaptcha__en.js:formatted:15037

Since the code in the api.js is not sanitized by Google, it can't be executed with the header in effect. Is there a workaround for this? Or is there a flag that forces Google to return a version of the api.js that has the src assignment wrapped in a TrustedType object?

How can reCAPTCHA be used in conjunction with Trusted Types enforcement?


Solution

  • To load a version of reCAPTCHA that uses Trusted Types, you have to pass trustedtypes=true in the GET parameters of the script URL.

    https://www.google.com/recaptcha/api.js?trustedtypes=true

    This version will create and use a Trusted Types policy called 'recaptcha'.