feat: 小程序演示版改造 + 服务端安全加固
- 许愿树移除付费许愿/商品选择/微信支付调用,全部走免费许愿 - 许愿发布前接入微信 msgSecCheck v2 内容安全检测(access_token 内存缓存) - 许愿字数限制改为按字符计算(中文按 1 字计) - 占卜页改名「民俗趣算」并弱化「算命」措辞,占卜/每日运势页加文化声明 - 生产环境 JWT_SECRET 缺失或为默认值/不足 32 位时拒绝启动 Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
co-authored by
Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
parent
12fa2b0d19
commit
51d1a1999f
@@ -18,6 +18,14 @@ import (
|
||||
func Bootstrap() *config.Config {
|
||||
_ = godotenv.Load(".env.local", "../.env.local", ".env")
|
||||
cfg := config.Load()
|
||||
|
||||
// 生产环境安全底线:JWT 密钥必须是强随机值
|
||||
if cfg.Server.Env == "production" {
|
||||
if cfg.JWT.Secret == "" || cfg.JWT.Secret == "your-secret-key" || len(cfg.JWT.Secret) < 32 {
|
||||
log.Fatal("JWT_SECRET 未配置或过短:生产环境必须设置至少 32 位的强随机密钥")
|
||||
}
|
||||
}
|
||||
|
||||
if err := config.InitDB(cfg); err != nil {
|
||||
log.Fatalf("Failed to initialize database: %v", err)
|
||||
}
|
||||
|
||||
@@ -9,6 +9,9 @@ import (
|
||||
"github.com/gouki/lunar-server/internal/service"
|
||||
)
|
||||
|
||||
// 内容安全检测服务(微信 msgSecCheck),access_token 内部缓存
|
||||
var securityService = service.NewContentSecurityService()
|
||||
|
||||
// GetWishTrees 获取许愿树列表
|
||||
func GetWishTrees(c *gin.Context) {
|
||||
wishService := service.NewWishService()
|
||||
@@ -79,12 +82,12 @@ func CreateWish(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// 检查内容长度
|
||||
// 检查内容长度(按字符数,中文按 1 字计)
|
||||
maxLength := 20
|
||||
if req.Type == "paid" {
|
||||
maxLength = 100
|
||||
}
|
||||
if len(req.Content) > maxLength {
|
||||
if len([]rune(req.Content)) > maxLength {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"code": 400,
|
||||
"msg": "内容长度超过限制",
|
||||
@@ -92,6 +95,18 @@ func CreateWish(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// 内容安全检测(微信 msgSecCheck):UGC 内容发布前必须过检
|
||||
userService := service.NewUserService()
|
||||
if user, err := userService.GetUserByID(userID.(uint)); err == nil && user != nil {
|
||||
if err := securityService.CheckText(user.OpenID, req.Content); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"code": 400,
|
||||
"msg": "内容未通过安全检测:" + err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
wishService := service.NewWishService()
|
||||
wish := &model.Wish{
|
||||
UserID: userID.(uint),
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gouki/lunar-server/internal/config"
|
||||
)
|
||||
|
||||
// ContentSecurityService 微信内容安全检测(msgSecCheck v2)。
|
||||
// 小程序 UGC 内容(许愿等)发布前必须过检测,否则有下架风险。
|
||||
type ContentSecurityService struct {
|
||||
mu sync.Mutex
|
||||
accessToken string
|
||||
tokenExpire time.Time
|
||||
}
|
||||
|
||||
func NewContentSecurityService() *ContentSecurityService {
|
||||
return &ContentSecurityService{}
|
||||
}
|
||||
|
||||
// 获取小程序 access_token,内存缓存到过期前 5 分钟
|
||||
func (s *ContentSecurityService) getAccessToken(cfg *config.Config) (string, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
if s.accessToken != "" && time.Now().Before(s.tokenExpire) {
|
||||
return s.accessToken, nil
|
||||
}
|
||||
|
||||
query := url.Values{
|
||||
"grant_type": {"client_credential"},
|
||||
"appid": {cfg.Wechat.AppID},
|
||||
"secret": {cfg.Wechat.AppSecret},
|
||||
}
|
||||
client := &http.Client{Timeout: 10 * time.Second}
|
||||
resp, err := client.Get("https://api.weixin.qq.com/cgi-bin/token?" + query.Encode())
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("get access_token failed: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(io.LimitReader(resp.Body, 64*1024))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("read access_token response failed: %w", err)
|
||||
}
|
||||
var result struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
ExpiresIn int `json:"expires_in"`
|
||||
ErrCode int `json:"errcode"`
|
||||
ErrMsg string `json:"errmsg"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &result); err != nil {
|
||||
return "", fmt.Errorf("parse access_token response failed: %w", err)
|
||||
}
|
||||
if result.ErrCode != 0 || result.AccessToken == "" {
|
||||
return "", fmt.Errorf("get access_token failed: errcode=%d errmsg=%s", result.ErrCode, result.ErrMsg)
|
||||
}
|
||||
|
||||
s.accessToken = result.AccessToken
|
||||
s.tokenExpire = time.Now().Add(time.Duration(result.ExpiresIn-300) * time.Second)
|
||||
return s.accessToken, nil
|
||||
}
|
||||
|
||||
// CheckText 校验文本是否安全。返回 nil 表示通过;
|
||||
// 返回错误表示内容违规或检测失败(调用方应拒绝发布)。
|
||||
//
|
||||
// 未配置小程序凭证时(本地开发)放行并打日志;
|
||||
// 生产环境若必须严格放行策略可再收紧。
|
||||
func (s *ContentSecurityService) CheckText(openID, content string) error {
|
||||
cfg := config.Load()
|
||||
if cfg.Wechat.AppID == "" || cfg.Wechat.AppSecret == "" {
|
||||
log.Printf("[content-security] 未配置小程序凭证,跳过检测")
|
||||
return nil
|
||||
}
|
||||
|
||||
token, err := s.getAccessToken(cfg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
reqBody, _ := json.Marshal(map[string]interface{}{
|
||||
"version": 2,
|
||||
"openid": openID,
|
||||
"scene": 2, // 2=评论/留言类 UGC
|
||||
"content": content,
|
||||
})
|
||||
client := &http.Client{Timeout: 10 * time.Second}
|
||||
resp, err := client.Post(
|
||||
"https://api.weixin.qq.com/wxa/msg_sec_check?access_token="+token,
|
||||
"application/json",
|
||||
bytes.NewReader(reqBody),
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("msg_sec_check request failed: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(io.LimitReader(resp.Body, 64*1024))
|
||||
if err != nil {
|
||||
return fmt.Errorf("read msg_sec_check response failed: %w", err)
|
||||
}
|
||||
var result struct {
|
||||
ErrCode int `json:"errcode"`
|
||||
ErrMsg string `json:"errmsg"`
|
||||
Result struct {
|
||||
Suggest string `json:"suggest"`
|
||||
Label int `json:"label"`
|
||||
} `json:"result"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &result); err != nil {
|
||||
return fmt.Errorf("parse msg_sec_check response failed: %w", err)
|
||||
}
|
||||
if result.ErrCode != 0 {
|
||||
return fmt.Errorf("msg_sec_check failed: errcode=%d errmsg=%s", result.ErrCode, result.ErrMsg)
|
||||
}
|
||||
|
||||
switch result.Result.Suggest {
|
||||
case "pass":
|
||||
return nil
|
||||
case "review":
|
||||
// 人工复核档位:许愿类短文本直接拒绝,提示修改
|
||||
return fmt.Errorf("内容需要审核,请修改后重试")
|
||||
default:
|
||||
return fmt.Errorf("内容不符合社区规范")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user