feat(hide): 密码可见隐藏块,发帖双栏预览与门禁体验修复
增加密码解锁与游客签名 cookie;发帖页对齐 1440 并默认双栏预览;修复 locked 解析、按钮对比度与回复聚焦。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -30,6 +30,7 @@ type Handlers struct {
|
||||
Chat *service.ChatService
|
||||
Telemetry *service.TelemetryService
|
||||
Analytics *service.AnalyticsService
|
||||
HidePwd *service.HidePasswordCookie
|
||||
}
|
||||
|
||||
// resolvePublishStatus 决定新帖/新评的初始状态:
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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 <kind> [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 <pwd> [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
|
||||
}
|
||||
|
||||
@@ -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") {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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"`
|
||||
|
||||
@@ -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)
|
||||
|
||||
157
backend/service/hide_password_cookie.go
Normal file
157
backend/service/hide_password_cookie.go
Normal file
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user