From 1b153a5e40b847ae2d6101c34e19048f69cd4762 Mon Sep 17 00:00:00 2001 From: Paul Miller Date: Sun, 1 Sep 2024 15:35:54 +0000 Subject: [PATCH] Add nodejs v14 compat, copied from hashes --- .github/workflows/nodejs.yml | 2 ++ src/cryptoNode.ts | 10 +++++++--- src/webcrypto.ts | 7 ++++++- 3 files changed, 15 insertions(+), 4 deletions(-) diff --git a/.github/workflows/nodejs.yml b/.github/workflows/nodejs.yml index 81bf353..4ba38e4 100644 --- a/.github/workflows/nodejs.yml +++ b/.github/workflows/nodejs.yml @@ -9,6 +9,8 @@ jobs: strategy: matrix: node: + - 14 + - 16 - 18 - 20 steps: diff --git a/src/cryptoNode.ts b/src/cryptoNode.ts index 6fdba9e..e872405 100644 --- a/src/cryptoNode.ts +++ b/src/cryptoNode.ts @@ -1,7 +1,11 @@ -// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. +// We prefer WebCrypto aka globalThis.crypto, which exists in node.js 16+. +// Falls back to Node.js built-in crypto for Node.js <=v14 // See utils.ts for details. -// The file will throw on node.js 14 and earlier. // @ts-ignore import * as nc from 'node:crypto'; export const crypto = - nc && typeof nc === 'object' && 'webcrypto' in nc ? (nc.webcrypto as any) : undefined; + nc && typeof nc === 'object' && 'webcrypto' in nc + ? (nc.webcrypto as any) + : nc && typeof nc === 'object' && 'randomBytes' in nc + ? nc + : undefined; diff --git a/src/webcrypto.ts b/src/webcrypto.ts index b7f9468..3368454 100644 --- a/src/webcrypto.ts +++ b/src/webcrypto.ts @@ -14,8 +14,13 @@ import { AsyncCipher, Cipher, concatBytes } from './utils.js'; * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS. */ export function randomBytes(bytesLength = 32): Uint8Array { - if (crypto && typeof crypto.getRandomValues === 'function') + if (crypto && typeof crypto.getRandomValues === 'function') { return crypto.getRandomValues(new Uint8Array(bytesLength)); + } + // Legacy Node.js compatibility + if (crypto && typeof crypto.randomBytes === 'function') { + return crypto.randomBytes(bytesLength); + } throw new Error('crypto.getRandomValues must be defined'); }