From c44b0efa7dfce21dad6bab77904509045b1b93be Mon Sep 17 00:00:00 2001 From: freefire Date: Thu, 17 Sep 2026 05:46:42 +0800 Subject: [PATCH] =?UTF-8?q?feat(hide):=20=E5=AF=86=E7=A0=81=E5=8F=AF?= =?UTF-8?q?=E8=A7=81=E9=9A=90=E8=97=8F=E5=9D=97=EF=BC=8C=E5=8F=91=E5=B8=96?= =?UTF-8?q?=E5=8F=8C=E6=A0=8F=E9=A2=84=E8=A7=88=E4=B8=8E=E9=97=A8=E7=A6=81?= =?UTF-8?q?=E4=BD=93=E9=AA=8C=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 增加密码解锁与游客签名 cookie;发帖页对齐 1440 并默认双栏预览;修复 locked 解析、按钮对比度与回复聚焦。 Co-authored-by: Cursor --- backend/handler/handlers.go | 1 + backend/handler/post.go | 53 +++++- backend/markdown/hide.go | 162 +++++++++++++----- backend/markdown/hide_test.go | 50 ++++++ backend/middleware/csrf.go | 20 +++ backend/model/models.go | 15 +- backend/router/router.go | 6 +- backend/service/hide_password_cookie.go | 157 ++++++++++++++++++ backend/service/post.go | 38 ++++- backend/service/post_interact.go | 2 +- backend/service/ratelimit.go | 30 ++-- frontend/app/compose/layout.tsx | 2 +- frontend/app/globals.css | 164 +++++++++++++++++-- frontend/app/post/[id]/edit/page.tsx | 2 +- frontend/app/post/[id]/page.tsx | 6 +- frontend/components/CommentSection.tsx | 20 ++- frontend/components/MarkdownEditor.tsx | 107 ++++++++++-- frontend/components/PostComposer.tsx | 2 +- frontend/components/markdown/MdHideBlock.tsx | 123 +++++++++++++- frontend/lib/api.ts | 9 + frontend/lib/cookies.ts | 25 +++ frontend/lib/hideBlocks.ts | 48 ++++-- frontend/lib/postMeta.ts | 1 + 23 files changed, 911 insertions(+), 132 deletions(-) create mode 100644 backend/service/hide_password_cookie.go diff --git a/backend/handler/handlers.go b/backend/handler/handlers.go index d710611..5300723 100644 --- a/backend/handler/handlers.go +++ b/backend/handler/handlers.go @@ -30,6 +30,7 @@ type Handlers struct { Chat *service.ChatService Telemetry *service.TelemetryService Analytics *service.AnalyticsService + HidePwd *service.HidePasswordCookie } // resolvePublishStatus 决定新帖/新评的初始状态: diff --git a/backend/handler/post.go b/backend/handler/post.go index 414f870..c16b598 100644 --- a/backend/handler/post.go +++ b/backend/handler/post.go @@ -78,7 +78,8 @@ func (h *Handlers) PostDetail(c *gin.Context) { viewerID = claims.ID loadActor = h.actorLoader(claims.ID) } - post, err := h.Post.GetByIDForViewer(uint(id), viewerID, loadActor) + pwdUnlocked := h.HidePwd.ReadUnlocked(c, uint(id)) + post, err := h.Post.GetByIDForViewer(uint(id), viewerID, loadActor, pwdUnlocked) if err != nil { c.JSON(http.StatusNotFound, gin.H{"error": "帖子不存在"}) return @@ -189,6 +190,56 @@ func (h *Handlers) UnlockPostContent(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"post": post}) } +// UnlockPostPasswordRequest 密码解锁隐藏块 +type UnlockPostPasswordRequest struct { + Password string `json:"password" binding:"required,min=1,max=64"` +} + +// UnlockPostPassword 输入密码解锁正文密码隐藏块(游客可用,签名 cookie 记住) +func (h *Handlers) UnlockPostPassword(c *gin.Context) { + id, err := strconv.ParseUint(c.Param("id"), 10, 64) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "无效的帖子 ID"}) + return + } + var req UnlockPostPasswordRequest + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "请输入密码"}) + return + } + matched, err := h.Post.UnlockByPassword(uint(id), req.Password) + if err != nil { + if errors.Is(err, service.ErrPostNotFound) { + c.JSON(http.StatusNotFound, gin.H{"error": "帖子不存在"}) + return + } + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + h.HidePwd.WriteUnlocked(c, uint(id), matched) + + claims := middleware.CurrentUser(c) + var viewerID uint + var loadActor func() *service.Actor + if claims != nil { + viewerID = claims.ID + loadActor = h.actorLoader(claims.ID) + } + pwdUnlocked := h.HidePwd.ReadUnlocked(c, uint(id)) + for _, i := range matched { + pwdUnlocked[i] = true + } + post, err := h.Post.GetByIDForViewer(uint(id), viewerID, loadActor, pwdUnlocked) + if err != nil { + c.JSON(http.StatusNotFound, gin.H{"error": "帖子不存在"}) + return + } + if claims != nil { + post.Liked = h.Like.HasLiked(post.ID, claims.ID) + } + c.JSON(http.StatusOK, gin.H{"post": post}) +} + // GetPointsBalance 当前用户积分余额 func (h *Handlers) GetPointsBalance(c *gin.Context) { claims := middleware.CurrentUser(c) diff --git a/backend/markdown/hide.go b/backend/markdown/hide.go index b7140e4..047c86c 100644 --- a/backend/markdown/hide.go +++ b/backend/markdown/hide.go @@ -6,47 +6,59 @@ import ( "fmt" "strconv" "strings" + "unicode/utf8" ) const ( - HideKindLogin = "login" - HideKindReply = "reply" - HideKindPoints = "points" + HideKindLogin = "login" + HideKindReply = "reply" + HideKindPoints = "points" + HideKindPassword = "password" +) + +const ( + // MaxHidePasswordLen 密码可见块密码最大长度(字符) + MaxHidePasswordLen = 64 + // MinHidePasswordLen 密码最小长度 + MinHidePasswordLen = 1 ) // HideBlock 正文中的一段隐藏内容 type HideBlock struct { - Kind string // login | reply | points - Points int // 仅 points 有效 - Body string // 块内 Markdown(不含开闭标记行) - Start int // 开标记行在 lines 中的下标 - End int // 闭标记行在 lines 中的下标(含) - Locked bool // 开标记是否已带 locked(脱敏输出) + Kind string // login | reply | points | password + Points int // 仅 points 有效 + Password string // 仅 password 有效(原文;脱敏输出时清空) + Body string // 块内 Markdown(不含开闭标记行) + Start int // 开标记行在 lines 中的下标 + End int // 闭标记行在 lines 中的下标(含) + Locked bool // 开标记是否已带 locked(脱敏输出) + Index int // 在全文隐藏块列表中的下标(0-based) } // DerivedAccess 由正文隐藏块派生的帖级可见性 type DerivedAccess struct { - Access string // public | login | reply | points | mixed + Access string // public | login | reply | points | password | mixed Points int // 所有积分块价格之和 } // ViewerCaps 读者对隐藏块的能力(由 service 填充) type ViewerCaps struct { - Bypass bool // 作者 / 版主 - LoggedIn bool - HasReplied bool - PointsPaid bool // 已支付本帖积分解锁 + Bypass bool // 作者 / 版主 + LoggedIn bool + HasReplied bool + PointsPaid bool // 已支付本帖积分解锁 + PasswordUnlocked map[int]bool // 已凭密码解锁的隐藏块下标 } var ( - ErrHideNested = errors.New("隐藏块不可嵌套") - ErrHideUnclosed = errors.New("隐藏块未正确闭合") - ErrHideInvalid = errors.New("隐藏块语法无效") - ErrHidePointsNeed = errors.New("积分可见块须指定 1–100000 的积分") + ErrHideNested = errors.New("隐藏块不可嵌套") + ErrHideUnclosed = errors.New("隐藏块未正确闭合") + ErrHideInvalid = errors.New("隐藏块语法无效") + ErrHidePointsNeed = errors.New("积分可见块须指定 1–100000 的积分") + ErrHidePasswordNeed = errors.New("密码可见块须设置 1–64 字符且不含空格的密码") ) // ParseHideBlocks 扫描正文中的 :::hide 块(忽略代码围栏内伪语法)。 -// 校验失败返回 error(用于 Create/Update)。 func ParseHideBlocks(content string) ([]HideBlock, error) { lines := splitLines(content) var blocks []HideBlock @@ -65,7 +77,7 @@ func ParseHideBlocks(content string) ([]HideBlock, error) { continue } - if kind, pts, locked, ok := parseOpenMarker(trimmed); ok { + if kind, pts, pwd, locked, ok := parseOpenMarker(trimmed); ok { j := i + 1 bodyLines := make([]string, 0) foundClose := false @@ -83,7 +95,7 @@ func ParseHideBlocks(content string) ([]HideBlock, error) { j++ continue } - if _, _, _, isOpen := parseOpenMarker(inner); isOpen { + if _, _, _, _, isOpen := parseOpenMarker(inner); isOpen { return nil, ErrHideNested } if isCloseMarker(inner) { @@ -101,13 +113,23 @@ func ParseHideBlocks(content string) ([]HideBlock, error) { return nil, ErrHidePointsNeed } } + if kind == HideKindPassword { + // 已 locked 的脱敏行无密码,仅服务端原文必须带合法密码 + if !locked { + if err := validatePassword(pwd); err != nil { + return nil, err + } + } + } blocks = append(blocks, HideBlock{ - Kind: kind, - Points: pts, - Body: strings.Join(bodyLines, "\n"), - Start: i, - End: j, - Locked: locked, + Kind: kind, + Points: pts, + Password: pwd, + Body: strings.Join(bodyLines, "\n"), + Start: i, + End: j, + Locked: locked, + Index: len(blocks), }) i = j + 1 continue @@ -153,7 +175,7 @@ func DeriveAccessFromContent(content string) (DerivedAccess, error) { } // SanitizeForViewer 按读者能力脱敏:未满足条件的块清空正文并加 locked。 -// fullyLocked 表示读者当前看不到任何可见正文(整篇都在锁块里或公开区为空)。 +// 密码块即使已解锁,也不向读者回传明文密码(开标记写成 :::hide password)。 func SanitizeForViewer(content string, caps ViewerCaps) (sanitized string, fullyLocked bool) { blocks, err := ParseHideBlocks(content) if err != nil { @@ -180,7 +202,7 @@ func SanitizeForViewer(content string, caps ViewerCaps) (sanitized string, fully } if blockUnlocked(b, caps) { - out = append(out, openMarkerLine(b.Kind, b.Points, false)) + out = append(out, openMarkerLine(b.Kind, b.Points, "", false)) if b.Body != "" { out = append(out, splitLines(b.Body)...) if strings.TrimSpace(b.Body) != "" { @@ -189,7 +211,7 @@ func SanitizeForViewer(content string, caps ViewerCaps) (sanitized string, fully } out = append(out, ":::") } else { - out = append(out, openMarkerLine(b.Kind, b.Points, true)) + out = append(out, openMarkerLine(b.Kind, b.Points, "", true)) out = append(out, ":::") } cursor = b.End + 1 @@ -204,10 +226,28 @@ func SanitizeForViewer(content string, caps ViewerCaps) (sanitized string, fully return strings.Join(out, "\n"), !anyVisible } +// MatchPasswordBlocks 返回密码匹配的隐藏块下标 +func MatchPasswordBlocks(content, password string) ([]int, error) { + blocks, err := ParseHideBlocks(content) + if err != nil { + return nil, err + } + var hit []int + for _, b := range blocks { + if b.Kind != HideKindPassword { + continue + } + if constantTimeEqual(b.Password, password) { + hit = append(hit, b.Index) + } + } + return hit, nil +} + // WrapContentAsHide 将整篇正文包进单一隐藏块(旧帖迁移用) func WrapContentAsHide(kind string, points int, content string) string { body := strings.TrimRight(content, "\n") - open := openMarkerLine(kind, points, false) + open := openMarkerLine(kind, points, "", false) if body == "" { return open + "\n:::\n" } @@ -231,12 +271,15 @@ func blockUnlocked(b HideBlock, caps ViewerCaps) bool { return caps.HasReplied case HideKindPoints: return caps.PointsPaid + case HideKindPassword: + return caps.PasswordUnlocked != nil && caps.PasswordUnlocked[b.Index] default: return true } } -func openMarkerLine(kind string, points int, locked bool) string { +// openMarkerLine 生成开标记。密码仅在原文存储时写入;对外脱敏输出传空 password。 +func openMarkerLine(kind string, points int, password string, locked bool) string { var b strings.Builder b.WriteString(":::hide ") b.WriteString(kind) @@ -244,50 +287,72 @@ func openMarkerLine(kind string, points int, locked bool) string { b.WriteByte(' ') b.WriteString(strconv.Itoa(points)) } + if kind == HideKindPassword && password != "" && !locked { + b.WriteByte(' ') + b.WriteString(password) + } if locked { b.WriteString(" locked") } return b.String() } -func parseOpenMarker(trimmed string) (kind string, points int, locked bool, ok bool) { +// parseOpenMarker 解析 :::hide [points|password] [locked] +func parseOpenMarker(trimmed string) (kind string, points int, password string, locked bool, ok bool) { if !strings.HasPrefix(trimmed, ":::hide") { - return "", 0, false, false + return "", 0, "", false, false } rest := strings.TrimSpace(trimmed[len(":::hide"):]) if rest == "" { - return "", 0, false, false + return "", 0, "", false, false } parts := strings.Fields(rest) if len(parts) == 0 { - return "", 0, false, false + return "", 0, "", false, false } kind = parts[0] switch kind { - case HideKindLogin, HideKindReply, HideKindPoints: + case HideKindLogin, HideKindReply, HideKindPoints, HideKindPassword: default: - return "", 0, false, false + return "", 0, "", false, false } idx := 1 if kind == HideKindPoints { if idx >= len(parts) { - return "", 0, false, false + return "", 0, "", false, false } n, err := strconv.Atoi(parts[idx]) if err != nil { - return "", 0, false, false + return "", 0, "", false, false } points = n idx++ + } else if kind == HideKindPassword { + // 允许::::hide password locked(脱敏)或 :::hide password [locked] + if idx < len(parts) && parts[idx] != "locked" { + password = parts[idx] + idx++ + } } for ; idx < len(parts); idx++ { if parts[idx] == "locked" { locked = true } else { - return "", 0, false, false + return "", 0, "", false, false } } - return kind, points, locked, true + return kind, points, password, locked, true +} + +func validatePassword(pwd string) error { + if pwd == "" || strings.ContainsAny(pwd, " \t") { + return ErrHidePasswordNeed + } + n := utf8.RuneCountInString(pwd) + if n < MinHidePasswordLen || n > MaxHidePasswordLen { + return ErrHidePasswordNeed + } + return nil } func isCloseMarker(trimmed string) bool { @@ -316,9 +381,22 @@ func ValidateHideContent(content string) error { return fmt.Errorf("隐藏块未正确闭合,请检查 ::: 标记") case errors.Is(err, ErrHidePointsNeed): return fmt.Errorf("积分可见块须指定 1–100000 的积分") + case errors.Is(err, ErrHidePasswordNeed): + return fmt.Errorf("密码可见块须设置 1–64 字符且不含空格的密码") case errors.Is(err, ErrHideInvalid): return fmt.Errorf("隐藏块语法无效") default: return err } } + +func constantTimeEqual(a, b string) bool { + if len(a) != len(b) { + return false + } + var v byte + for i := 0; i < len(a); i++ { + v |= a[i] ^ b[i] + } + return v == 0 +} diff --git a/backend/markdown/hide_test.go b/backend/markdown/hide_test.go index 84e9103..56cd28a 100644 --- a/backend/markdown/hide_test.go +++ b/backend/markdown/hide_test.go @@ -111,6 +111,56 @@ func TestCodeInsideHide(t *testing.T) { } } +func TestParsePasswordAndSanitize(t *testing.T) { + src := "公开\n\n:::hide password secret1\n密码内容\n:::\n" + blocks, err := ParseHideBlocks(src) + if err != nil { + t.Fatal(err) + } + if len(blocks) != 1 || blocks[0].Kind != HideKindPassword || blocks[0].Password != "secret1" { + t.Fatalf("%+v", blocks) + } + d := DeriveAccess(blocks) + if d.Access != "password" { + t.Fatalf("access=%s", d.Access) + } + out, fully := SanitizeForViewer(src, ViewerCaps{}) + if fully { + t.Fatal("public visible") + } + if strings.Contains(out, "secret1") || strings.Contains(out, "密码内容") { + t.Fatalf("leaked: %q", out) + } + if !strings.Contains(out, ":::hide password locked") { + t.Fatalf("%q", out) + } + out2, _ := SanitizeForViewer(src, ViewerCaps{PasswordUnlocked: map[int]bool{0: true}}) + if !strings.Contains(out2, "密码内容") { + t.Fatalf("unlock failed: %q", out2) + } + if strings.Contains(out2, "secret1") { + t.Fatalf("password leaked after unlock: %q", out2) + } +} + +func TestMatchPasswordBlocks(t *testing.T) { + src := ":::hide password aaa\nA\n:::\n\n:::hide password bbb\nB\n:::\n" + hit, err := MatchPasswordBlocks(src, "bbb") + if err != nil { + t.Fatal(err) + } + if len(hit) != 1 || hit[0] != 1 { + t.Fatalf("%v", hit) + } +} + +func TestPasswordNeed(t *testing.T) { + _, err := ParseHideBlocks(":::hide password\n无密码\n:::\n") + if err != ErrHidePasswordNeed { + t.Fatalf("got %v", err) + } +} + func TestWrapContentAsHide(t *testing.T) { got := WrapContentAsHide("points", 20, "旧正文") if !strings.HasPrefix(got, ":::hide points 20\n") { diff --git a/backend/middleware/csrf.go b/backend/middleware/csrf.go index 6e72407..bf5fcf6 100644 --- a/backend/middleware/csrf.go +++ b/backend/middleware/csrf.go @@ -3,11 +3,31 @@ package middleware import ( "crypto/subtle" "net/http" + "time" "github.com/freefire/jiang13-bbs/service" "github.com/gin-gonic/gin" ) +// EnsureCSRFCookie 若请求尚无 CSRF cookie 则签发一枚(游客也可拿到,供公开写接口双提交)。 +// 不改写已有 cookie;生命周期与 refresh 一致(7 天)。 +func EnsureCSRFCookie(secure bool) gin.HandlerFunc { + return func(c *gin.Context) { + if raw, err := c.Cookie(service.CSRFCookieName); err != nil || raw == "" { + http.SetCookie(c.Writer, &http.Cookie{ + Name: service.CSRFCookieName, + Value: service.GenerateCSRFToken(), + Path: "/", + MaxAge: int((7 * 24 * time.Hour).Seconds()), + HttpOnly: false, + Secure: secure, + SameSite: http.SameSiteLaxMode, + }) + } + c.Next() + } +} + // CSRFMiddleware CSRF 防护中间件 // 对 POST/PUT/DELETE 等状态变更请求,校验 X-CSRF-Token header 与 cookie 中的 CSRF token 是否一致 func CSRFMiddleware() gin.HandlerFunc { diff --git a/backend/model/models.go b/backend/model/models.go index ca21fea..a3e97bb 100644 --- a/backend/model/models.go +++ b/backend/model/models.go @@ -82,17 +82,18 @@ func NormalizePostType(t string) string { // 正文可见性(由正文 :::hide 块派生;mixed = 多种隐藏类型并存) const ( - ContentAccessPublic = "public" // 公开 - ContentAccessLogin = "login" // 仅登录可见块 - ContentAccessReply = "reply" // 仅回复可见块 - ContentAccessPoints = "points" // 仅积分可见块 - ContentAccessMixed = "mixed" // 多种隐藏块混合 + ContentAccessPublic = "public" // 公开 + ContentAccessLogin = "login" // 仅登录可见块 + ContentAccessReply = "reply" // 仅回复可见块 + ContentAccessPoints = "points" // 仅积分可见块 + ContentAccessPassword = "password" // 仅密码可见块 + ContentAccessMixed = "mixed" // 多种隐藏块混合 ) // ValidContentAccess 可见性白名单 func ValidContentAccess(a string) bool { switch a { - case ContentAccessPublic, ContentAccessLogin, ContentAccessReply, ContentAccessPoints, ContentAccessMixed: + case ContentAccessPublic, ContentAccessLogin, ContentAccessReply, ContentAccessPoints, ContentAccessPassword, ContentAccessMixed: return true } return false @@ -168,7 +169,7 @@ type Post struct { Content string `gorm:"type:text;not null" json:"content"` Tags string `gorm:"size:256" json:"tags"` PostType string `gorm:"size:16;default:discussion;index" json:"post_type"` - ContentAccess string `gorm:"size:16;default:public;index" json:"content_access"` // public|login|reply|points|mixed(由正文隐藏块派生) + ContentAccess string `gorm:"size:16;default:public;index" json:"content_access"` // public|login|reply|points|password|mixed(由正文隐藏块派生) AccessPoints int `gorm:"not null;default:0" json:"access_points"` // 积分隐藏块价格之和 TypeMeta string `gorm:"type:text;default:''" json:"type_meta"` // 类型扩展 JSON(投票/悬赏/抽奖壳) Pinned int `gorm:"default:0" json:"pinned"` diff --git a/backend/router/router.go b/backend/router/router.go index 4d3e4fa..d4497e8 100644 --- a/backend/router/router.go +++ b/backend/router/router.go @@ -86,6 +86,7 @@ func Setup(cfg *config.Config) (*gin.Engine, error) { Chat: chatSvc, Telemetry: telemetrySvc, Analytics: analyticsSvc, + HidePwd: service.NewHidePasswordCookie(cfg.JWTSecret, !cfg.DevMode), } // 通知落库后统一推 WS 红点(点赞/评论/审核/@ 等共用) notifSvc.OnNotifyNew = func(userID uint) { @@ -110,8 +111,8 @@ func Setup(cfg *config.Config) (*gin.Engine, error) { // 实时通信总线(WebSocket,cookie 鉴权 + Origin 校验,处理器内部完成鉴权升级) r.GET("/api/ws", h.RealtimeWS) - // 公开 API(可选登录) - pubAPI := r.Group("/api", authMW.OptionalAuth()) + // 公开 API(可选登录);EnsureCSRF 让游客也能拿到双提交 token(密码解锁等) + pubAPI := r.Group("/api", authMW.OptionalAuth(), middleware.EnsureCSRFCookie(!cfg.DevMode)) { pubAPI.GET("/me", h.Me) pubAPI.GET("/boards", h.Boards) @@ -119,6 +120,7 @@ func Setup(cfg *config.Config) (*gin.Engine, error) { pubAPI.GET("/overview", h.Overview) pubAPI.GET("/posts", h.Posts) pubAPI.GET("/posts/:id", h.PostDetail) + pubAPI.POST("/posts/:id/unlock-password", middleware.CSRFMiddleware(), middleware.RateLimitMiddleware(limiter, service.RateHidePassword), h.UnlockPostPassword) pubAPI.GET("/posts/:id/attachments/:aid/download", h.DownloadPostAttachment) pubAPI.GET("/posts/:id/comments", h.PostComments) pubAPI.GET("/users/:id", h.UserProfile) diff --git a/backend/service/hide_password_cookie.go b/backend/service/hide_password_cookie.go new file mode 100644 index 0000000..d1a984c --- /dev/null +++ b/backend/service/hide_password_cookie.go @@ -0,0 +1,157 @@ +package service + +import ( + "crypto/hmac" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "fmt" + "net/http" + "sort" + "strconv" + "strings" + "time" + + "github.com/gin-gonic/gin" +) + +const ( + hidePwdCookiePrefix = "j13_hp_" + hidePwdCookieMaxAge = 30 * 24 * 3600 // 30 天 + hidePwdCookieVersion = "1" +) + +// HidePasswordCookie 帖子密码隐藏块解锁 cookie(游客可用) +type HidePasswordCookie struct { + secret []byte + secure bool +} + +func NewHidePasswordCookie(jwtSecret string, secure bool) *HidePasswordCookie { + sum := sha256.Sum256([]byte("j13-hide-pwd-v1:" + jwtSecret)) + return &HidePasswordCookie{secret: sum[:], secure: secure} +} + +func (h *HidePasswordCookie) cookieName(postID uint) string { + return hidePwdCookiePrefix + strconv.FormatUint(uint64(postID), 10) +} + +// ReadUnlocked 读取某帖已解锁的隐藏块下标 +func (h *HidePasswordCookie) ReadUnlocked(c *gin.Context, postID uint) map[int]bool { + out := map[int]bool{} + if h == nil || c == nil { + return out + } + raw, err := c.Cookie(h.cookieName(postID)) + if err != nil || raw == "" { + return out + } + idxs, ok := h.verify(postID, raw) + if !ok { + return out + } + for _, i := range idxs { + out[i] = true + } + return out +} + +// WriteUnlocked 写入/合并已解锁下标 +func (h *HidePasswordCookie) WriteUnlocked(c *gin.Context, postID uint, idxs []int) { + if h == nil || c == nil || len(idxs) == 0 { + return + } + merged := h.ReadUnlocked(c, postID) + for _, i := range idxs { + merged[i] = true + } + list := make([]int, 0, len(merged)) + for i := range merged { + list = append(list, i) + } + sort.Ints(list) + val := h.sign(postID, list) + http.SetCookie(c.Writer, &http.Cookie{ + Name: h.cookieName(postID), + Value: val, + Path: "/", + MaxAge: hidePwdCookieMaxAge, + HttpOnly: true, + Secure: h.secure, + SameSite: http.SameSiteLaxMode, + }) +} + +func (h *HidePasswordCookie) sign(postID uint, idxs []int) string { + payload := fmt.Sprintf("%s|%d|%s|%d", + hidePwdCookieVersion, + postID, + joinInts(idxs), + time.Now().Add(hidePwdCookieMaxAge*time.Second).Unix(), + ) + mac := hmac.New(sha256.New, h.secret) + _, _ = mac.Write([]byte(payload)) + sig := hex.EncodeToString(mac.Sum(nil)) + return base64.RawURLEncoding.EncodeToString([]byte(payload)) + "." + sig +} + +func (h *HidePasswordCookie) verify(postID uint, raw string) ([]int, bool) { + parts := strings.Split(raw, ".") + if len(parts) != 2 { + return nil, false + } + payloadBytes, err := base64.RawURLEncoding.DecodeString(parts[0]) + if err != nil { + return nil, false + } + payload := string(payloadBytes) + mac := hmac.New(sha256.New, h.secret) + _, _ = mac.Write([]byte(payload)) + expect := hex.EncodeToString(mac.Sum(nil)) + if !hmac.Equal([]byte(expect), []byte(parts[1])) { + return nil, false + } + fields := strings.Split(payload, "|") + if len(fields) != 4 || fields[0] != hidePwdCookieVersion { + return nil, false + } + pid, err := strconv.ParseUint(fields[1], 10, 64) + if err != nil || uint(pid) != postID { + return nil, false + } + exp, err := strconv.ParseInt(fields[3], 10, 64) + if err != nil || time.Now().Unix() > exp { + return nil, false + } + return parseInts(fields[2]), true +} + +func joinInts(idxs []int) string { + if len(idxs) == 0 { + return "" + } + var b strings.Builder + for i, n := range idxs { + if i > 0 { + b.WriteByte(',') + } + b.WriteString(strconv.Itoa(n)) + } + return b.String() +} + +func parseInts(s string) []int { + if s == "" { + return nil + } + parts := strings.Split(s, ",") + out := make([]int, 0, len(parts)) + for _, p := range parts { + n, err := strconv.Atoi(p) + if err != nil || n < 0 { + continue + } + out = append(out, n) + } + return out +} diff --git a/backend/service/post.go b/backend/service/post.go index fed4b97..1452ae8 100644 --- a/backend/service/post.go +++ b/backend/service/post.go @@ -426,8 +426,9 @@ type UpdatePostInput struct { } // GetByIDForViewer 获取帖子详情(带状态可见性 + 正文访问控制)。 +// pwdUnlocked 为密码隐藏块已解锁下标(来自签名 cookie);可为 nil。 // 已软删帖返回 tombstone(无正文/附件);已硬删或不存在返回 ErrPostNotFound。 -func (s *PostService) GetByIDForViewer(id, viewerID uint, loadActor func() *Actor) (*PostDetail, error) { +func (s *PostService) GetByIDForViewer(id, viewerID uint, loadActor func() *Actor, pwdUnlocked map[int]bool) (*PostDetail, error) { var post model.Post err := s.db.Preload("Board").Preload("User").First(&post, id).Error if err != nil { @@ -461,7 +462,7 @@ func (s *PostService) GetByIDForViewer(id, viewerID uint, loadActor func() *Acto post.ViewCount++ detail := buildPostDetail(&post) - sanitized, fullyLocked, hint := s.sanitizePostContent(&post, viewerID, loadActor) + sanitized, fullyLocked, hint := s.sanitizePostContent(&post, viewerID, loadActor, pwdUnlocked) detail.Content = sanitized detail.ContentLocked = fullyLocked detail.AccessHint = hint @@ -517,8 +518,8 @@ func buildPostDetail(post *model.Post) *PostDetail { } // sanitizePostContent 按读者能力对正文 :::hide 块脱敏;fullyLocked 表示无可见正文。 -func (s *PostService) sanitizePostContent(post *model.Post, viewerID uint, loadActor func() *Actor) (content string, fullyLocked bool, hint string) { - caps := s.buildHideViewerCaps(post, viewerID, loadActor) +func (s *PostService) sanitizePostContent(post *model.Post, viewerID uint, loadActor func() *Actor, pwdUnlocked map[int]bool) (content string, fullyLocked bool, hint string) { + caps := s.buildHideViewerCaps(post, viewerID, loadActor, pwdUnlocked) sanitized, fully := markdown.SanitizeForViewer(post.Content, caps) if !fully { return sanitized, false, "" @@ -527,10 +528,9 @@ func (s *PostService) sanitizePostContent(post *model.Post, viewerID uint, loadA switch access { case model.ContentAccessPoints: return sanitized, true, "支付积分后可见隐藏内容" + case model.ContentAccessPassword: + return sanitized, true, "输入密码后可见隐藏内容" case model.ContentAccessMixed: - if post.AccessPoints > 0 { - return sanitized, true, "满足条件后可见隐藏内容" - } return sanitized, true, "满足条件后可见隐藏内容" case model.ContentAccessReply: return sanitized, true, "回复本帖后可见隐藏内容" @@ -541,8 +541,8 @@ func (s *PostService) sanitizePostContent(post *model.Post, viewerID uint, loadA } } -func (s *PostService) buildHideViewerCaps(post *model.Post, viewerID uint, loadActor func() *Actor) markdown.ViewerCaps { - caps := markdown.ViewerCaps{} +func (s *PostService) buildHideViewerCaps(post *model.Post, viewerID uint, loadActor func() *Actor, pwdUnlocked map[int]bool) markdown.ViewerCaps { + caps := markdown.ViewerCaps{PasswordUnlocked: pwdUnlocked} if viewerID > 0 && post.UserID == viewerID { caps.Bypass = true caps.LoggedIn = true @@ -625,6 +625,26 @@ func (s *PostService) listAttachmentDTOs(postID, viewerID, authorID uint) ([]Pos return out, nil } +// UnlockByPassword 校验密码,返回匹配的隐藏块下标(调用方写 cookie) +func (s *PostService) UnlockByPassword(postID uint, password string) (matched []int, err error) { + var post model.Post + if err := s.db.Select("id", "content", "status").First(&post, postID).Error; err != nil { + return nil, ErrPostNotFound + } + password = strings.TrimSpace(password) + if password == "" { + return nil, errors.New("请输入密码") + } + hit, err := markdown.MatchPasswordBlocks(post.Content, password) + if err != nil { + return nil, err + } + if len(hit) == 0 { + return nil, errors.New("密码错误") + } + return hit, nil +} + // UnlockContent 积分解锁正文隐藏块(一次支付解锁本帖全部积分块) func (s *PostService) UnlockContent(userID, postID uint) (*PostDetail, error) { var post model.Post diff --git a/backend/service/post_interact.go b/backend/service/post_interact.go index fc28609..c02b7bf 100644 --- a/backend/service/post_interact.go +++ b/backend/service/post_interact.go @@ -1519,7 +1519,7 @@ func (s *PostService) loadManageablePost(actor *Actor, userID, postID uint) (*mo func (s *PostService) detailAfterInteract(post *model.Post, viewerID uint) (*PostDetail, error) { detail := buildPostDetail(post) - sanitized, fullyLocked, hint := s.sanitizePostContent(post, viewerID, nil) + sanitized, fullyLocked, hint := s.sanitizePostContent(post, viewerID, nil, nil) detail.Content = sanitized detail.ContentLocked = fullyLocked detail.AccessHint = hint diff --git a/backend/service/ratelimit.go b/backend/service/ratelimit.go index 3840594..a60c466 100644 --- a/backend/service/ratelimit.go +++ b/backend/service/ratelimit.go @@ -62,24 +62,26 @@ func (r *RateLimiter) Allow(key string) bool { // 速率限制类型常量 const ( - RateLogin = "login" - RateRegister = "register" - RatePost = "post" - RateComment = "comment" - RateChat = "chat" // 群聊发消息 - RateUpload = "upload" // 帖子插图等上传 - RateInteract = "interact" // 投票/抽奖/解锁等互动 + RateLogin = "login" + RateRegister = "register" + RatePost = "post" + RateComment = "comment" + RateChat = "chat" // 群聊发消息 + RateUpload = "upload" // 帖子插图等上传 + RateInteract = "interact" // 投票/抽奖/解锁等互动 + RateHidePassword = "hide_password" // 密码隐藏块尝试 ) // DefaultRateLimiter 创建默认速率限制器 func DefaultRateLimiter() *RateLimiter { rl := NewRateLimiter() - rl.SetLimit(RateLogin, 20) // 登录 20/分钟 - rl.SetLimit(RateRegister, 10) // 注册 10/分钟 - rl.SetLimit(RatePost, 10) // 发帖 10/分钟 - rl.SetLimit(RateComment, 30) // 评论 30/分钟 - rl.SetLimit(RateChat, 30) // 群聊消息 30/分钟 - rl.SetLimit(RateUpload, 20) // 图片上传 20/分钟 - rl.SetLimit(RateInteract, 40) // 互动 40/分钟 + rl.SetLimit(RateLogin, 20) // 登录 20/分钟 + rl.SetLimit(RateRegister, 10) // 注册 10/分钟 + rl.SetLimit(RatePost, 10) // 发帖 10/分钟 + rl.SetLimit(RateComment, 30) // 评论 30/分钟 + rl.SetLimit(RateChat, 30) // 群聊消息 30/分钟 + rl.SetLimit(RateUpload, 20) // 图片上传 20/分钟 + rl.SetLimit(RateInteract, 40) // 互动 40/分钟 + rl.SetLimit(RateHidePassword, 20) // 密码尝试 20/分钟(按 IP) return rl } diff --git a/frontend/app/compose/layout.tsx b/frontend/app/compose/layout.tsx index 1195e6c..735c8ea 100644 --- a/frontend/app/compose/layout.tsx +++ b/frontend/app/compose/layout.tsx @@ -10,7 +10,7 @@ export default function ComposeLayout({ return (
{children}
diff --git a/frontend/app/globals.css b/frontend/app/globals.css index d4f2933..184529e 100644 --- a/frontend/app/globals.css +++ b/frontend/app/globals.css @@ -1367,14 +1367,26 @@ body { text-align: left; padding: 8px 10px; border-radius: 8px; + border: 0; + appearance: none; + -webkit-appearance: none; font-size: 13px; - color: var(--ink); - background: transparent; + font-weight: 500; + line-height: 1.35; + cursor: pointer; + /* 强制可读对比:避免暗色下系统 buttonface 浅底 + 浅字 */ + color: var(--ink) !important; + background: transparent !important; } .j13-md-popover button[role="menuitem"]:hover, .j13-md-menu-item:hover { - background: var(--accent-soft); - color: var(--accent); + background: var(--panel-2) !important; + color: var(--ink) !important; +} +.j13-md-popover button[role="menuitem"]:focus-visible, +.j13-md-menu-item:focus-visible { + outline: 2px solid var(--accent); + outline-offset: 0; } .j13-md-popover-input { width: 100%; @@ -1401,13 +1413,18 @@ body { text-align: left; padding: 7px 10px; border-radius: 8px; + border: 0; + appearance: none; + -webkit-appearance: none; font-size: 12.5px; font-family: var(--font-mono, ui-monospace, monospace); - color: var(--ink-2); + cursor: pointer; + color: var(--ink-2) !important; + background: transparent !important; } .j13-md-popover-list button:hover { - background: var(--accent-soft); - color: var(--accent); + background: var(--panel-2) !important; + color: var(--ink) !important; } .j13-md-field { display: flex; @@ -1433,6 +1450,8 @@ body { display: flex; flex-direction: column; min-height: 0; + min-width: 0; + height: 100%; } .j13-md-write-wrap.is-dragover .j13-md-textarea { opacity: 0.35; @@ -1462,18 +1481,65 @@ body { } .j13-md-mode button { height: 30px; - padding: 0 12px; + padding: 0 10px; border-radius: 999px; + border: 0; + appearance: none; + -webkit-appearance: none; font-size: 12.5px; font-weight: 500; display: inline-flex; align-items: center; gap: 5px; - color: var(--ink-3); + cursor: pointer; + color: var(--ink-2); + background: transparent; } .j13-md-mode button.is-on { - background: var(--accent-soft); + background: color-mix(in srgb, var(--accent) 18%, var(--panel)); color: var(--accent); + font-weight: 600; +} +.j13-md-panes { + flex: 1 1 auto; + display: grid; + grid-template-columns: 1fr; + grid-template-rows: minmax(0, 1fr); + min-height: 0; + gap: 0; +} +.j13-md-panes.is-split { + grid-template-columns: 1fr; +} +@media (min-width: 960px) { + .j13-md-panes.is-split { + grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); + } + .j13-md-panes.is-split .j13-md-write-wrap { + border-right: 1px solid var(--line); + padding-right: 1rem; + margin-right: 0; + } + .j13-md-panes.is-split .j13-md-preview { + padding-left: 1rem; + } +} +/* 窄屏双栏:上下分栏仍同时显示 */ +@media (max-width: 959px) { + .j13-md-panes.is-split { + grid-template-rows: minmax(220px, 1fr) minmax(220px, 1fr); + gap: 0; + } + .j13-md-panes.is-split .j13-md-write-wrap { + border-bottom: 1px solid var(--line); + padding-bottom: 0.5rem; + } + .j13-md-panes.is-split .j13-md-preview { + padding-top: 0.35rem; + } +} +.j13-md-panes > [hidden] { + display: none !important; } .j13-md-textarea { flex: 1 1 auto; @@ -1505,9 +1571,23 @@ body { .j13-md-preview { flex: 1 1 auto; min-height: 320px; + height: 100%; overflow-y: auto; - padding: 1rem 0 0.75rem; + padding: 0.65rem 0 0.75rem; background: transparent; + min-width: 0; +} +.j13-md-preview-label { + font-size: 11.5px; + font-weight: 600; + letter-spacing: 0.04em; + text-transform: uppercase; + margin-bottom: 0.35rem; + color: var(--ink-3); +} +.j13-md-panes.is-preview .j13-md-preview-label, +.j13-md-panes.is-write .j13-md-preview-label { + display: none; } .j13-md-foot { flex-shrink: 0; @@ -1545,8 +1625,8 @@ body { border-radius: 999px; font-size: 11.5px; font-weight: 600; - color: var(--accent); - background: var(--accent-soft); + color: var(--accent-on); + background: var(--accent); } .j13-hide-block-body { padding: 12px 16px 14px; @@ -1581,6 +1661,52 @@ body { gap: 8px; flex-wrap: wrap; } +.j13-hide-pwd-wrap { + display: flex; + flex-direction: column; + align-items: center; + gap: 8px; + width: 100%; + max-width: 360px; + margin: 0 auto; +} +.j13-hide-pwd-form { + display: flex; + align-items: center; + gap: 8px; + flex-wrap: wrap; + justify-content: center; + width: 100%; +} +.j13-hide-pwd-input { + flex: 1 1 160px; + min-width: 140px; + height: 36px; + padding: 0 12px; + border-radius: 10px; + border: 1px solid var(--line-2); + background: var(--panel); + color: var(--ink); + font-size: 14px; +} +.j13-hide-pwd-input:focus { + outline: 2px solid var(--accent); + outline-offset: 0; +} +.j13-hide-pwd-input.is-invalid { + border-color: var(--danger); + outline: none; + box-shadow: 0 0 0 2px color-mix(in srgb, var(--danger) 22%, transparent); +} +.j13-hide-pwd-error { + margin: 0; + width: 100%; + text-align: center; + font-size: 13px; + font-weight: 600; + line-height: 1.4; + color: var(--danger); +} .j13-compose-shell { background: var(--panel); @@ -3703,6 +3829,18 @@ a.j13-mention-token:hover { text-underline-offset: 3px; font-weight: 500; } +/* 正文内嵌按钮链接:未分层的 .prose-content a 会盖掉 @layer 的 .btn-primary 字色 */ +.prose-content a.btn, +.prose-content a.btn-primary, +.prose-content a.btn-accent { + color: var(--accent-on) !important; + text-decoration: none; + font-weight: 500; +} +.prose-content a.btn-line { + color: var(--ink) !important; + text-decoration: none; +} .prose-content img, .prose-content .md-content-img { max-width: 100%; diff --git a/frontend/app/post/[id]/edit/page.tsx b/frontend/app/post/[id]/edit/page.tsx index 5c82049..44441d5 100644 --- a/frontend/app/post/[id]/edit/page.tsx +++ b/frontend/app/post/[id]/edit/page.tsx @@ -37,7 +37,7 @@ export default async function EditPostPage({ params }: PageProps) { return (
); diff --git a/frontend/lib/api.ts b/frontend/lib/api.ts index 096c2f7..2f2e0fa 100644 --- a/frontend/lib/api.ts +++ b/frontend/lib/api.ts @@ -838,6 +838,15 @@ export async function apiUnlockPost(postId: string) { return res.json(); } +export async function apiUnlockPostPassword(postId: string, password: string) { + const res = await fetchWithRefresh(`/api/posts/${postId}/unlock-password`, { + method: "POST", + headers: clientHeaders({ "Content-Type": "application/json" }), + body: JSON.stringify({ password }), + }); + return res.json(); +} + export async function apiGetPoints(): Promise<{ points: number }> { const res = await fetchWithRefresh("/api/points", { method: "GET", diff --git a/frontend/lib/cookies.ts b/frontend/lib/cookies.ts index 1e12122..9397ce8 100644 --- a/frontend/lib/cookies.ts +++ b/frontend/lib/cookies.ts @@ -7,10 +7,17 @@ export const TOKEN_COOKIE = `${HOST_PREFIX}j13_token`; export const REFRESH_COOKIE = `${HOST_PREFIX}j13_refresh`; export const CSRF_COOKIE = `${HOST_PREFIX}j13_csrf`; +/** 密码隐藏块解锁 cookie 前缀(与 backend HidePasswordCookie 一致) */ +export const HIDE_PWD_COOKIE_PREFIX = "j13_hp_"; + type CookieReader = { get(name: string): { value: string } | undefined; }; +type CookieStoreLike = CookieReader & { + getAll?: () => { name: string; value: string }[]; +}; + // 构造转发给后端的最小 Cookie 头:SSR 公开/鉴权接口只需要 access token 来 // 识别用户(填充 liked 等状态),不应把 refresh token、主题等无关 cookie 全量转发。 // 返回空串表示当前无登录凭据,调用方应省略 Cookie 头。 @@ -19,6 +26,24 @@ export function authCookieHeader(store: CookieReader): string { return token ? `${TOKEN_COOKIE}=${token.value}` : ""; } +/** + * 帖子详情 SSR:access token + 密码隐藏块解锁 cookie。 + * 解锁 cookie 为 HttpOnly,必须随 SSR 转发,否则 refresh 后密码块会再次锁上。 + */ +export function postViewerCookieHeader(store: CookieStoreLike): string { + const parts: string[] = []; + const auth = authCookieHeader(store); + if (auth) parts.push(auth); + if (typeof store.getAll === "function") { + for (const c of store.getAll()) { + if (c.name.startsWith(HIDE_PWD_COOKIE_PREFIX)) { + parts.push(`${c.name}=${c.value}`); + } + } + } + return parts.join("; "); +} + // 客户端判断浏览器是否可能持有登录态:j13_csrf 非 HttpOnly 可读, // 生命周期与 refresh 一致,适合作为挂载后静默校正的触发信号。 export function hasAuthCookieHint(): boolean { diff --git a/frontend/lib/hideBlocks.ts b/frontend/lib/hideBlocks.ts index 572ee0d..30484fe 100644 --- a/frontend/lib/hideBlocks.ts +++ b/frontend/lib/hideBlocks.ts @@ -1,6 +1,6 @@ /** 正文 :::hide 块解析(与 backend/markdown/hide.go 契约一致) */ -export type HideKind = "login" | "reply" | "points"; +export type HideKind = "login" | "reply" | "points" | "password"; export type HideSegment = | { type: "md"; text: string } @@ -12,26 +12,50 @@ export type HideSegment = body: string; }; -const OPEN_RE = /^:::hide\s+(login|reply|points)(?:\s+(\d+))?(?:\s+(locked))?\s*$/; +const HIDE_KINDS = new Set(["login", "reply", "points", "password"]); function isClose(line: string): boolean { return line.trim() === ":::"; } +/** 与 Go parseOpenMarker 对齐::::hide [points|password] [locked] */ function parseOpen(trimmed: string): { kind: HideKind; points: number; locked: boolean; } | null { - const m = OPEN_RE.exec(trimmed); - if (!m) return null; - const kind = m[1] as HideKind; - const points = m[2] ? Number(m[2]) : 0; - const locked = m[3] === "locked"; - if (kind === "points" && (!Number.isFinite(points) || points < 1)) { - return null; + if (!trimmed.startsWith(":::hide")) return null; + const parts = trimmed + .slice(":::hide".length) + .trim() + .split(/\s+/) + .filter(Boolean); + if (parts.length === 0) return null; + const kind = parts[0] as HideKind; + if (!HIDE_KINDS.has(kind)) return null; + + let idx = 1; + let points = 0; + let locked = false; + + if (kind === "points") { + if (idx >= parts.length) return null; + const n = Number(parts[idx]); + if (!Number.isFinite(n) || n < 1 || n > 100000) return null; + points = n; + idx++; + } else if (kind === "password") { + // 脱敏::::hide password locked;原文::::hide password [locked] + if (idx < parts.length && parts[idx] !== "locked") { + idx++; + } } - return { kind, points: kind === "points" ? points : 0, locked }; + + for (; idx < parts.length; idx++) { + if (parts[idx] === "locked") locked = true; + else return null; + } + return { kind, points, locked }; } /** @@ -87,7 +111,6 @@ export function splitHideSegments(content: string): HideSegment[] { continue; } if (parseOpen(inner)) { - // 嵌套:放弃隐藏语义,整段当普通文本 buf.push(lines[i]); i++; found = false; @@ -101,7 +124,6 @@ export function splitHideSegments(content: string): HideSegment[] { j++; } if (!found) { - // 未闭合:开标记行起当普通文本 buf.push(lines[i]); i++; continue; @@ -150,5 +172,7 @@ export function hideKindLabel(kind: HideKind): string { return "回复可见"; case "points": return "积分可见"; + case "password": + return "密码可见"; } } diff --git a/frontend/lib/postMeta.ts b/frontend/lib/postMeta.ts index 16700a5..50e9a66 100644 --- a/frontend/lib/postMeta.ts +++ b/frontend/lib/postMeta.ts @@ -15,6 +15,7 @@ export const CONTENT_ACCESS = [ { value: "login", label: "登录可见" }, { value: "reply", label: "回复可见" }, { value: "points", label: "积分可见" }, + { value: "password", label: "密码可见" }, { value: "mixed", label: "含隐藏内容" }, ] as const;