后台/会话三诉求:子会话(一台设备一会话)+ 离线消息队列 + 被登出推送 + 后台唤醒层
- Req 1 子会话(iOS 多进程在用户视角=一台设备一会话,内部多条独立刷新逻辑会话):brokerclient 加 MintParams.Sub + SessionInfo.Sub + RevokeDeviceSessions(user,meta) 级联;device-session sub!="" 挂在主 device_id 之下、走 tier=clipboard 且不建第二个 device 行;handleSessionsList 按 meta 归并、隐藏 sub!=""(但保留“仅控件会话存活”的设备,不简单丢弃);revokeDevice 改走 meta 级联(移除设备连带吊控件子会话)。iOS provisionWidgetSessionIfNeeded 改用主 device_id + sub="widget"(弃用独立 dev_widget),控件令牌仍隔离持有、独立刷新——不碰引擎主会话,#7 隔离不变。蓝本 auth/docs/子会话方案.md(cdrop 提案 + Broker 评审接受 + cdrop 确认 6 点:用 sub、R1 cdrop 归并、scope 复用 tier=clipboard、级联 DELETE …?meta=)。 - Req 2a 离线消息队列:新增 pending_messages 表(0001_init + sqlc 查询);message.go 收件设备离线即入队(无论是否配推送都入队,恒 202),修“离线消息只随推送横幅一闪、不入收件列表”;GET /api/messages/pending 取即删(DELETE..RETURNING,单次投递);web hub.ts onOpen 每次 SSE 连接 / 重连即拉取补收、逐条 addMessage(全端受益,iOS 经桥推原生 + 累积未读);复用 login-request reaper 清 TTL。 - Req 3 被登出推送:push 加 KindSessionRevoked + 本地化文案,apns/web 双通道;revokeDevice 加 notifyRevoked 参(跨端 revoke=true、自登出=false),跨端移除时推送告知被踢设备;iOS AppDelegate 收 session:revoked 即清 Keychain 主会话 + 控件会话、发 .cdropSessionRevoked,前台经 AppRoot 即时回登录页、关闭态下次启动即登出。 - #6 后台唤醒层:apns apsEnvelope 加 content-available:1(服务端有消息时既弹可点横幅又短暂后台唤醒);iOS DeviceItem 加 Codable、presence 快照持久化(冷启即时显示设备列表,缓解“长时间重连”观感,SSE 一连即整组替换自校正);控件会话回前台补铸(scenePhase active)+ content-available 唤醒时刷新隔离的控件会话(剪贴板保活,绝不碰引擎主会话以免 #7 回归)。 - 测试:qr_test mock broker 加 sub 幂等键 + 级联吊销端点;bootstrap_test 期望表集加 pending_messages。
This commit is contained in:
@@ -28,6 +28,12 @@ type deviceSessionReq struct {
|
||||
DeviceID string `json:"device_id"`
|
||||
DeviceName string `json:"device_name"`
|
||||
DeviceType string `json:"device_type"` // browser | macos | windows | linux | ios
|
||||
// Sub, when non-empty, mints a subordinate session under the SAME device (DeviceID is the
|
||||
// main device's id) instead of a new device: it shares the device identity (one device in
|
||||
// every list) but holds its own independently-refreshed tokens. cdrop uses "widget" for the
|
||||
// clipboard control / home-screen widget extension (separate OS process), scoped to clipboard
|
||||
// only. Requires a non-empty DeviceID (the main device to attach to).
|
||||
Sub string `json:"sub"`
|
||||
}
|
||||
|
||||
type deviceSessionResp struct {
|
||||
@@ -62,8 +68,20 @@ func (s *Server) handleDeviceSession(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
// Sub != "" mints a subordinate session under an existing device (DeviceID is the main
|
||||
// device's id), not a new device. It must attach to a concrete device_id (no auto-gen).
|
||||
sub := strings.TrimSpace(req.Sub)
|
||||
if sub != "" && !validSub(sub) {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid sub"})
|
||||
return
|
||||
}
|
||||
|
||||
deviceID := strings.TrimSpace(req.DeviceID)
|
||||
if deviceID == "" {
|
||||
if sub != "" {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "sub requires device_id"})
|
||||
return
|
||||
}
|
||||
var err error
|
||||
if deviceID, err = newDeviceID(); err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "id gen"})
|
||||
@@ -81,12 +99,16 @@ func (s *Server) handleDeviceSession(w http.ResponseWriter, r *http.Request) {
|
||||
deviceType := qrDeviceType(req.DeviceType)
|
||||
|
||||
// Mint at the caller's current trust tier: an SSO / device-authorize login is full, a
|
||||
// restricted guest stays guest. This stops a borrowed (guest) browser from minting
|
||||
// itself a full device session.
|
||||
// restricted guest stays guest. This stops a borrowed (guest) browser from minting itself a
|
||||
// full device session. A subordinate session instead carries a reduced capability scope
|
||||
// (clipboard) — the widget extension can only read/write the clipboard, not act as the device.
|
||||
tier := "full"
|
||||
if claims.Guest() {
|
||||
tier = "guest"
|
||||
}
|
||||
if sub != "" {
|
||||
tier = "clipboard"
|
||||
}
|
||||
accessTTL, refreshTTL := s.tierTTLs(tier)
|
||||
|
||||
sess, err := s.broker.MintSession(r.Context(), brokerclient.MintParams{
|
||||
@@ -97,6 +119,7 @@ func (s *Server) handleDeviceSession(w http.ResponseWriter, r *http.Request) {
|
||||
Sliding: true,
|
||||
Label: deviceName,
|
||||
Meta: deviceID,
|
||||
Sub: sub,
|
||||
})
|
||||
if err != nil {
|
||||
slog.Error("device-session mint failed", "err", err, "user", claims.UserID)
|
||||
@@ -105,19 +128,24 @@ func (s *Server) handleDeviceSession(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
now := time.Now().Unix()
|
||||
if err := s.queries.CreateDevice(r.Context(), db.CreateDeviceParams{
|
||||
DeviceID: deviceID,
|
||||
UserID: claims.UserID,
|
||||
Name: deviceName,
|
||||
Type: deviceType,
|
||||
Tier: tier,
|
||||
BrokerSid: sess.SID,
|
||||
CreatedAt: now,
|
||||
LastSeen: now,
|
||||
}); err != nil {
|
||||
// The session is minted and usable; a failed cache-row write only costs the local
|
||||
// type/presence overlay, so proceed rather than strand the device without tokens.
|
||||
slog.Error("device-session cache write failed", "err", err, "user", claims.UserID, "device", deviceID)
|
||||
// A subordinate session shares the main device's row — do NOT create a second device row
|
||||
// (it would collide on the device_id PK / surface as a duplicate device). The main device's
|
||||
// row already represents this device in every list; the sub is revoked via the meta cascade.
|
||||
if sub == "" {
|
||||
if err := s.queries.CreateDevice(r.Context(), db.CreateDeviceParams{
|
||||
DeviceID: deviceID,
|
||||
UserID: claims.UserID,
|
||||
Name: deviceName,
|
||||
Type: deviceType,
|
||||
Tier: tier,
|
||||
BrokerSid: sess.SID,
|
||||
CreatedAt: now,
|
||||
LastSeen: now,
|
||||
}); err != nil {
|
||||
// The session is minted and usable; a failed cache-row write only costs the local
|
||||
// type/presence overlay, so proceed rather than strand the device without tokens.
|
||||
slog.Error("device-session cache write failed", "err", err, "user", claims.UserID, "device", deviceID)
|
||||
}
|
||||
}
|
||||
|
||||
name := claims.Name
|
||||
@@ -140,6 +168,23 @@ func (s *Server) handleDeviceSession(w http.ResponseWriter, r *http.Request) {
|
||||
})
|
||||
}
|
||||
|
||||
// validSub accepts a subordinate-session discriminator: a short [a-z0-9_-] token (broker-safe,
|
||||
// control-byte-free). Today cdrop only mints "widget" (clipboard control / home-screen widget);
|
||||
// the format check reserves room for future extension processes without re-validating per value.
|
||||
func validSub(sub string) bool {
|
||||
if len(sub) == 0 || len(sub) > 32 {
|
||||
return false
|
||||
}
|
||||
for _, c := range sub {
|
||||
switch {
|
||||
case c >= 'a' && c <= 'z', c >= '0' && c <= '9', c == '_', c == '-':
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// validDeviceID accepts a cdrop device_id: the "dev_" prefix plus pure [A-Za-z0-9_-], capped
|
||||
// in length. This both recognises cdrop's own ids (newDeviceID) and guarantees the value is
|
||||
// control-byte-free, so it is safe to pass to the broker as meta (echoed into X-Auth-Meta).
|
||||
|
||||
@@ -58,7 +58,7 @@ func (s *Server) handleDeleteDevice(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "missing device id"})
|
||||
return
|
||||
}
|
||||
status, ok := s.revokeDevice(r, claims.UserID, deviceID)
|
||||
status, ok := s.revokeDevice(r, claims.UserID, deviceID, true)
|
||||
if !ok {
|
||||
writeJSON(w, status, map[string]string{"error": revokeErrorMsg(status)})
|
||||
return
|
||||
|
||||
+77
-14
@@ -2,16 +2,25 @@ package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"commilitia.net/cdrop/internal/db"
|
||||
"commilitia.net/cdrop/internal/hub"
|
||||
"commilitia.net/cdrop/internal/jwtauth"
|
||||
"commilitia.net/cdrop/internal/push"
|
||||
)
|
||||
|
||||
// pendingMessageTTL bounds how long an offline message waits in the queue before the
|
||||
// reaper drops it. A day matches the push TTL — past that the message is stale anyway.
|
||||
const pendingMessageTTL = 24 * 60 * 60
|
||||
|
||||
// 4 KB caps DoS-via-paste; longer payloads should use file transfer instead.
|
||||
const maxMessageBytes = 4 * 1024
|
||||
|
||||
@@ -79,26 +88,80 @@ func (s *Server) handleMessage(w http.ResponseWriter, r *http.Request) {
|
||||
},
|
||||
})
|
||||
if !delivered {
|
||||
// Peer's page is closed (no live SSE). The message has no DB row, so the
|
||||
// only delivery left is a push notification (Web Push or APNs) carrying
|
||||
// the text itself. If any push channel is enabled and may have a
|
||||
// subscription, send and report 202; otherwise the message is truly gone.
|
||||
// 收件设备页面 / app 关闭(无活 SSE):把消息入离线队列,待其唤醒 / 回前台经
|
||||
// GET /api/messages/pending 取走入库并累积未读——无论是否配推送都入队,故消息不再「只随
|
||||
// 推送横幅一闪而过、不入收件列表」。同时发推送唤醒(横幅即时可见)。返回 202(已受理、离线投递)。
|
||||
sentAt := time.Now().Unix()
|
||||
if err := s.queries.InsertPendingMessage(r.Context(), db.InsertPendingMessageParams{
|
||||
ID: newMessageID(),
|
||||
UserID: claims.UserID,
|
||||
ToDevice: req.To,
|
||||
FromDevice: from,
|
||||
Text: req.Text,
|
||||
SentAt: sentAt,
|
||||
CreatedAt: sentAt,
|
||||
ExpiresAt: sentAt + pendingMessageTTL,
|
||||
}); err != nil {
|
||||
slog.Error("queue offline message failed", "err", err, "user", claims.UserID, "to", req.To)
|
||||
}
|
||||
n := push.Notification{
|
||||
Type: push.KindMessage,
|
||||
Params: map[string]string{"sender": from, "text": req.Text},
|
||||
}
|
||||
if s.push.Enabled() || s.apns.Enabled() {
|
||||
if s.push.Enabled() {
|
||||
go s.push.Notify(context.Background(), claims.UserID, req.To, n)
|
||||
}
|
||||
if s.apns.Enabled() {
|
||||
go s.apns.Notify(context.Background(), claims.UserID, req.To, n)
|
||||
}
|
||||
w.WriteHeader(http.StatusAccepted)
|
||||
return
|
||||
if s.push.Enabled() {
|
||||
go s.push.Notify(context.Background(), claims.UserID, req.To, n)
|
||||
}
|
||||
writeJSON(w, http.StatusGone, map[string]string{"error": "peer offline"})
|
||||
if s.apns.Enabled() {
|
||||
go s.apns.Notify(context.Background(), claims.UserID, req.To, n)
|
||||
}
|
||||
w.WriteHeader(http.StatusAccepted)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// newMessageID returns a random opaque id for a queued message so the client can dedup it
|
||||
// against the live SSE path (which assigns its own ids).
|
||||
func newMessageID() string {
|
||||
var b [16]byte
|
||||
if _, err := rand.Read(b[:]); err != nil {
|
||||
// crypto/rand only fails if the OS RNG is broken; panicking is correct.
|
||||
panic("crypto/rand: " + err.Error())
|
||||
}
|
||||
return hex.EncodeToString(b[:])
|
||||
}
|
||||
|
||||
type pendingMessageWire struct {
|
||||
ID string `json:"id"`
|
||||
From string `json:"from"`
|
||||
Text string `json:"text"`
|
||||
SentAt int64 `json:"sent_at"`
|
||||
}
|
||||
|
||||
// handlePendingMessages delivers (once) the messages queued for this device while it was
|
||||
// offline, then deletes them (DELETE...RETURNING — at-most-once). The device polls this on wake
|
||||
// / foreground, saves them locally, and accrues unread. Returns [] when none. Guests included
|
||||
// (messaging is allowed for guest sessions). A device with no managed name gets [].
|
||||
func (s *Server) handlePendingMessages(w http.ResponseWriter, r *http.Request) {
|
||||
claims, _ := jwtauth.ClaimsFromContext(r.Context())
|
||||
device, _ := jwtauth.DeviceNameFromContext(r.Context())
|
||||
if device == "" {
|
||||
writeJSON(w, http.StatusOK, []pendingMessageWire{})
|
||||
return
|
||||
}
|
||||
rows, err := s.queries.PopPendingMessages(r.Context(), db.PopPendingMessagesParams{
|
||||
UserID: claims.UserID,
|
||||
ToDevice: device,
|
||||
})
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "db"})
|
||||
return
|
||||
}
|
||||
// DELETE...RETURNING order is unspecified; present oldest-first for natural chat order.
|
||||
sort.Slice(rows, func(i, j int) bool { return rows[i].SentAt < rows[j].SentAt })
|
||||
out := make([]pendingMessageWire, 0, len(rows))
|
||||
for _, m := range rows {
|
||||
out = append(out, pendingMessageWire{ID: m.ID, From: m.FromDevice, Text: m.Text, SentAt: m.SentAt})
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
||||
@@ -35,8 +35,8 @@ type mockBrokerState struct {
|
||||
}
|
||||
|
||||
type mockSession struct {
|
||||
sid, userID, app, meta, label, scope string
|
||||
createdAt, lastUsedAt int64
|
||||
sid, userID, app, meta, sub, label, scope string
|
||||
createdAt, lastUsedAt int64
|
||||
}
|
||||
|
||||
// newMockBroker stands in for the Auth Broker's internal API: POST /internal/sessions
|
||||
@@ -67,7 +67,7 @@ func newMockBroker(t *testing.T) (*brokerclient.Client, *mockBrokerState) {
|
||||
sid := ""
|
||||
if meta != "" {
|
||||
for _, sess := range st.sessions {
|
||||
if !st.revoked[sess.sid] && sess.userID == userID && sess.app == app && sess.meta == meta {
|
||||
if !st.revoked[sess.sid] && sess.userID == userID && sess.app == app && sess.meta == meta && sess.sub == str(body, "sub") {
|
||||
sid = sess.sid
|
||||
break
|
||||
}
|
||||
@@ -81,7 +81,7 @@ func newMockBroker(t *testing.T) (*brokerclient.Client, *mockBrokerState) {
|
||||
if existing, ok := st.sessions[sid]; ok {
|
||||
created = existing.createdAt // rotation preserves CreatedAt
|
||||
}
|
||||
st.sessions[sid] = &mockSession{sid: sid, userID: userID, app: app, meta: meta, label: label, scope: scope, createdAt: created, lastUsedAt: now}
|
||||
st.sessions[sid] = &mockSession{sid: sid, userID: userID, app: app, meta: meta, sub: str(body, "sub"), label: label, scope: scope, createdAt: created, lastUsedAt: now}
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"id": sid, "app": "cdrop",
|
||||
"access": "acc-" + sid, "refresh": "rtk-" + sid,
|
||||
@@ -101,12 +101,24 @@ func newMockBroker(t *testing.T) (*brokerclient.Client, *mockBrokerState) {
|
||||
continue
|
||||
}
|
||||
out = append(out, map[string]any{
|
||||
"id": sess.sid, "scope": sess.scope, "label": sess.label, "meta": sess.meta,
|
||||
"id": sess.sid, "sub": sess.sub, "scope": sess.scope, "label": sess.label, "meta": sess.meta,
|
||||
"created_at": sess.createdAt, "last_used_at": sess.lastUsedAt,
|
||||
"expires_at": time.Now().Add(24 * time.Hour).Unix(),
|
||||
})
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"sessions": out})
|
||||
case r.Method == http.MethodDelete && r.URL.Path == "/internal/sessions":
|
||||
q := r.URL.Query()
|
||||
st.lastRevokeApp = r.Header.Get("X-Broker-App")
|
||||
revoked := 0
|
||||
for _, sess := range st.sessions {
|
||||
if st.revoked[sess.sid] || sess.userID != q.Get("user_id") || sess.app != q.Get("app") || sess.meta != q.Get("meta") {
|
||||
continue
|
||||
}
|
||||
st.revoked[sess.sid] = true
|
||||
revoked += 1
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"revoked": revoked})
|
||||
case r.Method == http.MethodDelete && strings.HasPrefix(r.URL.Path, "/internal/sessions/"):
|
||||
st.revoked[strings.TrimPrefix(r.URL.Path, "/internal/sessions/")] = true
|
||||
st.lastRevokeApp = r.Header.Get("X-Broker-App")
|
||||
|
||||
@@ -147,6 +147,8 @@ func (s *Server) routes() {
|
||||
r.Get("/hub/events", s.handleEvents)
|
||||
r.Post("/hub/signal", s.handleSignal)
|
||||
r.Post("/message", s.handleMessage)
|
||||
// 离线消息取件:设备唤醒 / 回前台时取走离线期间入队的消息(取即删),入库 + 累积未读。
|
||||
r.Get("/messages/pending", s.handlePendingMessages)
|
||||
r.Get("/devices", s.handleDevices)
|
||||
r.Get("/push/vapid-key", s.handlePushVAPIDKey)
|
||||
r.Post("/push/subscribe", s.handlePushSubscribe)
|
||||
|
||||
@@ -68,11 +68,16 @@ func RunLoginRequestReaper(ctx context.Context, q *db.Queries) {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
if n, err := q.DeleteExpiredLoginRequests(ctx, time.Now().Unix()); err != nil {
|
||||
now := time.Now().Unix()
|
||||
if n, err := q.DeleteExpiredLoginRequests(ctx, now); err != nil {
|
||||
slog.Warn("login request reaper failed", "err", err)
|
||||
} else if n > 0 {
|
||||
slog.Info("login requests reaped", "count", n)
|
||||
}
|
||||
// 顺带清陈旧未取走的离线消息(同 1h 节律,复用本 goroutine)。
|
||||
if err := q.DeleteExpiredPendingMessages(ctx, now); err != nil {
|
||||
slog.Warn("pending message reaper failed", "err", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +1,16 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
"commilitia.net/cdrop/internal/brokerclient"
|
||||
"commilitia.net/cdrop/internal/db"
|
||||
"commilitia.net/cdrop/internal/jwtauth"
|
||||
"commilitia.net/cdrop/internal/push"
|
||||
)
|
||||
|
||||
// Session management. After the unified-session-model rework, every logged-in client —
|
||||
@@ -82,19 +85,33 @@ func (s *Server) handleSessionsList(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
}
|
||||
|
||||
out := make([]sessionView, 0, len(sessions))
|
||||
// 按 meta 归并:一台设备(meta)只呈现一条。子会话(sub!="",如控件剪贴板会话)与主会话共享 meta
|
||||
// ——优先用主会话作代表;但若某设备只剩子会话存活(主会话已过期、控件会话仍独立刷新着),仍按该
|
||||
// meta 呈现一台,故不能简单丢弃 sub!="" 行(否则“仅控件存活”的设备会从列表消失,见 auth/docs/
|
||||
// 子会话方案.md §四)。meta-less 会话是非 cdrop 托管的机器会话(桌面 device-authorize bootstrap,
|
||||
// 随即被代铸替换),无 device_id、不是托管设备,跳过。
|
||||
rep := make(map[string]brokerclient.SessionInfo, len(sessions))
|
||||
order := make([]string, 0, len(sessions))
|
||||
for _, sess := range sessions {
|
||||
// A meta-less session is a non-cdrop-managed machine session — a desktop
|
||||
// device-authorize bootstrap that the desktop replaces via 代铸 right away. It has
|
||||
// no device_id, so it isn't a managed device and must not show as a phantom row.
|
||||
if sess.Meta == "" {
|
||||
continue
|
||||
}
|
||||
typ := typeByID[sess.Meta]
|
||||
if cur, ok := rep[sess.Meta]; !ok {
|
||||
rep[sess.Meta] = sess
|
||||
order = append(order, sess.Meta)
|
||||
} else if cur.Sub != "" && sess.Sub == "" {
|
||||
rep[sess.Meta] = sess // 主会话优先覆盖先到的子会话,作该设备的代表
|
||||
}
|
||||
}
|
||||
|
||||
out := make([]sessionView, 0, len(order))
|
||||
for _, meta := range order {
|
||||
sess := rep[meta]
|
||||
typ := typeByID[meta]
|
||||
if typ == "" {
|
||||
typ = "browser"
|
||||
}
|
||||
name := nameByID[sess.Meta]
|
||||
name := nameByID[meta]
|
||||
if name == "" {
|
||||
name = sess.Label
|
||||
}
|
||||
@@ -103,13 +120,13 @@ func (s *Server) handleSessionsList(w http.ResponseWriter, r *http.Request) {
|
||||
scope = "guest"
|
||||
}
|
||||
out = append(out, sessionView{
|
||||
ID: sess.Meta,
|
||||
DeviceID: sess.Meta,
|
||||
ID: meta,
|
||||
DeviceID: meta,
|
||||
DeviceName: name,
|
||||
Kind: typ,
|
||||
Scope: scope,
|
||||
Current: sess.Meta == claims.DeviceID,
|
||||
Online: s.hub.Online(claims.UserID, sess.Meta),
|
||||
Current: meta == claims.DeviceID,
|
||||
Online: s.hub.Online(claims.UserID, meta),
|
||||
CreatedAt: sess.CreatedAt,
|
||||
LastUsedAt: sess.LastUsedAt,
|
||||
})
|
||||
@@ -127,7 +144,7 @@ func (s *Server) handleSessionRevoke(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "missing id"})
|
||||
return
|
||||
}
|
||||
status, ok := s.revokeDevice(r, claims.UserID, id)
|
||||
status, ok := s.revokeDevice(r, claims.UserID, id, true)
|
||||
if !ok {
|
||||
writeJSON(w, status, map[string]string{"error": revokeErrorMsg(status)})
|
||||
return
|
||||
@@ -141,63 +158,62 @@ func (s *Server) handleSessionRevoke(w http.ResponseWriter, r *http.Request) {
|
||||
// (they are the same operation). The broker session id is resolved cache-first (the local row
|
||||
// holds the stable broker_sid) and falls back to R1 — the authoritative list — so a missing or
|
||||
// pruned cache row still revokes correctly and stays authorized to this user.
|
||||
func (s *Server) revokeDevice(r *http.Request, userID, deviceID string) (int, bool) {
|
||||
sid, name := "", ""
|
||||
func (s *Server) revokeDevice(r *http.Request, userID, deviceID string, notifyRevoked bool) (int, bool) {
|
||||
// Resolve the device name (for the live SSE kick + the cross-device revoke push). Cache-first
|
||||
// (the local row holds the live name, which a decoupled rename keeps current); fall back to the
|
||||
// broker R1 label for a row-less session.
|
||||
name := ""
|
||||
localRowOwned := false
|
||||
if dev, err := s.queries.GetDevice(r.Context(), deviceID); err == nil && dev.UserID == userID {
|
||||
sid = dev.BrokerSid
|
||||
name = dev.Name
|
||||
localRowOwned = true
|
||||
}
|
||||
if sid == "" {
|
||||
sessions, err := s.broker.ListSessions(r.Context(), userID)
|
||||
if err != nil {
|
||||
slog.Error("revoke: list sessions failed", "err", err, "user", userID)
|
||||
return http.StatusBadGateway, false
|
||||
}
|
||||
for _, sess := range sessions {
|
||||
if sess.Meta == deviceID {
|
||||
sid = sess.SID
|
||||
name = sess.Label
|
||||
break
|
||||
if name == "" {
|
||||
if sessions, err := s.broker.ListSessions(r.Context(), userID); err == nil {
|
||||
for _, sess := range sessions {
|
||||
if sess.Meta == deviceID {
|
||||
name = sess.Label
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if sid == "" {
|
||||
// No broker session for this device_id. If we still own a local cache row, it is a stale /
|
||||
// phantom entry — a synthetic test device (the Diag residue) or a row whose broker session
|
||||
// is long gone. Drop the local row + kick + republish so the user can always clear such a
|
||||
// device from their list; only a device_id we own nothing for is a genuine 404.
|
||||
if !localRowOwned {
|
||||
return http.StatusNotFound, false
|
||||
}
|
||||
if _, err := s.queries.DeleteDevice(r.Context(), db.DeleteDeviceParams{
|
||||
DeviceID: deviceID,
|
||||
UserID: userID,
|
||||
}); err != nil {
|
||||
slog.Warn("delete phantom device cache failed", "err", err, "user", userID, "device", deviceID)
|
||||
}
|
||||
s.hub.Kick(userID, deviceID, name)
|
||||
s.hub.PublishPresence(r.Context(), userID)
|
||||
return http.StatusNoContent, true
|
||||
}
|
||||
// Revoke the broker session first so the device can't refresh; a 404 (already gone) is
|
||||
// idempotent success inside RevokeSession.
|
||||
if err := s.broker.RevokeSession(r.Context(), sid); err != nil {
|
||||
slog.Error("broker revoke failed", "err", err, "user", userID, "sid", sid)
|
||||
|
||||
// Cascade-revoke the whole device by meta: the main session AND any subordinate (clipboard
|
||||
// widget) sessions sharing this device_id, so no orphan sub-session survives to keep reading
|
||||
// the clipboard. Idempotent — revoked:0 when the device's sessions are already gone.
|
||||
revoked, err := s.broker.RevokeDeviceSessions(r.Context(), userID, deviceID)
|
||||
if err != nil {
|
||||
slog.Error("broker cascade revoke failed", "err", err, "user", userID, "meta", deviceID)
|
||||
return http.StatusBadGateway, false
|
||||
}
|
||||
// Nothing revoked and we own no local row → a device_id we have nothing for is a genuine 404.
|
||||
// (A phantom row with no broker session still owns a local row, so it falls through to cleanup
|
||||
// below — the user can always clear such a stale entry from their list.)
|
||||
if revoked == 0 && !localRowOwned {
|
||||
return http.StatusNotFound, false
|
||||
}
|
||||
|
||||
// 跨设备登出(非自登出):推送告知被踢设备,使其立即知晓并清本地登录态——即便其页面 / app 已关闭,
|
||||
// 也不必等下次请求 401 才发现。用一次性 context(请求 ctx 会随响应取消),best-effort 异步发。
|
||||
if notifyRevoked && name != "" {
|
||||
n := push.Notification{Type: push.KindSessionRevoked, Tag: "session:revoked"}
|
||||
if s.push.Enabled() {
|
||||
go s.push.Notify(context.Background(), userID, name, n)
|
||||
}
|
||||
if s.apns.Enabled() {
|
||||
go s.apns.Notify(context.Background(), userID, name, n)
|
||||
}
|
||||
}
|
||||
// Drop the local cache row (idempotent; non-fatal — the sweeper / next list-prune also clean it).
|
||||
if _, err := s.queries.DeleteDevice(r.Context(), db.DeleteDeviceParams{
|
||||
DeviceID: deviceID,
|
||||
UserID: userID,
|
||||
}); err != nil {
|
||||
// The session is already revoked; a failed cache delete is non-fatal (the sweeper
|
||||
// and the next list-prune clean it). Report success so the client sees the logout.
|
||||
slog.Warn("delete device cache failed", "err", err, "user", userID, "device", deviceID)
|
||||
}
|
||||
// Kick by the stable device_id (the hub key); name rides along for the code-less fallback
|
||||
// path inside Kick. This makes cross-device revoke land reliably (the prior name-keyed Kick
|
||||
// could miss a renamed device, leaving it able to keep refreshing — the "移除失败" symptom).
|
||||
// Kick by the stable device_id (the hub key); name rides along for the code-less fallback path
|
||||
// inside Kick, so a renamed device is still kicked reliably (the prior "移除失败" symptom).
|
||||
s.hub.Kick(userID, deviceID, name)
|
||||
s.hub.PublishPresence(r.Context(), userID)
|
||||
return http.StatusNoContent, true
|
||||
@@ -214,7 +230,7 @@ func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
claims, _ := jwtauth.ClaimsFromContext(r.Context())
|
||||
if claims.DeviceID != "" {
|
||||
if status, ok := s.revokeDevice(r, claims.UserID, claims.DeviceID); !ok && status != http.StatusNotFound {
|
||||
if status, ok := s.revokeDevice(r, claims.UserID, claims.DeviceID, false); !ok && status != http.StatusNotFound {
|
||||
slog.Warn("logout revoke failed", "status", status, "user", claims.UserID)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user