"use client"; import DOMPurify, { type DOMPurify as DOMPurifyInstance } from "dompurify"; import type { KriEditorWysiwygCompatibility } from "@/components/kri-editor"; const EMAIL_ALLOWED_ATTRIBUTES = { a: ["href", "title", "style", "target", "rel"], area: ["shape", "coords", "href", "alt", "title", "target"], b: ["style"], blockquote: ["cite"], col: ["span", "width"], colgroup: ["span", "width"], div: ["style", "align"], img: ["src", "width", "height", "alt", "title", "align", "style", "loading", "usemap"], map: ["name", "id"], mark: ["style", "data-color"], ol: ["start", "type"], p: ["style"], q: ["cite"], qrcode: ["src", "width", "height", "alt"], span: ["style"], table: ["summary", "width", "height", "style", "cellpadding", "cellspacing", "border", "align", "bgcolor", "role"], tbody: ["style", "align", "valign"], td: ["abbr", "axis", "colspan", "rowspan", "width", "height", "style", "align", "valign", "bgcolor"], th: ["abbr", "axis", "colspan", "rowspan", "scope", "width", "height", "style", "align", "valign", "bgcolor"], tr: ["style", "align", "valign", "bgcolor", "height"], ul: ["type"], } as const; export const EMAIL_ALLOWED_TAGS = [ "a", "area", "b", "blockquote", "br", "caption", "cite", "code", "col", "colgroup", "dd", "div", "dl", "dt", "em", "h1", "h2", "h3", "h4", "h5", "h6", "i", "img", "li", "map", "mark", "ol", "p", "pre", "q", "qrcode", "small", "span", "strike", "strong", "sub", "sup", "table", "tbody", "td", "tfoot", "th", "thead", "tr", "u", "ul", ] as const; const TAGS_WITHOUT_ATTRIBUTES = new Set( EMAIL_ALLOWED_TAGS.filter((tag) => !(tag in EMAIL_ALLOWED_ATTRIBUTES)), ); const ALLOWED_TAG_SET = new Set(EMAIL_ALLOWED_TAGS); const ALLOWED_ATTRIBUTE_SET = new Set(Object.values(EMAIL_ALLOWED_ATTRIBUTES).flat()); const ALLOWED_PROTOCOLS: Record> = { "a.href": new Set(["http", "https", "mailto", "tel", "ftp"]), "area.href": new Set(["http", "https", "mailto", "tel"]), "img.src": new Set(["http", "https"]), "blockquote.cite": new Set(["http", "https"]), "q.cite": new Set(["http", "https"]), }; const WYSIWYG_ATTRIBUTES: Record> = { a: new Set(["href", "target", "rel", "class"]), area: new Set(EMAIL_ALLOWED_ATTRIBUTES.area), div: new Set(["style", "class"]), img: new Set([...EMAIL_ALLOWED_ATTRIBUTES.img, "class", "data-kri-image"]), map: new Set(EMAIL_ALLOWED_ATTRIBUTES.map), mark: new Set(EMAIL_ALLOWED_ATTRIBUTES.mark), ol: new Set(["start"]), p: new Set(["style"]), qrcode: new Set(EMAIL_ALLOWED_ATTRIBUTES.qrcode), span: new Set(["style"]), td: new Set(["colspan", "rowspan"]), th: new Set(["colspan", "rowspan"]), }; const WYSIWYG_TAGS = new Set([ "a", "area", "b", "br", "div", "em", "i", "img", "li", "map", "mark", "ol", "p", "qrcode", "span", "strong", "table", "tbody", "td", "th", "tr", "u", "ul", ]); const WYSIWYG_SPAN_STYLE_PROPERTIES = new Set(["color", "font-family", "font-size"]); const WYSIWYG_PARAGRAPH_STYLE_PROPERTIES = new Set(["text-align"]); function resolvePurifier(): DOMPurifyInstance | null { if (typeof window === "undefined") return null; if (typeof DOMPurify.sanitize === "function") return DOMPurify; return DOMPurify(window); } function parseHtml(html: string): HTMLTemplateElement | null { if (typeof document === "undefined") return null; const template = document.createElement("template"); template.innerHTML = html; return template; } function allowedAttributesFor(tagName: string): ReadonlySet { if (TAGS_WITHOUT_ATTRIBUTES.has(tagName as typeof EMAIL_ALLOWED_TAGS[number])) return new Set(); return new Set((EMAIL_ALLOWED_ATTRIBUTES as Record)[tagName] ?? []); } function hasAllowedProtocol(tagName: string, attributeName: string, value: string): boolean { const protocols = ALLOWED_PROTOCOLS[`${tagName}.${attributeName}`]; if (!protocols) return true; const match = /^([a-z][a-z\d+.-]*):/i.exec(value.trim()); return Boolean(match && protocols.has(match[1].toLowerCase())); } function styleProperties(value: string): Set { return new Set( value.split(";") .map((declaration) => declaration.split(":", 1)[0]?.trim().toLowerCase()) .filter((property): property is string => Boolean(property)), ); } function isWysiwygStyleCompatible(tagName: string, value: string): boolean { if (tagName === "div" || tagName === "img" || tagName === "mark") return true; const supported = tagName === "span" ? WYSIWYG_SPAN_STYLE_PROPERTIES : tagName === "p" ? WYSIWYG_PARAGRAPH_STYLE_PROPERTIES : null; return Boolean(supported && [...styleProperties(value)].every((property) => supported.has(property))); } function summarizeIssues(issues: readonly string[]): string { const unique = [...new Set(issues)]; const visible = unique.slice(0, 3).join(", "); const suffix = unique.length > 3 ? ` 외 ${unique.length - 3}개` : ""; return `${visible}${suffix} 항목은 WYSIWYG에서 손실될 수 있어 HTML 모드로 유지됩니다.`; } export function getEmailWysiwygCompatibility(html: string): KriEditorWysiwygCompatibility { const template = parseHtml(html); const issues: string[] = []; if (!template) { const tags = [...html.matchAll(/<\/?\s*([a-z][\w-]*)\b/gi)].map((match) => match[1].toLowerCase()); for (const tagName of tags) { if (!WYSIWYG_TAGS.has(tagName)) issues.push(`<${tagName}>`); } } else { for (const element of Array.from(template.content.querySelectorAll("*"))) { const tagName = element.tagName.toLowerCase(); if (!WYSIWYG_TAGS.has(tagName)) { issues.push(`<${tagName}>`); continue; } const supportedAttributes = WYSIWYG_ATTRIBUTES[tagName] ?? new Set(); for (const attribute of Array.from(element.attributes)) { const attributeName = attribute.name.toLowerCase(); if (!supportedAttributes.has(attributeName)) { issues.push(`<${tagName}>의 ${attributeName}`); } else if (attributeName === "style" && !isWysiwygStyleCompatible(tagName, attribute.value)) { issues.push(`<${tagName}>의 일부 style`); } } if (tagName === "area" && element.parentElement?.tagName.toLowerCase() !== "map") { issues.push(" 밖의 "); } } } return issues.length > 0 ? { compatible: false, reason: summarizeIssues(issues) } : { compatible: true }; } function isEditorDecoration(tagName: string, attributeName: string, value: string): boolean { if (tagName === "a" && attributeName === "class" && value === "kri-editor-link") return true; if (tagName !== "img") return false; return (attributeName === "class" && value === "max-w-full h-auto") || (attributeName === "data-kri-image" && value === "true"); } export function getEmailHtmlPolicyIssues(html: string): string[] { const template = parseHtml(html); if (!template) return []; const issues: string[] = []; for (const element of Array.from(template.content.querySelectorAll("*"))) { const tagName = element.tagName.toLowerCase(); if (!ALLOWED_TAG_SET.has(tagName)) { issues.push(`<${tagName}> 태그`); continue; } const allowedAttributes = allowedAttributesFor(tagName); for (const attribute of Array.from(element.attributes)) { const attributeName = attribute.name.toLowerCase(); if (isEditorDecoration(tagName, attributeName, attribute.value)) continue; if (!allowedAttributes.has(attributeName)) { issues.push(`<${tagName}>의 ${attributeName} 속성`); } else if (!hasAllowedProtocol(tagName, attributeName, attribute.value)) { issues.push(`<${tagName}>의 ${attributeName} URL`); } } } return [...new Set(issues)]; } export function hasImageMapMarkup(html: string): boolean { if (!html) return false; const template = parseHtml(html); if (!template) return /<\s*(map|area)\b/i.test(html); return template.content.querySelector("map, area") !== null; } export function sanitizeEmailHtml(html: string): string { if (!html) return ""; const purifier = resolvePurifier(); if (!purifier) return html.replace(/<[^>]*>/g, ""); const sanitized = purifier.sanitize(html, { ALLOWED_TAGS: [...EMAIL_ALLOWED_TAGS], ALLOWED_ATTR: [...ALLOWED_ATTRIBUTE_SET], ALLOW_DATA_ATTR: false, }); const template = parseHtml(sanitized); if (!template) return ""; for (const element of Array.from(template.content.querySelectorAll("*"))) { const tagName = element.tagName.toLowerCase(); const allowedAttributes = allowedAttributesFor(tagName); for (const attribute of Array.from(element.attributes)) { const attributeName = attribute.name.toLowerCase(); if (!allowedAttributes.has(attributeName) || !hasAllowedProtocol(tagName, attributeName, attribute.value)) { element.removeAttribute(attribute.name); } } } return template.innerHTML.replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/g, "").trim(); }