Skip to content

Commit c406f1b

Browse files
committed
Add notes on security
1 parent 0a4242c commit c406f1b

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed

readme.md

+26
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,28 @@ Partial matches are not supported.
109109

110110
The given, modified, `tree`.
111111

112+
## Security
113+
114+
Improper use of the `replace` can open you up to a
115+
[cross-site scripting (XSS)][xss] attack as the value of `replace` is injected
116+
into the syntax tree.
117+
The following example shows how a script is injected that runs when loaded in a
118+
browser.
119+
120+
```js
121+
findAndReplace(h('p', 'This and that.'), 'and', function() {
122+
return h('script', 'alert(1)')
123+
})
124+
```
125+
126+
Yields:
127+
128+
```html
129+
<p>This <script>alert(1)</script> that.</p>
130+
```
131+
132+
Do not use user input in `replace` or use [`hast-util-santize`][sanitize].
133+
112134
## Contribute
113135

114136
See [`contributing.md` in `syntax-tree/.github`][contributing] for ways to get
@@ -172,3 +194,7 @@ abide by its terms.
172194
[preorder]: https://github.com/syntax-tree/unist#preorder
173195

174196
[text]: https://github.com/syntax-tree/hast#text
197+
198+
[xss]: https://en.wikipedia.org/wiki/Cross-site_scripting
199+
200+
[sanitize]: https://github.com/syntax-tree/hast-util-sanitize

test.js

+34
Original file line numberDiff line numberDiff line change
@@ -204,6 +204,40 @@ test('findAndReplace', function(t) {
204204
'should not be order-sensitive with regexes'
205205
)
206206

207+
t.deepEqual(
208+
findAndReplace(create(), 'and', 'alert(1)'),
209+
h('p', [
210+
'Some ',
211+
h('em', 'emphasis'),
212+
', ',
213+
h('strong', 'importance'),
214+
', ',
215+
'alert(1)',
216+
' ',
217+
h('code', 'code'),
218+
'.'
219+
]),
220+
'security: replacer as string (safe)'
221+
)
222+
223+
t.deepEqual(
224+
findAndReplace(create(), 'and', function() {
225+
return h('script', 'alert(1)')
226+
}),
227+
h('p', [
228+
'Some ',
229+
h('em', 'emphasis'),
230+
', ',
231+
h('strong', 'importance'),
232+
', ',
233+
h('script', 'alert(1)'),
234+
' ',
235+
h('code', 'code'),
236+
'.'
237+
]),
238+
'security: replacer as function (unsafe)'
239+
)
240+
207241
t.end()
208242
})
209243

0 commit comments

Comments
 (0)