In my application, a user can load custom content such as a third-party hosted image. I have specific goals (for security):
- Load the image in a sandboxed iframe and “transfer” the image to the “host”. This allows the “host” to avoid needing to define a CSP with
image-src
for each possible user-uploaded image. It also allows the browser to handle things like CSP validation for the image source and then the host can trust a data URL of the image. - Keep the “host” CSP restricted to only allow iframes from our “sandbox” iframe.
- Keep the “sandbox” CSP restricted for user-defined content. E.g. using
img-src
to only allow images from that image’s host source.
In order to “transfer” the image to the host, I need a blob/data URL/object URL. I’ve tried the following solutions:
- Use
fetch()
in the “sandbox” to make an HTTP request for the image URL and get the blob. This is treated asconnect-src
rather thanimg-src
and “opens up” security problems. - Create an
<img>
with the source of the image, dynamically create a<canvas>
, usecanvas.getContext('2d').drawImage(img, 0, 0)
(and/or related APIs), and then finally usecanvas.toBlob()
. This works great for JPEGs and PNGs, but only grabs the first frame for GIFs and doesn’t include the raw source for an SVG.
Ideally, I’m looking for an image-oriented API (so that img-src
is respected). For example:
- Telling
fetch()
to expect an image? - Using an API like
createImageBitmap()
from the<img>
but with all the data in the loaded image. - Using an API directly on
<img>
to “transfer” it to a different context (e.g. “sandbox” iframe to “host”).
Is this possible?