修复登录续期与数据库验证回归

- 修复密码登录、续期和账号编辑链路的边界问题
- 补齐 dbverify、后端与前端单测
- 同步 Docker 与前端构建产物
This commit is contained in:
Christ committed 2026-07-09 16:08:16 +08:00
1 parent 3436acecdc
commit 25419c027f
87 files changed
+7485 -900

No files matched your search

+131 -57
View File
@@ -13,6 +13,8 @@ package main
import (
"context"
"crypto/rand"
"encoding/hex"
"fmt"
"os"
"strings"
@@ -22,6 +24,17 @@ import (
)
func main() {
var cleanup func() error
fail := func(format string, args ...any) {
if cleanup != nil {
if err := cleanup(); err != nil {
fmt.Printf("⚠️ 清理验证数据失败: %v\n", err)
}
}
fmt.Printf(format, args...)
os.Exit(1)
}
if len(os.Args) < 2 {
fmt.Println("用法: dbverify <database-url>")
os.Exit(1)
@@ -33,8 +46,7 @@ func main() {
fmt.Printf("连接 %s ...\n", maskURL(url))
database, dialect, err := db.Open(ctx, url)
if err != nil {
fmt.Printf("❌ Open 失败: %v\n", err)
os.Exit(1)
fail("❌ Open 失败: %v\n", err)
}
defer database.Close()
fmt.Printf("✅ 迁移成功,方言=%s\n", dialect)
@@ -42,72 +54,79 @@ func main() {
store := db.NewStore(database, dialect)
// 1) 创建用户(用唯一用户名,避免在已有数据的库上因 admin 重名而失败)。
username := fmt.Sprintf("verify_%d", time.Now().UnixNano())
ok, err := store.Users.Create(ctx, username, username+"@test.local", "pw123456")
ids := newVerifyIDs(time.Now().UnixNano())
username := ids.username
accountID := ids.accountID
orderID := ids.orderID
itemID := ids.itemID
buyerID := ids.buyerID
cleanup = func() error {
cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cleanupCancel()
return cleanupVerifyData(cleanupCtx, store, ids)
}
password, err := newVerifyPassword()
if err != nil {
fail("❌ 生成验证密码失败: %v\n", err)
}
ok, err := store.Users.Create(ctx, username, username+"@test.local", password)
if err != nil || !ok {
fmt.Printf("❌ 创建用户失败: err=%v ok=%v\n", err, ok)
os.Exit(1)
fail("❌ 创建用户失败: err=%v ok=%v\n", err, ok)
}
if err := store.Users.SetAdmin(ctx, username); err != nil {
fmt.Printf("❌ 设置管理员失败: %v\n", err)
os.Exit(1)
adminUser, err := store.Users.GetByUsername(ctx, username)
if err != nil {
fail("❌ 查询验证用户失败: %v\n", err)
}
adminUser, _ := store.Users.GetByUsername(ctx, username)
userID := adminUser.ID
fmt.Printf("✅ 创建用户 %s (id=%d)\n", username, userID)
fmt.Printf("✅ 创建验证用户 %s (id=%d)\n", username, userID)
// 2) 保存 cookie(dialectUpsert: ON CONFLICT/ON DUPLICATE KEY)
if err := store.Cookies.Save(ctx, "acc1", "unb=123; _m_h5_tk=tk_1;", userID); err != nil {
fmt.Printf("❌ 保存 cookie 失败: %v\n", err)
os.Exit(1)
if err := store.Cookies.Save(ctx, accountID, "unb=123; _m_h5_tk=tk_1;", userID); err != nil {
fail("❌ 保存 cookie 失败: %v\n", err)
}
if err := store.Cookies.SetStatus(ctx, accountID, false); err != nil {
fail("❌ 禁用验证账号失败: %v\n", err)
}
// 再 Save 一次验证 upsert
if err := store.Cookies.Save(ctx, "acc1", "unb=123; _m_h5_tk=tk_2;", userID); err != nil {
fmt.Printf("❌ 二次保存 cookie 失败: %v\n", err)
os.Exit(1)
if err := store.Cookies.Save(ctx, accountID, "unb=123; _m_h5_tk=tk_2;", userID); err != nil {
fail("❌ 二次保存 cookie 失败: %v\n", err)
}
v, _ := store.Cookies.GetValue(ctx, "acc1")
v, _ := store.Cookies.GetValue(ctx, accountID)
fmt.Printf("✅ cookie upsert 成功,value=%s\n", v)
// 3) 系统设置 upsert(dialectUpsert + key 保留字引用)
if err := store.Settings.Set(ctx, "theme_color", "blue"); err != nil {
fmt.Printf("❌ 系统设置 Set 失败: %v\n", err)
os.Exit(1)
fail("❌ 系统设置 Set 失败: %v\n", err)
}
if err := store.Settings.Set(ctx, "theme_color", "green"); err != nil {
fmt.Printf("❌ 系统设置二次 Set 失败: %v\n", err)
os.Exit(1)
fail("❌ 系统设置二次 Set 失败: %v\n", err)
}
fmt.Println("✅ 系统设置 upsert 成功(key 保留字处理 OK)")
// 4) 订单 upsert(INSERT IGNORE + 动态 UPDATE)
if err := store.Orders.Upsert(ctx, "order-1", db.OrderUpsertOpts{
ItemID: "item-1", BuyerID: "buyer-1", CookieID: "acc1", OrderStatus: "paid", Amount: "19.90",
if err := store.Orders.Upsert(ctx, orderID, db.OrderUpsertOpts{
ItemID: itemID, BuyerID: buyerID, CookieID: accountID, OrderStatus: "paid", Amount: "19.90",
}); err != nil {
fmt.Printf("❌ 订单 Upsert 失败: %v\n", err)
os.Exit(1)
fail("❌ 订单 Upsert 失败: %v\n", err)
}
// 二次 upsert 验证不重复插入
if err := store.Orders.Upsert(ctx, "order-1", db.OrderUpsertOpts{
if err := store.Orders.Upsert(ctx, orderID, db.OrderUpsertOpts{
OrderStatus: "shipped", ChatID: "chat-1",
}); err != nil {
fmt.Printf("❌ 订单二次 Upsert 失败: %v\n", err)
os.Exit(1)
fail("❌ 订单二次 Upsert 失败: %v\n", err)
}
fmt.Println("✅ 订单 upsert 成功(INSERT IGNORE + UPDATE OK)")
// 5) 商品信息 upsert(dialectUpsert,UNIQUE(cookie_id, item_id))
if err := store.Items.Upsert(ctx, &db.ItemInfoRow{
CookieID: "acc1", ItemID: "item-1", ItemTitle: "测试商品", ItemPrice: "19.90",
CookieID: accountID, ItemID: itemID, ItemTitle: "测试商品", ItemPrice: "19.90",
}); err != nil {
fmt.Printf("❌ 商品 Upsert 失败: %v\n", err)
os.Exit(1)
fail("❌ 商品 Upsert 失败: %v\n", err)
}
if err := store.Items.Upsert(ctx, &db.ItemInfoRow{
CookieID: "acc1", ItemID: "item-1", ItemTitle: "更新后商品", ItemPrice: "29.90",
CookieID: accountID, ItemID: itemID, ItemTitle: "更新后商品", ItemPrice: "29.90",
}); err != nil {
fmt.Printf("❌ 商品二次 Upsert 失败: %v\n", err)
os.Exit(1)
fail("❌ 商品二次 Upsert 失败: %v\n", err)
}
fmt.Println("✅ 商品信息 upsert 成功")
@@ -116,63 +135,61 @@ func main() {
Name: "测试卡组", Type: "data", DataContent: "card-1\ncard-2\ncard-3", Enabled: true, UserID: userID,
})
if err != nil {
fmt.Printf("❌ 创建卡密失败: %v\n", err)
os.Exit(1)
fail("❌ 创建卡密失败: %v\n", err)
}
fmt.Printf("✅ 创建卡密组 (id=%d)\n", cardID)
// 7) 卡密批量追加(AppendBatchData)
added, err := store.Cards.AppendBatchData(ctx, cardID, "card-4\ncard-5")
if err != nil {
fmt.Printf("❌ 追加卡密失败: %v\n", err)
os.Exit(1)
fail("❌ 追加卡密失败: %v\n", err)
}
fmt.Printf("✅ 追加卡密 %d 个\n", added)
// 8) 通知渠道 + 绑定(dialectUpsert)
chID, err := store.Notifications.CreateChannel(ctx, &db.NotificationChannelRow{
Name: "测试渠道", Type: "webhook", Config: `{"webhook_url":"http://x"}`, Enabled: true, UserID: userID,
Name: "测试渠道", Type: "webhook", Config: `{"webhook_url":"http://x"}`, Enabled: false, UserID: userID,
})
if err != nil {
fmt.Printf("❌ 创建通知渠道失败: %v\n", err)
os.Exit(1)
fail("❌ 创建通知渠道失败: %v\n", err)
}
if err := store.Notifications.SetBindings(ctx, "acc1", []int64{chID}); err != nil {
fmt.Printf("❌ 绑定通知渠道失败: %v\n", err)
os.Exit(1)
if err := store.Notifications.SetBindings(ctx, accountID, []int64{chID}); err != nil {
fail("❌ 绑定通知渠道失败: %v\n", err)
}
fmt.Printf("✅ 通知渠道 + 绑定 OK (channel=%d)\n", chID)
// 9) 自动化规则(TryStartRun 用 INSERT IGNORE + UNIQUE 防重)
ruleID, err := store.Automation.Create(ctx, db.AutomationRuleInput{
UserID: userID, CookieID: "acc1", ItemID: "item-1", Name: "付款发货",
TriggerType: "order_paid", Enabled: true, Priority: 100,
UserID: userID, CookieID: accountID, ItemID: itemID, Name: "付款发货",
TriggerType: "order_paid", Enabled: false, Priority: 100,
})
if err != nil {
fmt.Printf("❌ 创建自动化规则失败: %v\n", err)
os.Exit(1)
fail("❌ 创建自动化规则失败: %v\n", err)
}
runID, started, err := store.Automation.TryStartRun(ctx, db.AutomationRun{
RuleID: ruleID, CookieID: "acc1", TriggerType: "order_paid", TriggerKey: "order-1", Status: "running",
RuleID: ruleID, CookieID: accountID, TriggerType: "order_paid", TriggerKey: orderID, Status: "running",
})
if err != nil || !started {
fmt.Printf("❌ TryStartRun 失败: err=%v started=%v\n", err, started)
os.Exit(1)
fail("❌ TryStartRun 失败: err=%v started=%v\n", err, started)
}
// 重复触发应 started=false
_, started2, err := store.Automation.TryStartRun(ctx, db.AutomationRun{
RuleID: ruleID, CookieID: "acc1", TriggerType: "order_paid", TriggerKey: "order-1", Status: "running",
RuleID: ruleID, CookieID: accountID, TriggerType: "order_paid", TriggerKey: orderID, Status: "running",
})
if err != nil {
fmt.Printf("❌ TryStartRun 二次调用失败: %v\n", err)
os.Exit(1)
fail("❌ TryStartRun 二次调用失败: %v\n", err)
}
if started2 {
fmt.Printf("❌ TryStartRun 重复触发未防重\n")
os.Exit(1)
fail("❌ TryStartRun 重复触发未防重\n")
}
fmt.Printf("✅ 自动化规则 + 防重 OK (rule=%d run=%d)\n", ruleID, runID)
if err := cleanup(); err != nil {
fmt.Printf("❌ 清理验证数据失败: %v\n", err)
os.Exit(1)
}
cleanup = nil
fmt.Println("✅ 验证数据已清理")
fmt.Println("\n🎉 全部验证通过")
}
@@ -189,3 +206,60 @@ func maskURL(url string) string {
}
return url
}
type verifyIDs struct {
username string
accountID string
orderID string
itemID string
buyerID string
}
func newVerifyIDs(n int64) verifyIDs {
suffix := fmt.Sprintf("%d", n)
return verifyIDs{
username: "verify_" + suffix,
accountID: "acc_" + suffix,
orderID: "order_" + suffix,
itemID: "item_" + suffix,
buyerID: "buyer_" + suffix,
}
}
func newVerifyPassword() (string, error) {
var b [24]byte
if _, err := rand.Read(b[:]); err != nil {
return "", err
}
return "verify_" + hex.EncodeToString(b[:]), nil
}
func cleanupVerifyData(ctx context.Context, store *db.Store, ids verifyIDs) error {
userID := int64(0)
if user, err := store.Users.GetByUsername(ctx, ids.username); err == nil {
userID = user.ID
}
queries := []struct {
query string
args []any
}{
{`DELETE FROM automation_runs WHERE trigger_key=? OR cookie_id=?`, []any{ids.orderID, ids.accountID}},
{`DELETE FROM automation_rule_actions WHERE rule_id IN (SELECT id FROM automation_rules WHERE cookie_id=? OR user_id=?)`, []any{ids.accountID, userID}},
{`DELETE FROM automation_rules WHERE cookie_id=? OR user_id=?`, []any{ids.accountID, userID}},
{`DELETE FROM message_notifications WHERE cookie_id=? OR channel_id IN (SELECT id FROM notification_channels WHERE user_id=? AND name=?)`, []any{ids.accountID, userID, "测试渠道"}},
{`DELETE FROM notification_channels WHERE user_id=? AND name=?`, []any{userID, "测试渠道"}},
{`DELETE FROM cards WHERE user_id=? AND name=?`, []any{userID, "测试卡组"}},
{`DELETE FROM item_info WHERE cookie_id=? AND item_id=?`, []any{ids.accountID, ids.itemID}},
{`DELETE FROM orders WHERE order_id=? OR cookie_id=?`, []any{ids.orderID, ids.accountID}},
{`DELETE FROM cookie_status WHERE cookie_id=?`, []any{ids.accountID}},
{`DELETE FROM cookies WHERE id=?`, []any{ids.accountID}},
{`DELETE FROM sessions WHERE user_id=?`, []any{userID}},
{`DELETE FROM users WHERE username=? AND email=?`, []any{ids.username, ids.username + "@test.local"}},
}
for _, q := range queries {
if _, err := store.DB.ExecContext(ctx, q.query, q.args...); err != nil {
return err
}
}
return nil
}
+164 -6
View File
@@ -1,15 +1,22 @@
package main
import "testing"
import (
"context"
"errors"
"path/filepath"
"testing"
"xianyu-go/internal/db"
)
// TestMaskURL 验证带凭证的数据库 URL 脱敏:保留 scheme + host,密码替换为 ***。
func TestMaskURL(t *testing.T) {
cases := map[string]string{
"mysql://user:secret@tcp(host:3306)/db?x=1": "mysql://***@tcp(host:3306)/db?x=1",
"postgres://user:pass@host:5432/db": "postgres://***@host:5432/db",
"postgresql://u:p@h:5432/d": "postgresql://***@h:5432/d",
"sqlite://data/x.db": "sqlite://data/x.db", // 无密码,原样
"/local/path.db": "/local/path.db", // 非 URL,原样
"mysql://user:secret@tcp(host:3306)/db?x=1": "mysql://***@tcp(host:3306)/db?x=1",
"postgres://user:pass@host:5432/db": "postgres://***@host:5432/db",
"postgresql://u:p@h:5432/d": "postgresql://***@h:5432/d",
"sqlite://data/x.db": "sqlite://data/x.db", // 无密码,原样
"/local/path.db": "/local/path.db", // 非 URL,原样
}
for in, want := range cases {
if got := maskURL(in); got != want {
@@ -17,3 +24,154 @@ func TestMaskURL(t *testing.T) {
}
}
}
func TestNewVerifyIDsAreUniqueForPersistentRuns(t *testing.T) {
ids := newVerifyIDs(12345)
want := map[string]string{
"username": "verify_12345",
"accountID": "acc_12345",
"orderID": "order_12345",
"itemID": "item_12345",
"buyerID": "buyer_12345",
}
got := map[string]string{
"username": ids.username,
"accountID": ids.accountID,
"orderID": ids.orderID,
"itemID": ids.itemID,
"buyerID": ids.buyerID,
}
for key, wantValue := range want {
if got[key] != wantValue {
t.Fatalf("%s=%q want %q", key, got[key], wantValue)
}
}
if ids.username == ids.accountID || ids.accountID == ids.orderID || ids.orderID == ids.itemID {
t.Fatalf("验证用 ID 不应互相复用: %+v", ids)
}
}
func TestNewVerifyPasswordIsNotFixedDefault(t *testing.T) {
first, err := newVerifyPassword()
if err != nil {
t.Fatalf("newVerifyPassword: %v", err)
}
second, err := newVerifyPassword()
if err != nil {
t.Fatalf("newVerifyPassword second: %v", err)
}
if first == "pw123456" || second == "pw123456" {
t.Fatal("验证用户不应使用固定弱密码")
}
if first == second {
t.Fatalf("验证密码应随机生成,got %q", first)
}
}
func TestCleanupVerifyDataRemovesRowsAndVerifyDataIsDisabled(t *testing.T) {
ctx := context.Background()
database, dialect, err := db.Open(ctx, filepath.Join(t.TempDir(), "verify.db"))
if err != nil {
t.Fatalf("Open: %v", err)
}
defer database.Close()
store := db.NewStore(database, dialect)
ids := newVerifyIDs(987654321)
password, err := newVerifyPassword()
if err != nil {
t.Fatalf("newVerifyPassword: %v", err)
}
ok, err := store.Users.Create(ctx, ids.username, ids.username+"@test.local", password)
if err != nil || !ok {
t.Fatalf("Create user: ok=%v err=%v", ok, err)
}
user, err := store.Users.GetByUsername(ctx, ids.username)
if err != nil {
t.Fatalf("GetByUsername: %v", err)
}
if user.IsAdmin {
t.Fatal("dbverify 创建的验证用户不应是管理员")
}
if err := store.Cookies.Save(ctx, ids.accountID, "unb=123; _m_h5_tk=tk_1;", user.ID); err != nil {
t.Fatalf("Save cookie: %v", err)
}
if err := store.Cookies.SetStatus(ctx, ids.accountID, false); err != nil {
t.Fatalf("SetStatus false: %v", err)
}
if store.Cookies.GetStatus(ctx, ids.accountID) {
t.Fatal("dbverify 验证账号应默认禁用,避免被服务启动")
}
if err := store.Orders.Upsert(ctx, ids.orderID, db.OrderUpsertOpts{ItemID: ids.itemID, BuyerID: ids.buyerID, CookieID: ids.accountID}); err != nil {
t.Fatalf("Orders.Upsert: %v", err)
}
if err := store.Items.Upsert(ctx, &db.ItemInfoRow{CookieID: ids.accountID, ItemID: ids.itemID, ItemTitle: "测试商品"}); err != nil {
t.Fatalf("Items.Upsert: %v", err)
}
cardID, err := store.Cards.Create(ctx, &db.CardFull{Name: "测试卡组", Type: "data", DataContent: "card", Enabled: true, UserID: user.ID})
if err != nil || cardID == 0 {
t.Fatalf("Cards.Create: id=%d err=%v", cardID, err)
}
channelID, err := store.Notifications.CreateChannel(ctx, &db.NotificationChannelRow{
Name: "测试渠道", Type: "webhook", Config: `{"webhook_url":"http://x"}`, Enabled: false, UserID: user.ID,
})
if err != nil {
t.Fatalf("CreateChannel: %v", err)
}
var channelEnabled int
if err := store.DB.QueryRowContext(ctx, `SELECT enabled FROM notification_channels WHERE id=?`, channelID).Scan(&channelEnabled); err != nil {
t.Fatalf("query channel enabled: %v", err)
}
if channelEnabled != 0 {
t.Fatal("dbverify 验证通知渠道应默认禁用")
}
if err := store.Notifications.SetBindings(ctx, ids.accountID, []int64{channelID}); err != nil {
t.Fatalf("SetBindings: %v", err)
}
ruleID, err := store.Automation.Create(ctx, db.AutomationRuleInput{
UserID: user.ID, CookieID: ids.accountID, ItemID: ids.itemID, Name: "付款发货",
TriggerType: "order_paid", Enabled: false, Priority: 100,
})
if err != nil {
t.Fatalf("Automation.Create: %v", err)
}
if _, started, err := store.Automation.TryStartRun(ctx, db.AutomationRun{
RuleID: ruleID, CookieID: ids.accountID, TriggerType: "order_paid", TriggerKey: ids.orderID, Status: "running",
}); err != nil || !started {
t.Fatalf("TryStartRun: started=%v err=%v", started, err)
}
if err := cleanupVerifyData(ctx, store, ids); err != nil {
t.Fatalf("cleanupVerifyData: %v", err)
}
if _, err := store.Users.GetByUsername(ctx, ids.username); !errors.Is(err, db.ErrNotFound) {
t.Fatalf("验证用户应被清理,err=%v", err)
}
if _, err := store.Cookies.GetValue(ctx, ids.accountID); !errors.Is(err, db.ErrNotFound) {
t.Fatalf("验证账号应被清理,err=%v", err)
}
var count int
for name, query := range map[string]string{
"automation_runs": `SELECT COUNT(*) FROM automation_runs WHERE cookie_id=? OR trigger_key=?`,
"automation_rules": `SELECT COUNT(*) FROM automation_rules WHERE cookie_id=? OR item_id=?`,
"notification_links": `SELECT COUNT(*) FROM message_notifications WHERE cookie_id=?`,
"orders": `SELECT COUNT(*) FROM orders WHERE cookie_id=? OR order_id=?`,
"items": `SELECT COUNT(*) FROM item_info WHERE cookie_id=? OR item_id=?`,
} {
var err error
switch name {
case "automation_runs", "orders":
err = store.DB.QueryRowContext(ctx, query, ids.accountID, ids.orderID).Scan(&count)
case "automation_rules", "items":
err = store.DB.QueryRowContext(ctx, query, ids.accountID, ids.itemID).Scan(&count)
default:
err = store.DB.QueryRowContext(ctx, query, ids.accountID).Scan(&count)
}
if err != nil {
t.Fatalf("count %s: %v", name, err)
}
if count != 0 {
t.Fatalf("%s 未清理干净,count=%d", name, count)
}
}
}