Skip to content

Commit

Permalink
refactor: use randomBytes from @noble/hashes
Browse files Browse the repository at this point in the history
  • Loading branch information
twhy committed Jun 5, 2024
1 parent 671b750 commit 04a3700
Show file tree
Hide file tree
Showing 4 changed files with 9 additions and 31 deletions.
4 changes: 3 additions & 1 deletion packages/crypto/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,9 @@
"ts-node/register"
]
},
"dependencies": {},
"dependencies": {
"@noble/hashes": "^1.4.0"
},
"publishConfig": {
"access": "public"
}
Expand Down
23 changes: 1 addition & 22 deletions packages/crypto/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1 @@
/**
* Generates cryptographically secure random bytes.
* @param size The number of random bytes to generate. The `size` must not be greater than 65536.
* @returns A Uint8Array containing the random bytes.
* @throws {RangeError} If `size` is greater than 65536.
*/
export function randomBytes(size: number): Uint8Array {
const MAX_BYTES = 65536; // limit of Crypto.getRandomValues()
if (size > MAX_BYTES) {
throw new RangeError(`size must be less than or equal to ${MAX_BYTES}`);
}

const bytes = new Uint8Array(size);
try {
crypto.getRandomValues(bytes); // Node.js 20+ and modern browsers
} catch {
/* eslint-disable @typescript-eslint/no-var-requires */
require("crypto").getRandomValues(bytes); // Node.js 18
}

return bytes;
}
export { randomBytes } from "@noble/hashes/utils";
6 changes: 0 additions & 6 deletions packages/crypto/tests/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,4 @@ test("randomBytes", (t) => {
t.is(bytes.length, size);
t.is(bytes.byteLength, size);
t.is(bytes.constructor, Uint8Array);

const TOO_MANY_BYTES = 65538;
t.throws(() => randomBytes(TOO_MANY_BYTES), {
instanceOf: RangeError,
message: `size must be less than or equal to 65536`,
});
});
7 changes: 5 additions & 2 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 04a3700

Please sign in to comment.