Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 36 additions & 1 deletion src/lib/isJWT.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,32 @@
import assertString from './util/assertString';
import isBase64 from './isBase64';

function getGlobalScope() {
if (typeof global !== 'undefined') return global;
if (typeof self !== 'undefined') return self;
if (typeof window !== 'undefined') return window;
return {};
}

function isBase64EncodedJSON(base64Str) {
// Convert URL-safe base64 to standard base64
const standardBase64 = base64Str.replace(/-/g, '+').replace(/_/g, '/');
try {
const scope = getGlobalScope();
const decoded = typeof scope.atob === 'function'
? scope.atob(standardBase64)
: Buffer.from(standardBase64, 'base64').toString('binary');
try {
JSON.parse(decoded);
return true;
} catch (e2) {
return false;
}
} catch (e) {
return false;
}
}

export default function isJWT(str) {
assertString(str);

Expand All @@ -11,5 +37,14 @@ export default function isJWT(str) {
return false;
}

return dotSplit.reduce((acc, currElem) => acc && isBase64(currElem, { urlSafe: true }), true);
const [header, payload, signature] = dotSplit;

if (!isBase64(header, { urlSafe: true })
|| !isBase64(payload, { urlSafe: true })
|| !isBase64(signature, { urlSafe: true })) {
return false;
}

// header and payload must be valid JSON when decoded
return isBase64EncodedJSON(header) && isBase64EncodedJSON(payload);
}
4 changes: 4 additions & 0 deletions test/validators.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -5549,6 +5549,10 @@ describe('Validators', () => {
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NSIsIm5hbWUiOiJKb2huIERvZSIsImlhdCI6MTYxNjY1Mzg3Mn0.eyJpc3MiOiJodHRwczovL2V4YW1wbGUuY29tIiwiaWF0IjoxNjE2NjUzODcyLCJleHAiOjE2MTY2NTM4ODJ9.a1jLRQkO5TV5y5ERcaPAiM9Xm2gBdRjKrrCpHkGr_8M',
'$Zs.ewu.su84',
'ks64$S/9.dy$§kz.3sd73b',
// non-JSON header (valid base64 URL-safe but not valid JSON when decoded)
'ZmFrZSBoZWFkZXI.eyJzdWIiOiIxMjM0NTY3ODkwIn0.ZmFrZXNpZw',
// non-JSON payload (valid base64 URL-safe but not valid JSON)
'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.bm9uLWpzb24tcGF5bG9hZA.sig',
],
error: [
[],
Expand Down
Loading