Skip to content

Commit 367578f

Browse files
authored
Merge pull request #28 from DuendeSoftware/wca/jwt-decoder/improve-json-end-detection
Improve encoded JSON-end detection
2 parents 1839953 + 2ef95a1 commit 367578f

File tree

1 file changed

+23
-15
lines changed

1 file changed

+23
-15
lines changed

src/Pages/Home/JwtDecoder/JwtDecoder.cshtml

Lines changed: 23 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -407,25 +407,33 @@
407407
return []; // No JSON object found
408408
}
409409
410-
// Find the base64 marker for a JSON object to end parsing ('In0' for '"}' or 'fQ' for '}')
410+
/* Finding a valid ending for base64 URL safe encoded JSON object is a bit trickier, as the encoded version
411+
is different for JSON objects ending with ']' to close an array, '"' for ending a string value,
412+
a number value or a boolean value.
413+
*/
411414
let jsonEndPos = part.length;
412-
while (jsonEndPos > jsonStartPos && (part.substring(jsonEndPos - 3, jsonEndPos) !== 'In0') && (part.substring(jsonEndPos - 2, jsonEndPos) !== 'fQ')) {
413-
jsonEndPos--;
414-
}
415-
if (jsonEndPos <= jsonStartPos) {
416-
return []; // No valid JSON object found
417-
}
415+
let encodedPart = part.substring(jsonStartPos, jsonEndPos);
416+
let decodedPart = '';
417+
let json = null;
418418
419-
try {
420-
const encodedPart = part.substring(jsonStartPos, jsonEndPos);
421-
const decodedPart = decodeBase64UrlSafe(encodedPart);
422-
return [JSON.parse(decodedPart), encodedPart];
423-
}
424-
catch {
425-
419+
do {
420+
try {
421+
decodedPart = decodeBase64UrlSafe(encodedPart);
422+
json = JSON.parse(decodedPart);
423+
if (json && typeof json === 'object') {
424+
// If we successfully parsed a JSON object, we can return it
425+
return [json, encodedPart];
426+
}
427+
}
428+
catch {
429+
// If decoding fails, we need to reduce the end position until we find a valid JSON object
430+
jsonEndPos--;
431+
encodedPart = part.substring(jsonStartPos, jsonEndPos);
432+
}
426433
}
434+
while (jsonEndPos > jsonStartPos);
427435
428-
return [];
436+
return []; // No valid JSON object found
429437
}
430438
431439
function colorJwtInput(target, originalParts, encodedHeader, encodedPayload, signature) {

0 commit comments

Comments
 (0)