Skip to content
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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
## HEAD

### Bug fixes 🐛

- Fix potential XSS when rendering place name [#547](https://github.com/mapbox/mapbox-gl-geocoder/pull/547)

## 5.1.1

### Dependency update
Expand Down
12 changes: 11 additions & 1 deletion lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,16 @@ function MapboxGeocoder(options) {
this.geolocation = new Geolocation();
}

function escapeHtml(str) {
if (!str) return '';
return String(str)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need to include / as well?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think so. Without the preceding <, the slash is a harmless character.

.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
}

MapboxGeocoder.prototype = {
options: {
zoom: 16,
Expand All @@ -116,7 +126,7 @@ MapboxGeocoder.prototype = {
return item.place_name
},
render: function(item) {
var placeName = item.place_name.split(',');
var placeName = escapeHtml(item.place_name).split(',');
return '<div class="mapboxgl-ctrl-geocoder--suggestion"><div class="mapboxgl-ctrl-geocoder--suggestion-title">' + placeName[0]+ '</div><div class="mapboxgl-ctrl-geocoder--suggestion-address">' + placeName.splice(1, placeName.length).join(',') + '</div></div>';
}
},
Expand Down
16 changes: 16 additions & 0 deletions test/test.geocoder.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,22 @@ test('geocoder', function(tt) {
t.end();
});

tt.test('rendered place name is HTML-sanitized', function(t){
t.plan(2);

const html = '<script>alert(1)</script>'; // should not render this as-is!
const escapedHtml = '&lt;script&gt;alert(1)&lt;/script&gt';

var fixture = {
id: 'abc123',
place_name: html
}

const rendered = geocoder.options.render(fixture);
t.ok(rendered.indexOf(html) === -1, 'rendered result does not contain original dangerous HTML');
t.ok(rendered.indexOf(escapedHtml) > 0, 'rendered result contains escaped version of HTML');
})

tt.test('set/get input', function(t) {
t.plan(4)
setup({ proximity: { longitude: -79.45, latitude: 43.65 } });
Expand Down