Skip to content

Commit 018dfb4

Browse files
fix(isJWT): replace Buffer.from with cross-env decode helper; add unsecured JWT valid test
1 parent f44c09e commit 018dfb4

2 files changed

Lines changed: 29 additions & 1 deletion

File tree

src/lib/isJWT.js

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,40 @@
11
import assertString from './util/assertString';
22
import isBase64 from './isBase64';
33

4+
function decodeBase64Url(b64) {
5+
if (typeof Buffer !== 'undefined') {
6+
if (typeof Buffer.from === 'function') {
7+
return Buffer.from(b64, 'base64').toString('utf8');
8+
}
9+
// eslint-disable-next-line no-buffer-constructor
10+
return new Buffer(b64, 'base64').toString('utf8');
11+
}
12+
if (typeof atob === 'function') {
13+
const binary = atob(b64);
14+
if (typeof TextDecoder !== 'undefined') {
15+
const bytes = new Uint8Array(binary.length);
16+
for (let i = 0; i < binary.length; i += 1) {
17+
bytes[i] = binary.charCodeAt(i);
18+
}
19+
return new TextDecoder('utf-8').decode(bytes);
20+
}
21+
let encoded = '';
22+
for (let i = 0; i < binary.length; i += 1) {
23+
const code = binary.charCodeAt(i).toString(16).padStart(2, '0');
24+
encoded += `%${code}`;
25+
}
26+
return decodeURIComponent(encoded);
27+
}
28+
return b64;
29+
}
30+
431
function tryDecodeJSON(segment) {
532
if (!isBase64(segment, { urlSafe: true })) return false;
633
try {
734
// Normalize base64url alphabet to base64, then restore stripped padding
835
let b64 = segment.replace(/-/g, '+').replace(/_/g, '/');
936
while (b64.length % 4) b64 += '=';
10-
const decoded = Buffer.from(b64, 'base64').toString('utf8');
37+
const decoded = decodeBase64Url(b64);
1138
const parsed = JSON.parse(decoded);
1239
if (typeof parsed !== 'object') return false;
1340
if (parsed === null) return false;

test/validators.test.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5542,6 +5542,7 @@ describe('Validators', () => {
55425542
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJsb3JlbSI6Imlwc3VtIn0.ymiJSsMJXR6tMSr8G9usjQ15_8hKPDv_CArLhxw28MI',
55435543
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkb2xvciI6InNpdCIsImFtZXQiOlsibG9yZW0iLCJpcHN1bSJdfQ.rRpe04zbWbbJjwM43VnHzAboDzszJtGrNsUxaqQ-GQ8',
55445544
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqb2huIjp7ImFnZSI6MjUsImhlaWdodCI6MTg1fSwiamFrZSI6eyJhZ2UiOjMwLCJoZWlnaHQiOjI3MH19.YRLPARDmhGMC3BBk_OhtwwK21PIkVCqQe8ncIRPKo-E',
5545+
'eyJhbGciOiJub25lIn0.eyJpc3MiOiJqb2UiLCJleHAiOjEzMDA4MTkzODAsImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.',
55455546
],
55465547
invalid: [
55475548
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9',

0 commit comments

Comments
 (0)