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.

13.6 KB
Raw Blame
/**
 * Semantic Search — Shared Module
 *
 * Reusable functions for semantic search across any page:
 * - renderSnippet: markdown-to-HTML for search snippets
 * - buildTieredResults: three-tier merge of text + semantic results
 * - createSemanticResultCard: standalone card element for a semantic match
 * - isSafeExternalUrl: URL scheme validation
 *
 * Exposed via window.SemanticSearch
 */
(function() {

// bearer:disable javascript_lang_manual_html_sanitization
const esc = window.escapeHtml || (s => String(s || '').replace(/[&<>"']/g, m => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":"&#39;"})[m]));

/**
 * Render a markdown snippet as sanitized inline HTML.
 * Falls back to escapeHtml when marked/DOMPurify are not loaded.
 * @param {string} md - markdown snippet
 * @param {string} [query] - optional search query for keyword highlighting
 */
function renderSnippet(md, query) {
    if (!md) return '';
    let html;
    // isSupported must be exactly true: an unsupported DOMPurify returns
    // its input unchanged from sanitize(), so treat it as missing.
    if (window.marked && window.DOMPurify?.isSupported === true) {
        html = window.marked.parseInline(String(md));
        // ORDER IS LOAD-BEARING: highlight BEFORE sanitizing, never after.
        //
        // highlightTerms() splits HTML with the regex /(<[^>]*>)|([^<]+)/,
        // which treats the first ">" as ending a tag. HTML attribute values
        // are NOT ">"-escaped when serialized, so a value containing ">"
        // (e.g. a title="...") makes the regex see a tag boundary that the
        // real parser does not, and the <mark> it then injects supplies the
        // quote that closes the attribute for real. Running that surgery on
        // sanitizer OUTPUT therefore reintroduces markup DOMPurify had
        // already decided was safe, turning inert attribute text into live
        // elements. Sanitizing last means any boundary the highlighter
        // breaks is repaired (or dropped) before the string reaches a
        // caller's innerHTML.
        //
        // "mark" and "class" are in the allowlists below, so the highlight
        // itself survives the pass.
        if (query) {
            html = highlightTerms(html, query);
        }
        html = window.DOMPurify.sanitize(html, {
            ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'span', 'a', 'code', 'br', 'p', 'ul', 'ol', 'li', 'mark'],
            ALLOWED_ATTR: ['href', 'title', 'class'],
            ALLOW_DATA_ATTR: false,
        });
        return html;
    }
    // Fallback path: no sanitizer available, so the snippet is escaped
    // wholesale and highlightTerms is skipped -- injecting <mark> into
    // esc'd text would produce garbled entities like &lt;<mark>b</mark>&gt;,
    // and there would be no sanitizer pass afterwards to repair a broken
    // boundary.
    return esc(md);
}

/**
 * Highlight query terms in an HTML string by wrapping matches in <mark> tags.
 *
 * SECURITY: never call this on the OUTPUT of a sanitizer. The tag-splitting
 * regex below treats the first ">" as ending a tag, but HTML serialization
 * does not escape ">" inside attribute values -- so an attribute containing
 * ">" desynchronizes this function's view of the markup from the real
 * parser's, and the <mark> injected at that point can close the attribute
 * and introduce live elements. Callers must sanitize AFTER highlighting, so
 * that any boundary broken here is repaired before the string is assigned to
 * innerHTML. See renderSnippet(), which is the only intended caller.
 *
 * @param {string} html - HTML string, NOT yet sanitized
 * @param {string} query - search query (split into words, each highlighted)
 * @returns {string} HTML with <mark> wrapped terms; must still be sanitized
 */
function highlightTerms(html, query) {
    if (!html || !query) return html;
    // Extract meaningful words (3+ chars to avoid noise)
    const words = query.split(/\s+/).filter(function(w) { return w.length >= 3; });
    if (words.length === 0) return html;
    // Escape regex special characters in each word
    const escaped = words.map(function(w) {
        return w.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    });
    const pattern = new RegExp('(' + escaped.join('|') + ')', 'gi');
    // Split on HTML tags to only highlight text content, not inside tags
    return html.replace(/(<[^>]*>)|([^<]+)/g, function(match, tag, text) {
        if (tag) return tag; // preserve HTML tags as-is
        return text.replace(pattern, '<mark class="ldr-search-highlight">$1</mark>');
    });
}

/**
 * Three-tier merge of text-filtered and semantic search results.
 *
 * Tier 1: items matching both text + semantic (sorted by similarity DESC)
 * Tier 2: text-only matches (original order, typically recency)
 * Tier 3: semantic-only matches (sorted by similarity DESC)
 *
 * @param {Array} textResults - items from text filter
 * @param {Array} semanticResults - results from semantic API (must have .similarity)
 * @param {Object} [options] - optional ID key configuration
 * @param {string} [options.textIdKey='id'] - property name for ID on text result items
 * @param {string} [options.semanticIdKey='research_id'] - property name for ID on semantic results
 * @returns {{ tier1: Array, tier2: Array, tier3: Array }}
 */
function buildTieredResults(textResults, semanticResults, options) {
    const textIdKey = (options && options.textIdKey) || 'id';
    const semanticIdKey = (options && options.semanticIdKey) || 'research_id';

    // Group semantic results by ID, keep best per unique ID
    const semanticMap = new Map();
    for (const sr of semanticResults) {
        if (!sr[semanticIdKey]) continue;
        const rid = String(sr[semanticIdKey]);
        const existing = semanticMap.get(rid);
        if (!existing || sr.similarity > existing.similarity) {
            semanticMap.set(rid, sr);
        }
    }

    // Classify text results
    const tier1 = [];
    const tier2 = [];
    const matchedSemanticIds = new Set();

    for (const textItem of textResults) {
        const rid = String(textItem[textIdKey]);
        const sr = semanticMap.get(rid);
        if (sr) {
            tier1.push({
                historyItem: textItem,
                semanticMatch: { similarity: sr.similarity, snippet: sr.snippet || '' }
            });
            matchedSemanticIds.add(rid);
        } else {
            tier2.push({ historyItem: textItem });
        }
    }

    // Collect semantic-only results
    const tier3 = [];
    for (const [rid, sr] of semanticMap) {
        if (!matchedSemanticIds.has(rid)) {
            tier3.push({ semanticResult: sr });
        }
    }

    // Sort within tiers
    tier1.sort((a, b) => b.semanticMatch.similarity - a.semanticMatch.similarity);
    tier3.sort((a, b) => b.semanticResult.similarity - a.semanticResult.similarity);

    return { tier1, tier2, tier3 };
}

/**
 * Flatten buildTieredResults output into one ordered array of the
 * caller's item shape: tier-1 text items enriched with their semantic
 * similarity + snippet (as content_preview), then tier-2 keyword-only
 * items, then tier-3 semantic-only results verbatim.
 *
 * Shared by the notes and unified-search pages, whose page-local copies
 * of this flatten had already started drifting apart.
 */
function flattenTieredResults(tiered) {
    const out = [];
    for (const entry of tiered.tier1) {
        const item = { ...entry.historyItem };
        item.similarity = entry.semanticMatch.similarity;
        if (entry.semanticMatch.snippet) {
            item.content_preview = entry.semanticMatch.snippet;
        }
        out.push(item);
    }
    for (const entry of tiered.tier2) {
        out.push(entry.historyItem);
    }
    for (const entry of tiered.tier3) {
        out.push(entry.semanticResult);
    }
    return out;
}

/**
 * Create a self-contained semantic result card element.
 *
 * @param {Object} result - semantic search result with: similarity, snippet, and
 *                          domain-specific fields
 * @param {Object} [config] - optional card configuration for different domains.
 *   Defaults produce the original research-history card.
 *   Each function receives the result object:
 *   - getId(r):       data-id attribute value (default: r.research_id)
 *   - getTitle(r):    display title (default: r.research_title || r.title)
 *   - getUrl(r):      link/click target URL (default: URLBuilder.resultsPage)
 *   - getBadges(r):   array of {icon, label} (default: report/source badge)
 *   - getDate(r):     date string or null (default: r.research_created_at)
 *   - getSubtitle(r): optional subtitle line or null
 * @returns {HTMLElement}
 */
function createSemanticResultCard(result, config, query) {
    const cfg = config || {};

    const cardId = (cfg.getId || function(r) { return r.research_id || ''; })(result);
    const displayTitle = (cfg.getTitle || function(r) { return r.research_title || r.title || 'Untitled'; })(result);
    const cardUrl = (cfg.getUrl || function(r) {
        return (typeof URLBuilder !== 'undefined' && r.research_id)
            ? URLBuilder.resultsPage(r.research_id) : '#';
    })(result);

    const badges = cfg.getBadges
        ? cfg.getBadges(result)
        : [{ icon: result.type === 'report' ? 'file-alt' : 'link',
             label: result.type === 'report' ? 'Report' : 'Source' }];

    const rawDate = cfg.getDate
        ? cfg.getDate(result)
        : (result.research_created_at || null);

    const subtitle = cfg.getSubtitle ? cfg.getSubtitle(result) : null;

    const similarity = result.similarity != null ? String(result.similarity) : '';

    let dateStr = '';
    if (rawDate) {
        try {
            dateStr = new Date(rawDate).toLocaleDateString();
        } catch {
            dateStr = '';
        }
    }

    const card = document.createElement('div');
    card.className = 'ldr-semantic-result';
    card.dataset.id = cardId;

    // Build badges HTML
    let badgesHtml = '';
    for (const b of badges) {
        if (b && b.label) {
            badgesHtml += `<span class="ldr-badge ldr-badge-info ldr-semantic-type-badge"><i class="fas fa-${esc(b.icon || 'file')}"></i> ${esc(b.label)}</span> `;
        }
    }

    // Re-audited 2026-09-04: every interpolation below is esc()'d or a
    // hardcoded string EXCEPT the snippet, which is DOMPurify output from
    // renderSnippet() above. That helper now sanitizes as its LAST step --
    // it previously highlighted afterwards, which could reopen a closed
    // attribute -- so the value assigned here is sanitizer output that
    // nothing has modified since. Six callers append this card verbatim,
    // with no re-sanitize of their own: the library tier-3 list
    // (library_search_ui.js), both news search paths and its own tier-3
    // list (news.js), collection-details search results
    // (collection_details.js), library search (library_search.js), and
    // history search (history_search.js). A third tier-3 list, in
    // history.js, does not call this function at all -- it builds its own
    // card via createSemanticOnlyElement(), audited separately there. So
    // this assignment is the last sanitizing step for those six callers.
    // bearer:disable javascript_lang_dangerous_insert_html
    // eslint-disable-next-line no-unsanitized/property -- re-audited 2026-09-04: esc()'d/literal, plus sanitizer-last renderSnippet output (see above)
    card.innerHTML = `
        <div class="ldr-semantic-result-header">
            <div>
                ${badgesHtml}
                ${similarity ? `<span class="ldr-ai-match-badge"><i class="fas fa-brain"></i> ${esc(similarity)}% match</span>` : ''}
            </div>
            ${dateStr ? `<small class="ldr-semantic-result-date">${esc(dateStr)}</small>` : ''}
        </div>
        <h4 class="ldr-semantic-result-title">
            <a href="${esc(cardUrl)}">${esc(displayTitle)}</a>
        </h4>
        ${subtitle ? `<p class="ldr-semantic-result-subtitle">${esc(subtitle)}</p>` : ''}
        ${result.snippet ? `<div class="ldr-history-item-snippet">${renderSnippet(result.snippet, query)}</div>` : ''}
        ${result.url && isSafeExternalUrl(result.url) ? `
            <p class="ldr-semantic-result-source">
                <a href="${esc(result.url)}" target="_blank" rel="noopener noreferrer">
                    <i class="fas fa-external-link-alt"></i> View Source
                </a>
            </p>
        ` : ''}
    `;

    // Click handler — navigate to card URL
    card.addEventListener('click', (e) => {
        if (!e.target.closest('a') && cardId && cardUrl !== '#' && typeof URLValidator !== 'undefined') {
            URLValidator.safeAssign(window.location, 'href', cardUrl);
        }
    });

    return card;
}

/**
 * Validate external URL for safe rendering.
 */
function isSafeExternalUrl(url) {
    if (!url || typeof url !== 'string') return false;

    if (typeof URLValidator !== 'undefined' && URLValidator.isSafeUrl) {
        return URLValidator.isSafeUrl(url, { allowMailto: false });
    }

    const trimmedUrl = url.trim().toLowerCase();
    const unsafeSchemes = ['javascript:', 'data:', 'vbscript:', 'about:', 'blob:', 'file:'];
    for (const scheme of unsafeSchemes) {
        if (trimmedUrl.startsWith(scheme)) return false;
    }
    return trimmedUrl.startsWith('http://') || trimmedUrl.startsWith('https://');
}

// Expose shared API
window.SemanticSearch = {
    renderSnippet,
    buildTieredResults,
    flattenTieredResults,
    createSemanticResultCard,
    isSafeExternalUrl,
    // Shared semantic-search tuning, previously inlined as bare literals in
    // both the notes page and the unified-search page (they could silently
    // diverge). MIN_SIMILARITY = FAISS score cutoff; MIN_QUERY_LENGTH = the
    // shortest query the AI modes will embed.
    MIN_SIMILARITY: 0.25,
    MIN_QUERY_LENGTH: 2,
};

})();