feat(backend): 会话安全加固 + 授权实时 phase + 首次使用自动试用

会话安全(jti 轮换 / 重用检测 / 改密吊销 / 禁用即时下线 / 清理 / 失败登录落库):
- refresh token 轮换 jti + token-family 重用检测,旧 token 重放即吊销整条会话
- 改密码、停用用户即时吊销其全部活跃会话(revoked_by 审计)
- 中间件 session JOIN user 校验,禁用/删除用户带 token 请求返回 401 USER_DISABLED
- 新增 login_attempts 失败登录落库 + 会话保留期清理 goroutine

授权实时 phase + 心跳回带:
- LicenseGuard 改为按当前 DB 实时计算 phase(30s 每店缓存),续费/过期/被改 ~30s 内对写操作生效,无需重登
- /auth/ping 回带授权概况(ShopInfoView,与 /license/info 同构),客户端一次心跳即刷新横幅/门禁

首次使用自动试用 + code-review 修复:
- 门店首次登录/续期无有效授权时自动签发 30 天 trial(快路径无锁 Count,仅首用走 FOR UPDATE 事务)
- ShopInfo 区分「确无授权」与瞬时 DB 错误,避免误降级
- trial 签发后改为在事务提交后再失效 phase 缓存(修复早于提交的竞态)
- 存量无 sid token 续期纳入显式上限,legacy 会话不再游离于并发配额之外

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
wangjia
2026-06-19 07:34:04 +08:00
parent 2d84bda99a
commit e41085a878
23 changed files with 1248 additions and 74 deletions
+18
View File
@@ -0,0 +1,18 @@
package model
import "time"
// LoginAttempt 登录尝试审计。当前只记录失败尝试(成功登录已由 user_sessions
// + users.last_login_at 覆盖),用于风控/审计排查异常登录。由保留期清理任务定期删除旧行。
type LoginAttempt struct {
ID uint64 `gorm:"primaryKey;autoIncrement" json:"id"`
ShopCode string `gorm:"size:64;index:idx_attempt_user" json:"shop_code"`
Username string `gorm:"size:50;index:idx_attempt_user" json:"username"`
IP string `gorm:"size:64;index:idx_attempt_ip" json:"ip"`
UserAgent string `gorm:"size:512" json:"user_agent"`
Success bool `gorm:"default:false" json:"success"`
Reason string `gorm:"size:40" json:"reason"` // invalid_shop|invalid_user|bad_password|locked|inactive|platform_not_allowed
CreatedAt time.Time `gorm:"autoCreateTime;index:idx_attempt_user;index:idx_attempt_ip" json:"created_at"`
}
func (LoginAttempt) TableName() string { return "login_attempts" }
+8 -1
View File
@@ -15,10 +15,17 @@ type UserSession struct {
PlatformClass string `gorm:"size:20;index" json:"platform_class"` // desktop|mobile|web
IP string `gorm:"size:64" json:"ip"`
UserAgent string `gorm:"size:512" json:"user_agent"`
// RefreshJTI 当前有效 refresh token 的 jti,用于「轮换 + 重用检测」:
// 每次续期轮换此值,若 refresh 携带的 jti 与之不符即判定为旧 token 重放(盗用),吊销整条会话。
RefreshJTI string `gorm:"column:refresh_jti;size:64" json:"-"`
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
// LastSeenAt 手工维护(Login 建行赋值、心跳/refresh 显式 Update)。
// 故意用 autoCreateTime(建行给默认、之后不被 ORM 自动改);切勿改成 autoUpdateTime
// 否则 revoke/cleanup 等任意 Updates 都会把已撤销会话误刷成「刚活跃」。
LastSeenAt time.Time `gorm:"autoCreateTime" json:"last_seen_at"`
RevokedAt *time.Time `gorm:"index" json:"revoked_at,omitempty"`
RevokedReason string `gorm:"size:30" json:"revoked_reason,omitempty"` // kicked|logout|admin|disabled
RevokedReason string `gorm:"size:30" json:"revoked_reason,omitempty"` // kicked|logout|admin|disabled|reuse|pwd_reset
RevokedBy *uint64 `gorm:"column:revoked_by" json:"revoked_by,omitempty"` // 吊销操作人 user_id;系统/自助吊销为 NULL
RefreshExpAt time.Time `json:"refresh_exp_at"`
}