fix(frontend): add fallback for DOMPurify in Cloudflare Workers
This commit is contained in:
@@ -4,11 +4,28 @@
|
||||
*/
|
||||
import DOMPurify from 'isomorphic-dompurify'
|
||||
|
||||
/**
|
||||
* Basic SVG sanitization for environments without DOM
|
||||
* Removes dangerous tags and attributes
|
||||
*/
|
||||
const basicSanitize = (svg: string): string => {
|
||||
// Remove script tags and their content
|
||||
let sanitized = svg.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '')
|
||||
// Remove dangerous attributes
|
||||
sanitized = sanitized.replace(/\s*on\w+\s*=\s*["'][^"']*["']/gi, '')
|
||||
// Remove other dangerous tags
|
||||
sanitized = sanitized.replace(/<(iframe|object|embed|style)[^>]*>.*?<\/\1>/gi, '')
|
||||
return sanitized
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitize SVG content to prevent XSS attacks
|
||||
* Only allows safe SVG elements and attributes
|
||||
*/
|
||||
export const sanitizeSvg = (svg: string): string => {
|
||||
// Check if DOMPurify is available (has sanitize method)
|
||||
if (typeof DOMPurify?.sanitize === 'function') {
|
||||
try {
|
||||
return DOMPurify.sanitize(svg, {
|
||||
USE_PROFILES: { svg: true, svgFilters: true },
|
||||
ADD_TAGS: ['use', 'defs', 'symbol'],
|
||||
@@ -37,4 +54,11 @@ export const sanitizeSvg = (svg: string): string => {
|
||||
FORBID_TAGS: ['script', 'iframe', 'object', 'embed', 'style'],
|
||||
FORBID_ATTR: ['onload', 'onerror', 'onclick', 'onmouseover'],
|
||||
})
|
||||
} catch {
|
||||
// Fallback to basic sanitization if DOMPurify fails
|
||||
return basicSanitize(svg)
|
||||
}
|
||||
}
|
||||
// Fallback for non-browser environments (Cloudflare Workers)
|
||||
return basicSanitize(svg)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user