fix: 修复19个Bug (P0-P3) — 持续性调试第7轮发现的问题

P0 (5): crypto/rand session ID, TTS fallback可达性, goroutine defer recover, adminAuth前缀修正
P1 (5): 普通用户密码验证, context传递, priority clamp, 超时重试, 自主思考速率限制
P2 (4): Briefing AI降级, 前端消息类型渲染, Docker Compose补全, PWA 192图标
P3 (5): goroutine错误处理, .gitignore完善, reminder created_at, voice Dockerfile, Go版本更新
This commit is contained in:
2026-05-20 13:30:32 +08:00
parent baaf90fc47
commit 4b35736f73
37 changed files with 556 additions and 118 deletions
+1 -1
View File
@@ -1,5 +1,5 @@
# ========== 构建阶段 ==========
FROM golang:1.23-alpine AS builder
FROM golang:1.26-alpine AS builder
RUN apk add --no-cache git ca-certificates
+5 -1
View File
@@ -124,7 +124,11 @@ func main() {
hub.StartIoTBroadcast(cfg.IoTDebugServiceURL)
// 注册路由
router.Setup(r, hub, cfg, sessionStore, reminderStore, briefingStore, automationStore, fileStore, ruleEngine, knowledgeStore, nil)
var db interface{}
if sessionStore != nil {
db = sessionStore.DB()
}
router.Setup(r, hub, cfg, sessionStore, reminderStore, briefingStore, automationStore, fileStore, ruleEngine, knowledgeStore, nil, db)
// 启动提醒调度器
if reminderStore != nil {
@@ -1,11 +1,15 @@
package handler
import (
"database/sql"
"fmt"
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
_ "github.com/lib/pq"
"golang.org/x/crypto/bcrypt"
"github.com/yourname/cyrene-ai/gateway/internal/config"
)
@@ -13,11 +17,12 @@ import (
// AuthHandler 认证处理器
type AuthHandler struct {
cfg *config.Config
db *sql.DB
}
// NewAuthHandler 创建认证处理器
func NewAuthHandler(cfg *config.Config) *AuthHandler {
return &AuthHandler{cfg: cfg}
func NewAuthHandler(cfg *config.Config, db *sql.DB) *AuthHandler {
return &AuthHandler{cfg: cfg, db: db}
}
// Register 用户注册 (需要邮箱验证码、昵称必填)
@@ -96,7 +101,16 @@ func (h *AuthHandler) Login(c *gin.Context) {
}
userID = "admin_" + req.Username
} else {
// MVP阶段:普通用户登录 (简化逻辑,后续需要验证密码哈希)
// 普通用户登录:从数据库查询密码哈希并验证
authenticated, err := h.verifyUserPassword(req.Username, req.Password)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "服务器内部错误"})
return
}
if !authenticated {
c.JSON(http.StatusUnauthorized, gin.H{"error": "用户名或密码错误"})
return
}
userID = "user_" + req.Username
}
@@ -113,6 +127,44 @@ func (h *AuthHandler) Login(c *gin.Context) {
})
}
// verifyUserPassword 验证普通用户的密码
// 从数据库查询用户的密码哈希并与输入密码比对
// 如果用户不存在,返回 (false, nil);如果密码匹配,返回 (true, nil)
func (h *AuthHandler) verifyUserPassword(username, password string) (bool, error) {
if h.db == nil {
// 数据库不可用时回退到简单验证(开发阶段兼容)
// 仅允许固定测试密码,不允许空密码登录
return password == "test123", nil
}
var storedHash string
err := h.db.QueryRow(
"SELECT password_hash FROM users WHERE username = $1",
username,
).Scan(&storedHash)
if err == sql.ErrNoRows {
// 用户不存在
return false, nil
}
if err != nil {
return false, fmt.Errorf("查询用户失败: %w", err)
}
// 使用 bcrypt 验证密码哈希
// 如果存储的是明文密码(向后兼容),则直接比对
if strings.HasPrefix(storedHash, "$2a$") || strings.HasPrefix(storedHash, "$2b$") || strings.HasPrefix(storedHash, "$2y$") {
// bcrypt 哈希
if err := bcrypt.CompareHashAndPassword([]byte(storedHash), []byte(password)); err != nil {
return false, nil
}
return true, nil
}
// 明文密码向后兼容(开发阶段)
return password == storedHash, nil
}
// RefreshToken 刷新令牌
func (h *AuthHandler) RefreshToken(c *gin.Context) {
authHeader := c.GetHeader("Authorization")
@@ -221,6 +221,9 @@ func (h *BriefingHandler) GenerateDailyBriefing(userID string) (*store.Briefing,
if err != nil {
log.Printf("[briefing] AI 摘要生成失败 (降级): %v", err)
summary = h.buildFallbackSummary(briefing)
briefing.SummarySource = "fallback"
} else {
briefing.SummarySource = "ai"
}
briefing.Summary = summary
@@ -1,6 +1,7 @@
package handler
import (
"crypto/rand"
"encoding/json"
"fmt"
"log"
@@ -576,8 +577,15 @@ func (h *SessionHandler) exportTXT(c *gin.Context, session *store.Session, messa
func randomID(n int) string {
const letters = "abcdefghijklmnopqrstuvwxyz0123456789"
b := make([]byte, n)
if _, err := rand.Read(b); err != nil {
// fallback to deterministic IDs only if crypto/rand fails
for i := range b {
b[i] = letters[i%len(letters)]
}
return string(b)
}
for i := range b {
b[i] = letters[i%len(letters)]
b[i] = letters[int(b[i])%len(letters)]
}
return string(b)
}
@@ -11,6 +11,7 @@ import (
// Auth 用户键值在context中的key
const UserIDKey = "user_id"
const IsAdminKey = "is_admin"
// JWTAuth JWT认证中间件
func JWTAuth(cfg *config.Config) gin.HandlerFunc {
@@ -40,6 +41,8 @@ func JWTAuth(cfg *config.Config) gin.HandlerFunc {
// 将userID注入上下文
c.Set(UserIDKey, userID)
// 设置管理员标记 (admin 用户 ID 以 "admin_" 为前缀)
c.Set(IsAdminKey, strings.HasPrefix(userID, "admin_"))
c.Next()
}
}
+10 -6
View File
@@ -1,8 +1,8 @@
package router
import (
"database/sql"
"net/http"
"strings"
"github.com/gin-gonic/gin"
@@ -15,12 +15,16 @@ import (
)
// Setup 注册所有路由
func Setup(r *gin.Engine, hub *ws.Hub, cfg *config.Config, sessionStore *store.SessionStore, reminderStore *store.ReminderStore, briefingStore *store.BriefingStore, automationStore *store.AutomationStore, fileStore *store.FileStore, ruleEngine *engine.RuleEngine, knowledgeStore *store.KnowledgeStore, imageHandler *handler.ImageHandler) {
func Setup(r *gin.Engine, hub *ws.Hub, cfg *config.Config, sessionStore *store.SessionStore, reminderStore *store.ReminderStore, briefingStore *store.BriefingStore, automationStore *store.AutomationStore, fileStore *store.FileStore, ruleEngine *engine.RuleEngine, knowledgeStore *store.KnowledgeStore, imageHandler *handler.ImageHandler, db interface{}) {
// 限流器
rateLimiter := middleware.NewRateLimiter(10, 20) // 每秒10个请求,突发20
// 初始化处理器
authHandler := handler.NewAuthHandler(cfg)
var authDB *sql.DB
if db != nil {
authDB = db.(*sql.DB)
}
authHandler := handler.NewAuthHandler(cfg, authDB)
sessionHandler := handler.NewSessionHandler(hub, sessionStore)
memoryHandler := handler.NewMemoryHandler(cfg.MemoryServiceURL)
chatHandler := handler.NewChatHandler(cfg, hub)
@@ -227,11 +231,11 @@ func Setup(r *gin.Engine, hub *ws.Hub, cfg *config.Config, sessionStore *store.S
}
}
// adminAuth 管理员权限中间件 (检查 userID 是否以 "admin_" 开头)
// adminAuth 管理员权限中间件 (检查认证中间件设置的 is_admin 标记)
func adminAuth() gin.HandlerFunc {
return func(c *gin.Context) {
userID := middleware.GetUserID(c)
if userID == "" || !strings.HasPrefix(userID, "admin_") {
isAdmin, _ := c.Get(middleware.IsAdminKey)
if isAdmin == nil || !isAdmin.(bool) {
c.JSON(http.StatusForbidden, gin.H{"error": "需要管理员权限"})
c.Abort()
return
@@ -10,17 +10,18 @@ import (
// Briefing 每日简报模型
type Briefing struct {
ID string `json:"id"`
UserID string `json:"user_id"`
Date string `json:"date"` // YYYY-MM-DD
Weather *WeatherData `json:"weather"`
News []NewsItem `json:"news"`
Reminders []BriefReminder `json:"reminders"`
Summary string `json:"summary"`
Status string `json:"status"` // pending, generated, delivered
GeneratedAt *time.Time `json:"generated_at,omitempty"`
DeliveredAt *time.Time `json:"delivered_at,omitempty"`
CreatedAt time.Time `json:"created_at"`
ID string `json:"id"`
UserID string `json:"user_id"`
Date string `json:"date"` // YYYY-MM-DD
Weather *WeatherData `json:"weather"`
News []NewsItem `json:"news"`
Reminders []BriefReminder `json:"reminders"`
Summary string `json:"summary"`
SummarySource string `json:"summary_source"` // "ai" | "fallback"
Status string `json:"status"` // pending, generated, delivered
GeneratedAt *time.Time `json:"generated_at,omitempty"`
DeliveredAt *time.Time `json:"delivered_at,omitempty"`
CreatedAt time.Time `json:"created_at"`
}
// WeatherData 天气数据
@@ -74,12 +75,14 @@ func (s *BriefingStore) migrate() error {
news JSONB DEFAULT '[]',
reminders JSONB DEFAULT '[]',
summary TEXT DEFAULT '',
summary_source VARCHAR(20) DEFAULT 'ai',
status VARCHAR(20) DEFAULT 'pending',
generated_at TIMESTAMPTZ,
delivered_at TIMESTAMPTZ,
created_at TIMESTAMPTZ DEFAULT NOW(),
UNIQUE(user_id, date)
)`,
`ALTER TABLE daily_briefings ADD COLUMN IF NOT EXISTS summary_source VARCHAR(20) DEFAULT 'ai'`,
`CREATE INDEX IF NOT EXISTS idx_briefings_user_id ON daily_briefings(user_id)`,
`CREATE INDEX IF NOT EXISTS idx_briefings_date ON daily_briefings(date)`,
`CREATE INDEX IF NOT EXISTS idx_briefings_user_date ON daily_briefings(user_id, date)`,
@@ -108,19 +111,24 @@ func (s *BriefingStore) CreateOrUpdateBriefing(b *Briefing) error {
return fmt.Errorf("序列化提醒数据失败: %w", err)
}
if b.SummarySource == "" {
b.SummarySource = "ai"
}
_, err = s.db.Exec(
`INSERT INTO daily_briefings (id, user_id, date, weather, news, reminders, summary, status, generated_at, delivered_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
`INSERT INTO daily_briefings (id, user_id, date, weather, news, reminders, summary, summary_source, status, generated_at, delivered_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
ON CONFLICT (user_id, date) DO UPDATE SET
weather = EXCLUDED.weather,
news = EXCLUDED.news,
reminders = EXCLUDED.reminders,
summary = EXCLUDED.summary,
summary_source = EXCLUDED.summary_source,
status = EXCLUDED.status,
generated_at = EXCLUDED.generated_at,
delivered_at = EXCLUDED.delivered_at`,
b.ID, b.UserID, b.Date, string(weatherJSON), string(newsJSON), string(remindersJSON),
b.Summary, b.Status, b.GeneratedAt, b.DeliveredAt,
b.Summary, b.SummarySource, b.Status, b.GeneratedAt, b.DeliveredAt,
)
if err != nil {
return fmt.Errorf("upsert 简报失败: %w", err)
@@ -131,7 +139,7 @@ func (s *BriefingStore) CreateOrUpdateBriefing(b *Briefing) error {
// GetBriefingByDate 获取指定日期简报
func (s *BriefingStore) GetBriefingByDate(userID, date string) (*Briefing, error) {
row := s.db.QueryRow(
`SELECT id, user_id, date::TEXT, weather, news, reminders, summary, status, generated_at, delivered_at, created_at
`SELECT id, user_id, date::TEXT, weather, news, reminders, summary, COALESCE(summary_source, 'ai'), status, generated_at, delivered_at, created_at
FROM daily_briefings WHERE user_id = $1 AND date = $2::DATE`,
userID, date,
)
@@ -153,7 +161,7 @@ func (s *BriefingStore) GetLatestBriefings(userID string, limit int) ([]Briefing
}
rows, err := s.db.Query(
`SELECT id, user_id, date::TEXT, weather, news, reminders, summary, status, generated_at, delivered_at, created_at
`SELECT id, user_id, date::TEXT, weather, news, reminders, summary, COALESCE(summary_source, 'ai'), status, generated_at, delivered_at, created_at
FROM daily_briefings WHERE user_id = $1
ORDER BY date DESC LIMIT $2`,
userID, limit,
@@ -166,21 +174,22 @@ func (s *BriefingStore) GetLatestBriefings(userID string, limit int) ([]Briefing
var briefings []Briefing
for rows.Next() {
var (
id, uid, date, summary, status string
id, uid, date, summary, summarySource, status string
weatherRaw, newsRaw, remindersRaw []byte
generatedAt, deliveredAt, createdAt sql.NullTime
)
if err := rows.Scan(&id, &uid, &date, &weatherRaw, &newsRaw, &remindersRaw,
&summary, &status, &generatedAt, &deliveredAt, &createdAt); err != nil {
&summary, &summarySource, &status, &generatedAt, &deliveredAt, &createdAt); err != nil {
return nil, fmt.Errorf("扫描简报行失败: %w", err)
}
b := Briefing{
ID: id,
UserID: uid,
Date: date,
Summary: summary,
Status: status,
ID: id,
UserID: uid,
Date: date,
Summary: summary,
SummarySource: summarySource,
Status: status,
}
if weatherRaw != nil {
@@ -270,22 +279,23 @@ func (s *BriefingStore) GetAllUsers() ([]string, error) {
// scanBriefing 扫描单行简报
func (s *BriefingStore) scanBriefing(row *sql.Row) (*Briefing, error) {
var (
id, uid, date, summary, status string
id, uid, date, summary, summarySource, status string
weatherRaw, newsRaw, remindersRaw []byte
generatedAt, deliveredAt, createdAt sql.NullTime
)
if err := row.Scan(&id, &uid, &date, &weatherRaw, &newsRaw, &remindersRaw,
&summary, &status, &generatedAt, &deliveredAt, &createdAt); err != nil {
&summary, &summarySource, &status, &generatedAt, &deliveredAt, &createdAt); err != nil {
return nil, err
}
b := &Briefing{
ID: id,
UserID: uid,
Date: date,
Summary: summary,
Status: status,
ID: id,
UserID: uid,
Date: date,
Summary: summary,
SummarySource: summarySource,
Status: status,
}
if weatherRaw != nil {
@@ -71,10 +71,13 @@ func (s *ReminderStore) migrate() error {
// CreateReminder 创建新提醒
func (s *ReminderStore) CreateReminder(r *Reminder) error {
if r.CreatedAt.IsZero() {
r.CreatedAt = time.Now()
}
_, err := s.db.Exec(
`INSERT INTO reminders (id, user_id, title, description, remind_at, status, repeat_type, session_id)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,
r.ID, r.UserID, r.Title, r.Description, r.RemindAt, r.Status, r.RepeatType, r.SessionID,
`INSERT INTO reminders (id, user_id, title, description, remind_at, status, created_at, repeat_type, session_id)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`,
r.ID, r.UserID, r.Title, r.Description, r.RemindAt, r.Status, r.CreatedAt, r.RepeatType, r.SessionID,
)
if err != nil {
return fmt.Errorf("创建提醒失败: %w", err)
+13 -1
View File
@@ -99,6 +99,11 @@ func NewHub() *Hub {
// 每5分钟检查一次,将超过 idleTimeout 无活动的会话标记为 idle
func (h *Hub) StartIdleCleanup() {
go func() {
defer func() {
if r := recover(); r != nil {
log.Printf("[WS] 闲置会话清理 panic 恢复: %v", r)
}
}()
ticker := time.NewTicker(5 * time.Minute)
defer ticker.Stop()
@@ -453,7 +458,14 @@ func (h *Hub) StartIoTBroadcast(iotServiceURL string) {
h.iotPollRunning = true
h.mu.Unlock()
go h.iotPollLoop()
go func() {
defer func() {
if r := recover(); r != nil {
log.Printf("[IoT广播] 轮询循环 panic 恢复: %v", r)
}
}()
h.iotPollLoop()
}()
log.Printf("[IoT广播] 已启动 (IoT服务地址: %s)", iotServiceURL)
}