Skip to content

Commit

Permalink
Add nodejs v14 compat, copied from hashes
Browse files Browse the repository at this point in the history
  • Loading branch information
paulmillr committed Sep 1, 2024
1 parent cfc574e commit 1b153a5
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 4 deletions.
2 changes: 2 additions & 0 deletions .github/workflows/nodejs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ jobs:
strategy:
matrix:
node:
- 14
- 16
- 18
- 20
steps:
Expand Down
10 changes: 7 additions & 3 deletions src/cryptoNode.ts
Original file line number Diff line number Diff line change
@@ -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;
7 changes: 6 additions & 1 deletion src/webcrypto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
}

Expand Down

0 comments on commit 1b153a5

Please sign in to comment.