From 0b33f124002d5ae2be26763264dbbb51b2ee1bbc Mon Sep 17 00:00:00 2001 From: wangjia <809946525@qq.com> Date: Tue, 30 Jun 2026 07:25:16 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E8=BF=91=E5=AE=9E=E6=97=B6=E8=BF=9C?= =?UTF-8?q?=E7=A8=8B=E4=B8=8B=E7=BA=BF=20=E2=80=94=20=E5=AE=A2=E6=88=B7?= =?UTF-8?q?=E7=AB=AF=E8=BD=AE=E8=AF=A2=E4=BC=9A=E8=AF=9D=E6=9C=89=E6=95=88?= =?UTF-8?q?=E6=80=A7(~15s),=E6=9C=8D=E5=8A=A1=E7=AB=AF=20GET=20/v1/me/sess?= =?UTF-8?q?ion?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 控制面无推送通道,access token 是无状态 JWT(15min),强制退出后被踢设备要等 token 过期 (≤15min)才登出。改成客户端每 15s 轮询会话是否仍有效,被强制退出即登出 → 延迟压到 ~15s。 - 服务端:sessions.HasActiveSession(user,device) + devices.SessionActive(按 UUID,fail-open) + GET /v1/me/session?device_id= 返回 {active}(恒 200,判据在 body)。无新迁移。 - 客户端:account_api.sessionActive + main.dart _RootFlowState 15s 轮询,active=false 即 logout (网络/鉴权异常不据此登出,fail-safe)。 - 测试:TestSQLite_SessionHasActiveSession(建会话=活跃→RevokeByDevice→非活跃)。 Co-Authored-By: Claude Opus 4.8 --- client/lib/main.dart | 37 +++++++++++++++++++- client/lib/services/account_api.dart | 8 +++++ server/internal/devices/handler.go | 23 +++++++++++++ server/internal/devices/service.go | 24 +++++++++++++ server/internal/sessions/store.go | 14 ++++++++ server/internal/store/sqlite_stores_test.go | 38 +++++++++++++++++++++ 6 files changed, 143 insertions(+), 1 deletion(-) diff --git a/client/lib/main.dart b/client/lib/main.dart index 23ee5a4..064b3b8 100644 --- a/client/lib/main.dart +++ b/client/lib/main.dart @@ -12,8 +12,10 @@ import 'bridge/log.dart'; import 'bridge/vpn_bridge_provider.dart'; import 'models/node.dart'; import 'pangolin_theme.dart'; +import 'services/device_identity.dart'; import 'services/token_store.dart'; import 'shell/home_shell.dart'; +import 'state/account_providers.dart'; import 'state/app_providers.dart'; import 'state/auth_provider.dart'; import 'state/connection_provider.dart'; @@ -129,6 +131,36 @@ class _RootFlowState extends ConsumerState { bool _forceOnboarding = false; bool _autoConnectArmed = false; // 自动连接每进程只尝试一次 bool _homeLogged = false; // 仅日志:HomeShell 首次显示打一行 + bool _sessionWatchdogArmed = false; // 会话有效性轮询每进程只起一次 + Timer? _sessionPoll; + + @override + void dispose() { + _sessionPoll?.cancel(); + super.dispose(); + } + + // 会话有效性轮询:每 15s 问服务端「本设备会话还在吗」,被其他设备强制退出即登出。 + // 控制面无推送通道,用轮询把远程下线延迟压到 ~15s(而非 access token 的 15 分钟)。 + void _startSessionWatchdog() { + if (_sessionWatchdogArmed) return; + _sessionWatchdogArmed = true; + _sessionPoll = Timer.periodic(const Duration(seconds: 15), (_) => _checkSession()); + } + + Future _checkSession() async { + if (!mounted || !ref.read(authProvider).isLoggedIn) return; + try { + final deviceId = await ref.read(deviceIdentityProvider).deviceId(); + final active = await ref.read(accountApiProvider).sessionActive(deviceId); + if (!active && mounted && ref.read(authProvider).isLoggedIn) { + logLine('Session', 'server revoked this device → logout'); + await ref.read(authProvider.notifier).logout(); + } + } catch (_) { + // 网络/鉴权异常不据此登出(fail-safe):只在服务端明确 active=false 才登出。 + } + } // 进入登录态主界面后:开了「自动连接」且当前未连接,就自动连一次。 // 关键:必须同时等「设置已从持久化加载完(settings.loaded)」与「节点已就绪」—— @@ -220,7 +252,10 @@ class _RootFlowState extends ConsumerState { logLine('AutoConnect', 'HomeShell shown; scheduling auto-connect check'); } WidgetsBinding.instance.addPostFrameCallback((_) { - if (mounted) _maybeAutoConnect(); + if (mounted) { + _maybeAutoConnect(); + _startSessionWatchdog(); + } }); return const HomeShell(); } diff --git a/client/lib/services/account_api.dart b/client/lib/services/account_api.dart index 4fdb832..f416fd8 100644 --- a/client/lib/services/account_api.dart +++ b/client/lib/services/account_api.dart @@ -69,6 +69,14 @@ class AccountApi { await _c.postJson('/v1/me/devices/$uuid/rename', {'name': name}); } + /// GET /v1/me/session?device_id= — 本设备会话是否仍有效。 + /// false = 已被其他设备强制退出 → 客户端应登出。供 ~15s 轮询实现近实时远程下线。 + Future sessionActive(String deviceId) async { + final body = await _c.getJson( + '/v1/me/session?device_id=${Uri.encodeQueryComponent(deviceId)}'); + return body['active'] == true; + } + /// GET /v1/usage?days=N&tz_offset=M — 最近 N 天用量(默认 7,后端范围 [1,90])。 /// 带本机时区偏移(分钟,如 UTC+8=480),服务端按「本地日」聚合 → 「今天」与本地日历一致 /// (修「29 号却显示 28 号数据」的时区 bug)。 diff --git a/server/internal/devices/handler.go b/server/internal/devices/handler.go index 7f7c0fe..9d4bc18 100644 --- a/server/internal/devices/handler.go +++ b/server/internal/devices/handler.go @@ -3,6 +3,7 @@ package devices import ( "encoding/json" "net/http" + "strings" "github.com/go-chi/chi/v5" "github.com/wangjia/pangolin/server/internal/apierr" @@ -29,6 +30,7 @@ func (h *Handler) RegisterRoutes(r chi.Router) { r.Delete("/devices/{id}", h.DeleteDevice) r.Post("/devices/{id}/logout", h.ForceLogout) r.Post("/devices/{id}/rename", h.RenameDevice) + r.Get("/session", h.SessionCheck) // GET /v1/me/session?device_id= — 会话有效性轮询 } type listDevicesResponse struct { @@ -89,6 +91,27 @@ func (h *Handler) ForceLogout(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNoContent) } +// SessionCheck handles GET /v1/me/session?device_id=UUID — reports whether the +// caller's device still has a live session. false ⇒ force-logged-out elsewhere; +// the client polls this (~15s) and logs out on {"active":false} → near-instant kick. +// Always 200 (the verdict is in the body); device_id 取自 query。 +func (h *Handler) SessionCheck(w http.ResponseWriter, r *http.Request) { + userID, ok := auth.UserIDFromContext(r.Context()) + if !ok { + apierr.WriteJSON(w, http.StatusUnauthorized, apierr.ErrUnauthorized) + return + } + deviceUUID := strings.TrimSpace(r.URL.Query().Get("device_id")) + active, apiErr := h.svc.SessionActive(r.Context(), userID, deviceUUID) + if apiErr != nil { + apierr.WriteJSON(w, StatusForError(apiErr), apiErr) + return + } + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.WriteHeader(http.StatusOK) + _ = json.NewEncoder(w).Encode(map[string]bool{"active": active}) +} + // RenameDevice handles POST /v1/me/devices/{id}/rename — set a device's name. func (h *Handler) RenameDevice(w http.ResponseWriter, r *http.Request) { userID, ok := auth.UserIDFromContext(r.Context()) diff --git a/server/internal/devices/service.go b/server/internal/devices/service.go index 0f1bf1d..ca72609 100644 --- a/server/internal/devices/service.go +++ b/server/internal/devices/service.go @@ -36,6 +36,7 @@ func (n *NoopRevoker) RevokeDevice(_ context.Context, dpUUID string) error { type SessionPort interface { LastLoginByDevice(ctx context.Context, userID int64) (map[int64]time.Time, error) RevokeByDevice(ctx context.Context, userID, deviceID int64) ([]string, error) + HasActiveSession(ctx context.Context, userID, deviceID int64) (bool, error) } // JTIRevoker drops a refresh JTI from the Redis whitelist. Satisfied by @@ -342,6 +343,29 @@ func (svc *Service) RenameDevice(ctx context.Context, userID int64, deviceUUID, return nil } +// SessionActive reports whether the device (by UUID) still has a live login session +// for the user — false after a force-logout elsewhere. The client polls this (~15s) +// and logs out on false → near-instant remote kick. Fail-open (return true) on a +// missing session port / blank or unknown / not-own device, so transient ambiguity +// never spuriously logs a user out. +func (svc *Service) SessionActive(ctx context.Context, userID int64, deviceUUID string) (bool, *apierr.Error) { + if svc.sessions == nil || strings.TrimSpace(deviceUUID) == "" { + return true, nil + } + dev, err := svc.store.FindByUUID(ctx, deviceUUID) + if err != nil { + return false, apierr.ErrInternal + } + if dev == nil || dev.UserID != userID { + return true, nil // 未知 / 非本人设备:不据此登出 + } + active, err := svc.sessions.HasActiveSession(ctx, userID, dev.ID) + if err != nil { + return false, apierr.ErrInternal + } + return active, nil +} + // revokeDeviceSessions marks all of a device's sessions revoked and drops their // refresh JTIs from the Redis whitelist. Best-effort. func (svc *Service) revokeDeviceSessions(ctx context.Context, userID, deviceID int64) { diff --git a/server/internal/sessions/store.go b/server/internal/sessions/store.go index ae02c14..ec47b99 100644 --- a/server/internal/sessions/store.go +++ b/server/internal/sessions/store.go @@ -47,6 +47,20 @@ func (s *Store) Rotate(ctx context.Context, oldJTI, newJTI string) error { return nil } +// HasActiveSession reports whether the (user, device) has at least one non-revoked +// session — i.e. the device has NOT been force-logged-out. Backs the client's +// periodic session-validity poll: near-instant remote logout without a push channel +// (access token is a stateless JWT, so we can't see revocation on normal requests). +func (s *Store) HasActiveSession(ctx context.Context, userID, deviceID int64) (bool, error) { + var n int + if err := s.db.QueryRowContext(ctx, + `SELECT COUNT(1) FROM sessions WHERE user_id=? AND device_id=? AND revoked_at IS NULL`, + userID, deviceID).Scan(&n); err != nil { + return false, fmt.Errorf("sessions.HasActiveSession: %w", err) + } + return n > 0, nil +} + // Revoke marks the session with the given JTI revoked (logout). Idempotent. func (s *Store) Revoke(ctx context.Context, jti string) error { now := time.Now().UTC() diff --git a/server/internal/store/sqlite_stores_test.go b/server/internal/store/sqlite_stores_test.go index 4d65c02..ca1e105 100644 --- a/server/internal/store/sqlite_stores_test.go +++ b/server/internal/store/sqlite_stores_test.go @@ -12,6 +12,7 @@ import ( "github.com/wangjia/pangolin/server/internal/nodes" agentv1 "github.com/wangjia/pangolin/server/internal/pb/agentv1" "github.com/wangjia/pangolin/server/internal/provision" + "github.com/wangjia/pangolin/server/internal/sessions" "github.com/wangjia/pangolin/server/internal/store" "github.com/wangjia/pangolin/server/internal/usage" ) @@ -57,6 +58,43 @@ func TestSQLite_UsageAccumulate(t *testing.T) { } } +// HasActiveSession 是「近实时远程下线」的服务端判据:有非吊销会话=在线, +// 强制退出(RevokeByDevice)后=离线 → 客户端轮询到即登出。 +func TestSQLite_SessionHasActiveSession(t *testing.T) { + ctx := context.Background() + db := openSQLite(t) + // FK 前置:user + device。 + res, err := db.ExecContext(ctx, + `INSERT INTO users (uuid, email, pw_hash, dp_uuid) VALUES ('u-1','a@b.c','h','dp-1')`) + if err != nil { + t.Fatalf("user: %v", err) + } + uid, _ := res.LastInsertId() + res, err = db.ExecContext(ctx, + `INSERT INTO devices (uuid, user_id, name, platform) VALUES ('d-1', ?, 'Mac', 'macos')`, uid) + if err != nil { + t.Fatalf("device: %v", err) + } + did, _ := res.LastInsertId() + + ss := sessions.NewStore(db) + if ok, err := ss.HasActiveSession(ctx, uid, did); err != nil || ok { + t.Fatalf("无会话应为非活跃: ok=%v err=%v", ok, err) + } + if err := ss.Create(ctx, uid, did, "jti-1", "1.2.3.4", "v1.0"); err != nil { + t.Fatalf("create: %v", err) + } + if ok, err := ss.HasActiveSession(ctx, uid, did); err != nil || !ok { + t.Fatalf("建会话后应活跃: ok=%v err=%v", ok, err) + } + if _, err := ss.RevokeByDevice(ctx, uid, did); err != nil { + t.Fatalf("revoke: %v", err) + } + if ok, err := ss.HasActiveSession(ctx, uid, did); err != nil || ok { + t.Fatalf("强制退出后应非活跃: ok=%v err=%v", ok, err) + } +} + func TestSQLite_NodeAccumulateUsage(t *testing.T) { ctx := context.Background() db := openSQLite(t)