fixes and refactor
This commit is contained in:
50
static/js/__tests__/search_snippet.ui.test.js
Normal file
50
static/js/__tests__/search_snippet.ui.test.js
Normal file
@@ -0,0 +1,50 @@
|
||||
/** @jest-environment jsdom */
|
||||
|
||||
// Load sanitizer and highlight utils used by the UI
|
||||
require('../sanitizer.js');
|
||||
require('../highlight.js');
|
||||
|
||||
describe('Search highlight integration (server snippet rendering)', () => {
|
||||
const { formatSnippet, highlight, buildTokens } = window.highlightUtils;
|
||||
|
||||
test('formatSnippet preserves server <strong> and sanitizes dangerous HTML', () => {
|
||||
const tokens = buildTokens('alpha');
|
||||
const serverSnippet = 'Hello <strong>Alpha</strong> <img src=x onerror=alert(1)> <a href="javascript:evil()">link</a>';
|
||||
const html = formatSnippet(serverSnippet, tokens);
|
||||
// Server-provided strong is preserved
|
||||
expect(html).toContain('<strong>Alpha</strong>');
|
||||
// Dangerous attributes removed
|
||||
expect(html).not.toContain('onerror=');
|
||||
// javascript: protocol removed
|
||||
expect(html.toLowerCase()).not.toContain('href="javascript:');
|
||||
// Image tag should remain but sanitized (no onerror)
|
||||
expect(html).toContain('<img');
|
||||
});
|
||||
|
||||
test('setSafeHTML inserts sanitized content into DOM safely', () => {
|
||||
const container = document.createElement('div');
|
||||
const rawHtml = '<div onclick="evil()"><script>alert(1)</script>Text <b>bold</b></div>';
|
||||
// Using global helper installed by sanitizer.js
|
||||
window.setSafeHTML(container, rawHtml);
|
||||
// Script tags removed
|
||||
expect(container.innerHTML).not.toContain('<script>');
|
||||
// Event handlers stripped
|
||||
expect(container.innerHTML).not.toContain('onclick=');
|
||||
// Harmless markup preserved
|
||||
expect(container.innerHTML).toContain('<b>bold</b>');
|
||||
});
|
||||
|
||||
test('highlight then sanitize flow escapes original tags and wraps tokens', () => {
|
||||
const tokens = buildTokens('john smith');
|
||||
const out = highlight('Hello <b>John</b> Smith & Sons', tokens);
|
||||
// Original b-tags escaped
|
||||
expect(out).toContain('<b>');
|
||||
// Tokens wrapped with strong
|
||||
expect(out).toMatch(/<strong>John<\/strong>/);
|
||||
expect(out).toMatch(/<strong>Smith<\/strong>/);
|
||||
// Ampersand escaped
|
||||
expect(out).toContain('& Sons');
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user