feat(server): 设备上限登录闸(超限非硬拒登,返回 device_limit 信号)#16

启用设备数量限制的服务端部分。登录照常成功签发 token(非硬拒登),但若账户活跃
设备数超套餐上限,登录响应带 device_limit 信号,客户端据此弹「移除设备」页。

- devices/store.go:CountActiveDevices(last_seen 近 staleWindow)+ PruneStaleDevices
  (删超期僵尸行,免费版重装 churn 自愈)
- devices/service.go:staleWindow=30d;DeviceLimitStatus + CheckDeviceLimit
  (best-effort prune → ResolvePlan → 活跃 count > cap 即 Over,附活跃设备列表)
- auth:DeviceRegistrar 加 CheckDeviceLimit;recordLogin 回传 *DeviceLimit;
  LoginOutcome.DeviceLimit;Login 透传;handler tokenPairResponse.device_limit(omitempty)
- main.go:authDeviceRegistrar 适配 devices.CheckDeviceLimit → auth.DeviceLimit
- 测试:auth 登录透传超限信号(仍签发 token);devices within/over/prune-stale

连接侧 backstop(服务端硬拦)本轮从简未做,作为后续硬化(登录闸为客户端可信信号)。
DB 无 schema 变更。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
wangjia
2026-07-01 19:16:10 +08:00
parent 27dc59ed63
commit 6bac7fd2f0
7 changed files with 225 additions and 8 deletions
+28
View File
@@ -131,6 +131,34 @@ func (s *Store) countDevicesTx(ctx context.Context, tx *sql.Tx, userID int64) (i
return n, nil
}
// CountActiveDevices counts the user's devices seen within the active window
// (last_seen > cutoff). Stale rows (churned free-plan reinstalls) and never-seen
// rows are excluded so they don't count against the plan cap.
func (s *Store) CountActiveDevices(ctx context.Context, userID int64, cutoff time.Time) (int, error) {
var n int
if err := s.db.QueryRowContext(ctx,
`SELECT COUNT(1) FROM devices WHERE user_id=? AND last_seen IS NOT NULL AND last_seen > ?`,
userID, cutoff.UTC()).Scan(&n); err != nil {
return 0, fmt.Errorf("store.CountActiveDevices: %w", err)
}
return n, nil
}
// PruneStaleDevices deletes the user's devices not seen since cutoff (best-effort
// churn cleanup). Stale devices are offline; their sessions/credentials have long
// expired and node resync reconciles any residue, so a plain row delete is safe.
// Returns the number of rows removed.
func (s *Store) PruneStaleDevices(ctx context.Context, userID int64, cutoff time.Time) (int64, error) {
res, err := s.db.ExecContext(ctx,
`DELETE FROM devices WHERE user_id=? AND last_seen IS NOT NULL AND last_seen < ?`,
userID, cutoff.UTC())
if err != nil {
return 0, fmt.Errorf("store.PruneStaleDevices: %w", err)
}
n, _ := res.RowsAffected()
return n, nil
}
// insertDeviceTx inserts a new device row inside tx and returns it.
func (s *Store) insertDeviceTx(ctx context.Context, tx *sql.Tx, uuid string, userID int64, name, platform, clientVersion string) (*DeviceRow, error) {
now := time.Now().UTC()