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
@@ -1,4 +1,4 @@
|
||||
{
|
||||
"navigationBarTitleText": "占卜",
|
||||
"navigationBarTitleText": "民俗趣算",
|
||||
"enablePullDownRefresh": false
|
||||
}
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
<view class="container">
|
||||
<!-- 文化声明 -->
|
||||
<view class="culture-card">
|
||||
<view class="culture-title">民俗趣算 · 传统文化</view>
|
||||
<view class="culture-text">梅花易数与称骨歌诀源自古代典籍与民间传统文化,属于传统民俗知识与趣味体验,仅供学习参考与娱乐,不构成任何决策建议,请理性看待,切勿迷信。</view>
|
||||
</view>
|
||||
|
||||
<!-- 梅花易数 -->
|
||||
<view class="card">
|
||||
<view class="section-title">梅花易数</view>
|
||||
@@ -48,9 +54,9 @@
|
||||
</view>
|
||||
</view>
|
||||
|
||||
<!-- 称骨算命 -->
|
||||
<!-- 称骨测算 -->
|
||||
<view class="card mt-2">
|
||||
<view class="section-title">称骨算命</view>
|
||||
<view class="section-title">称骨测算</view>
|
||||
<view class="form-item">
|
||||
<text class="form-label">出生年份(干支)</text>
|
||||
<picker mode="selector" range="{{yearGanzhiList}}" value="{{boneYearIndex}}" bindchange="onBoneYearChange">
|
||||
@@ -75,7 +81,7 @@
|
||||
<view class="picker-input">{{hourList[boneHourIndex]}}</view>
|
||||
</picker>
|
||||
</view>
|
||||
<view class="btn-primary" bindtap="calcBone">算命</view>
|
||||
<view class="btn-primary" bindtap="calcBone">测算</view>
|
||||
</view>
|
||||
|
||||
<!-- 称骨结果 -->
|
||||
|
||||
@@ -50,3 +50,24 @@
|
||||
.trigram-name {
|
||||
font-size: 28rpx;
|
||||
}
|
||||
|
||||
/* 文化声明 */
|
||||
.culture-card {
|
||||
background: linear-gradient(135deg, #C41E3A 0%, #8B1A2B 100%);
|
||||
border-radius: 24rpx;
|
||||
padding: 28rpx 24rpx;
|
||||
margin-bottom: 16rpx;
|
||||
}
|
||||
|
||||
.culture-title {
|
||||
color: #FFFFFF;
|
||||
font-size: 32rpx;
|
||||
font-weight: 700;
|
||||
margin-bottom: 12rpx;
|
||||
}
|
||||
|
||||
.culture-text {
|
||||
color: rgba(255, 255, 255, 0.92);
|
||||
font-size: 24rpx;
|
||||
line-height: 1.7;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
<view class="container">
|
||||
<!-- 文化声明 -->
|
||||
<view class="culture-card">
|
||||
<view class="culture-title">每日运势 · 传统文化参考</view>
|
||||
<view class="culture-text">本页内容基于传统干支历法与五行文化的趣味化呈现,仅供休闲娱乐与传统文化学习参考,不构成任何人生决策建议,请理性看待,切勿迷信。</view>
|
||||
</view>
|
||||
|
||||
<!-- 无八字提示 -->
|
||||
<view class="card text-center" wx:if="{{!hasBazi}}">
|
||||
<text class="text-lg text-muted">请先排八字以查看每日运势</text>
|
||||
|
||||
@@ -45,3 +45,24 @@
|
||||
.suggestion-item {
|
||||
padding: 12rpx 0;
|
||||
}
|
||||
|
||||
/* 文化声明 */
|
||||
.culture-card {
|
||||
background: linear-gradient(135deg, #C41E3A 0%, #8B1A2B 100%);
|
||||
border-radius: 24rpx;
|
||||
padding: 28rpx 24rpx;
|
||||
margin-bottom: 16rpx;
|
||||
}
|
||||
|
||||
.culture-title {
|
||||
color: #FFFFFF;
|
||||
font-size: 32rpx;
|
||||
font-weight: 700;
|
||||
margin-bottom: 12rpx;
|
||||
}
|
||||
|
||||
.culture-text {
|
||||
color: rgba(255, 255, 255, 0.92);
|
||||
font-size: 24rpx;
|
||||
line-height: 1.7;
|
||||
}
|
||||
|
||||
@@ -59,7 +59,7 @@
|
||||
<text class="menu-arrow">›</text>
|
||||
</view>
|
||||
<view class="menu-item" bindtap="navigateTo" data-url="/pages/divination/divination">
|
||||
<text class="menu-label">占卜</text>
|
||||
<text class="menu-label">民俗趣算</text>
|
||||
<text class="menu-arrow">›</text>
|
||||
</view>
|
||||
<view class="menu-item" bindtap="navigateTo" data-url="/pages/solar-terms/solar-terms">
|
||||
|
||||
@@ -54,11 +54,7 @@ Page({
|
||||
fireflies: [],
|
||||
showCreateModal: false,
|
||||
wishContent: '',
|
||||
wishType: 'free',
|
||||
maxFreeLength: 20,
|
||||
maxPaidLength: 100,
|
||||
products: [],
|
||||
selectedProduct: null,
|
||||
},
|
||||
|
||||
onLoad() {
|
||||
@@ -72,7 +68,6 @@ Page({
|
||||
|
||||
this.initAmbiance();
|
||||
this.loadTrees();
|
||||
this.loadProducts();
|
||||
},
|
||||
|
||||
onUnload() {
|
||||
@@ -407,7 +402,7 @@ Page({
|
||||
id: i + 1,
|
||||
content: texts[i % texts.length],
|
||||
author: authors[i % authors.length],
|
||||
type: i % 5 === 0 ? 'paid' : 'free',
|
||||
type: 'free',
|
||||
position: i === 0 ? 100 : 0,
|
||||
isTop: i === 0,
|
||||
createdAt: new Date(Date.now() - i * 3600 * 1000).toISOString(),
|
||||
@@ -427,26 +422,6 @@ Page({
|
||||
this.setData({ detailWish: null });
|
||||
},
|
||||
|
||||
// 加载许愿商品
|
||||
async loadProducts() {
|
||||
try {
|
||||
const res = await request({ url: '/api/wish/products', method: 'GET' });
|
||||
if (res.code === 0) {
|
||||
this.setData({ products: res.data.list || [] });
|
||||
return;
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('加载商品失败:', err);
|
||||
}
|
||||
this.setData({
|
||||
products: [
|
||||
{ id: 1, name: '普通许愿条', price: 100, duration: 7 },
|
||||
{ id: 2, name: '精品许愿条', price: 500, duration: 30 },
|
||||
{ id: 3, name: '至尊许愿条', price: 2000, duration: 90 },
|
||||
],
|
||||
});
|
||||
},
|
||||
|
||||
// 打开/关闭许愿弹窗
|
||||
openCreateModal() {
|
||||
this.setData({ showCreateModal: true });
|
||||
@@ -456,8 +431,6 @@ Page({
|
||||
this.setData({
|
||||
showCreateModal: false,
|
||||
wishContent: '',
|
||||
wishType: 'free',
|
||||
selectedProduct: null,
|
||||
});
|
||||
},
|
||||
|
||||
@@ -465,16 +438,6 @@ Page({
|
||||
this.setData({ wishContent: e.detail.value });
|
||||
},
|
||||
|
||||
selectType(e) {
|
||||
this.setData({ wishType: e.currentTarget.dataset.type });
|
||||
},
|
||||
|
||||
selectProduct(e) {
|
||||
const id = e.currentTarget.dataset.id;
|
||||
const product = this.data.products.find((p) => p.id === id);
|
||||
this.setData({ selectedProduct: product });
|
||||
},
|
||||
|
||||
// 当前树ID
|
||||
currentTreeId() {
|
||||
const { trees, currentTreeIndex } = this.data;
|
||||
@@ -484,54 +447,32 @@ Page({
|
||||
|
||||
// 提交许愿
|
||||
async submitWish() {
|
||||
const { wishContent, wishType, selectedProduct, maxFreeLength, maxPaidLength } = this.data;
|
||||
const { wishContent, maxFreeLength } = this.data;
|
||||
|
||||
if (!wishContent.trim()) {
|
||||
wx.showToast({ title: '请输入许愿内容', icon: 'none' });
|
||||
return;
|
||||
}
|
||||
|
||||
const maxLength = wishType === 'free' ? maxFreeLength : maxPaidLength;
|
||||
if (wishContent.length > maxLength) {
|
||||
wx.showToast({ title: `最多输入${maxLength}个字`, icon: 'none' });
|
||||
return;
|
||||
}
|
||||
|
||||
if (wishType === 'paid' && !selectedProduct) {
|
||||
wx.showToast({ title: '请选择许愿商品', icon: 'none' });
|
||||
if (wishContent.length > maxFreeLength) {
|
||||
wx.showToast({ title: `最多输入${maxFreeLength}个字`, icon: 'none' });
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (wishType === 'paid') {
|
||||
const orderRes = await request({
|
||||
url: '/api/pay/create',
|
||||
method: 'POST',
|
||||
data: {
|
||||
type: 'wish',
|
||||
productId: selectedProduct.id,
|
||||
content: wishContent,
|
||||
treeId: this.currentTreeId(),
|
||||
},
|
||||
});
|
||||
if (orderRes.code === 0) {
|
||||
await this.wxPay(orderRes.data);
|
||||
}
|
||||
} else {
|
||||
const res = await request({
|
||||
url: '/api/wish/create',
|
||||
method: 'POST',
|
||||
data: {
|
||||
content: wishContent,
|
||||
type: 'free',
|
||||
treeId: this.currentTreeId(),
|
||||
},
|
||||
});
|
||||
if (res.code === 0) {
|
||||
wx.showToast({ title: '许愿成功', icon: 'success' });
|
||||
this.closeCreateModal();
|
||||
this.loadTreeWishes(this.data.currentTreeIndex, true);
|
||||
}
|
||||
const res = await request({
|
||||
url: '/api/wish/create',
|
||||
method: 'POST',
|
||||
data: {
|
||||
content: wishContent,
|
||||
type: 'free',
|
||||
treeId: this.currentTreeId(),
|
||||
},
|
||||
});
|
||||
if (res.code === 0) {
|
||||
wx.showToast({ title: '许愿成功', icon: 'success' });
|
||||
this.closeCreateModal();
|
||||
this.loadTreeWishes(this.data.currentTreeIndex, true);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('许愿失败:', err);
|
||||
@@ -539,30 +480,6 @@ Page({
|
||||
}
|
||||
},
|
||||
|
||||
// 微信支付
|
||||
async wxPay(orderData) {
|
||||
return new Promise((resolve, reject) => {
|
||||
wx.requestPayment({
|
||||
timeStamp: orderData.timeStamp,
|
||||
nonceStr: orderData.nonceStr,
|
||||
package: orderData.package,
|
||||
signType: orderData.signType,
|
||||
paySign: orderData.paySign,
|
||||
success: () => {
|
||||
wx.showToast({ title: '支付成功', icon: 'success' });
|
||||
this.closeCreateModal();
|
||||
this.loadTreeWishes(this.data.currentTreeIndex, true);
|
||||
resolve();
|
||||
},
|
||||
fail: (err) => {
|
||||
console.error('支付失败:', err);
|
||||
wx.showToast({ title: '支付失败', icon: 'none' });
|
||||
reject(err);
|
||||
},
|
||||
});
|
||||
});
|
||||
},
|
||||
|
||||
// 分享
|
||||
onShareAppMessage() {
|
||||
return {
|
||||
|
||||
@@ -122,64 +122,22 @@
|
||||
</view>
|
||||
|
||||
<view class="modal-body">
|
||||
<!-- 许愿类型选择 -->
|
||||
<view class="type-selector">
|
||||
<view
|
||||
class="type-item {{wishType === 'free' ? 'active' : ''}}"
|
||||
bindtap="selectType"
|
||||
data-type="free"
|
||||
>
|
||||
<text class="type-name">免费许愿</text>
|
||||
<text class="type-desc">20字以内</text>
|
||||
</view>
|
||||
<view
|
||||
class="type-item {{wishType === 'paid' ? 'active' : ''}}"
|
||||
bindtap="selectType"
|
||||
data-type="paid"
|
||||
>
|
||||
<text class="type-name">付费许愿</text>
|
||||
<text class="type-desc">更多特权</text>
|
||||
</view>
|
||||
</view>
|
||||
|
||||
<!-- 许愿内容输入 -->
|
||||
<textarea
|
||||
class="wish-input"
|
||||
placeholder="请输入你的愿望..."
|
||||
maxlength="{{wishType === 'free' ? maxFreeLength : maxPaidLength}}"
|
||||
maxlength="{{maxFreeLength}}"
|
||||
bindinput="onInputContent"
|
||||
value="{{wishContent}}"
|
||||
></textarea>
|
||||
<view class="input-count">
|
||||
{{wishContent.length}}/{{wishType === 'free' ? maxFreeLength : maxPaidLength}}
|
||||
</view>
|
||||
|
||||
<!-- 付费商品选择 -->
|
||||
<view class="product-section" wx:if="{{wishType === 'paid'}}">
|
||||
<view class="product-title">选择许愿商品</view>
|
||||
<view class="product-list">
|
||||
<view
|
||||
wx:for="{{products}}"
|
||||
wx:key="id"
|
||||
class="product-item {{selectedProduct && selectedProduct.id === item.id ? 'active' : ''}}"
|
||||
bindtap="selectProduct"
|
||||
data-id="{{item.id}}"
|
||||
>
|
||||
<view class="product-info">
|
||||
<text class="product-name">{{item.name}}</text>
|
||||
<text class="product-desc">展示{{item.duration}}天</text>
|
||||
</view>
|
||||
<view class="product-price">¥{{item.price / 100}}</view>
|
||||
</view>
|
||||
</view>
|
||||
{{wishContent.length}}/{{maxFreeLength}}
|
||||
</view>
|
||||
</view>
|
||||
|
||||
<view class="modal-footer">
|
||||
<button class="btn-outline" bindtap="closeCreateModal">取消</button>
|
||||
<button class="btn-primary" bindtap="submitWish">
|
||||
{{wishType === 'paid' ? '支付并许愿' : '提交许愿'}}
|
||||
</button>
|
||||
<button class="btn-primary" bindtap="submitWish">提交许愿</button>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
|
||||
@@ -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