Skip to content

Commit e7111df

Browse files
authored
SGEO-2914: Sanitize HTML output for place_name (#547)
1 parent cff503b commit e7111df

File tree

3 files changed

+31
-1
lines changed

3 files changed

+31
-1
lines changed

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
## HEAD
22

3+
### Bug fixes 🐛
4+
5+
- Fix potential XSS when rendering place name [#547](https://github.com/mapbox/mapbox-gl-geocoder/pull/547)
6+
37
## 5.1.1
48

59
### Dependency update

lib/index.js

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,16 @@ function MapboxGeocoder(options) {
9393
this.geolocation = new Geolocation();
9494
}
9595

96+
function escapeHtml(str) {
97+
if (!str) return '';
98+
return String(str)
99+
.replace(/&/g, '&')
100+
.replace(/</g, '&lt;')
101+
.replace(/>/g, '&gt;')
102+
.replace(/"/g, '&quot;')
103+
.replace(/'/g, '&#39;');
104+
}
105+
96106
MapboxGeocoder.prototype = {
97107
options: {
98108
zoom: 16,
@@ -116,7 +126,7 @@ MapboxGeocoder.prototype = {
116126
return item.place_name
117127
},
118128
render: function(item) {
119-
var placeName = item.place_name.split(',');
129+
var placeName = escapeHtml(item.place_name).split(',');
120130
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>';
121131
}
122132
},

test/test.geocoder.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,22 @@ test('geocoder', function(tt) {
4040
t.end();
4141
});
4242

43+
tt.test('rendered place name is HTML-sanitized', function(t){
44+
t.plan(2);
45+
46+
const html = '<script>alert(1)</script>'; // should not render this as-is!
47+
const escapedHtml = '&lt;script&gt;alert(1)&lt;/script&gt';
48+
49+
var fixture = {
50+
id: 'abc123',
51+
place_name: html
52+
}
53+
54+
const rendered = geocoder.options.render(fixture);
55+
t.ok(rendered.indexOf(html) === -1, 'rendered result does not contain original dangerous HTML');
56+
t.ok(rendered.indexOf(escapedHtml) > 0, 'rendered result contains escaped version of HTML');
57+
})
58+
4359
tt.test('set/get input', function(t) {
4460
t.plan(4)
4561
setup({ proximity: { longitude: -79.45, latitude: 43.65 } });

0 commit comments

Comments
 (0)