Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

6.8 KB
Raw Blame
/**
 * Fail-closed contracts for renderMarkdown's sanitizer availability.
 *
 * ``services/ui.js`` renderMarkdown parses report markdown through
 * ``marked`` — which passes raw HTML in markdown through by default —
 * and then sanitizes with DOMPurify. The marked-missing branch fails
 * closed to escaped plaintext, but the DOMPurify-missing branch
 * returned the parsed HTML **unsanitized**: on a page where the
 * sanitizer failed to load, hostile report/note content (web-influenced
 * through research results) rendered raw — a fail-open stored-XSS path.
 *
 * These contracts pin: payloads never survive when DOMPurify is
 * unavailable (escaped plaintext instead), and the sanitizing path is
 * actually taken when it is available.
 */

import '@js/security/xss-protection.js';
import '@js/services/ui.js';

const HOSTILE_MARKDOWN = '# Title\n\n<img src=x onerror="window.__pwnedA=1">';
// What a pass-through marked would produce for hostile markdown
// (raw HTML survives marked by default).
const HOSTILE_PARSED_HTML = [
    '<h1>Title</h1><p>body</p>',
    '<img src=x onerror="window.__pwnedA=1">',
    '<script>window.__pwnedB=1</script>',
    '<a href="javascript:window.__pwnedC=1">click</a>',
].join('');

class _StubRenderer {
    link() {
        return '<a href="#">x</a>';
    }
}

function _stubMarked(html = HOSTILE_PARSED_HTML) {
    globalThis.marked = {
        Renderer: _StubRenderer,
        setOptions() {},
        parse: () => html,
    };
}

const BENIGN_MARKDOWN = '# H with <b>bold</b>';
const BENIGN_PARSED_HTML = '<h1>H with <b>bold</b></h1>';

describe('renderMarkdown fails closed when DOMPurify is unavailable', () => {
    let _savedPurify;
    let _savedMarked;

    beforeEach(() => {
        _savedPurify = globalThis.DOMPurify;
        _savedMarked = globalThis.marked;
    });

    afterEach(() => {
        globalThis.DOMPurify = _savedPurify;
        globalThis.marked = _savedMarked;
        delete globalThis.__pwnedA;
    });

    it('never returns raw payload HTML without the sanitizer', () => {
        _stubMarked();
        globalThis.DOMPurify = undefined;

        const out = window.ui.renderMarkdown(HOSTILE_MARKDOWN);

        // No raw markup survives: only escaped text inside <pre>.
        // (Attribute substrings like "onerror" may appear ESCAPED —
        // that is the safe rendering; raw tags must not exist.)
        expect(out).toMatch(/<pre/);
        expect(out).not.toContain('<img');
        expect(out).not.toContain('<script');
        expect(out).not.toContain('href="javascript:');
    });

    it('renders escaped plaintext on the closed path', () => {
        _stubMarked();
        globalThis.DOMPurify = undefined;

        const out = window.ui.renderMarkdown(HOSTILE_MARKDOWN);

        // Same contract as the marked-missing branch: the markdown's
        // own markup is visible only as escaped text.
        expect(out).toMatch(/<pre/);
        expect(out).toContain('&lt;img');
        expect(out).toContain('onerror=&quot;');  // escaped attr form
    });

    it('fails closed when DOMPurify is present but unsupported', () => {
        _stubMarked();
        let sanitizeCalled = false;
        // An unsupported DOMPurify returns its input unchanged from
        // sanitize() -- that must not be treated as sanitized output.
        globalThis.DOMPurify = {
            isSupported: false,
            sanitize: (html) => {
                sanitizeCalled = true;
                return html;
            },
        };

        const out = window.ui.renderMarkdown(HOSTILE_MARKDOWN);

        expect(sanitizeCalled).toBe(false);
        expect(out).toMatch(/<pre/);
        expect(out).not.toContain('<img');
        expect(out).not.toContain('<script');
        expect(out).toContain('&lt;img');
    });

    // DOMPurify computes isSupported as an && chain (typeof entries ===
    // 'function' && ... && implementation && implementation.createHTMLDocument
    // !== undefined), so a broken environment can yield null or undefined
    // rather than false -- and sanitize() passes input through on any falsy
    // value. Only isSupported === true may take the sanitize path.
    it.each([
        ['null', null],
        ['undefined', undefined],
        ['missing', '__omit__'],
    ])('fails closed when DOMPurify.isSupported is %s', (_label, value) => {
        _stubMarked();
        let sanitizeCalled = false;
        const purifier = {
            sanitize: (html) => {
                sanitizeCalled = true;
                return html;
            },
        };
        if (value !== '__omit__') {
            purifier.isSupported = value;
        }
        globalThis.DOMPurify = purifier;

        const out = window.ui.renderMarkdown(HOSTILE_MARKDOWN);

        expect(sanitizeCalled).toBe(false);
        expect(out).toMatch(/<pre/);
        expect(out).not.toContain('<img');
        expect(out).not.toContain('<script');
        expect(out).toContain('&lt;img');
    });

    it('sanitizes through DOMPurify when it is available', () => {
        _stubMarked();
        const sanitizedInputs = [];
        globalThis.DOMPurify = {
            isSupported: true,
            sanitize: (html) => {
                sanitizedInputs.push(html);
                return '<p>clean</p>';
            },
        };

        const out = window.ui.renderMarkdown(HOSTILE_MARKDOWN);

        expect(sanitizedInputs[0]).toBe(HOSTILE_PARSED_HTML);
        expect(out).toContain('<p>clean</p>');
    });

    it('survives benign markdown when marked is unavailable', () => {
        globalThis.marked = undefined;
        globalThis.DOMPurify = undefined;

        const out = window.ui.renderMarkdown(BENIGN_MARKDOWN);

        // Escaped observable: the raw markup is visible only escaped.
        expect(out).toContain('&lt;b&gt;');
        expect(out).not.toContain('<b>');
        expect(out).not.toContain('<h1');
    });

    it('survives benign markdown when marked is available but DOMPurify is not', () => {
        _stubMarked(BENIGN_PARSED_HTML);
        globalThis.DOMPurify = undefined;

        const out = window.ui.renderMarkdown(BENIGN_MARKDOWN);

        // Same fail-closed contract as the marked-missing branch: escaped
        // plaintext, never the parsed markup, even though the input is benign.
        expect(out).toMatch(/<pre/);
        expect(out).toContain('&lt;b&gt;');
        expect(out).not.toContain('<b>bold</b>');
    });

    it('passes benign markdown through the sanitize path when both are available', () => {
        _stubMarked(BENIGN_PARSED_HTML);
        globalThis.DOMPurify = {
            isSupported: true,
            sanitize: (html) => html,
        };

        const out = window.ui.renderMarkdown(BENIGN_MARKDOWN);

        // The sanitize path is taken (not the plaintext fallback), and
        // safe markup like <b> survives it untouched.
        expect(out).not.toMatch(/<pre/);
        expect(out).toContain('<b>bold</b>');
    });
});