fix: reconcile SIM ownership across device changes

This commit is contained in:
yibaiba committed 2026-10-14 17:52:09 +08:00
1 parent 2bb6afb373
commit 130c055113
6 files changed
+270 -25

No files matched your search

+1 -1
View File
@@ -1644,7 +1644,7 @@ func (s *Server) handleDeviceMgmtDeleteDevice(c *gin.Context) {
if s.pool != nil {
abandon = s.pool.AbandonDevice
}
deleteManagedDevice(c, s.configPath, abandon)
deleteManagedDevice(c, s.configPath, databaseManagedDeviceDeleteOps(abandon))
}
type addDeviceRequest struct {
+20 -2
View File
@@ -5,9 +5,15 @@ import (
"github.com/gin-gonic/gin"
"github.com/yibaiba/hideck/internal/config"
"github.com/yibaiba/hideck/internal/db"
"github.com/yibaiba/hideck/pkg/logger"
)
type managedDeviceDeleteOps struct {
abandon func(string) error
detach func(string) error
}
func stopManagedDevice(c *gin.Context, id string, abandon func(string) error) bool {
if abandon == nil {
return true
@@ -22,18 +28,30 @@ func stopManagedDevice(c *gin.Context, id string, abandon func(string) error) bo
return true
}
func deleteManagedDevice(c *gin.Context, configPath string, abandon func(string) error) {
func deleteManagedDevice(c *gin.Context, configPath string, ops managedDeviceDeleteOps) {
id := deviceIDParam(c)
if id == "" {
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "message": "必须填写 id"})
return
}
if !stopManagedDevice(c, id, abandon) {
if !stopManagedDevice(c, id, ops.abandon) {
return
}
if err := config.DeleteDeviceInFile(configPath, id); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "message": "删除设备配置失败: " + err.Error()})
return
}
if ops.detach != nil {
if err := ops.detach(id); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"status": "error", "message": "设备配置已删除,但清理历史设备绑定失败: " + err.Error(),
})
return
}
}
c.JSON(http.StatusOK, gin.H{"status": "ok"})
}
func databaseManagedDeviceDeleteOps(abandon func(string) error) managedDeviceDeleteOps {
return managedDeviceDeleteOps{abandon: abandon, detach: db.DetachDeviceAlias}
}
+18 -8
View File
@@ -22,14 +22,21 @@ func TestDeleteManagedDevicePreservesConfigOnStopFailure(t *testing.T) {
rec := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(rec)
ctx.Params = gin.Params{{Key: "device_id", Value: "wwan0"}}
deleteManagedDevice(ctx, path, func(id string) error {
if id != "wwan0" {
t.Fatal("wrong device", id)
}
if fail {
return errors.New("modem hangup failed")
}
return nil
detached := false
deleteManagedDevice(ctx, path, managedDeviceDeleteOps{
abandon: func(id string) error {
if id != "wwan0" {
t.Fatal("wrong device", id)
}
if fail {
return errors.New("modem hangup failed")
}
return nil
},
detach: func(string) error {
detached = true
return nil
},
})
want := http.StatusOK
if fail {
@@ -42,6 +49,9 @@ func TestDeleteManagedDevicePreservesConfigOnStopFailure(t *testing.T) {
if (got != nil) != fail {
t.Fatalf("config preserved=%v stop failed=%v", got != nil, fail)
}
if detached == fail {
t.Fatalf("binding detached=%v stop failed=%v", detached, fail)
}
}
}
+16 -14
View File
@@ -279,6 +279,7 @@ func UpsertSIMCardIdentity(iccid, imsi, operator string, currentIMEI *string) er
iccid = CanonicalICCID(iccid)
imsi = strings.TrimSpace(imsi)
operator = strings.TrimSpace(operator)
currentIMEI = normalizedIMEIPointer(currentIMEI)
if iccid == "" {
return nil
}
@@ -309,13 +310,12 @@ func UpsertSIMCardIdentity(iccid, imsi, operator string, currentIMEI *string) er
if err := reconcileLiveICCIDTx(tx, SMSIdentity{ICCID: iccid, IMSI: imsi}); err != nil {
return err
}
if currentIMEI == nil {
if err := tx.Model(&Device{}).Where("iccid = ?", iccid).Updates(map[string]any{
"iccid": nil,
"updated_at": now,
}).Error; err != nil {
return err
}
binding := simDeviceBinding{ICCID: iccid, Now: now}
if currentIMEI != nil {
binding.IMEI = *currentIMEI
}
if err := reconcileSIMDeviceBindingTx(tx, binding); err != nil {
return err
}
if imsi == "" {
return nil
@@ -546,14 +546,16 @@ func allSameRune(s string, r rune) bool {
// UpdateDeviceCurrentSIM 更新设备当前插入的 SIM 卡
func UpdateDeviceCurrentSIM(imei string, iccid *string) error {
if iccid != nil {
canonical := CanonicalICCID(*iccid)
iccid = &canonical
if DB == nil {
return nil
}
return DB.Model(&Device{}).Where("imei = ?", imei).Updates(map[string]interface{}{
"iccid": iccid,
"last_seen": time.Now(),
}).Error
binding := simDeviceBinding{IMEI: strings.TrimSpace(imei), Now: time.Now()}
if iccid != nil {
binding.ICCID = CanonicalICCID(*iccid)
}
return DB.Transaction(func(tx *gorm.DB) error {
return reconcileSIMDeviceBindingTx(tx, binding)
})
}
// UpdateDeviceSignal 更新设备信号强度
+104
View File
@@ -0,0 +1,104 @@
package db
import (
"strings"
"time"
"gorm.io/gorm"
)
type simDeviceBinding struct {
ICCID string
IMEI string
Now time.Time
}
func normalizedIMEIPointer(value *string) *string {
if value == nil {
return nil
}
normalized := strings.TrimSpace(*value)
if normalized == "" {
return nil
}
return &normalized
}
func reconcileSIMDeviceBindingTx(tx *gorm.DB, binding simDeviceBinding) error {
binding.ICCID = CanonicalICCID(binding.ICCID)
binding.IMEI = strings.TrimSpace(binding.IMEI)
if binding.Now.IsZero() {
binding.Now = time.Now()
}
if binding.ICCID == "" {
return detachDeviceSIMTx(tx, binding.IMEI, binding.Now)
}
if binding.IMEI == "" {
return detachSIMFromDevicesTx(tx, binding.ICCID, binding.Now)
}
if err := clearPreviousSIMOwnersTx(tx, binding); err != nil {
return err
}
if err := clearPreviousDeviceSIMTx(tx, binding); err != nil {
return err
}
if err := tx.Model(&SIMCard{}).Where("iccid = ?", binding.ICCID).
Updates(map[string]any{"current_imei": binding.IMEI, "updated_at": binding.Now}).Error; err != nil {
return err
}
return tx.Model(&Device{}).Where("imei = ?", binding.IMEI).
Updates(map[string]any{"iccid": binding.ICCID, "last_seen": binding.Now}).Error
}
func clearPreviousSIMOwnersTx(tx *gorm.DB, binding simDeviceBinding) error {
return tx.Model(&Device{}).
Where("iccid = ? AND imei <> ?", binding.ICCID, binding.IMEI).
Updates(map[string]any{"iccid": nil, "updated_at": binding.Now}).Error
}
func clearPreviousDeviceSIMTx(tx *gorm.DB, binding simDeviceBinding) error {
return tx.Model(&SIMCard{}).
Where("current_imei = ? AND iccid <> ?", binding.IMEI, binding.ICCID).
Updates(map[string]any{"current_imei": nil, "updated_at": binding.Now}).Error
}
func detachSIMFromDevicesTx(tx *gorm.DB, iccid string, now time.Time) error {
if err := tx.Model(&Device{}).Where("iccid = ?", iccid).
Updates(map[string]any{"iccid": nil, "updated_at": now}).Error; err != nil {
return err
}
return tx.Model(&SIMCard{}).Where("iccid = ?", iccid).
Updates(map[string]any{"current_imei": nil, "updated_at": now}).Error
}
func detachDeviceSIMTx(tx *gorm.DB, imei string, now time.Time) error {
if imei == "" {
return nil
}
if err := tx.Model(&SIMCard{}).Where("current_imei = ?", imei).
Updates(map[string]any{"current_imei": nil, "updated_at": now}).Error; err != nil {
return err
}
return tx.Model(&Device{}).Where("imei = ?", imei).
Updates(map[string]any{"iccid": nil, "updated_at": now}).Error
}
// DetachDeviceAlias clears current SIM ownership without deleting device or SMS history.
func DetachDeviceAlias(alias string) error {
alias = strings.TrimSpace(alias)
if DB == nil || alias == "" {
return nil
}
return DB.Transaction(func(tx *gorm.DB) error {
var devices []Device
if err := tx.Select("imei").Where("alias = ?", alias).Find(&devices).Error; err != nil {
return err
}
for _, device := range devices {
if err := detachDeviceSIMTx(tx, device.IMEI, time.Now()); err != nil {
return err
}
}
return nil
})
}
+111
View File
@@ -0,0 +1,111 @@
package db
import (
"testing"
"time"
)
func TestSIMMoveReassignsDeviceAndCardOwnership(t *testing.T) {
openTestDB(t)
const (
imeiA = "860000000000101"
imeiB = "860000000000102"
cardA = "8944100000000000101"
cardB = "8944100000000000102"
)
for _, device := range []Device{{IMEI: imeiA, Alias: "wwan0"}, {IMEI: imeiB, Alias: "wwan1"}} {
if err := DB.Create(&device).Error; err != nil {
t.Fatal(err)
}
}
if err := UpsertSIMCardIdentity(cardA, "imsi-a", "", ptrString(imeiA)); err != nil {
t.Fatal(err)
}
if err := UpsertSIMCardIdentity(cardB, "imsi-b", "", ptrString(imeiB)); err != nil {
t.Fatal(err)
}
if err := UpsertSIMCardIdentity(cardA, "imsi-a", "", ptrString(imeiB)); err != nil {
t.Fatal(err)
}
assertDeviceSIMBinding(t, imeiA, "")
assertDeviceSIMBinding(t, imeiB, cardA)
assertSIMDeviceBinding(t, cardA, imeiB)
assertSIMDeviceBinding(t, cardB, "")
}
func TestDetachAndReaddDeviceAliasDoesNotReuseOldSIM(t *testing.T) {
openTestDB(t)
const (
alias = "wwan0"
oldIMEI = "860000000000111"
newIMEI = "860000000000112"
oldCard = "8944100000000000111"
newCard = "8944100000000000112"
)
if err := DB.Create(&Device{IMEI: oldIMEI, Alias: alias}).Error; err != nil {
t.Fatal(err)
}
if err := UpsertSIMCardIdentity(oldCard, "imsi-old", "", ptrString(oldIMEI)); err != nil {
t.Fatal(err)
}
if err := DB.Create(&SMS{
ICCID: oldCard, IMSI: "imsi-old", Peer: "10086", Content: "history",
Type: 1, Timestamp: time.Now(),
}).Error; err != nil {
t.Fatal(err)
}
if err := DetachDeviceAlias(alias); err != nil {
t.Fatal(err)
}
assertDeviceSIMBinding(t, oldIMEI, "")
assertSIMDeviceBinding(t, oldCard, "")
if err := DB.Create(&Device{IMEI: newIMEI, Alias: alias}).Error; err != nil {
t.Fatal(err)
}
if err := UpsertSIMCardIdentity(newCard, "imsi-new", "", ptrString(newIMEI)); err != nil {
t.Fatal(err)
}
identity, found, err := LookupSMSIdentityForDevice(SMSDeviceSelector{DeviceID: alias})
if err != nil || !found || identity.ICCID != newCard || identity.IMSI != "imsi-new" {
t.Fatalf("re-added device identity=%+v found=%v err=%v", identity, found, err)
}
var historyCount int64
if err := DB.Model(&SMS{}).Where("iccid = ?", oldCard).Count(&historyCount).Error; err != nil {
t.Fatal(err)
}
if historyCount != 1 {
t.Fatalf("old SIM history count=%d want 1", historyCount)
}
}
func assertDeviceSIMBinding(t *testing.T, imei, wantICCID string) {
t.Helper()
var device Device
if err := DB.First(&device, "imei = ?", imei).Error; err != nil {
t.Fatal(err)
}
got := ""
if device.CurrentICCID != nil {
got = *device.CurrentICCID
}
if got != wantICCID {
t.Fatalf("device %s ICCID=%q want %q", imei, got, wantICCID)
}
}
func assertSIMDeviceBinding(t *testing.T, iccid, wantIMEI string) {
t.Helper()
var sim SIMCard
if err := DB.First(&sim, "iccid = ?", iccid).Error; err != nil {
t.Fatal(err)
}
got := ""
if sim.CurrentIMEI != nil {
got = *sim.CurrentIMEI
}
if got != wantIMEI {
t.Fatalf("SIM %s IMEI=%q want %q", iccid, got, wantIMEI)
}
}