Skip to content

Commit

Permalink
[FIX] simplified the nuid "shim" for getRandomValues
Browse files Browse the repository at this point in the history
[FIX] put an assertion for crypto.subtle on the objectstore create, as this is required
  • Loading branch information
aricart committed Aug 10, 2022
1 parent 24eed1a commit ecceb6a
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 27 deletions.
32 changes: 11 additions & 21 deletions nats-base-client/nuid.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

/**
Expand Down Expand Up @@ -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);
Expand Down
15 changes: 9 additions & 6 deletions nats-base-client/objectstore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -635,12 +635,6 @@ export class ObjectStoreImpl implements ObjectStore {
}

async init(opts: Partial<ObjectStoreOptions> = {}): Promise<void> {
// 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) {
Expand Down Expand Up @@ -669,6 +663,15 @@ export class ObjectStoreImpl implements ObjectStore {
name: string,
opts: Partial<ObjectStoreOptions> = {},
): Promise<ObjectStore> {
// 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;
Expand Down

0 comments on commit ecceb6a

Please sign in to comment.