@@ -117,9 +117,9 @@ function renderAdminUsers(page = 1, search = '') {
`;
});
@@ -340,7 +340,7 @@ function renderAdminLogs(page = 1) {
`;
}
- container.innerHTML = html;
+ container.innerHTML = sanitizeHTML(html);
// 绑定分页按钮事件
container.querySelectorAll('.logs-page-btn:not([disabled])').forEach(btn => {
@@ -383,7 +383,7 @@ function renderAdminLinks() {
links.forEach(l => {
html += `
`;
});
- ul.innerHTML = html;
+ ul.innerHTML = sanitizeHTML(html);
ul.querySelectorAll('[data-linkid]').forEach(btn => {
btn.addEventListener('click', function() {
if (!confirm('确定删除该链接吗?')) return;
@@ -624,9 +624,9 @@ function loadCustomPageList() {
pages.forEach(p => {
html += `
- ${p.name} |
- ${p.title} |
- ?custom=${p.name} |
+ ${escapeHTML(p.name)} |
+ ${escapeHTML(p.title)} |
+ ?custom=${escapeHTML(p.name)} |
${p.enabled ? `${getIcon('success')} 启用` : `${getIcon('error')} 禁用`} |
@@ -636,7 +636,7 @@ function loadCustomPageList() {
`;
});
html += '';
- container.innerHTML = html;
+ container.innerHTML = sanitizeHTML(html);
container.querySelectorAll('[data-action="edit"]').forEach(btn => {
btn.addEventListener('click', function() {
@@ -673,13 +673,13 @@ function openCustomPageEditor(page) {
${isEdit ? getIcon('edit') + ' 编辑页面' : getIcon('add') + ' 添加页面'}
-
${isEdit ? ' ⚠️ 名称不可修改 ' : ' 只允许字母、数字、短横线和下划线 '}
-
@@ -691,7 +691,7 @@ function openCustomPageEditor(page) {
-
+
支持 HTML、CSS(<style>)、JS(<script>),内容会在独立的沙盒中渲染
diff --git a/js/app.js b/js/app.js
index 28c5e10..24b6a44 100644
--- a/js/app.js
+++ b/js/app.js
@@ -19,7 +19,7 @@ function showToast(message, type = 'success', duration = 3000) {
toast.innerHTML = `
${icons[type] || icons.success}
- ${message}
+ ${escapeHTML(message)}
`;
document.body.appendChild(toast);
@@ -224,25 +224,30 @@ async function renderMessageList() {
const unread = c.unread_count || 0;
const lastMsg = c.last_message || '暂无消息';
const time = c.last_message_time ? new Date(c.last_message_time).toLocaleString('zh-CN') : '';
+ const avatar = c.other_avatar_url || 'https://ui-avatars.com/api/?name=' + encodeURIComponent(c.other_username) + '&background=6366f1&color=fff&size=64';
html += `
-
-  + '&background=6366f1&color=fff&size=64'})
+
- ${c.other_username}
+ ${escapeHTML(c.other_username)}
${time}
- ${lastMsg}
+ ${escapeHTML(lastMsg)}
${unread > 0 ? `${unread}` : ''}
`;
});
- container.innerHTML = html;
+ container.innerHTML = sanitizeHTML(html);
+ container.querySelectorAll('.message-list-item').forEach(item => {
+ item.addEventListener('click', function() {
+ openChat(this.dataset.conversationId, this.dataset.userId, this.dataset.username);
+ });
+ });
} catch (err) {
container.innerHTML = '加载失败 ';
}
@@ -294,12 +299,13 @@ async function renderMessages(conversationId, silent = false) {
messages.forEach(m => {
const isMine = m.sender_id === currentUser.id;
const time = m.created_at ? new Date(m.created_at).toLocaleString('zh-CN') : '';
+ const avatar = m.sender_avatar_url || 'https://ui-avatars.com/api/?name=' + encodeURIComponent(m.sender_username) + '&background=6366f1&color=fff&size=64';
html += `
- ${!isMine ? `  + '&background=6366f1&color=fff&size=64'}) ` : ''}
+ ${!isMine ? ` )}) ` : ''}
- ${m.content}
+ ${renderPlainText(m.content)}
${time} ${isMine ? (m.is_read ? '✓✓' : '✓') : ''}
@@ -308,7 +314,7 @@ async function renderMessages(conversationId, silent = false) {
`;
});
- container.innerHTML = html;
+ container.innerHTML = sanitizeHTML(html);
container.scrollTop = container.scrollHeight;
} catch (err) {
if (!silent) {
@@ -452,7 +458,7 @@ function showCustomPage(pageName) {
API.getCustomPage(pageName).then(page => {
const iframe = document.createElement('iframe');
iframe.style.cssText = 'width:100%;min-height:70vh;border:none;border-radius:8px;background:var(--surface);';
- iframe.sandbox = 'allow-scripts allow-modals allow-same-origin';
+ iframe.sandbox = 'allow-scripts allow-modals';
iframe.srcdoc = `
@@ -483,7 +489,7 @@ function showCustomPage(pageName) {
el.style.color = el.dataset.custom === pageName ? 'var(--primary)' : 'var(--text-secondary)';
});
}).catch(err => {
- container.innerHTML = ' 页面加载失败:' + err.message + ' ';
+ container.innerHTML = ' 页面加载失败:' + escapeHTML(err.message) + ' ';
});
}
@@ -527,15 +533,15 @@ async function renderMessagesPage() {
${icon}
- ${n.title}
- ${n.content}
- ${n.link ? ` 查看详情 →` : ''}
+ ${escapeHTML(n.title)}
+ ${escapeHTML(n.content)}
+ ${n.link ? ` 查看详情 →` : ''}
${time}
`;
});
- container.innerHTML = html;
+ container.innerHTML = sanitizeHTML(html);
} catch (err) {
container.innerHTML = ' 加载失败 ';
}
@@ -579,9 +585,9 @@ function renderLinks() {
} else {
let html = '';
links.forEach(l => {
- html += ' ' + l.title + '';
+ html += ' ' + escapeHTML(l.title) + '';
});
- ul.innerHTML = html;
+ ul.innerHTML = sanitizeHTML(html);
}
}
@@ -593,9 +599,9 @@ function renderLinks() {
} else {
let html = '';
links.forEach(l => {
- html += ' ' + l.title + '';
+ html += ' ' + escapeHTML(l.title) + '';
});
- ul2.innerHTML = html;
+ ul2.innerHTML = sanitizeHTML(html);
}
}
}).catch(() => {});
@@ -640,15 +646,15 @@ async function renderSettingsPage(tab = 'profile') {
-
- ${user.username}
- ${user.bio || '这个人很懒,什么都没写'}
+ ${escapeHTML(user.username)}
+ ${escapeHTML(user.bio || '这个人很懒,什么都没写')}
${getIcon('calendar')} 加入 ${user.created_at ? new Date(user.created_at).toLocaleDateString('zh-CN') : '未知'}
${getIcon('file')} ${postCount} 帖
@@ -661,15 +667,15 @@ async function renderSettingsPage(tab = 'profile') {
-
+
-
+
-
+
用 --- 分隔,支持 Markdown
@@ -916,8 +922,8 @@ function openEditModal(postId, currentTitle, currentContent) {
×
${getIcon('edit')} 编辑帖子
-
-
+
+
`;
diff --git a/js/feed.js b/js/feed.js
index 662c169..5656b31 100644
--- a/js/feed.js
+++ b/js/feed.js
@@ -38,18 +38,18 @@ function renderFeed() {
if (p.images && p.images.length > 0) {
imagesHtml = ' ';
p.images.forEach(img => {
- imagesHtml += '  ';
+ imagesHtml += ' ) + ') ';
});
imagesHtml += ' ';
}
const replyCount = p.reply_count || 0;
- const renderedContent = marked ? marked.parse(p.content || '') : (p.content || '').replace(/\n/g, ' ');
+ const renderedContent = renderMarkdown(p.content || '');
// 签名渲染
let signatureHtml = '';
if (p.signature) {
- const sigContent = marked ? marked.parse(p.signature) : p.signature;
+ const sigContent = renderMarkdown(p.signature);
signatureHtml = `
${sigContent}
@@ -61,12 +61,12 @@ function renderFeed() {
${p.is_pinned ? ' 📌 置顶 ' : ''}
- ${p.title || '无标题'}
+ ${escapeHTML(p.title || '无标题')}
${renderedContent}
${imagesHtml}
@@ -87,7 +87,7 @@ function renderFeed() {
`;
});
- container.innerHTML = html;
+ container.innerHTML = sanitizeHTML(html);
// 分页控件
if (totalPages > 1) {
@@ -167,6 +167,20 @@ function renderFeed() {
});
});
+ container.querySelectorAll('.post-username').forEach(username => {
+ username.addEventListener('click', function(e) {
+ e.stopPropagation();
+ switchPage('user', this.dataset.username);
+ });
+ });
+
+ container.querySelectorAll('.post-image').forEach(image => {
+ image.addEventListener('click', function(e) {
+ e.stopPropagation();
+ openImageViewer(this.src);
+ });
+ });
+
container.querySelectorAll('.action-report').forEach(btn => {
btn.addEventListener('click', function(e) {
e.stopPropagation();
@@ -187,7 +201,7 @@ function renderFeed() {
});
});
}).catch(err => {
- container.innerHTML = ' 加载失败:' + err.message +
+ container.innerHTML = ' 加载失败:' + escapeHTML(err.message) +
' ';
});
}
@@ -210,9 +224,9 @@ function renderLinks() {
}
let html = '';
links.forEach(l => {
- html += ' ' + l.title + '';
+ html += ' ' + escapeHTML(l.title) + '';
});
- ul.innerHTML = html;
+ ul.innerHTML = sanitizeHTML(html);
}).catch(() => {});
}
diff --git a/js/post.js b/js/post.js
index 87d5919..cd7af84 100644
--- a/js/post.js
+++ b/js/post.js
@@ -49,26 +49,17 @@ async function renderPostDetail(postId) {
if (post.images && post.images.length > 0) {
imagesHtml = ' ';
post.images.forEach(img => {
- imagesHtml += '  ';
+ imagesHtml += ' ) + ') ';
});
imagesHtml += ' ';
}
- let renderedContent = post.content || '';
- try {
- if (typeof marked !== 'undefined' && marked.parse) {
- renderedContent = marked.parse(renderedContent);
- } else {
- renderedContent = renderedContent.replace(/\n/g, ' ');
- }
- } catch (e) {
- renderedContent = renderedContent.replace(/\n/g, ' ');
- }
+ const renderedContent = renderMarkdown(post.content || '');
// 签名渲染
let signatureHtml = '';
if (post.signature) {
- const sigContent = marked ? marked.parse(post.signature) : post.signature;
+ const sigContent = renderMarkdown(post.signature);
signatureHtml = `
${sigContent}
@@ -79,8 +70,8 @@ async function renderPostDetail(postId) {
let html = `
';
- container.innerHTML = html;
+ container.innerHTML = sanitizeHTML(html);
replyArea.style.display = 'block';
document.getElementById('replyContent').value = '';
document.getElementById('replyCaptchaInput').value = '';
refreshCaptcha('reply');
+ container.querySelectorAll('.post-username, .reply-username').forEach(usernameEl => {
+ usernameEl.addEventListener('click', function() {
+ switchPage('user', this.dataset.username);
+ });
+ });
+
+ container.querySelectorAll('.post-image').forEach(image => {
+ image.addEventListener('click', function() {
+ openImageViewer(this.src);
+ });
+ });
+
// 置顶按钮
const pinBtn = document.getElementById('pinPostBtn');
if (pinBtn) {
@@ -210,7 +213,7 @@ async function renderPostDetail(postId) {
currentPostId = postId;
} catch (err) {
- container.innerHTML = ' 加载失败:' + err.message +
+ container.innerHTML = ' 加载失败:' + escapeHTML(err.message) +
' ';
replyArea.style.display = 'none';
}
diff --git a/js/security.js b/js/security.js
new file mode 100644
index 0000000..f6ad76c
--- /dev/null
+++ b/js/security.js
@@ -0,0 +1,77 @@
+// ============================================================
+// Safe rendering helpers
+// ============================================================
+
+function escapeHTML(value) {
+ return String(value ?? '')
+ .replace(/&/g, '&')
+ .replace(//g, '>')
+ .replace(/"/g, '"')
+ .replace(/'/g, ''');
+}
+
+function safeURL(value, { allowRelative = true, image = false } = {}) {
+ if (!value) return image ? '' : '#';
+
+ try {
+ const raw = String(value).trim();
+ const parsed = new URL(raw, window.location.origin);
+ const isRelative = parsed.origin === window.location.origin && !/^[a-z][a-z0-9+.-]*:/i.test(raw);
+ const allowedProtocol = parsed.protocol === 'http:' || parsed.protocol === 'https:';
+
+ if (!allowedProtocol || (!allowRelative && isRelative)) return image ? '' : '#';
+ return isRelative ? parsed.pathname + parsed.search + parsed.hash : parsed.href;
+ } catch (error) {
+ return image ? '' : '#';
+ }
+}
+
+function sanitizeHTML(html) {
+ const template = document.createElement('template');
+ template.innerHTML = String(html ?? '');
+
+ // Application templates contain legitimate controls. Raw user HTML is escaped
+ // before Markdown parsing, while this pass removes executable/embed elements.
+ const forbidden = 'script,iframe,object,embed,link,meta,base,style';
+ template.content.querySelectorAll(forbidden).forEach(node => node.remove());
+
+ template.content.querySelectorAll('*').forEach(node => {
+ for (const attribute of Array.from(node.attributes)) {
+ const name = attribute.name.toLowerCase();
+ if (name.startsWith('on') || name === 'srcdoc') {
+ node.removeAttribute(attribute.name);
+ }
+ }
+
+ if (node.hasAttribute('href')) {
+ const href = safeURL(node.getAttribute('href'));
+ if (href === '#') node.removeAttribute('href');
+ else node.setAttribute('href', href);
+ }
+
+ if (node.hasAttribute('src')) {
+ const src = safeURL(node.getAttribute('src'), { image: true });
+ if (!src) node.removeAttribute('src');
+ else node.setAttribute('src', src);
+ }
+
+ if (node.tagName === 'A' && node.getAttribute('target') === '_blank') {
+ node.setAttribute('rel', 'noopener noreferrer');
+ }
+ });
+
+ return template.innerHTML;
+}
+
+function renderMarkdown(value) {
+ const escaped = escapeHTML(value);
+ if (typeof marked !== 'undefined' && marked.parse) {
+ return sanitizeHTML(marked.parse(escaped));
+ }
+ return escaped.replace(/\r?\n/g, ' ');
+}
+
+function renderPlainText(value) {
+ return escapeHTML(value).replace(/\r?\n/g, ' ');
+}
diff --git a/js/user.js b/js/user.js
index 4d05be0..0aba932 100644
--- a/js/user.js
+++ b/js/user.js
@@ -24,9 +24,9 @@ async function renderUserProfile(username) {
let html = `
- 
- ${user.username}
- ${user.bio || '这个人很懒,什么都没写'}
+ )})
+ ${escapeHTML(user.username)}
+ ${escapeHTML(user.bio || '这个人很懒,什么都没写')}
📅 加入于 ${user.created_at ? new Date(user.created_at).toLocaleDateString('zh-CN') : '未知'}
📝 发了 ${posts.length} 个帖子
@@ -48,16 +48,22 @@ async function renderUserProfile(username) {
posts.forEach(p => {
const time = p.created_at ? new Date(p.created_at).toLocaleString('zh-CN') : '';
html += `
-
- ${p.title || '无标题'}
- ${(p.content || '').substring(0, 100)}${(p.content || '').length > 100 ? '...' : ''}
+
+ ${escapeHTML(p.title || '无标题')}
+ ${escapeHTML((p.content || '').substring(0, 100))}${(p.content || '').length > 100 ? '...' : ''}
${time}
`;
});
}
- container.innerHTML = html;
+ container.innerHTML = sanitizeHTML(html);
+
+ container.querySelectorAll('.post-card[data-postid]').forEach(card => {
+ card.addEventListener('click', function() {
+ switchToPost(this.dataset.postid);
+ });
+ });
const dmBtn = document.getElementById('dmBtn');
if (dmBtn) {
@@ -67,7 +73,7 @@ async function renderUserProfile(username) {
}
} catch (err) {
- container.innerHTML = ' 加载失败:' + err.message + ' ';
+ container.innerHTML = ' 加载失败:' + escapeHTML(err.message) + ' ';
}
}
|