Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix JSON object key displaying #26

Merged
merged 2 commits into from
May 3, 2022
Merged
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
23 changes: 16 additions & 7 deletions json-viewer/jquery.json-viewer.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,18 @@
return urlRegexp.test(string);
}

/**
* Return the input string html escaped
* @return string
*/
function htmlEscape(s) {
return s.replace(/&/g, '&')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/'/g, '&apos;')
.replace(/"/g, '&quot;')
}

/**
* Transform a json object into html representation
* @return string
Expand All @@ -30,12 +42,7 @@
var html = '';
if (typeof json === 'string') {
// Escape tags and quotes
json = json
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/'/g, '&apos;')
.replace(/"/g, '&quot;');
json = htmlEscape(json)

if (options.withLinks && isUrl(json)) {
html += '<a href="' + json + '" class="json-string" target="_blank">' + json + '</a>';
Expand Down Expand Up @@ -76,9 +83,11 @@
html += '{<ul class="json-dict">';
for (var key in json) {
if (Object.prototype.hasOwnProperty.call(json, key)) {
html += '<li>';
key = htmlEscape(key);
var keyRepr = options.withQuotes ?
'<span class="json-string">"' + key + '"</span>' : key;

html += '<li>';
// Add toggle button if item is collapsable
if (isCollapsable(json[key])) {
html += '<a href class="json-toggle">' + keyRepr + '</a>';
Expand Down
26 changes: 26 additions & 0 deletions test/jquery.json-viewer.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,29 @@ test('withQuotes option', () => {
);
});


/**
* Tests for the presence of a script tag inside the 'json' id.
* If none are found, the value was correctly escaped for XSS.
*/
function test_XSS(input) {
$('#json').jsonViewer(input);
scripts_in_json = $('#json script');
expect(scripts_in_json.length).toEqual(0);
}

test('XSS in object value', () => {
const input = {
key_1: '<script>alert(1)</script>'
};

test_XSS(input);
});

test('XSS in object key', () => {
const input = {
'<script>alert(1)</script>': 'val_1'
};

test_XSS(input);
});