From ecceb6a87f015f1e1eae5a0d775069672be5e3d4 Mon Sep 17 00:00:00 2001 From: Alberto Ricart Date: Wed, 10 Aug 2022 14:51:47 -0500 Subject: [PATCH] [FIX] simplified the nuid "shim" for getRandomValues [FIX] put an assertion for crypto.subtle on the objectstore create, as this is required --- nats-base-client/nuid.ts | 32 +++++++++++--------------------- nats-base-client/objectstore.ts | 15 +++++++++------ 2 files changed, 20 insertions(+), 27 deletions(-) diff --git a/nats-base-client/nuid.ts b/nats-base-client/nuid.ts index d62e9767..36570f90 100644 --- a/nats-base-client/nuid.ts +++ b/nats-base-client/nuid.ts @@ -24,28 +24,18 @@ const minInc = 33; const maxInc = 333; const totalLen = preLen + seqLen; -const cryptoObj = initCrypto(); - -function initCrypto() { - let cryptoObj = null; - if (typeof globalThis !== "undefined") { - if ( - "crypto" in globalThis && globalThis.crypto.getRandomValues !== undefined - ) { - cryptoObj = globalThis.crypto; - } +function _getRandomValues(a: Uint8Array) { + for (let i = 0; i < a.length; i++) { + a[i] = Math.floor(Math.random() * 255); } - if (!cryptoObj) { - // shim it - cryptoObj = { - getRandomValues: function (array: Uint8Array) { - for (let i = 0; i < array.length; i++) { - array[i] = Math.floor(Math.random() * 255); - } - }, - }; +} + +function fillRandom(a: Uint8Array) { + if (globalThis?.crypto?.getRandomValues) { + globalThis.crypto.getRandomValues(a); + } else { + _getRandomValues(a); } - return cryptoObj; } /** @@ -92,7 +82,7 @@ export class Nuid { */ private setPre() { const cbuf = new Uint8Array(preLen); - cryptoObj.getRandomValues(cbuf); + fillRandom(cbuf); for (let i = 0; i < preLen; i++) { const di = cbuf[i] % base; this.buf[i] = digits.charCodeAt(di); diff --git a/nats-base-client/objectstore.ts b/nats-base-client/objectstore.ts index 179fb522..dd1e44c7 100644 --- a/nats-base-client/objectstore.ts +++ b/nats-base-client/objectstore.ts @@ -635,12 +635,6 @@ export class ObjectStoreImpl implements ObjectStore { } async init(opts: Partial = {}): Promise { - // we may not have support in the environment - if (typeof crypto?.subtle?.digest !== "function") { - throw new Error( - "unable to calculate hashes - crypto.subtle.digest with sha256 support is required", - ); - } try { this.stream = objectStoreStreamName(this.name); } catch (err) { @@ -669,6 +663,15 @@ export class ObjectStoreImpl implements ObjectStore { name: string, opts: Partial = {}, ): Promise { + // we may not have support in the environment + if (typeof crypto?.subtle?.digest !== "function") { + return Promise.reject( + new Error( + "objectstore: unable to calculate hashes - crypto.subtle.digest with sha256 support is required", + ), + ); + } + const jsi = js as JetStreamClientImpl; let jsopts = jsi.opts || {} as JetStreamOptions; const to = jsopts.timeout || 2000;