From: Chris Duncan Date: Mon, 4 Aug 2025 16:45:45 +0000 (-0700) Subject: Improve entropy validation when importing. X-Git-Tag: v0.10.5~46^2~17 X-Git-Url: https://git.codecow.com/?a=commitdiff_plain;h=97a7eefd6a46ed1c6abba8f613e762a62be4f365;p=libnemo.git Improve entropy validation when importing. --- diff --git a/src/lib/entropy.ts b/src/lib/entropy.ts index 3e1aaa0..614b1c1 100644 --- a/src/lib/entropy.ts +++ b/src/lib/entropy.ts @@ -74,21 +74,8 @@ export class Entropy { * @param {Uint8Array} bytes - Byte array */ static async import (bytes: Uint8Array): Promise - static async import (input: string | ArrayBuffer | Uint8Array): Promise { + static async import (input: unknown): Promise { return new Promise((resolve, reject) => { - if (typeof input === 'string') { - if (input.length < this.MIN * 2 || input.length > this.MAX * 2) { - throw new RangeError(`Entropy must be ${this.MIN * 2}-${this.MAX * 2} characters`) - } - if (input.length % this.MOD * 2 !== 0) { - throw new RangeError(`Entropy must be a multiple of ${this.MOD * 2} characters`) - } - if (!/^[0-9a-fA-F]+$/i.test(input)) { - throw new RangeError('Entropy contains invalid hexadecimal characters') - } - Entropy.#isInternal = true - resolve(new this(hex.toBytes(input))) - } if (input instanceof ArrayBuffer) { if (input.byteLength < this.MIN || input.byteLength > this.MAX) { @@ -99,23 +86,35 @@ export class Entropy { } Entropy.#isInternal = true resolve(new this(new Uint8Array(input))) + return } if (input instanceof Uint8Array) { - if (!(input.buffer instanceof ArrayBuffer)) { + const { buffer } = input + if (!(buffer instanceof ArrayBuffer)) { throw new TypeError(`Entropy imported bytes must be backed by an ArrayBuffer.`) } - if (input.length < this.MIN || input.length > this.MAX) { - throw new Error(`Entropy must be ${this.MIN}-${this.MAX} bytes`) + this.import(buffer).then(resolve).catch(reject) + return + } + + if (typeof input === 'string') { + if (input.length < this.MIN * 2 || input.length > this.MAX * 2) { + throw new RangeError(`Entropy must be ${this.MIN * 2}-${this.MAX * 2} characters`) } - if (input.length % this.MOD !== 0) { - throw new RangeError(`Entropy must be a multiple of ${this.MOD} bytes`) + if (input.length % this.MOD * 2 !== 0) { + throw new RangeError(`Entropy must be a multiple of ${this.MOD * 2} characters`) + } + if (!/^[0-9a-fA-F]+$/i.test(input)) { + throw new RangeError('Entropy contains invalid hexadecimal characters') } Entropy.#isInternal = true - resolve(new this(input)) + resolve(new this(hex.toBytes(input))) + return } reject(new TypeError(`Entropy cannot import ${typeof input}`)) + return }) }