Ravi Sharma

Ravi Sharma

decode-jwt

by Ravi Sharma

Enter any string which contains valid jwt.

// Menu: Decode JWT
// Description: Enter any string which contains valid jwt.
// Author: Ravi Sharma
// Twitter: @irvisharma
/** @type typeof import("jsonwebtoken") */
const jwt = await npm('jsonwebtoken');
try {
const dirtyEncodedToken = await arg('Paste token here', generateLiveHint);
const decoded = decodeToken(dirtyEncodedToken)
if (decoded === null) {
throw 'cannot parse, invalid token'
}
showOutput(decoded);
console.log(decoded);
} catch (e) {
showError(e)
}
function decodeToken(dirtyEncodedToken){
try{
const extractedToken = dirtyEncodedToken.match(/[A-Za-z0-9-_=]+\.[A-Za-z0-9-_=]+\.?[A-Za-z0-9-_.+/=]*/)[0]
return jwt.decode(extractedToken);
} catch (e) {
return null;
}
}
async function generateLiveHint(userInput){
const tokenValidHint = decodeToken(userInput) !== null ? '✅ Found valid token' : `❌ Could not parse <br><br> ${userInput}`;
return md(`
_Press enter after entering to token show details_
<br/><br/>
${userInput && tokenValidHint}
`)
}
function showOutput(value) {
return show(`
<pre style="font-family: Menlo; background: darkslategray; color: navajowhite; font-size: 1.2rem; padding: 1.5em;">
${JSON.stringify(value, null, 2)}
</pre>
`);
}
function showError(e){
show(`
<h1 style="background: darkslategray; color: white; font-family: Menlo;">Could not decode, Did you entered valid token? <br/><br/> ${e}</h1>
`);
}