web icon indicating copy to clipboard operation
web copied to clipboard

Add helpers to make it easier to use trusted types

Open ditman opened this issue 1 year ago • 6 comments

I think HTMLScriptElement needs a src setter that accepts a TrustedScriptURL.

After conditionally creating a trustedUrl like this:

  // If TrustedTypes are available, prepare a trusted URL.
  web.TrustedScriptURL? trustedUrl;
  if ((web.window as JSObject).hasProperty('trustedTypes'.toJS).toDart) {
    // create a TrustedTypePolicy `policy` object
    trustedUrl = policy.createScriptURL(_url, null);
  }

I'm finding myself doing this:

  final web.HTMLScriptElement script =
      // ignore: avoid_dynamic_calls
      (web.document.createElement('script') as dynamic
        // ignore: unsafe_html
        ..src = (trustedUrl ?? _url)
        ..async = true
        ..defer = true) as web.HTMLScriptElement;

Docs:

  • https://developer.mozilla.org/en-US/docs/Web/API/Trusted_Types_API
    • See "Injection Sinks": Setters for Element attributes that accept a URL of code to load or execute.
  • https://developer.mozilla.org/en-US/docs/Web/API/TrustedScriptURL

(Another way would be to pass trustedUrl.toString(), but that kind of defeats the purpose of TrustedScriptURLs, and would still flag me as unsafe_html I think :/)

ditman avatar Dec 05 '23 02:12 ditman

Thanks for filing the issue - I like the alternative you did in https://github.com/flutter/packages/pull/5581/files#diff-fef182cc76f54d7074aee070ced4ddd44ad9233ebf438472221dc834f5f342d9 where you added an extra setter with the right type. The workaround using dynamic relies on using the dart:html interceptor, and if one day we remove it (which we hope we do in the future), it would stop working.

sigmundch avatar Dec 07 '23 17:12 sigmundch

Yes, the workaround with dynamic felt very iffy, and it triggered a bunch of unsafe_html lints :) Being able to rename the setter was nice!

ditman avatar Dec 07 '23 19:12 ditman

I'm generalizing this issue a bit more to address some other use cases I'm seeing like checking whether trustedTypes is available, and the ability to not pass anything for args in createScriptURL.

srujzs avatar Jan 09 '24 22:01 srujzs

Trusted Types with the latest syntax has landed #173 again, but it still needs tweaks to be usable. I've created #175 so we don't forget :)

ditman avatar Feb 16 '24 00:02 ditman

I wonder if we should be able to flag certain top-level..."things" as optional so the generator can understand them...

kevmoo avatar Feb 16 '24 00:02 kevmoo

TrustedTypes is one of the most egregious examples, though:

  • https://caniuse.com/mdn-api_trustedtypes

I'm not aware of any other non-prefixed chrome-only "top level" APIs like this!

ditman avatar Feb 16 '24 00:02 ditman