Skip to content

Commit ebfd9da

Browse files
committed
feedback: error check
1 parent 5a0ed1e commit ebfd9da

2 files changed

Lines changed: 15 additions & 1 deletion

File tree

auth/index.html

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -218,10 +218,15 @@ <h2>Message log</h2>
218218
if (!hexString || hexString.length % 2 != 0 || !hexRegex.test(hexString)) {
219219
throw new Error('cannot create uint8array from invalid hex string');
220220
}
221+
221222
var buffer = new Uint8Array(hexString.match(/../g).map((h) => parseInt(h, 16)));
222223
if (!length) {
223224
return buffer;
224225
}
226+
if ((hexString.length) / 2 > length) {
227+
throw new Error("hex value cannot fit in a buffer of " + length + " byte(s)");
228+
}
229+
225230
var paddedBuffer = new Uint8Array(length);
226231
paddedBuffer.set(buffer, length - buffer.length);
227232
return paddedBuffer;
@@ -503,7 +508,7 @@ <h2>Message log</h2>
503508
/**
504509
* Converts a `BigInt` into a base64url encoded string
505510
* @param {BigInt} num
506-
* @param {number} length: optional number of bytes contained in the resulting string
511+
* @param {number} length: optional number of bytes contained in the intermediary buffer before encoding as base64url
507512
* @return {string}
508513
*/
509514
var bigIntToBase64Url = function(num, length) {

auth/index.test.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -262,6 +262,10 @@ describe("TKHQ", () => {
262262
expect(TKHQ.uint8arrayFromHexString("01", 2).toString()).toEqual("0,1");
263263
// Happy path: if length parameter is omitted, do not pad the resulting buffer
264264
expect(TKHQ.uint8arrayFromHexString("01").toString()).toEqual("1");
265+
// Error case: hex value cannot fit in desired length
266+
expect(() => {
267+
TKHQ.uint8arrayFromHexString("0100", 1).toString(); // the number 256 cannot fit into 1 byte
268+
}).toThrow("hex value cannot fit in a buffer of 1 byte(s)")
265269
});
266270

267271
it("contains bigIntToHex", () => {
@@ -282,6 +286,11 @@ describe("TKHQ", () => {
282286
// extrapolate to larger numbers
283287
expect(TKHQ.bigIntToBase64Url(BigInt(255))).toEqual("_w"); // max 1 byte
284288
expect(TKHQ.bigIntToBase64Url(BigInt(255), 2)).toEqual("AP8"); // max 1 byte expressed in 2 bytes
289+
290+
// error case
291+
expect(() => {
292+
TKHQ.bigIntToBase64Url(BigInt(256), 1);
293+
}).toThrow("hex value cannot fit in a buffer of 1 byte(s)");
285294
});
286295

287296
it("logs messages and sends messages up", async () => {

0 commit comments

Comments
 (0)