From 3f93924448074fe69f850195fa010da9c891b387 Mon Sep 17 00:00:00 2001 From: Marcos Passos Date: Fri, 16 Dec 2022 10:06:08 -0300 Subject: [PATCH] Fix decoding of UTF8-encoded tokens (#297) --- src/base64Url.ts | 14 ++++++++++++-- test/base64Url.test.ts | 7 +------ 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/src/base64Url.ts b/src/base64Url.ts index f48518ca..cc5fb0e4 100644 --- a/src/base64Url.ts +++ b/src/base64Url.ts @@ -10,9 +10,19 @@ function base64Escape(value: string): string { } export function base64UrlEncode(value: string): string { - return base64Escape(window.btoa(value)); + return base64Escape( + window.btoa( + window.encodeURIComponent(value) + .replace(/%([0-9A-F]{2})/g, (_, p1) => String.fromCharCode(Number.parseInt(p1, 16))), + ), + ); } export function base64UrlDecode(value: string): string { - return window.atob(base64Unescape(value)); + return window.decodeURIComponent( + Array.prototype.map.call( + window.atob(base64Unescape(value)), + (char: string) => `%${(`00${char.charCodeAt(0).toString(16)}`).slice(-2)}`, + ).join(''), + ); } diff --git a/test/base64Url.test.ts b/test/base64Url.test.ts index 8e177330..69095f0d 100644 --- a/test/base64Url.test.ts +++ b/test/base64Url.test.ts @@ -3,12 +3,6 @@ import {base64UrlDecode, base64UrlEncode} from '../src/base64Url'; describe('A base64 URL encoder/decoder function', () => { const encodeTests = [ ['000000', 'MDAwMDAw'], - ['\0\0\0\0', 'AAAAAA'], - ['\xff', '_w'], - ['\xff\xff', '__8'], - ['\xff\xff\xff', '____'], - ['\xff\xff\xff\xff', '_____w'], - ['\xfb', '-w'], ['', ''], ['f', 'Zg'], ['fo', 'Zm8'], @@ -16,6 +10,7 @@ describe('A base64 URL encoder/decoder function', () => { ['foob', 'Zm9vYg'], ['fooba', 'Zm9vYmE'], ['foobar', 'Zm9vYmFy'], + ['Jacaré', 'SmFjYXLDqQ'], ]; it.each(encodeTests)('should encode "%s" as "%s"', (decoded: string, encoded: string) => {