diff --git a/auth/index.html b/auth/index.html
index f4f7cd2..c630845 100644
--- a/auth/index.html
+++ b/auth/index.html
@@ -268,12 +268,19 @@
Message log
) {
throw new Error("cannot create uint8array from invalid hex string");
}
+
var buffer = new Uint8Array(
hexString.match(/../g).map((h) => parseInt(h, 16))
);
if (!length) {
return buffer;
}
+ if (hexString.length / 2 > length) {
+ throw new Error(
+ "hex value cannot fit in a buffer of " + length + " byte(s)"
+ );
+ }
+
var paddedBuffer = new Uint8Array(length);
paddedBuffer.set(buffer, length - buffer.length);
return paddedBuffer;
@@ -588,7 +595,7 @@ Message log
/**
* Converts a `BigInt` into a base64url encoded string
* @param {BigInt} num
- * @param {number} length: optional number of bytes contained in the resulting string
+ * @param {number} length: optional number of bytes contained in the intermediary buffer before encoding as base64url
* @return {string}
*/
var bigIntToBase64Url = function (num, length) {
@@ -990,6 +997,7 @@ Message log
base64urlEncode,
base64urlDecode,
base58checkDecode,
+ bigIntToBase64Url,
bigIntToHex,
stringToBase64urlString,
uint8arrayToHexString,
diff --git a/auth/index.test.js b/auth/index.test.js
index caa8141..53675ff 100644
--- a/auth/index.test.js
+++ b/auth/index.test.js
@@ -262,6 +262,10 @@ describe("TKHQ", () => {
expect(TKHQ.uint8arrayFromHexString("01", 2).toString()).toEqual("0,1");
// Happy path: if length parameter is omitted, do not pad the resulting buffer
expect(TKHQ.uint8arrayFromHexString("01").toString()).toEqual("1");
+ // Error case: hex value cannot fit in desired length
+ expect(() => {
+ TKHQ.uint8arrayFromHexString("0100", 1).toString(); // the number 256 cannot fit into 1 byte
+ }).toThrow("hex value cannot fit in a buffer of 1 byte(s)");
});
it("contains bigIntToHex", () => {
@@ -275,6 +279,20 @@ describe("TKHQ", () => {
}).toThrow("number cannot fit in a hex string of 2 characters");
});
+ it("contains bigIntToBase64Url", () => {
+ expect(TKHQ.bigIntToBase64Url(BigInt(1))).toEqual("AQ");
+ expect(TKHQ.bigIntToBase64Url(BigInt(1), 2)).toEqual("AAE");
+
+ // extrapolate to larger numbers
+ expect(TKHQ.bigIntToBase64Url(BigInt(255))).toEqual("_w"); // max 1 byte
+ expect(TKHQ.bigIntToBase64Url(BigInt(255), 2)).toEqual("AP8"); // max 1 byte expressed in 2 bytes
+
+ // error case
+ expect(() => {
+ TKHQ.bigIntToBase64Url(BigInt(256), 1);
+ }).toThrow("hex value cannot fit in a buffer of 1 byte(s)");
+ });
+
it("logs messages and sends messages up", async () => {
// TODO: test logMessage / sendMessageUp
expect(true).toBe(true);