Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fails with CSP policy that includes require-trusted-types-for 'script' #446

Open
bman654 opened this issue Jan 6, 2025 · 1 comment
Open
Labels
enhancement New feature or request

Comments

@bman654
Copy link

bman654 commented Jan 6, 2025

This CSP policy

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

causes the shim to fail during init:

image

due to the manipulation of some DOM elements via innerHTML property.

I think the fix is to change the code to something more like:

// let call supply the trusted types name via config.trustedTypesPolicyName to opt-in to trusted types support
// at top of module
const ttpConfig = {
  // normally these methods would santize their input, but we know what we are doing and we trust the
  // input so our methods are merely identity functions
  createHTML: input => input
  createScript: input => input
  createScriptURL: input => input
}

const ttp = (typeof trustedTypes !== "undefined") && config.trustedTypesPolicyName ?
  // we know what we are doing and do not need to sanitize the input
  trustedTypes.createPolicy(config.trustedTypesPolicyName, ttpConfig)
  : ttpConfig;

// anywhere innerHTML is being set
// el.innerHTML = html
el.innerHTML = ttp.createHTML(html)

// anywhere script src is being set
//scriptEl.src = url
scriptEl.src = ttp.createScriptURL(url)

// anywhere Function constructor is being used:
// f = new Function ("a", "b", code)
f = new Function("a", "b", ttp.createScript(code))

See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/require-trusted-types-for

@guybedford
Copy link
Owner

This proposal does sound like it could work to me as a way to support trusted types. I would be happy to take a PR.

@guybedford guybedford added the enhancement New feature or request label Jan 27, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants