Barazo AppView backend barazo.forum
at main 83 lines 1.7 kB view raw
1import { sanitize } from 'isomorphic-dompurify' 2 3/** 4 * Bidirectional override and mark characters to strip from all text. 5 * Prevents text reordering attacks (bidi override) and invisible direction marks. 6 */ 7const BIDI_REGEX = /[\u202A-\u202E\u2066-\u2069\u200E\u200F]/g 8 9/** Tags allowed in forum content (markdown-rendered HTML). */ 10const ALLOWED_TAGS = [ 11 'p', 12 'br', 13 'strong', 14 'em', 15 'a', 16 'code', 17 'pre', 18 'blockquote', 19 'ul', 20 'ol', 21 'li', 22 'h1', 23 'h2', 24 'h3', 25 'h4', 26 'h5', 27 'h6', 28 'hr', 29 'img', 30 'table', 31 'thead', 32 'tbody', 33 'tr', 34 'th', 35 'td', 36 'del', 37 'sup', 38 'sub', 39 'span', 40] 41 42/** Attributes allowed on permitted tags. */ 43const ALLOWED_ATTR = ['href', 'src', 'alt', 'title', 'class', 'rel', 'target'] 44 45/** 46 * Apply Unicode NFC normalization and strip bidirectional override characters. 47 */ 48function normalizeText(input: string): string { 49 return input.normalize('NFC').replace(BIDI_REGEX, '') 50} 51 52/** 53 * Sanitize HTML content for storage. Allows safe markdown-rendered tags. 54 * Applies NFC normalization and strips bidi override characters. 55 * 56 * Use for topic content and reply content fields. 57 */ 58export function sanitizeHtml(input: string): string { 59 if (input === '') return '' 60 61 const normalized = normalizeText(input) 62 63 return sanitize(normalized, { 64 ALLOWED_TAGS, 65 ALLOWED_ATTR, 66 ALLOW_DATA_ATTR: false, 67 }) 68} 69 70/** 71 * Sanitize plain text (strip all HTML). Used for topic titles. 72 * Applies NFC normalization and strips bidi override characters. 73 */ 74export function sanitizeText(input: string): string { 75 if (input === '') return '' 76 77 const normalized = normalizeText(input) 78 79 return sanitize(normalized, { 80 ALLOWED_TAGS: [], 81 ALLOWED_ATTR: [], 82 }) 83}