From 2ad7cf390ba84b8e767ed6fe136800e38356d79c Mon Sep 17 00:00:00 2001 From: John Raptis Date: Tue, 4 Jul 2023 14:54:15 +0300 Subject: [PATCH] fix(backend): Add error when secret key is invalid --- .changeset/hungry-radios-protect.md | 5 +++++ .changeset/silent-games-joke.md | 2 -- packages/backend/src/tokens/keys.ts | 24 ++++++------------------ packages/backend/src/util/request.ts | 4 ++++ 4 files changed, 15 insertions(+), 20 deletions(-) create mode 100644 .changeset/hungry-radios-protect.md delete mode 100644 .changeset/silent-games-joke.md diff --git a/.changeset/hungry-radios-protect.md b/.changeset/hungry-radios-protect.md new file mode 100644 index 0000000000..655cd5c608 --- /dev/null +++ b/.changeset/hungry-radios-protect.md @@ -0,0 +1,5 @@ +--- +'@clerk/backend': patch +--- + +Add a more descriptive error when secret key is invalid diff --git a/.changeset/silent-games-joke.md b/.changeset/silent-games-joke.md deleted file mode 100644 index a845151cc8..0000000000 --- a/.changeset/silent-games-joke.md +++ /dev/null @@ -1,2 +0,0 @@ ---- ---- diff --git a/packages/backend/src/tokens/keys.ts b/packages/backend/src/tokens/keys.ts index f983434d39..be571bc8a7 100644 --- a/packages/backend/src/tokens/keys.ts +++ b/packages/backend/src/tokens/keys.ts @@ -208,28 +208,16 @@ async function fetchJWKSFromBAPI(apiUrl: string, key: string, apiVersion: string }); if (!response.ok) { - const errors = await response.json().then(({ errors }) => { - if (!errors) { - return false; - } - - const invalidSecretKey = getErrorObjectByCode(errors, TokenVerificationErrorCode.InvalidSecretKey); + const json = await response.json(); + const invalidSecretKeyError = getErrorObjectByCode(json?.errors, TokenVerificationErrorCode.InvalidSecretKey); - if (!invalidSecretKey) { - return false; - } - - return { - ...invalidSecretKey, - reason: TokenVerificationErrorReason.InvalidSecretKey, - }; - }); + if (invalidSecretKeyError) { + const reason = TokenVerificationErrorReason.InvalidSecretKey; - if (errors) { throw new TokenVerificationError({ action: TokenVerificationErrorAction.ContactSupport, - message: errors.message, - reason: errors.reason, + message: invalidSecretKeyError.message, + reason, }); } diff --git a/packages/backend/src/util/request.ts b/packages/backend/src/util/request.ts index ebffb344ce..112d9d0130 100644 --- a/packages/backend/src/util/request.ts +++ b/packages/backend/src/util/request.ts @@ -86,5 +86,9 @@ type ErrorFields = { }; export const getErrorObjectByCode = (errors: ErrorFields[], code: string) => { + if (!errors) { + return null; + } + return errors.find((err: ErrorFields) => err.code === code); };