transcend-io / penumbra

Encrypt/decrypt anything in the browser using streams on background threads.
https://penumbra-example.vercel.app/
Apache License 2.0
140 stars 18 forks source link

Penumbra Form File Input Support #230

Open jonmchan opened 2 years ago

jonmchan commented 2 years ago

I was slightly surprised that penumbra did not work out of the box with an HTML file input field:

<input type="file" id="testLocalFile">
  document.getElementById("testLocalFile").addEventListener("change", async (e) => {
    const file = e.target.files[0];
    const options = {};
    const [encrypted] = await penumbra.encrypt(options, file);
  });

This would error out with the following:

main.penumbra.js?15843758152258136:2 Uncaught (in promise) TypeError: i[t].stream.pipeTo is not a function
    at main.penumbra.js?15843758152258136:2:673494
    at Array.forEach (<anonymous>)
    at bo (main.penumbra.js?15843758152258136:2:673466)
    at async main.penumbra.js?15843758152258136:2:675698
    at async Promise.all (:8081/index 0)
    at async HTMLInputElement.<anonymous> (demo.js?15843758152258136:52:25)

I was finally able to get this working by extracting the arrayBuffer content of the file and putting it into a Response.

  document.getElementById("testLocalFile").addEventListener("change", async (e) => {
    const file = e.target.files[0];
    const options = {};
    const buffer = await file.arrayBuffer();
    const stream = new Response(buffer).body;
    const penumbraFile = {
      stream,
      size: file.size,
    };

    const [encrypted] = await penumbra.encrypt(options, penumbraFile);
  });

I might just be a newbie as I have no experience with streams in javascript, but I felt this could have been more intuitive. It would be helpful for either documentation to be added to help others implement this without digging through everything or for penumbra to work natively with the File object natively. At first glance, it would seem that a File has a stream and a size property and it should be compatible but it, unfortunately, is not.

Again, excuse my ignorance if this is something well known for those familiar with working with Files and streams. It was the first time I dealt with it, and I was surprised it took so long for me to figure everything out.

Am I using it improperly? Is there a more straightforward way to take a file from a File Input element?

Thank you for your consideration.

eligrey commented 2 years ago

We could definitely auto detect and convert the File format to improve the developer experience here. Stay tuned for changes soon!