Skip to content

Commit

Permalink
fix(utils): manally conver from b64 to b64url to avoid web polyfill i…
Browse files Browse the repository at this point in the history
…ssues
  • Loading branch information
dtfiedler committed May 2, 2024
1 parent 40be70a commit 766035c
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 3 deletions.
2 changes: 1 addition & 1 deletion jest.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ export default {
preset: 'ts-jest',
clearMocks: true,
moduleFileExtensions: ['ts', 'js', 'mjs'],
testMatch: ['**/src/**/*.test.ts'],
testMatch: ['**/tests/unit/**.test.ts'],
collectCoverage: true,
collectCoverageFrom: ['src/**/*.ts'],
testEnvironment: 'node',
Expand Down
31 changes: 29 additions & 2 deletions src/utils/base64.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,39 @@
*/
import { createHash } from 'crypto';

// safely encodes and decodes base64url strings to and from buffers
const BASE64_CHAR_62 = '+';
const BASE64_CHAR_63 = '/';
const BASE64URL_CHAR_62 = '-';
const BASE64URL_CHAR_63 = '_';
const BASE64_PADDING = '=';

function base64urlToBase64(str: string): string {
const padLength = str.length % 4;
if (padLength) {
str += BASE64_PADDING.repeat(4 - padLength);
}

return str
.replaceAll(BASE64URL_CHAR_62, BASE64_CHAR_62)
.replaceAll(BASE64URL_CHAR_63, BASE64_CHAR_63);
}

function base64urlFromBase64(str) {
return str
.replaceAll(BASE64_CHAR_62, BASE64URL_CHAR_62)
.replaceAll(BASE64_CHAR_63, BASE64URL_CHAR_63)
.replaceAll(BASE64_PADDING, '');
}

export function fromB64Url(input: string): Buffer {
return Buffer.from(input, 'base64');
const b64Str = base64urlToBase64(input);
return Buffer.from(b64Str, 'base64');
}

export function toB64Url(buffer: Buffer): string {
return buffer.toString('base64url');
const b64Str = buffer.toString('base64');
return base64urlFromBase64(b64Str);
}

export function sha256B64Url(input: Buffer): string {
Expand Down
15 changes: 15 additions & 0 deletions tests/unit/b64.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { fromB64Url, toB64Url } from '../../src/utils/base64';

describe('b64utils', () => {
it('should properly convert a buffer to base64url string', async () => {
const input = Buffer.from('hello+_world_+', 'base64');
const expected = input.toString('base64url');
expect(toB64Url(input)).toEqual(expected);
});

it('should properly convert a base64 string to a buffer', async () => {
const b64url = Buffer.from('hello+_world_+').toString('base64url');
const expected = Buffer.from(b64url, 'base64url');
expect(fromB64Url(b64url)).toEqual(expected);
});
});

0 comments on commit 766035c

Please sign in to comment.