refactor: 第三方库替换 & 代码精简 — v5.1.5
- Markdown 解析器:内联正则 → marked 库(完整 GFM 支持) - HTML 净化器:内联 DOM 遍历 → DOMPurify(业界标准) - crypto.ts:删除 sha256js/xorBytes 死代码回退路径 - 消除 5 个文件中 escapeHtml/formatSize 重复定义 - 版本号升级至 5.1.5
This commit is contained in:
@@ -8,6 +8,8 @@ let titleEl: HTMLElement | null = null;
|
||||
let bodyEl: HTMLElement | null = null;
|
||||
let inputEl: HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement | null = null;
|
||||
let okBtn: HTMLButtonElement | null = null;
|
||||
|
||||
import { escapeHtml } from '../utils/utils.js';
|
||||
let cancelBtn: HTMLButtonElement | null = null;
|
||||
let resolveFn: ((value: string | null) => void) | null = null;
|
||||
|
||||
@@ -136,6 +138,4 @@ export function showConfirm(message: string, title = '确认'): Promise<boolean>
|
||||
});
|
||||
}
|
||||
|
||||
function escapeHtml(text: string): string {
|
||||
return text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
import type { ToolCall } from '../types.js';
|
||||
import { getToolIcon, formatToolName } from '../services/tool-registry.js';
|
||||
import { logDebug, logInfo } from '../services/log-service.js';
|
||||
import { escapeHtml } from '../utils/utils.js';
|
||||
|
||||
let modalEl: HTMLElement | null = null;
|
||||
let resolveConfirm: ((confirmed: boolean) => void) | null = null;
|
||||
@@ -117,7 +118,4 @@ function cancelConfirm(): void {
|
||||
}
|
||||
}
|
||||
|
||||
function escapeHtml(str: string): string {
|
||||
const map: Record<string, string> = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' };
|
||||
return str.replace(/[&<>"']/g, c => map[c]);
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
*/
|
||||
|
||||
import { logInfo, logError, logDebug } from '../services/log-service.js';
|
||||
import { escapeHtml, formatSize } from '../utils/utils.js';
|
||||
|
||||
// ── 工具卡片类型 ──
|
||||
interface ToolCallRecord {
|
||||
@@ -105,13 +106,6 @@ const ANSI_COLORS: Record<string, string> = {
|
||||
'94': '#8ec8ff', '95': '#e8a0e8', '96': '#5ee8e8', '97': '#fff',
|
||||
};
|
||||
|
||||
function escapeHtml(text: string): string {
|
||||
return text
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"');
|
||||
}
|
||||
|
||||
function ansiToHtml(raw: string): string {
|
||||
// 先转义 HTML
|
||||
@@ -759,12 +753,6 @@ function getFileIcon(name: string): string {
|
||||
return iconMap[ext] || '📄';
|
||||
}
|
||||
|
||||
function formatSize(bytes: number): string {
|
||||
if (bytes < 1024) return bytes + ' B';
|
||||
if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
|
||||
return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
|
||||
}
|
||||
|
||||
// ── 工具调用管理 ──
|
||||
|
||||
/** 是否有命令正在终端中执行 */
|
||||
|
||||
@@ -28,7 +28,7 @@
|
||||
<div class="header-left">
|
||||
<span class="logo">🦙</span>
|
||||
<span class="app-title">Metona Ollama</span>
|
||||
<span class="app-version">v5.1.4</span>
|
||||
<span class="app-version">v5.1.5</span>
|
||||
<button class="icon-btn help-btn" id="btnHelp" title="使用帮助">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<circle cx="12" cy="12" r="10"/><path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"/>
|
||||
|
||||
+22
-123
@@ -1,112 +1,24 @@
|
||||
/**
|
||||
* Crypto - Metona 会话加密模块
|
||||
* Crypto — Metona 会话加密模块
|
||||
* Electron 环境下 crypto.subtle 始终可用,无需 JS 回退实现
|
||||
*/
|
||||
|
||||
const MAGIC = new TextEncoder().encode('METONA1\0');
|
||||
const PASSPHRASE = 'metona-ollama-v2';
|
||||
const PBKDF2_ITERATIONS = 100000;
|
||||
|
||||
const SECURE = !!(globalThis.crypto && globalThis.crypto.subtle);
|
||||
|
||||
async function sha256(data: Uint8Array): Promise<Uint8Array> {
|
||||
if (SECURE) {
|
||||
const buf = await crypto.subtle.digest('SHA-256', data);
|
||||
return new Uint8Array(buf);
|
||||
}
|
||||
return sha256js(data);
|
||||
}
|
||||
|
||||
function sha256js(message: Uint8Array): Uint8Array {
|
||||
const K = new Uint32Array([
|
||||
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
|
||||
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
|
||||
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
|
||||
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
|
||||
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
|
||||
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
|
||||
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
|
||||
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
|
||||
]);
|
||||
|
||||
const bytes = message instanceof Uint8Array ? message : new Uint8Array(message);
|
||||
const bitLen = bytes.length * 8;
|
||||
const paddedLen = Math.ceil((bytes.length + 9) / 64) * 64;
|
||||
const padded = new Uint8Array(paddedLen);
|
||||
padded.set(bytes);
|
||||
padded[bytes.length] = 0x80;
|
||||
const view = new DataView(padded.buffer);
|
||||
view.setUint32(paddedLen - 4, bitLen, false);
|
||||
|
||||
let h0 = 0x6a09e667, h1 = 0xbb67ae85, h2 = 0x3c6ef372, h3 = 0xa54ff53a;
|
||||
let h4 = 0x510e527f, h5 = 0x9b05688c, h6 = 0x1f83d9ab, h7 = 0x5be0cd19;
|
||||
|
||||
const w = new Uint32Array(64);
|
||||
|
||||
for (let offset = 0; offset < paddedLen; offset += 64) {
|
||||
for (let i = 0; i < 16; i++) w[i] = view.getUint32(offset + i * 4, false);
|
||||
for (let i = 16; i < 64; i++) {
|
||||
const s0 = (w[i - 15] >>> 7 | w[i - 15] << 25) ^ (w[i - 15] >>> 18 | w[i - 15] << 14) ^ (w[i - 15] >>> 3);
|
||||
const s1 = (w[i - 2] >>> 17 | w[i - 2] << 15) ^ (w[i - 2] >>> 19 | w[i - 2] << 13) ^ (w[i - 2] >>> 10);
|
||||
w[i] = (w[i - 16] + s0 + w[i - 7] + s1) >>> 0;
|
||||
}
|
||||
let a = h0, b = h1, c = h2, d = h3, e = h4, f = h5, g = h6, h = h7;
|
||||
for (let i = 0; i < 64; i++) {
|
||||
const S1 = (e >>> 6 | e << 26) ^ (e >>> 11 | e << 21) ^ (e >>> 25 | e << 7);
|
||||
const ch = (e & f) ^ (~e & g);
|
||||
const temp1 = (h + S1 + ch + K[i] + w[i]) >>> 0;
|
||||
const S0 = (a >>> 2 | a << 30) ^ (a >>> 13 | a << 19) ^ (a >>> 22 | a << 10);
|
||||
const maj = (a & b) ^ (a & c) ^ (b & c);
|
||||
const temp2 = (S0 + maj) >>> 0;
|
||||
h = g; g = f; f = e;
|
||||
e = (d + temp1) >>> 0;
|
||||
d = c; c = b; b = a;
|
||||
a = (temp1 + temp2) >>> 0;
|
||||
}
|
||||
h0 = (h0 + a) >>> 0; h1 = (h1 + b) >>> 0; h2 = (h2 + c) >>> 0; h3 = (h3 + d) >>> 0;
|
||||
h4 = (h4 + e) >>> 0; h5 = (h5 + f) >>> 0; h6 = (h6 + g) >>> 0; h7 = (h7 + h) >>> 0;
|
||||
}
|
||||
|
||||
const result = new Uint8Array(32);
|
||||
const rv = new DataView(result.buffer);
|
||||
rv.setUint32(0, h0, false); rv.setUint32(4, h1, false);
|
||||
rv.setUint32(8, h2, false); rv.setUint32(12, h3, false);
|
||||
rv.setUint32(16, h4, false); rv.setUint32(20, h5, false);
|
||||
rv.setUint32(24, h6, false); rv.setUint32(28, h7, false);
|
||||
return result;
|
||||
}
|
||||
|
||||
async function deriveKeyBytes(salt: Uint8Array): Promise<Uint8Array> {
|
||||
const passBytes = new TextEncoder().encode(PASSPHRASE);
|
||||
const input = new Uint8Array(passBytes.length + salt.length);
|
||||
input.set(passBytes);
|
||||
input.set(salt, passBytes.length);
|
||||
|
||||
if (SECURE) {
|
||||
const keyMaterial = await crypto.subtle.importKey('raw', passBytes, 'PBKDF2', false, ['deriveKey']);
|
||||
const key = await crypto.subtle.deriveKey(
|
||||
{ name: 'PBKDF2', salt, iterations: PBKDF2_ITERATIONS, hash: 'SHA-256' },
|
||||
keyMaterial,
|
||||
{ name: 'AES-GCM', length: 256 },
|
||||
true,
|
||||
['encrypt', 'decrypt']
|
||||
);
|
||||
const raw = await crypto.subtle.exportKey('raw', key);
|
||||
return new Uint8Array(raw);
|
||||
}
|
||||
|
||||
let key = input;
|
||||
for (let i = 0; i < 10000; i++) {
|
||||
key = await sha256(key);
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
function xorBytes(data: Uint8Array, keyBytes: Uint8Array): Uint8Array {
|
||||
const out = new Uint8Array(data.length);
|
||||
for (let i = 0; i < data.length; i++) {
|
||||
out[i] = data[i] ^ keyBytes[i % keyBytes.length];
|
||||
}
|
||||
return out;
|
||||
const keyMaterial = await crypto.subtle.importKey('raw', passBytes, 'PBKDF2', false, ['deriveKey']);
|
||||
const key = await crypto.subtle.deriveKey(
|
||||
{ name: 'PBKDF2', salt, iterations: PBKDF2_ITERATIONS, hash: 'SHA-256' },
|
||||
keyMaterial,
|
||||
{ name: 'AES-GCM', length: 256 },
|
||||
true,
|
||||
['encrypt', 'decrypt']
|
||||
);
|
||||
const raw = await crypto.subtle.exportKey('raw', key);
|
||||
return new Uint8Array(raw);
|
||||
}
|
||||
|
||||
export async function encryptData(data: unknown): Promise<Blob> {
|
||||
@@ -115,20 +27,11 @@ export async function encryptData(data: unknown): Promise<Blob> {
|
||||
const iv = crypto.getRandomValues(new Uint8Array(12));
|
||||
const keyBytes = await deriveKeyBytes(salt);
|
||||
|
||||
let payload: Uint8Array;
|
||||
if (SECURE) {
|
||||
const key = await crypto.subtle.importKey('raw', keyBytes, 'AES-GCM', false, ['encrypt']);
|
||||
const ciphertext = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, json);
|
||||
payload = new Uint8Array(ciphertext);
|
||||
} else {
|
||||
const lenBytes = new Uint32Array([json.length]);
|
||||
const withLen = new Uint8Array(4 + json.length);
|
||||
withLen.set(new Uint8Array(lenBytes.buffer));
|
||||
withLen.set(json, 4);
|
||||
payload = xorBytes(withLen, keyBytes);
|
||||
}
|
||||
const key = await crypto.subtle.importKey('raw', keyBytes, 'AES-GCM', false, ['encrypt']);
|
||||
const ciphertext = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, json);
|
||||
const payload = new Uint8Array(ciphertext);
|
||||
|
||||
const flag = new Uint8Array([SECURE ? 1 : 0]);
|
||||
const flag = new Uint8Array([1]); // mode=1: AES-GCM
|
||||
return new Blob([MAGIC, salt, iv, flag, payload]);
|
||||
}
|
||||
|
||||
@@ -144,17 +47,13 @@ export async function decryptData(buffer: ArrayBuffer): Promise<unknown> {
|
||||
const payload = data.slice(37);
|
||||
const keyBytes = await deriveKeyBytes(salt);
|
||||
|
||||
let jsonBytes: Uint8Array;
|
||||
if (mode === 1) {
|
||||
const key = await crypto.subtle.importKey('raw', keyBytes, 'AES-GCM', false, ['decrypt']);
|
||||
const decrypted = await crypto.subtle.decrypt({ name: 'AES-GCM', iv }, key, payload);
|
||||
jsonBytes = new Uint8Array(decrypted);
|
||||
} else {
|
||||
const withLen = xorBytes(payload, keyBytes);
|
||||
const len = new DataView(withLen.buffer).getUint32(0, true);
|
||||
jsonBytes = withLen.slice(4, 4 + len);
|
||||
if (mode !== 1) {
|
||||
throw new Error('不支持的加密格式,请使用最新版本重新导出');
|
||||
}
|
||||
|
||||
const key = await crypto.subtle.importKey('raw', keyBytes, 'AES-GCM', false, ['decrypt']);
|
||||
const decrypted = await crypto.subtle.decrypt({ name: 'AES-GCM', iv }, key, payload);
|
||||
const jsonBytes = new Uint8Array(decrypted);
|
||||
|
||||
return JSON.parse(new TextDecoder().decode(jsonBytes));
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
* 全程 try-catch,任何情况下不阻塞主流程
|
||||
*/
|
||||
|
||||
import { escapeHtml } from '../utils/utils.js';
|
||||
|
||||
export type LogLevel = 'info' | 'success' | 'warn' | 'error' | 'debug' | 'tool' | 'think' | 'stream';
|
||||
|
||||
export interface LogEntry {
|
||||
@@ -85,10 +87,6 @@ function formatTime(ts: number): string {
|
||||
return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}:${String(d.getSeconds()).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
function escapeHtml(text: string): string {
|
||||
return text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
||||
}
|
||||
|
||||
/** 批量渲染队列 — 使用 rAF 避免阻塞主线程 */
|
||||
function flushPending(): void {
|
||||
if (!logBodyEl || pendingEntries.length === 0) return;
|
||||
|
||||
@@ -1,84 +1,46 @@
|
||||
/**
|
||||
* Markdown 渲染器配置
|
||||
* Markdown 渲染器配置 — 基于 marked 库
|
||||
*/
|
||||
|
||||
import { SAFE_URI_SCHEMES } from './sanitizer.js';
|
||||
import { marked as markedLib, Renderer } from 'marked';
|
||||
import { sanitize } from './sanitizer.js';
|
||||
|
||||
// 简化的 Markdown 解析器(内联,不依赖外部 marked 库)
|
||||
// 支持基本 GFM 语法:标题、粗体、斜体、代码块、链接、列表、表格
|
||||
// 自定义渲染器:链接安全检查
|
||||
const renderer = new Renderer();
|
||||
const SAFE_SCHEMES = new Set(['http:', 'https:', 'mailto:', 'tel:', 'ftp:', 'ftps:', 'xmpp:']);
|
||||
|
||||
function parseMarkdown(md: string): string {
|
||||
renderer.link = function ({ href, text, tokens }) {
|
||||
try {
|
||||
const protocol = new URL(href, 'https://placeholder').protocol;
|
||||
if (!SAFE_SCHEMES.has(protocol)) {
|
||||
return `<span class="blocked-link">${text}</span>`;
|
||||
}
|
||||
} catch { /* 允许相对路径 */ }
|
||||
return `<a href="${href}" target="_blank" rel="noopener noreferrer">${text}</a>`;
|
||||
};
|
||||
|
||||
renderer.image = function ({ href, text }) {
|
||||
try {
|
||||
const protocol = new URL(href, 'https://placeholder').protocol;
|
||||
if (!SAFE_SCHEMES.has(protocol)) {
|
||||
return `<span class="blocked-link">${text || '图片'}</span>`;
|
||||
}
|
||||
} catch { /* 允许相对路径 */ }
|
||||
return `<img src="${href}" alt="${text || ''}" loading="lazy">`;
|
||||
};
|
||||
|
||||
// 配置 marked
|
||||
markedLib.use({
|
||||
renderer,
|
||||
gfm: true,
|
||||
breaks: true,
|
||||
});
|
||||
|
||||
/**
|
||||
* 解析 Markdown 并净化 HTML 输出
|
||||
*/
|
||||
export function marked(md: string): string {
|
||||
if (!md) return '';
|
||||
let html = escapeForMd(md);
|
||||
|
||||
// 代码块 ```...```
|
||||
const codeBlockRe = new RegExp('```(\\w*)\\n([\\s\\S]*?)```', 'g');
|
||||
html = html.replace(codeBlockRe, (_m, lang, code) => {
|
||||
return `<pre><code class="language-${lang}">${code.trim()}</code></pre>`;
|
||||
});
|
||||
|
||||
// 行内代码
|
||||
html = html.replace(/`([^`]+)`/g, '<code>$1</code>');
|
||||
|
||||
// 标题
|
||||
html = html.replace(/^######\s+(.+)$/gm, '<h6>$1</h6>');
|
||||
html = html.replace(/^#####\s+(.+)$/gm, '<h5>$1</h5>');
|
||||
html = html.replace(/^####\s+(.+)$/gm, '<h4>$1</h4>');
|
||||
html = html.replace(/^###\s+(.+)$/gm, '<h3>$1</h3>');
|
||||
html = html.replace(/^##\s+(.+)$/gm, '<h2>$1</h2>');
|
||||
html = html.replace(/^#\s+(.+)$/gm, '<h1>$1</h1>');
|
||||
|
||||
// 粗体+斜体
|
||||
html = html.replace(/\*\*\*(.+?)\*\*\*/g, '<strong><em>$1</em></strong>');
|
||||
// 粗体
|
||||
html = html.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>');
|
||||
// 斜体
|
||||
html = html.replace(/\*(.+?)\*/g, '<em>$1</em>');
|
||||
// 删除线
|
||||
html = html.replace(/~~(.+?)~~/g, '<del>$1</del>');
|
||||
|
||||
// 链接 [text](url)
|
||||
html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_m, text, href) => {
|
||||
try {
|
||||
const safe = SAFE_URI_SCHEMES.has(new URL(href, 'https://placeholder').protocol);
|
||||
if (!safe) return `<span class="blocked-link">${text}</span>`;
|
||||
} catch { /* allow relative */ }
|
||||
return `<a href="${href}" target="_blank" rel="noopener noreferrer">${text}</a>`;
|
||||
});
|
||||
|
||||
// 图片 
|
||||
html = html.replace(/!\[([^\]]*)\]\(([^)]+)\)/g, '<img src="$2" alt="$1" loading="lazy">');
|
||||
|
||||
// 引用块
|
||||
html = html.replace(/^>\s+(.+)$/gm, '<blockquote><p>$1</p></blockquote>');
|
||||
|
||||
// 水平线
|
||||
html = html.replace(/^---+$/gm, '<hr>');
|
||||
|
||||
// 无序列表
|
||||
html = html.replace(/^[\-\*]\s+(.+)$/gm, '<li>$1</li>');
|
||||
html = html.replace(/((?:<li>.*<\/li>\n?)+)/g, '<ul>$1</ul>');
|
||||
|
||||
// 有序列表
|
||||
html = html.replace(/^\d+\.\s+(.+)$/gm, '<li>$1</li>');
|
||||
|
||||
// 换行
|
||||
html = html.replace(/\n\n/g, '</p><p>');
|
||||
html = html.replace(/\n/g, '<br>');
|
||||
|
||||
// 包裹在 p 标签中
|
||||
if (!html.startsWith('<')) {
|
||||
html = '<p>' + html + '</p>';
|
||||
}
|
||||
|
||||
return html;
|
||||
const raw = markedLib.parse(md) as string;
|
||||
return sanitize(raw);
|
||||
}
|
||||
|
||||
function escapeForMd(str: string): string {
|
||||
return str
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>');
|
||||
}
|
||||
|
||||
export { parseMarkdown as marked };
|
||||
|
||||
@@ -1,73 +1,31 @@
|
||||
/**
|
||||
* Sanitizer - HTML 净化器
|
||||
* Sanitizer — 基于 DOMPurify 的 HTML 净化器
|
||||
*/
|
||||
|
||||
export const SAFE_URI_SCHEMES = new Set(['http:', 'https:', 'mailto:', 'tel:', 'ftp:', 'ftps:', 'xmpp:']);
|
||||
import DOMPurify from 'dompurify';
|
||||
|
||||
// 允许的 data URI 类型
|
||||
const SAFE_DATA_TYPES = new Set(['image/png', 'image/jpeg', 'image/gif', 'image/webp', 'image/svg+xml']);
|
||||
|
||||
const ALLOWED_TAGS = new Set([
|
||||
'a', 'abbr', 'b', 'blockquote', 'br', 'code', 'del', 'details', 'div',
|
||||
'dl', 'dt', 'dd', 'em', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr',
|
||||
'i', 'img', 'ins', 'kbd', 'li', 'ol', 'p', 'pre', 'q', 'rp', 'rt',
|
||||
'ruby', 's', 'samp', 'small', 'span', 'strike', 'strong', 'sub',
|
||||
'summary', 'sup', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead',
|
||||
'tr', 'u', 'ul', 'var', 'input',
|
||||
]);
|
||||
|
||||
const ALLOWED_ATTRS = new Set([
|
||||
'href', 'src', 'alt', 'title', 'width', 'height', 'align',
|
||||
'target', 'rel', 'class', 'id', 'type', 'checked', 'disabled',
|
||||
'start', 'value', 'scope', 'rowspan', 'colspan', 'lang',
|
||||
]);
|
||||
|
||||
const DANGEROUS_PREFIXES = ['on', 'xlink:href', 'xmlns:'];
|
||||
|
||||
/**
|
||||
* 净化 HTML,移除危险标签和属性
|
||||
*/
|
||||
export function sanitize(html: string): string {
|
||||
try {
|
||||
const template = document.createElement('template');
|
||||
template.innerHTML = html;
|
||||
const root = template.content;
|
||||
|
||||
const walker = document.createTreeWalker(root, NodeFilter.SHOW_COMMENT);
|
||||
const comments: Comment[] = [];
|
||||
while (walker.nextNode()) comments.push(walker.currentNode as Comment);
|
||||
comments.forEach(c => c.remove());
|
||||
|
||||
const elements = [...root.querySelectorAll('*')];
|
||||
for (const el of elements) {
|
||||
if (!el.parentNode) continue;
|
||||
const tag = el.tagName.toLowerCase();
|
||||
|
||||
if (!ALLOWED_TAGS.has(tag)) {
|
||||
while (el.firstChild) el.parentNode.insertBefore(el.firstChild, el);
|
||||
el.remove();
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const attr of [...el.attributes]) {
|
||||
const name = attr.name.toLowerCase();
|
||||
if (DANGEROUS_PREFIXES.some(p => name.startsWith(p))) {
|
||||
el.removeAttribute(attr.name);
|
||||
continue;
|
||||
}
|
||||
if (!ALLOWED_ATTRS.has(name)) {
|
||||
el.removeAttribute(attr.name);
|
||||
continue;
|
||||
}
|
||||
if ((name === 'href' || name === 'src' || name === 'action') && attr.value) {
|
||||
const val = attr.value.trim().toLowerCase();
|
||||
if (/^(javascript|vbscript|data|file):/i.test(val)) {
|
||||
const mimeMatch = val.match(/^data:([^;,]+)/i);
|
||||
if (!mimeMatch || !SAFE_DATA_TYPES.has(mimeMatch[1].toLowerCase())) {
|
||||
el.removeAttribute(attr.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return root.innerHTML;
|
||||
} catch (e) {
|
||||
return html;
|
||||
}
|
||||
return DOMPurify.sanitize(html, {
|
||||
ALLOWED_TAGS: [
|
||||
'a', 'abbr', 'b', 'blockquote', 'br', 'code', 'del', 'details', 'div',
|
||||
'dl', 'dt', 'dd', 'em', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr',
|
||||
'i', 'img', 'ins', 'kbd', 'li', 'ol', 'p', 'pre', 'q', 'rp', 'rt',
|
||||
'ruby', 's', 'samp', 'small', 'span', 'strike', 'strong', 'sub',
|
||||
'summary', 'sup', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead',
|
||||
'tr', 'u', 'ul', 'var', 'input',
|
||||
],
|
||||
ALLOWED_ATTR: [
|
||||
'href', 'src', 'alt', 'title', 'width', 'height', 'align',
|
||||
'target', 'rel', 'class', 'id', 'type', 'checked', 'disabled',
|
||||
'start', 'value', 'scope', 'rowspan', 'colspan', 'lang',
|
||||
],
|
||||
ALLOWED_URI_REGEXP: /^(?:(?:https?|ftp|ftps|mailto|tel|xmpp):|data:image\/(?:png|jpeg|gif|webp|svg\+xml);)/i,
|
||||
ADD_ATTR: ['target'],
|
||||
});
|
||||
}
|
||||
|
||||
@@ -44,9 +44,9 @@ export function formatSize(bytes: number): string {
|
||||
|
||||
/** HTML 转义 */
|
||||
export function escapeHtml(str: string): string {
|
||||
const map: Record<string, string> = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' };
|
||||
return String(str).replace(/[&<>"']/g, (c) => map[c]);
|
||||
return str.replace(/[&<>"']/g, (c) => ESCAPE_MAP[c]);
|
||||
}
|
||||
const ESCAPE_MAP: Record<string, string> = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' };
|
||||
|
||||
/** 根据文件名检测语言标识(用于 Markdown 代码块) */
|
||||
export function detectLanguage(filename: string): string {
|
||||
|
||||
Reference in New Issue
Block a user