jedisct1 / libsodium.js

libsodium compiled to Webassembly and pure JavaScript, with convenient wrappers.
Other
968 stars 138 forks source link

Sodium doesn't load in ts-node or jest tests #298

Closed cognivore closed 2 years ago

cognivore commented 2 years ago

Why?

It would be nice to be able to use libsodium both:

What's wrong?

I don't quite know, but both in jest and in ts-node, sodium doesn't get loaded. Observe:

tsconfig.json

{
  "compilerOptions": {
    "target": "es2022",
    "module": "CommonJS",
    // *snip
    }
}

crypto.ts

export async function getSodiumAndCfg(
    sodiumMaybe: typeof sodium0
): Promise<{ sodium: typeof sodium0; cfg: Config }> {
    await sodiumMaybe.ready;
    return { sodium: sodiumMaybe, cfg: config(sodiumMaybe) };
}

export async function blandHash(msg: string): Promise<Url> {
    const { sodium, cfg } = await getSodiumAndCfg(sodium0);
    return toUrl(sodium.crypto_generichash(cfg.hashSize, msg));
}

ts-node

Thu Apr 07 17:54:20:561555500 sweater@conflagrate ~/github/do-auth/priv/ui (main) 
λ npx ts-node 
> const c = require('./src/doauth/crypto')
undefined
> const y = await c.blandHash('boo')
Uncaught TypeError: sodium.crypto_generichash is not a function
    at async /home/sweater/github/do-auth/priv/ui/node_modules/ts-node/src/repl.ts:616:39
    at async /home/sweater/github/do-auth/priv/ui/<repl>.ts:1:33
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at Object.blandHash (/home/sweater/github/do-auth/priv/ui/src/doauth/crypto.ts:195:25)

jest

 FAIL  test/doauth_props.spec.ts
  ● libsodium loads fast

    TypeError: sodium.crypto_generichash is not a function

      16 |     const sodium = sodium0;
      17 |     expect(sodium.SODIUM_VERSION_STRING).toBeTruthy;
    > 18 |     expect(await toUrl(sodium.crypto_generichash(32, 'boo'))).toBe(
         |                               ^
      19 |         'UjuhVEXQembMCmLfemONVeBKhDCEeXbTtgiht472zGA='
      20 |     );
      21 | });

      at Object.<anonymous> (test/doauth_props.spec.ts:18:31)

How?

I have no idea what to do about it or how to even debug this. If someone would point me to it, I could try to debug myself.

cognivore commented 2 years ago

I fixed it. I had a wrong import: * as sodium0 instead of just sodium0.

Please see the following patch for details:

https://github.com/doma-engineering/do-auth/commit/5ccebd118c512fb47fdd0b4c58a31cf1f29b2025