❯ehsan.blog
~/blog/jose-deleted-200-files-when-node-grew-crypto — zsh
❯cat jose-deleted-200-files-when-node-grew-crypto.md

jose deleted 200 files when Node grew a crypto global

·7 min read

jose deleted 200 files when Node grew a crypto global — article card for a post by Ehsan Shahid

Here is a small piece of code. It signs the word hello with a secret.

js
const enc = new TextEncoder()
const secret = enc.encode('a-very-secret-value-at-least-32-bytes!!')

const key = await crypto.subtle.importKey(
  'raw', secret, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'],
)
const sig = await crypto.subtle.sign('HMAC', key, enc.encode('hello'))

I ran it in Node v22.16.0. Then I pasted the same lines into a browser console. Both printed the same signature:

plaintext
Vzd727FvOWJJl9xfp9601PZ9gz_QrEzCeYL_CLJ7A_0

Same code. Same bytes. No build step, no polyfill, no if checking where it was running.

That sounds boring. It was not always possible, and the library most Node projects use for tokens threw away about 200 files when it became possible.

I counted the files in both versions

jose is the library you land on when you need JSON Web Tokens in JavaScript. I downloaded two published versions and counted what was inside.

bash
npm pack jose@5.9.6 && tar xzf jose-5.9.6.tgz && mv package j5
npm pack jose@6.2.15 && tar xzf jose-6.2.15.tgz && mv package j6

ls j5/dist        # browser  node  types
ls j6/dist        # types  webapi

find j5/dist -name '*.js' | wc -l    # 246
find j6/dist -name '*.js' | wc -l    # 46

Version 5 shipped a browser folder and a node folder. Version 6 ships one folder called webapi. On disk that is 1.3 MB down to 392 KB.

The folder names are the whole story. Version 5 had to guess which world your code lived in, and carry a full answer for each one.

Two files with the same name and nothing else in common

Both folders held a file called runtime/sign.js. Same name, same job: take an algorithm, a key, and some bytes, and return a signature.

Here is the browser one, exactly as jose 5.9.6 published it:

js
const sign = async (alg, key, data) => {
    const cryptoKey = await getSignKey(alg, key, 'sign');
    checkKeyLength(alg, cryptoKey);
    const signature = await crypto.subtle.sign(
        subtleAlgorithm(alg, cryptoKey.algorithm), cryptoKey, data);
    return new Uint8Array(signature);
};

And here is the Node one:

js
const sign = async (alg, key, data) => {
    const k = getSignKey(alg, key, 'sign');
    if (alg.startsWith('HS')) {
        const hmac = crypto.createHmac(hmacDigest(alg), k);
        hmac.update(data);
        return hmac.digest();
    }
    return oneShotSign(nodeDigest(alg), data, nodeKey(alg, k));
};

Read them side by side. They do not share a single line. One awaits a promise from crypto.subtle. The other builds an HMAC object, feeds it data, and calls .digest(). One returns a Uint8Array, the other returns a Node Buffer.

Twenty-four file names existed in both folders like this. Two full implementations of the same maths, written against two unrelated APIs, kept in step by hand, release after release.

I counted them by listing each folder and keeping the names that appeared twice:

bash
comm -12 \
  <(ls j5/dist/browser/runtime | sort) \
  <(ls j5/dist/node/esm/runtime | sort) | wc -l    # 24

That is the part worth sitting with. Signing code is where a quiet disagreement between two code paths turns into a security bug, and nobody notices, because both paths still return something that looks like a signature.

jose did not get clever. Node changed.

I grepped the published JavaScript for Node’s own crypto module:

bash
grep -rl "node:crypto" j5/dist | wc -l    # 47
grep -rl "node:crypto" j6/dist | wc -l    # 0
grep -rl "createHmac"  j6/dist | wc -l    # 0

Forty-seven files, then none. jose 6 does not import Node’s crypto module at all. It calls crypto.subtle and stops.

It can do that because Node grew the browser’s crypto API as a global. The Node documentation records the dates:

  • added in v17.6.0 and v16.15.0
  • stopped needing the --experimental-global-webcrypto flag in v19.0.0
  • stopped being marked experimental in v23.0.0

Note what Node did there. It did not write a Node-flavoured wrapper with a Node-ish name. It exposed the same global, crypto, with the same method, subtle.sign, following the same W3C spec browsers follow. Cloudflare Workers and Vercel’s Edge Runtime expose it too.

So the browser folder was not deleted because somebody felt like tidying up. It was deleted because the thing it existed to work around went away.

flowchart TB
  subgraph v5["jose 5"]
    A["your import"] --> B["package.json exports<br/>8 conditions"]
    B --> C["dist/browser<br/>crypto.subtle"]
    B --> D["dist/node<br/>node:crypto"]
  end
  subgraph v6["jose 6"]
    E["your import"] --> F["dist/webapi<br/>crypto.subtle"]
  end

The package.json is the receipt

You do not have to read any crypto code to see this. Open each package.json and look at the main export.

jose 5.9.6:

json
{
  "bun": "./dist/browser/index.js",
  "deno": "./dist/browser/index.js",
  "browser": "./dist/browser/index.js",
  "worker": "./dist/browser/index.js",
  "workerd": "./dist/browser/index.js",
  "import": "./dist/node/esm/index.js",
  "require": "./dist/node/cjs/index.js"
}

jose 6.2.15:

json
{ "default": "./dist/webapi/index.js" }

Seven conditions pointing at two builds, down to one file for everybody. Every one of those seven lines was a place your bundler could pick the wrong branch and hand you code built for the wrong runtime.

That failure was never loud. Your bundler sees worker, hands you the browser build, and the tokens still sign. You find out when a key format one build accepts and the other rejects reaches production. A test suite running under one condition cannot see the branch it did not take.

Where the ground is still uneven

I do not want to oversell this. “Use crypto.subtle and never think again” is not true yet, and jose’s own error message admits it:

plaintext
alg <name> is not supported either by JOSE or your javascript runtime

Two different failures, one message. The library may not know your algorithm, or your runtime may not have it. I tested four algorithms from jose’s table on Node v22.16.0:

js
for (const alg of [
  { name: 'HMAC', hash: 'SHA-256' },
  { name: 'ECDSA', namedCurve: 'P-256' },
  { name: 'Ed25519' },
  { name: 'ML-DSA-44' },
]) {
  try {
    await crypto.subtle.generateKey(alg, false, ['sign', 'verify'])
    console.log(alg.name, 'supported')
  } catch {
    console.log(alg.name, 'NOT supported')
  }
}
plaintext
HMAC       supported
ECDSA      supported
Ed25519    supported
ML-DSA-44  NOT supported

jose 6 lists ML-DSA-44 as a signing algorithm. My Node threw on it anyway. The library is uniform; the runtimes underneath it are still catching up on newer algorithms.

Node also keeps primitives that Web Crypto has no answer for, such as scrypt. Reach for one of those and you are back to Node-only code on purpose, which is fine as long as you chose it.

What to do with this in your own code

If you are writing something that hashes or signs, and it might run on a server today and at the edge next quarter, check crypto.subtle first:

js
console.log(typeof crypto?.subtle?.sign)   // 'function' if you are fine

If that prints function everywhere you deploy, and your algorithm is in the common set, you can write one path. That is what I did for the session tokens in my Next.js logger, which has to mint the same token under the Node runtime and the Edge runtime. One HMAC call, no branch, nothing to keep in step.

The cost of guessing wrong here is not a crash on startup, which you would catch. It is two code paths that agree in testing and disagree on one input in production.

A library with far more users than mine deleted 200 files rather than keep that risk around. The smaller version of that decision is available to you in your own project, and it usually looks like deleting a file rather than adding one.

If you do write signing code by hand, the key-size check that Web Crypto will not do for you is the next thing worth reading, and the relay endpoint those session tokens protect shows where this lands in a real app.

Everything above came from running it: Node v22.16.0 on Linux, Chromium for the browser signature, jose 5.9.6 and jose 6.2.15 unpacked from npm.

❯ls ./related
❯cat ./comments

Comments are not configured yet. Enable GitHub Discussions and paste the giscus repo-id / category-id into src/consts.ts.