fix: 修复代码块语法高亮丢失 + 语言标签注入 + 安全性增强

- 新增 cdnjs.cloudflare.com CSP 白名单,允许加载 highlight.js
- 消毒策略放行 span 元素,保留 highlight.js 高亮 class
- 详情页和新帖子页引入 highlight.js 库和 GitHub 主题
- 代码块语言选择器默认 text,支持 prev/next 循环切换语言
- 代码块语言标签注入兼容 data-language 和 code class 双来源
- 修复 utils.js defer 导致 common.js 执行时 getCSRFToken 未定义
This commit is contained in:
2026-05-28 15:21:44 +08:00
parent 91f2cbebc1
commit fe81c879b0
6 changed files with 305 additions and 348 deletions

View File

@ -9,14 +9,14 @@ import (
func SecurityHeaders() gin.HandlerFunc {
return func(c *gin.Context) {
// Content-Security-Policy
// script-src: 本站 + esm.sh CDN (Tiptap ESM 模块)
// style-src: 本站 + esm.sh (Tiptap CSS)
// script-src: 本站 + esm.sh CDN (Tiptap ESM 模块) + cdnjs (highlight.js)
// style-src: 本站 + esm.sh (Tiptap CSS) + cdnjs (highlight.js 主题)
// connect-src: 本站 + esm.sh (source map 请求)
// img-src: 本站 + data: URI (头像裁切) + blob: (粘贴图片)
c.Header("Content-Security-Policy",
"default-src 'self'; "+
"script-src 'self' 'unsafe-inline' https://esm.sh; "+
"style-src 'self' 'unsafe-inline' https://esm.sh; "+
"script-src 'self' 'unsafe-inline' https://esm.sh https://cdnjs.cloudflare.com; "+
"style-src 'self' 'unsafe-inline' https://esm.sh https://cdnjs.cloudflare.com; "+
"img-src 'self' data: blob:; "+
"connect-src 'self' https://esm.sh")

View File

@ -16,10 +16,11 @@ import (
// sanitizePolicy Tiptap 输出 HTML 的消毒策略
// 前端 WYSIWYG 编辑器输出 HTML由 bluemonday UGC 策略消毒
// 放行 code/pre 的 class/data-language 属性以保留代码高亮和语言标签
// 放行 span class 属性以保留 highlight.js 的 hljs-* 高亮
// 放行 span 元素及其 hljs-* class 以保留 highlight.js 语法高亮
// 放行 img 的 src/alt/title 属性以保留图片
var sanitizePolicy = func() *bluemonday.Policy {
p := bluemonday.UGCPolicy()
p.AllowElements("span")
p.AllowAttrs("class", "data-language").OnElements("code", "pre")
p.AllowAttrs("class").Matching(regexp.MustCompile("^hljs-")).OnElements("span")
p.AllowAttrs("src", "alt", "title").OnElements("img")