Skip to content

Commit

Permalink
feedback: error check
Browse files Browse the repository at this point in the history
  • Loading branch information
andrewkmin committed Aug 8, 2024
1 parent 5a0ed1e commit ebfd9da
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
7 changes: 6 additions & 1 deletion auth/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -218,10 +218,15 @@ <h2>Message log</h2>
if (!hexString || hexString.length % 2 != 0 || !hexRegex.test(hexString)) {
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;
Expand Down Expand Up @@ -503,7 +508,7 @@ <h2>Message log</h2>
/**
* 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) {
Expand Down
9 changes: 9 additions & 0 deletions auth/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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", () => {
Expand All @@ -282,6 +286,11 @@ describe("TKHQ", () => {
// 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 () => {
Expand Down

0 comments on commit ebfd9da

Please sign in to comment.