File: hooks-link-proxy-demo.html

package info (click to toggle)
node-dompurify 3.3.2%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,956 kB
  • sloc: javascript: 11,284; makefile: 2; sh: 2
file content (51 lines) | stat: -rw-r--r-- 2,186 bytes parent folder | download | duplicates (2)
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>