260813_01_FST: First Commit
This commit is contained in:
53
src/components/kri-editor/utils/sanitizeHtml.ts
Normal file
53
src/components/kri-editor/utils/sanitizeHtml.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
"use client";
|
||||
|
||||
import DOMPurify, { type DOMPurify as DOMPurifyInstance } from "dompurify";
|
||||
|
||||
export type SanitizeHtmlOptions = {
|
||||
tags?: string[];
|
||||
attributes?: string[];
|
||||
};
|
||||
|
||||
// Next.js SSR(Node) 환경에서는 dompurify가 window에 바인딩된 인스턴스가 아니라
|
||||
// (window: Window) => DOMPurify 형태의 factory만 노출한다. window가 없으면
|
||||
// factory를 호출할 방법이 없으므로, 여기서 안전하게 null로 폴백한다.
|
||||
function resolvePurifier(): DOMPurifyInstance | null {
|
||||
if (typeof window === "undefined") return null;
|
||||
if (typeof DOMPurify.sanitize === "function") return DOMPurify;
|
||||
return DOMPurify(window);
|
||||
}
|
||||
|
||||
export function sanitizeHtml(
|
||||
input: string,
|
||||
options?: SanitizeHtmlOptions,
|
||||
): string {
|
||||
if (!input) {
|
||||
return "";
|
||||
}
|
||||
|
||||
const purifier = resolvePurifier();
|
||||
|
||||
if (!purifier) {
|
||||
// DOM이 없어 실제 sanitize를 수행할 수 없는 환경(SSR 등)에서는
|
||||
// 검증되지 않은 HTML을 그대로 노출하지 않도록 태그를 모두 제거한 텍스트만 반환한다.
|
||||
// 브라우저에서 하이드레이션된 이후 재계산될 때 실제 sanitize 결과로 대체된다.
|
||||
return input.replace(/<[^>]*>/g, "");
|
||||
}
|
||||
|
||||
return purifier.sanitize(
|
||||
input,
|
||||
{
|
||||
USE_PROFILES: {
|
||||
html: true,
|
||||
},
|
||||
ADD_TAGS: options?.tags ?? [],
|
||||
ADD_ATTR: options?.attributes ?? [],
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
export function sanitizeHtmlForPreview(
|
||||
input: string,
|
||||
options?: SanitizeHtmlOptions,
|
||||
): string {
|
||||
return sanitizeHtml(input, options);
|
||||
}
|
||||
Reference in New Issue
Block a user