sanitize()
建立消毒處理外掛,從編譯輸出中移除危險的 HTML 標籤、屬性與 URL 協定。
import { sanitize } from "@unifast/node";函式簽名
function sanitize(options?: SanitizePluginOptions): UnifastPlugin參數
options?
消毒處理設定
| 屬性 | 型別 | 預設值 | 說明 |
|---|---|---|---|
enabled | boolean | true | 啟用或停用消毒處理 |
schema | SanitizeSchema | — | 自訂消毒處理的 schema |
SanitizeSchema
| 屬性 | 型別 | 說明 |
|---|---|---|
allowedTags | string[] | 允許的 HTML 標籤名稱(其他都會被移除) |
allowedAttributes | Record<string, string[]> | 將標籤名稱對應到允許屬性名稱的對應表 |
allowedProtocols | Record<string, string[]> | 將屬性名稱對應到允許 URL 協定的對應表 |
用法
import { compile, sanitize } from "@unifast/node";
const result = compile(md, {
plugins: [
sanitize({
enabled: true,
schema: {
allowedTags: ["h1", "h2", "h3", "p", "a", "strong", "em", "code", "pre", "img", "ul", "ol", "li", "blockquote", "table", "thead", "tbody", "tr", "th", "td"],
allowedAttributes: {
a: ["href", "title", "target"],
img: ["src", "alt", "width", "height"],
code: ["class"],
pre: ["class"],
},
allowedProtocols: {
href: ["https", "http", "mailto"],
src: ["https", "http"],
},
},
}),
],
});範例
移除危險的 HTML
import { compile, sanitize } from "@unifast/node";
const untrustedMd = `
# Hello
<script>alert("xss")</script>
<img src="x" onerror="alert('xss')">
[Click me](javascript:alert('xss'))
`;
const result = compile(untrustedMd, {
plugins: [sanitize()],
});
console.log(result.output);
// <script> tags, onerror attributes, and javascript: URLs are removed自訂允許的標籤
import { compile, sanitize } from "@unifast/node";
const result = compile(md, {
plugins: [
sanitize({
schema: {
allowedTags: ["p", "a", "strong", "em", "code", "pre"],
},
}),
],
});
console.log(result.output);
// Only the specified tags are kept; all others are stripped限制 URL 協定
import { compile, sanitize } from "@unifast/node";
const result = compile(md, {
plugins: [
sanitize({
schema: {
allowedProtocols: {
href: ["https", "mailto"],
src: ["https"],
},
},
}),
],
});
console.log(result.output);
// Only https: and mailto: links are allowed停用消毒處理
import { compile, sanitize } from "@unifast/node";
const result = compile(md, {
plugins: [sanitize({ enabled: false })],
});
console.log(result.output);
// No sanitization applied — use only with trusted input