feat(devices): P2 sessions 表 + 在线/最后登录/客户端版本
ci-pangolin / Lint — shellcheck (push) Successful in 8s
ci-pangolin / OpenAPI Sync Check (push) Successful in 18s
ci-pangolin / Redline Scan — 脱敏 (UI 文案) (push) Successful in 6s
ci-pangolin / Flutter — analyze + test (push) Successful in 24s
ci-pangolin / Portable SQL — 可移植性 (mysql/sqlite) (push) Successful in 5s
ci-pangolin / Codegen Drift — token 生成物未漂移 (push) Successful in 4s
ci-pangolin / Go — build + test (push) Successful in 11s
ci-pangolin / E2E Smoke — L4 进程级端到端 (push) Successful in 14s
ci-pangolin / Go — integration (mysql/redis testcontainers) (push) Failing after 4m13s
ci-pangolin / Golden — 视觉回归 (components + auth) (push) Successful in 14s
ci-pangolin / Lint — shellcheck (push) Successful in 8s
ci-pangolin / OpenAPI Sync Check (push) Successful in 18s
ci-pangolin / Redline Scan — 脱敏 (UI 文案) (push) Successful in 6s
ci-pangolin / Flutter — analyze + test (push) Successful in 24s
ci-pangolin / Portable SQL — 可移植性 (mysql/sqlite) (push) Successful in 5s
ci-pangolin / Codegen Drift — token 生成物未漂移 (push) Successful in 4s
ci-pangolin / Go — build + test (push) Successful in 11s
ci-pangolin / E2E Smoke — L4 进程级端到端 (push) Successful in 14s
ci-pangolin / Go — integration (mysql/redis testcontainers) (push) Failing after 4m13s
ci-pangolin / Golden — 视觉回归 (components + auth) (push) Successful in 14s
migration 000016(mysql+sqlite,含 down):新增 sessions 表(绑 device+refresh JTI) + devices 加 client_version/totp_trusted_until。devices 唯一键改 + platform CHECK 加 linux(需 SQLite 表重建)拆出后续迁移,降风险。 后端:新 internal/sessions Store(Create/Rotate/Revoke/RevokeByDevice/ LastLoginByDevice);TokenManager 外露 refresh JTI(IssueWithJTI/RefreshWithJTI/ ParseRefreshJTI);auth.Service 注入 SessionStore——登录建会话、刷新轮换、登出吊销; DeviceRegistrar 返回 deviceID;ReportUsage 心跳 touch devices.last_seen(在线判定); devices.ListDevices 经 LastLoginSource 注入返回 online(last_seen<3min)/client_version/ last_login;RegisterIfAbsent 存 client_version。 客户端:Device model 加 online/clientVersion/lastLogin(fromJson 自动解析)。 测试:sessions store 3 例 + ListDevices 在线/最后登录 + device model 2 例 + migration v16;全量 go test/flutter test 绿。 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -86,40 +86,61 @@ type DeviceMeta struct {
|
||||
ClientVersion string // app version (stored from P2 onward)
|
||||
}
|
||||
|
||||
// DeviceRegistrar registers the logging-in device. Defined consumer-side to
|
||||
// avoid an import cycle; devices.Service is adapted to it in main wiring.
|
||||
// Registration is best-effort and must never block login (see registerDevice).
|
||||
// DeviceRegistrar registers the logging-in device and returns its internal id
|
||||
// (for session binding). Defined consumer-side to avoid an import cycle;
|
||||
// devices.Service is adapted to it in main wiring. Best-effort (see recordLogin).
|
||||
type DeviceRegistrar interface {
|
||||
RegisterDevice(ctx context.Context, userID int64, meta DeviceMeta) error
|
||||
RegisterDevice(ctx context.Context, userID int64, meta DeviceMeta) (deviceID int64, err error)
|
||||
}
|
||||
|
||||
// SessionStore persists login sessions bound to a refresh JTI. Satisfied by
|
||||
// sessions.Store; injected so auth stays decoupled.
|
||||
type SessionStore interface {
|
||||
Create(ctx context.Context, userID, deviceID int64, jti, ip, clientVersion string) error
|
||||
Rotate(ctx context.Context, oldJTI, newJTI string) error
|
||||
Revoke(ctx context.Context, jti string) error
|
||||
}
|
||||
|
||||
// Service is the auth business layer: code issuance, registration, login, and
|
||||
// token refresh. It is safe for concurrent use.
|
||||
type Service struct {
|
||||
store UserStore
|
||||
rdb *redis.Client
|
||||
rl *RateLimiter
|
||||
tokens *TokenManager
|
||||
mailer Mailer
|
||||
cfg ServiceConfig
|
||||
now func() time.Time
|
||||
devReg DeviceRegistrar // nil until wired; registration is best-effort
|
||||
store UserStore
|
||||
rdb *redis.Client
|
||||
rl *RateLimiter
|
||||
tokens *TokenManager
|
||||
mailer Mailer
|
||||
cfg ServiceConfig
|
||||
now func() time.Time
|
||||
devReg DeviceRegistrar // nil until wired; registration is best-effort
|
||||
sessions SessionStore // nil until wired; session recording is best-effort
|
||||
}
|
||||
|
||||
// SetDeviceRegistrar wires the device registrar after construction (main keeps
|
||||
// auth and devices decoupled). Safe to call once during startup.
|
||||
// SetDeviceRegistrar / SetSessionStore wire collaborators after construction
|
||||
// (main keeps auth, devices and sessions decoupled). Call once during startup.
|
||||
func (s *Service) SetDeviceRegistrar(r DeviceRegistrar) { s.devReg = r }
|
||||
func (s *Service) SetSessionStore(st SessionStore) { s.sessions = st }
|
||||
|
||||
// registerDevice records the logging-in device. Best-effort: a registrar error
|
||||
// (device cap, transient DB) is logged but never fails the login/registration —
|
||||
// the user must always be able to get in (notably: free-plan reinstall churns
|
||||
// the device UUID, so a hard cap here would lock users out).
|
||||
func (s *Service) registerDevice(ctx context.Context, userID int64, meta DeviceMeta) {
|
||||
if s.devReg == nil || meta.DeviceID == "" {
|
||||
// recordLogin registers the device and binds a session to the freshly-issued
|
||||
// refresh JTI. Best-effort: a registrar/session error (device cap, transient DB)
|
||||
// is logged but never fails login — the user must always be able to get in
|
||||
// (notably: free-plan reinstall churns the device UUID, so a hard cap here would
|
||||
// lock users out).
|
||||
func (s *Service) recordLogin(ctx context.Context, userID int64, refreshJTI, ip string, meta DeviceMeta) {
|
||||
if meta.DeviceID == "" {
|
||||
return
|
||||
}
|
||||
if err := s.devReg.RegisterDevice(ctx, userID, meta); err != nil {
|
||||
slog.Warn("auth: device register failed (login proceeds)", "uid", userID, "err", err)
|
||||
var deviceID int64
|
||||
if s.devReg != nil {
|
||||
id, err := s.devReg.RegisterDevice(ctx, userID, meta)
|
||||
if err != nil {
|
||||
slog.Warn("auth: device register failed (login proceeds)", "uid", userID, "err", err)
|
||||
}
|
||||
deviceID = id
|
||||
}
|
||||
if s.sessions != nil && deviceID > 0 && refreshJTI != "" {
|
||||
if err := s.sessions.Create(ctx, userID, deviceID, refreshJTI, ip, meta.ClientVersion); err != nil {
|
||||
slog.Warn("auth: session create failed (login proceeds)", "uid", userID, "err", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -218,7 +239,7 @@ func (s *Service) SendCode(ctx context.Context, rawEmail, ip string) (retryAfter
|
||||
|
||||
// Register verifies the code (one-time), creates the account plus a 7-day PRO
|
||||
// trial in a single transaction, and returns a fresh token pair.
|
||||
func (s *Service) Register(ctx context.Context, rawEmail, code, password string, device DeviceMeta) (*TokenPair, *apierr.Error) {
|
||||
func (s *Service) Register(ctx context.Context, rawEmail, code, password, ip string, device DeviceMeta) (*TokenPair, *apierr.Error) {
|
||||
email := NormalizeEmail(rawEmail)
|
||||
if !ValidEmail(email) || len(password) < 8 || len(code) != 6 {
|
||||
return nil, ErrInvalidRequest
|
||||
@@ -247,11 +268,11 @@ func (s *Service) Register(ctx context.Context, rawEmail, code, password string,
|
||||
return nil, ErrInternal
|
||||
}
|
||||
|
||||
pair, err := s.tokens.Issue(ctx, user.ID, user.UUID)
|
||||
pair, jti, err := s.tokens.IssueWithJTI(ctx, user.ID, user.UUID)
|
||||
if err != nil {
|
||||
return nil, ErrInternal
|
||||
}
|
||||
s.registerDevice(ctx, user.ID, device)
|
||||
s.recordLogin(ctx, user.ID, jti, ip, device)
|
||||
return pair, nil
|
||||
}
|
||||
|
||||
@@ -308,7 +329,6 @@ const (
|
||||
)
|
||||
|
||||
func (s *Service) Login(ctx context.Context, rawEmail, password, ip string, device DeviceMeta) (*LoginOutcome, time.Duration, *apierr.Error) {
|
||||
_ = ip // IP reserved for future per-IP login throttling; not logged.
|
||||
email := NormalizeEmail(rawEmail)
|
||||
if email == "" || password == "" {
|
||||
return nil, 0, ErrInvalidRequest
|
||||
@@ -360,11 +380,11 @@ func (s *Service) Login(ctx context.Context, rawEmail, password, ip string, devi
|
||||
return &LoginOutcome{PendingToken: pending}, 0, nil
|
||||
}
|
||||
|
||||
pair, err := s.tokens.Issue(ctx, user.ID, user.UUID)
|
||||
pair, jti, err := s.tokens.IssueWithJTI(ctx, user.ID, user.UUID)
|
||||
if err != nil {
|
||||
return nil, 0, ErrInternal
|
||||
}
|
||||
s.registerDevice(ctx, user.ID, device)
|
||||
s.recordLogin(ctx, user.ID, jti, ip, device)
|
||||
return &LoginOutcome{Tokens: pair}, 0, nil
|
||||
}
|
||||
|
||||
@@ -374,15 +394,22 @@ func (s *Service) Logout(ctx context.Context, refreshToken string) {
|
||||
if refreshToken == "" {
|
||||
return
|
||||
}
|
||||
// Mark the bound session revoked before dropping the Redis whitelist entry.
|
||||
if s.sessions != nil {
|
||||
if jti, err := s.tokens.ParseRefreshJTI(refreshToken); err == nil {
|
||||
_ = s.sessions.Revoke(ctx, jti)
|
||||
}
|
||||
}
|
||||
_ = s.tokens.RevokeRefresh(ctx, refreshToken)
|
||||
}
|
||||
|
||||
// Refresh validates and rotates a refresh token.
|
||||
// Refresh validates and rotates a refresh token, moving the bound session to the
|
||||
// new JTI.
|
||||
func (s *Service) Refresh(ctx context.Context, refreshToken string) (*TokenPair, *apierr.Error) {
|
||||
if refreshToken == "" {
|
||||
return nil, ErrInvalidRequest
|
||||
}
|
||||
pair, err := s.tokens.Refresh(ctx, refreshToken)
|
||||
pair, oldJTI, newJTI, err := s.tokens.RefreshWithJTI(ctx, refreshToken)
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrInvalidTokenSentinel) {
|
||||
return nil, ErrInvalidToken
|
||||
@@ -390,6 +417,9 @@ func (s *Service) Refresh(ctx context.Context, refreshToken string) (*TokenPair,
|
||||
// Parse / signature / expiry failures all map to an opaque invalid-token.
|
||||
return nil, ErrInvalidToken
|
||||
}
|
||||
if s.sessions != nil {
|
||||
_ = s.sessions.Rotate(ctx, oldJTI, newJTI)
|
||||
}
|
||||
return pair, nil
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user