Skip to content

Commit

Permalink
perf: use native node's base64url encoding when available
Browse files Browse the repository at this point in the history
  • Loading branch information
panva committed Jan 18, 2021
1 parent 299e8a7 commit 6149bd3
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 38 deletions.
34 changes: 12 additions & 22 deletions lib/helpers/base64url.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,16 @@
const b64uRegExp = /^[a-zA-Z0-9_-]*$/;
let encode;
let encodeBuffer;
if (Buffer.isEncoding('base64url')) {
encode = (input, encoding = 'utf8') => Buffer.from(input, encoding).toString('base64url');
encodeBuffer = (buf) => buf.toString('base64url');
} else {
const fromBase64 = (base64) => base64.replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
encode = (input, encoding = 'utf8') => fromBase64(Buffer.from(input, encoding).toString('base64'));
encodeBuffer = (buf) => fromBase64(buf.toString('base64'));
}

const fromBase64 = (base64) => base64.replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');

const toBase64 = (base64url) => base64url.replace(/-/g, '+').replace(/_/g, '/');

const encode = (input, encoding = 'utf8') => fromBase64(Buffer.from(input, encoding).toString('base64'));

const encodeBuffer = (buf) => fromBase64(buf.toString('base64'));

const decode = (input) => {
if (!b64uRegExp.test(input)) {
throw new TypeError('input is not a valid base64url encoded string');
}
return Buffer.from(toBase64(input), 'base64').toString('utf8');
};

const decodeToBuffer = (input) => {
if (!b64uRegExp.test(input)) {
throw new TypeError('input is not a valid base64url encoded string');
}
return Buffer.from(toBase64(input), 'base64');
};
const decode = (input) => Buffer.from(input, 'base64').toString('utf8');
const decodeToBuffer = (input) => Buffer.from(input, 'base64');

module.exports.decode = decode;
module.exports.decodeToBuffer = decodeToBuffer;
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,14 +55,14 @@
"debug": "^4.1.1",
"ejs": "^3.1.5",
"got": "^9.6.0",
"jose": "^2.0.2",
"jose": "^2.0.4",
"jsesc": "^3.0.1",
"koa": "^2.13.0",
"koa-compose": "^4.1.0",
"lru-cache": "^6.0.0",
"nanoid": "^3.1.10",
"object-hash": "^2.0.3",
"oidc-token-hash": "^5.0.0",
"oidc-token-hash": "^5.0.1",
"raw-body": "^2.4.1"
},
"devDependencies": {
Expand Down
14 changes: 0 additions & 14 deletions test/helpers/base64url.test.js

This file was deleted.

0 comments on commit 6149bd3

Please sign in to comment.