-
-
Notifications
You must be signed in to change notification settings - Fork 690
/
hooks-link-proxy-demo.html
51 lines (45 loc) · 2.13 KB
/
hooks-link-proxy-demo.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<!doctype html>
<html>
<head>
<script src="../dist/purify.js"></script>
</head>
<body>
<!-- Our DIV to receive content -->
<div id="sanitized"></div>
<!-- Now let's sanitize that content -->
<script>
'use strict';
// Assuming DOMPurify is globally available
// import DOMPurify from 'dompurify'; // Uncomment if using ES6 modules
const proxy = 'https://my.proxy.service/?';
// Specify dirty HTML
const dirty = `
<a href="http://evil.com/">CLICK</a>
<a href="http://evil.com/" target="jajaja">CLICK</a>
<svg><a xlink:href="http://evil.com/"><circle r=40></a></svg>
<svg><a xlink:href="http://evil.com/" href="http://evil.com/"><circle r=40></a></svg>
<form action="http://evil.com/"><input type="submit"></form>
<map name="test"><area href="http://evil.com/" shape="rect" coords="0,0,200,200"></area></map>
<math href="http://evil.com/">CLICKME</math>
`;
// Add a hook to make all links point to a proxy
DOMPurify.addHook('afterSanitizeAttributes', node => {
// proxy form actions
if ('action' in node) {
node.setAttribute('action', `${proxy}${encodeURIComponent(node.getAttribute('action'))}`);
}
// proxy regular HTML links
if (node.hasAttribute('href')) {
node.setAttribute('href', `${proxy}${encodeURIComponent(node.getAttribute('href'))}`);
}
// proxy SVG/MathML links
if (node.hasAttribute('xlink:href')) {
node.setAttribute('xlink:href', `${proxy}${encodeURIComponent(node.getAttribute('xlink:href'))}`);
}
});
// Clean HTML string and write into our DIV
const clean = DOMPurify.sanitize(dirty);
document.getElementById('sanitized').innerHTML = clean;
</script>
</body>
</html>