Skip to content

Commit

Permalink
Pkce challenge code empty (#221)
Browse files Browse the repository at this point in the history
* Fixing empty challenge code problem

* Adding test for bufferToBase64UrlEncoded method

* fix ie11 'digest' call
  • Loading branch information
benprime authored and Luís Rudge committed Sep 23, 2019
1 parent f21e769 commit 752615b
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 3 deletions.
19 changes: 19 additions & 0 deletions __tests__/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,25 @@ describe('utils', () => {
const result = await sha256('test');
expect(result).toBe(true);
});
it('handles ie11 digest.result scenario', async () => {
(<any>global).crypto = {
subtle: {
digest: jest.fn((alg, encoded) => {
expect(alg).toMatchObject({ name: 'SHA-256' });
expect(Array.from(encoded)).toMatchObject([116, 101, 115, 116]);
return { result: true };
})
}
};
const result = await sha256('test');
expect(result).toBe(true);
});
});
describe('bufferToBase64UrlEncoded ', () => {
it('generates correct base64 encoded value from a buffer', async () => {
const result = await bufferToBase64UrlEncoded([116, 101, 115, 116]);
expect(result).toBe('dGVzdA');
});
});
describe('openPopup', () => {
it('opens the popup', () => {
Expand Down
20 changes: 17 additions & 3 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,8 +108,22 @@ export const createQueryParams = (params: any) => {
.join('&');
};

export const sha256 = (s: string) =>
window.crypto.subtle.digest({ name: 'SHA-256' }, new TextEncoder().encode(s));
export const sha256 = async (s: string) => {
const response = await Promise.resolve(
window.crypto.subtle.digest(
{ name: 'SHA-256' },
new TextEncoder().encode(s)
)
);
// msCrypto (IE11) uses the old spec, which is not Promise based
// https://msdn.microsoft.com/en-us/expression/dn904640(v=vs.71)
// Instead of returning a promise, it returns a CryptoOperation
// with a `result` property in it
if ((<any>response).result) {
return (<any>response).result;
}
return response;
};

const urlEncodeB64 = (input: string) => {
const b64Chars = { '+': '-', '/': '_', '=': '' };
Expand All @@ -131,7 +145,7 @@ export const urlDecodeB64 = (input: string) =>
decodeB64(input.replace(/_/g, '/').replace(/-/g, '+'));

export const bufferToBase64UrlEncoded = input => {
const ie11SafeInput = new Uint8Array(Array.from(input));
const ie11SafeInput = new Uint8Array(input);
return urlEncodeB64(
window.btoa(String.fromCharCode(...Array.from(ie11SafeInput)))
);
Expand Down

0 comments on commit 752615b

Please sign in to comment.