From a3ff52554b93f8bbf31c47397f68c02e50ba50be Mon Sep 17 00:00:00 2001 From: Alvin Ng <243186+alvinsj@users.noreply.github.com> Date: Sat, 8 Jun 2024 17:01:19 +0800 Subject: [PATCH] minor fix --- src/lib/__tests__/pkce.test.js | 5 +++++ src/lib/pkce.ts | 7 ++++--- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/src/lib/__tests__/pkce.test.js b/src/lib/__tests__/pkce.test.js index 7992982..c1fdca6 100644 --- a/src/lib/__tests__/pkce.test.js +++ b/src/lib/__tests__/pkce.test.js @@ -45,6 +45,11 @@ describe('toSha256', () => { }) describe('toBase64Url', () => { + test('throws error on empty array', () => { + expect(() => toBase64Url([])) + .toThrow('bytes must not be empty') + }); + test('converts to base64url', () => { const base64url = toBase64Url([1, 2, 3, 4, 5]) diff --git a/src/lib/pkce.ts b/src/lib/pkce.ts index 473a6a1..d2f061f 100644 --- a/src/lib/pkce.ts +++ b/src/lib/pkce.ts @@ -13,6 +13,8 @@ export const toSha256 = async (data: string): Promise => { // refer to base64url-encoding in RFC 7636 // https://datatracker.ietf.org/doc/html/rfc7636#appendix-A export const toBase64Url = (bytes: Uint8Array) => { + if (bytes.length === 0) throw new Error('bytes must not be empty'); + const charCodes = Array.from(bytes); let str = btoa(String.fromCharCode.apply(null, charCodes)); str = str.split('=')[0]; @@ -35,9 +37,8 @@ export const createRandomString = (length: number = 34): string => { return randomString; } -export const createPKCECodeChallenge = async (codeVerifies: string): string => { - const hashed: Uint8Array = await toSha256(codeVerifies) +export const createPKCECodeChallenge = async (codeVerifier: string): string => { + const hashed: Uint8Array = await toSha256(codeVerifier) const codeChallenge = toBase64Url(hashed) return codeChallenge; } -