feat(hide): 密码可见隐藏块,发帖双栏预览与门禁体验修复

增加密码解锁与游客签名 cookie;发帖页对齐 1440 并默认双栏预览;修复 locked 解析、按钮对比度与回复聚焦。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-09-17 05:46:42 +08:00
parent 01e2fd05ca
commit c44b0efa7d
23 changed files with 911 additions and 132 deletions

View File

@@ -30,6 +30,7 @@ type Handlers struct {
Chat *service.ChatService
Telemetry *service.TelemetryService
Analytics *service.AnalyticsService
HidePwd *service.HidePasswordCookie
}
// resolvePublishStatus 决定新帖/新评的初始状态:

View File

@@ -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)

View File

@@ -6,27 +6,38 @@ import (
"fmt"
"strconv"
"strings"
"unicode/utf8"
)
const (
HideKindLogin = "login"
HideKindReply = "reply"
HideKindPoints = "points"
HideKindPassword = "password"
)
const (
// MaxHidePasswordLen 密码可见块密码最大长度(字符)
MaxHidePasswordLen = 64
// MinHidePasswordLen 密码最小长度
MinHidePasswordLen = 1
)
// HideBlock 正文中的一段隐藏内容
type HideBlock struct {
Kind string // login | reply | points
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 // 所有积分块价格之和
}
@@ -36,6 +47,7 @@ type ViewerCaps struct {
LoggedIn bool
HasReplied bool
PointsPaid bool // 已支付本帖积分解锁
PasswordUnlocked map[int]bool // 已凭密码解锁的隐藏块下标
}
var (
@@ -43,10 +55,10 @@ var (
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,
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
}

View File

@@ -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") {

View File

@@ -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 {

View File

@@ -86,13 +86,14 @@ const (
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"`

View File

@@ -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)

View 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
}

View File

@@ -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

View File

@@ -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

View File

@@ -69,6 +69,7 @@ const (
RateChat = "chat" // 群聊发消息
RateUpload = "upload" // 帖子插图等上传
RateInteract = "interact" // 投票/抽奖/解锁等互动
RateHidePassword = "hide_password" // 密码隐藏块尝试
)
// DefaultRateLimiter 创建默认速率限制器
@@ -81,5 +82,6 @@ func DefaultRateLimiter() *RateLimiter {
rl.SetLimit(RateChat, 30) // 群聊消息 30/分钟
rl.SetLimit(RateUpload, 20) // 图片上传 20/分钟
rl.SetLimit(RateInteract, 40) // 互动 40/分钟
rl.SetLimit(RateHidePassword, 20) // 密码尝试 20/分钟(按 IP)
return rl
}

View File

@@ -10,7 +10,7 @@ export default function ComposeLayout({
return (
<div
data-compose-viewport
className="flex flex-col flex-1 min-h-0 w-full max-w-6xl mx-auto"
className="flex flex-col flex-1 min-h-0 w-full"
>
{children}
</div>

View File

@@ -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%;

View File

@@ -37,7 +37,7 @@ export default async function EditPostPage({ params }: PageProps) {
return (
<div
data-compose-viewport
className="j13-compose-page w-full max-w-6xl mx-auto"
className="j13-compose-page w-full"
>
<nav className="meta mb-4 flex items-center gap-1.5 flex-wrap text-[13px] shrink-0">
<Link href="/" className="hover:text-[var(--accent)] transition-colors">

View File

@@ -24,7 +24,7 @@ import {
type Board,
type CommentsResponse,
} from "@/lib/api";
import { authCookieHeader } from "@/lib/cookies";
import { postViewerCookieHeader } from "@/lib/cookies";
import { getMeCached, getPublicSettingsCached } from "@/lib/serverData";
import CommentSection from "@/components/CommentSection";
import PostActions from "@/components/PostActions";
@@ -52,7 +52,7 @@ export async function generateMetadata({ params }: PageProps): Promise<Metadata>
const { id } = await params;
try {
// 带登录态:作者/管理团队看待审帖时标签标题也应是真实标题而非"帖子不存在"
const { post } = await fetchPostDetail(id, authCookieHeader(await cookies()));
const { post } = await fetchPostDetail(id, postViewerCookieHeader(await cookies()));
if (post.tombstone) {
return {
title: post.title || "帖子已删除",
@@ -402,7 +402,7 @@ export default async function PostDetailPage({ params, searchParams }: PageProps
const { id } = await params;
const sp = await searchParams;
const commentPage = Math.max(1, parseInt(sp.page || "1", 10) || 1);
const cookie = authCookieHeader(await cookies());
const cookie = postViewerCookieHeader(await cookies());
// 待审/被拒帖子对无权访问者由后端返回 404,这里落到全局 not-found 页而非 500
let post: Awaited<ReturnType<typeof fetchPostDetail>>["post"];
try {

View File

@@ -136,6 +136,22 @@ export default function CommentSection({
}
}, [commentsOpen]);
// 登录回跳 / 隐藏块「去回复」:滚到评论框并聚焦
useEffect(() => {
if (!user || !commentsOpen) return;
const focusComposer = () => {
const hash = window.location.hash;
if (hash !== "#comment-input" && hash !== "#comments") return;
const el = textareaRef.current ?? document.getElementById("comment-input");
if (!(el instanceof HTMLTextAreaElement)) return;
el.scrollIntoView({ behavior: "smooth", block: "center" });
window.setTimeout(() => el.focus({ preventScroll: true }), 280);
};
focusComposer();
window.addEventListener("hashchange", focusComposer);
return () => window.removeEventListener("hashchange", focusComposer);
}, [user, commentsOpen]);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!commentsOpen || !content.trim()) return;
@@ -1034,7 +1050,7 @@ export default function CommentSection({
}
return (
<section className="panel p-6 sm:p-8 mt-6" aria-label="评论区">
<section id="comments" className="panel p-6 sm:p-8 mt-6 scroll-mt-24" aria-label="评论区">
<div className="flex items-center gap-2.5 mb-6">
<h2 className="text-lg font-semibold" style={{ color: "var(--ink)" }}>
评论
@@ -1063,7 +1079,7 @@ export default function CommentSection({
}}
placeholder="友善发言,发表一个新楼层..."
rows={3}
className="field"
className="field scroll-mt-28"
aria-label="写评论"
/>
<div className="flex items-center justify-between gap-3 mt-2.5">

View File

@@ -5,6 +5,7 @@ import {
useState,
useCallback,
useEffect,
useDeferredValue,
type ReactNode,
type KeyboardEvent as ReactKeyboardEvent,
} from "react";
@@ -27,6 +28,7 @@ import {
Pencil,
Maximize2,
Minimize2,
Columns2,
Lock,
ChevronDown,
Upload,
@@ -47,6 +49,8 @@ type MarkdownEditorProps = {
id?: string;
};
type EditorMode = "split" | "write" | "preview";
type WrapOpts = {
before: string;
after?: string;
@@ -107,7 +111,8 @@ export default function MarkdownEditor({
const taRef = useRef<HTMLTextAreaElement>(null);
const fileRef = useRef<HTMLInputElement>(null);
const toolbarRef = useRef<HTMLDivElement>(null);
const [mode, setMode] = useState<"write" | "preview">("write");
const [mode, setMode] = useState<EditorMode>("split");
const deferredValue = useDeferredValue(value);
const [uploading, setUploading] = useState(false);
const [fullscreen, setFullscreen] = useState(false);
const [dragOver, setDragOver] = useState(false);
@@ -118,7 +123,8 @@ export default function MarkdownEditor({
const [imageAlt, setImageAlt] = useState("图片");
const [codeQuery, setCodeQuery] = useState("");
const [hidePoints, setHidePoints] = useState(10);
const [hideStep, setHideStep] = useState<"menu" | "points">("menu");
const [hidePassword, setHidePassword] = useState("");
const [hideStep, setHideStep] = useState<"menu" | "points" | "password">("menu");
const savedSel = useRef<{ start: number; end: number } | null>(null);
useEffect(() => {
@@ -260,6 +266,7 @@ export default function MarkdownEditor({
if (kind === "hide") {
setHideStep("menu");
setHidePoints(10);
setHidePassword("");
}
setPopover((prev) => (prev === kind ? null : kind));
};
@@ -320,17 +327,23 @@ export default function MarkdownEditor({
setPopover(null);
};
const insertHide = (kind: "login" | "reply" | "points", points?: number) => {
const insertHide = (
kind: "login" | "reply" | "points" | "password",
points?: number,
password?: string
) => {
restoreSel();
const el = taRef.current;
const start = el?.selectionStart ?? 0;
const end = el?.selectionEnd ?? 0;
const selected = value.slice(start, end);
const body = selected || "在此填写隐藏内容";
const open =
kind === "points"
? `:::hide points ${points || 10}`
: `:::hide ${kind}`;
let open = `:::hide ${kind}`;
if (kind === "points") {
open = `:::hide points ${points || 10}`;
} else if (kind === "password") {
open = `:::hide password ${password || "password"}`;
}
const block = `${open}\n${body}\n:::`;
const padBefore = start > 0 && value[start - 1] !== "\n" ? "\n" : "";
const padAfter = end < value.length && value[end] !== "\n" ? "\n" : "";
@@ -724,8 +737,15 @@ export default function MarkdownEditor({
>
积分可见…
</button>
<button
type="button"
className="j13-md-menu-item"
onClick={() => setHideStep("password")}
>
密码可见…
</button>
</>
) : (
) : hideStep === "points" ? (
<>
<label className="j13-md-field">
<span>所需积分</span>
@@ -770,6 +790,53 @@ export default function MarkdownEditor({
</button>
</div>
</>
) : (
<>
<label className="j13-md-field">
<span>查看密码(不含空格,1–64 字)</span>
<input
autoFocus
type="text"
value={hidePassword}
maxLength={64}
placeholder="例如:secret"
onChange={(e) => setHidePassword(e.target.value)}
className="j13-md-popover-input"
onKeyDown={(e) => {
if (e.key === "Enter") {
e.preventDefault();
const p = hidePassword.trim();
if (p && !/\s/.test(p)) {
insertHide("password", undefined, p);
}
}
}}
/>
</label>
<div className="j13-md-popover-footer">
<button
type="button"
className="btn btn-line btn-sm"
onClick={() => setHideStep("menu")}
>
返回
</button>
<button
type="button"
className="btn btn-primary btn-sm"
onClick={() => {
const p = hidePassword.trim();
if (!p || /\s/.test(p) || p.length > 64) {
toast("密码须为 1–64 字符且不含空格", "error");
return;
}
insertHide("password", undefined, p);
}}
>
插入
</button>
</div>
</>
)}
</div>
)}
@@ -786,6 +853,15 @@ export default function MarkdownEditor({
>
<Pencil size={12} /> 编写
</button>
<button
type="button"
role="tab"
aria-selected={mode === "split"}
className={mode === "split" ? "is-on" : ""}
onClick={() => setMode("split")}
>
<Columns2 size={12} /> 双栏
</button>
<button
type="button"
role="tab"
@@ -816,9 +892,10 @@ export default function MarkdownEditor({
onChange={(e) => void uploadImageFile(e.target.files?.[0] ?? null)}
/>
{mode === "write" ? (
<div className={`j13-md-panes is-${mode}`}>
<div
className={`j13-md-write-wrap${dragOver ? " is-dragover" : ""}`}
hidden={mode === "preview"}
onDragEnter={(e) => {
e.preventDefault();
if (e.dataTransfer.types.includes("Files")) setDragOver(true);
@@ -853,15 +930,17 @@ export default function MarkdownEditor({
onSelect={rememberSel}
/>
</div>
) : (
<div className="j13-md-preview">
{value.trim() ? (
<MarkdownBodyClient content={value} />
<div className="j13-md-preview" hidden={mode === "write"}>
<div className="j13-md-preview-label meta" aria-hidden>
预览
</div>
{deferredValue.trim() ? (
<MarkdownBodyClient content={deferredValue} />
) : (
<p className="meta text-center py-16">暂无内容可预览</p>
)}
</div>
)}
</div>
<div className="j13-md-foot">
<span>支持粘贴/拖拽图片 · Markdown · Ctrl/⌘ + Enter 提交</span>

View File

@@ -1178,7 +1178,7 @@ export default function PostComposer(props: PostComposerProps) {
disabled={loading}
rows={18}
placeholder={
"从这里开始写正文…\n\n工具栏可插入格式、代码块、链接、图片与隐藏内容(登录/回复/积分可见)。支持粘贴与拖拽上传图片。"
"从这里开始写正文…\n\n工具栏可插入格式、代码块、链接、图片与隐藏内容(登录/回复/积分/密码可见)。支持粘贴与拖拽上传图片;默认双栏实时预览。"
}
onSubmitShortcut={() => {
if (canSubmit) void handleSubmit();

View File

@@ -1,14 +1,27 @@
"use client";
import type { ReactNode } from "react";
import type { ReactNode, FormEvent } from "react";
import { Lock } from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { apiUnlockPost } from "@/lib/api";
import { useId, useState } from "react";
import { apiUnlockPost, apiUnlockPostPassword } from "@/lib/api";
import { CSRF_COOKIE } from "@/lib/cookies";
import { toast } from "@/lib/toast";
import { hideKindLabel, type HideKind } from "@/lib/hideBlocks";
/** 若浏览器尚无 CSRF cookie,请求公开接口以触发后端签发 */
async function ensureGuestCSRF() {
if (typeof document === "undefined") return;
const escaped = CSRF_COOKIE.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
if (new RegExp(`(?:^|;\\s*)${escaped}=`).test(document.cookie)) return;
try {
await fetch("/api/me", { credentials: "include", cache: "no-store" });
} catch {
/* 忽略:后续解锁会报 CSRF 错误 */
}
}
type MdHideBlockProps = {
kind: HideKind;
points?: number;
@@ -28,11 +41,14 @@ export default function MdHideBlock({
children,
}: MdHideBlockProps) {
const router = useRouter();
const pwdErrId = useId();
const [busy, setBusy] = useState(false);
const [pwd, setPwd] = useState("");
const [pwdError, setPwdError] = useState("");
const label = hideKindLabel(kind);
if (locked) {
const unlock = async () => {
const unlockPoints = async () => {
if (!postId) return;
setBusy(true);
try {
@@ -50,6 +66,35 @@ export default function MdHideBlock({
}
};
const unlockPassword = async (e: FormEvent) => {
e.preventDefault();
if (!postId) return;
const password = pwd.trim();
if (!password) {
setPwdError("请输入密码");
return;
}
setBusy(true);
setPwdError("");
try {
// 游客可能尚无 CSRF:先打一次公开 GET 让后端签发,再提交解锁
await ensureGuestCSRF();
const res = await apiUnlockPostPassword(String(postId), password);
if (res.post) {
toast("密码正确,已解锁", "ok");
setPwd("");
setPwdError("");
router.refresh();
} else {
setPwdError(res.error || "密码错误,请重试");
}
} catch {
setPwdError("验证失败,请稍后重试");
} finally {
setBusy(false);
}
};
return (
<aside
className="j13-hide-gate"
@@ -62,7 +107,11 @@ export default function MdHideBlock({
{kind === "points"
? `支付 ${points || 0} 积分后可阅读此段`
: kind === "reply"
? loggedIn
? "发表一条回复后即可阅读此段"
: "登录并发表一条回复后即可阅读此段"
: kind === "password"
? "输入正确密码后可阅读此段"
: "登录后即可阅读此段"}
</p>
<div className="j13-hide-gate-actions">
@@ -79,7 +128,7 @@ export default function MdHideBlock({
type="button"
className="btn btn-primary"
disabled={busy}
onClick={() => void unlock()}
onClick={() => void unlockPoints()}
>
{busy ? "解锁中…" : `支付 ${points || 0} 积分解锁`}
</button>
@@ -92,11 +141,67 @@ export default function MdHideBlock({
登录后解锁
</Link>
)}
{kind === "reply" && (
<a href="#comments" className="btn btn-primary">
{kind === "reply" && postId && !loggedIn && (
<Link
href={`/login?redirect=${encodeURIComponent(`/post/${postId}#comment-input`)}`}
className="btn btn-primary"
>
登录后去回复
</Link>
)}
{kind === "reply" && loggedIn && (
<a
href="#comment-input"
className="btn btn-primary"
onClick={(e) => {
e.preventDefault();
const el = document.getElementById("comment-input");
if (!(el instanceof HTMLTextAreaElement)) {
document.getElementById("comments")?.scrollIntoView({
behavior: "smooth",
block: "start",
});
return;
}
el.scrollIntoView({ behavior: "smooth", block: "center" });
window.setTimeout(() => {
el.focus({ preventScroll: true });
}, 280);
}}
>
去回复
</a>
)}
{kind === "password" && postId && (
<div className="j13-hide-pwd-wrap">
<form className="j13-hide-pwd-form" onSubmit={(e) => void unlockPassword(e)}>
<input
type="password"
className={`j13-hide-pwd-input${pwdError ? " is-invalid" : ""}`}
placeholder="输入密码"
value={pwd}
maxLength={64}
autoComplete="off"
disabled={busy}
aria-invalid={pwdError ? true : undefined}
aria-describedby={pwdError ? pwdErrId : undefined}
onChange={(e) => {
setPwd(e.target.value);
if (pwdError) setPwdError("");
}}
aria-label="隐藏内容密码"
/>
<button type="submit" className="btn btn-primary" disabled={busy}>
{busy ? "验证中…" : "查看"}
</button>
</form>
{pwdError && (
<p id={pwdErrId} className="j13-hide-pwd-error" role="alert">
{pwdError}
</p>
)}
</div>
)}
</div>
</aside>
);

View File

@@ -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",

View File

@@ -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 {

View File

@@ -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<HideKind>(["login", "reply", "points", "password"]);
function isClose(line: string): boolean {
return line.trim() === ":::";
}
/** 与 Go parseOpenMarker 对齐::::hide <kind> [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 <pwd> [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 "密码可见";
}
}

View File

@@ -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;