FiloSottile / typage

A TypeScript implementation of the age file encryption format, based on libsodium.
BSD 3-Clause "New" or "Revised" License
64 stars 9 forks source link

Minimal example for usage in a browser #7

Closed scristalli closed 8 months ago

scristalli commented 10 months ago

I was wondering if it would be possible to easily use the compiled JS library in a browser.

If the code has been thought for doing so, would it be possible to add a minimal example?

Thanks.

scristalli commented 9 months ago

To elaborate a bit:

I've tried to bundle the module for browser, using esbuild:

.\node_modules\.bin\esbuild .\node_modules\age-encryption\dist\index.js --bundle --outfile=browser.js

The following two issues are present:

1) The bundle JS file contains one enormous anonymous block

(() => {
  var __create = Object.create;
  var __defProp = Object.defineProperty;
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  var __getOwnPropNames = Object.getOwnPropertyNames;

  ...

  function generateIdentity() {
    const scalar = sodium4.randombytes_buf(sodium4.crypto_scalarmult_curve25519_SCALARBYTES);
    return (0, import_bech32_buffer.encode)("AGE-SECRET-KEY-", scalar);
  }

  ...

      return null;
    }
  };
})();

This results in the impossibility of using the top-level objects and functions in the browser, such as generateIdentity() Quick-fix: manually remove the first and last line. This works, but it would be nice if the bundle operation would produce no top-level anonymous block to begin with.

2) There are issues with libsodium in the bundle operation. Calling generateIdentity() in the browser after importing the esbuild bundle gives the following error: sodium4.randombytes_buf is not a function. I could verify that the function seems to exist as sodium4.libsodium._randombytes_buf, hinting as some problems with the bundling of libsodium-wrappers. Too bad, manually fixing the reference here doesn't work, as other errors follow.

scristalli commented 9 months ago

@FiloSottile is bundling and usage in a browser something that you envisioned for this code, or that you'd be interested in? Or would one be better off writing a browser-oriented library from scratch? I think it would be great to have "official" support for this feature :)

FiloSottile commented 9 months ago

Hello! Yeah I would love to have official support and docs for bundling. The fact that it doesn't work right now is very much a skill issue on my side :)

Is there maybe an example of bundle-friendly library that uses libsodium-wrappers anywhere I could look at? Otherwise I also welcome suggestions or PRs.

scristalli commented 9 months ago

@FiloSottile no issues at all! I made a pull request, I am not a JS expert and so the solution is for sure improvable, but it seems to be working and I only made some minimal changes.