后台/会话三诉求:子会话(一台设备一会话)+ 离线消息队列 + 被登出推送 + 后台唤醒层

- 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:
2026-06-27 17:42:53 +08:00
parent 1b94df1604
commit a2cad11224
23 changed files with 790 additions and 105 deletions
+9 -2
View File
@@ -54,6 +54,12 @@ type apsPayload struct {
type apsEnvelope struct {
Alert apsAlert `json:"alert"`
Sound string `json:"sound"`
// ContentAvailable=1 gives the app a brief background wake (in addition to the
// visible banner) so it can warm up — refresh the isolated widget/clipboard
// session, re-establish state — without the user tapping. iOS rate-limits these,
// and they ride the existing offline alert (push-type stays "alert"), so a server
// message is the only trigger. The app never holds a persistent connection.
ContentAvailable int `json:"content-available,omitempty"`
}
type apsAlert struct {
@@ -171,8 +177,9 @@ func (s *Sender) Notify(ctx context.Context, userID, deviceName string, n push.N
}
payload := apsPayload{
APS: apsEnvelope{
Alert: apsAlert{Title: title, Body: body},
Sound: "default",
Alert: apsAlert{Title: title, Body: body},
Sound: "default",
ContentAvailable: 1,
},
Type: n.Type,
URL: url,
+34 -3
View File
@@ -57,6 +57,11 @@ type MintParams struct {
Sliding bool
Label string
Meta string
// Sub is the intra-device session discriminator under one Meta (device): "" = the main
// session, a non-empty value (e.g. "widget") a subordinate session that shares the device
// identity but holds its own independently-refreshed tokens. The broker keys R2 idempotency
// on (user, app, meta, sub), so a sub session coexists with the main instead of rotating it.
Sub string
}
// Session is a freshly minted delegated session. SID is the broker's session id —
@@ -78,6 +83,7 @@ type mintReqWire struct {
Sliding bool `json:"sliding,omitempty"`
Label string `json:"label,omitempty"`
Meta string `json:"meta,omitempty"`
Sub string `json:"sub,omitempty"`
}
type sessionWire struct {
@@ -94,7 +100,7 @@ func (c *Client) MintSession(ctx context.Context, p MintParams) (Session, error)
body := mintReqWire{
UserID: p.UserID, App: c.app, Tier: p.Tier,
AccessTTL: p.AccessTTL, RefreshTTL: p.RefreshTTL, Sliding: p.Sliding,
Label: p.Label, Meta: p.Meta,
Label: p.Label, Meta: p.Meta, Sub: p.Sub,
}
headers := map[string]string{"X-Internal-Key": c.internalKey}
var out sessionWire
@@ -123,6 +129,29 @@ func (c *Client) RevokeSession(ctx context.Context, sid string) error {
return err
}
// RevokeDeviceSessions cascade-revokes every session under one device meta — the main session
// and any subordinate (e.g. clipboard widget) sessions sharing that device
// (DELETE /internal/sessions?user_id=&app=&meta=). cdrop calls this when removing a device or
// logging it out, so no orphan sub-session survives to keep reading the clipboard. Returns the
// count revoked; revoked:0 (nothing to revoke) is idempotent success, not an error.
func (c *Client) RevokeDeviceSessions(ctx context.Context, userID, meta string) (int, error) {
q := url.Values{"user_id": {userID}, "app": {c.app}, "meta": {meta}}
headers := map[string]string{
"X-Internal-Key": c.internalKey,
"X-Broker-App": c.app,
}
var out struct {
Revoked int `json:"revoked"`
}
// The cascade endpoint always returns 200 {revoked:N} (revoked:0 when nothing matched), never
// 404 — so a 404 here means the endpoint is absent (a broker predating sub support) and must
// surface as an error rather than masquerade as success and silently leak the session.
if err := c.do(ctx, http.MethodDelete, "/internal/sessions?"+q.Encode(), headers, nil, http.StatusOK, &out); err != nil {
return 0, err
}
return out.Revoked, nil
}
// Refreshed is the result of rolling a session's access token. The broker rotates
// the refresh credential, so the old one is now dead and the new one must be stored.
type Refreshed struct {
@@ -156,7 +185,8 @@ func (c *Client) RefreshSession(ctx context.Context, refresh string) (Refreshed,
// (the session<->device join key). The broker returns only kind==machine sessions for this
// app and never includes credentials.
type SessionInfo struct {
SID string
SID string
Sub string // intra-device discriminator: "" = main; non-empty = subordinate (cdrop hides it)
Scope string
Label string
Meta string
@@ -167,6 +197,7 @@ type SessionInfo struct {
type sessionInfoWire struct {
ID string `json:"id"`
Sub string `json:"sub"`
Scope string `json:"scope"`
Label string `json:"label"`
Meta string `json:"meta"`
@@ -192,7 +223,7 @@ func (c *Client) ListSessions(ctx context.Context, userID string) ([]SessionInfo
sessions := make([]SessionInfo, 0, len(out.Sessions))
for _, s := range out.Sessions {
sessions = append(sessions, SessionInfo{
SID: s.ID, Scope: s.Scope, Label: s.Label, Meta: s.Meta,
SID: s.ID, Sub: s.Sub, Scope: s.Scope, Label: s.Label, Meta: s.Meta,
CreatedAt: s.CreatedAt, LastUsedAt: s.LastUsedAt, ExpiresAt: s.ExpiresAt,
})
}
+1 -1
View File
@@ -19,7 +19,7 @@ func TestBootstrapCreatesAllTables(t *testing.T) {
t.Fatalf("bootstrap: %v", err)
}
want := []string{"clipboard_state", "devices", "login_requests", "push_subscriptions", "transfer_sessions"}
want := []string{"clipboard_state", "devices", "login_requests", "pending_messages", "push_subscriptions", "transfer_sessions"}
rows, err := d.Query("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name")
if err != nil {
t.Fatalf("query tables: %v", err)
+19
View File
@@ -94,3 +94,22 @@ CREATE TABLE IF NOT EXISTS login_requests (
);
CREATE INDEX IF NOT EXISTS idx_login_requests_expires ON login_requests (expires_at);
-- pending_messages:离线消息队列。设备间文本消息本是即时的(无 DB 行,仅经 SSE 转发);当收件
-- 设备页面 / app 关闭(无活 SSE)时,消息此前只随推送横幅一闪即逝、不入收件设备的消息列表。本表
-- 把离线消息入队,待收件设备唤醒 / 回前台经 GET /api/messages/pending 取走(单次投递:取即删,
-- DELETE...RETURNING)并累积未读。id 服务端生成,供客户端去重。按 (user_id, to_device) 取,与
-- hub.SendTo / push 一致按 device_name 定位收件设备。expires_at 短 TTLreaper 清陈旧未取走的。
CREATE TABLE IF NOT EXISTS pending_messages (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
to_device TEXT NOT NULL,
from_device TEXT NOT NULL,
text TEXT NOT NULL,
sent_at INTEGER NOT NULL,
created_at INTEGER NOT NULL,
expires_at INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_pending_messages_user_device ON pending_messages (user_id, to_device);
CREATE INDEX IF NOT EXISTS idx_pending_messages_expires ON pending_messages (expires_at);
+11
View File
@@ -42,6 +42,17 @@ type LoginRequest struct {
ApprovedAt *int64 `json:"approved_at"`
}
type PendingMessage struct {
ID string `json:"id"`
UserID string `json:"user_id"`
ToDevice string `json:"to_device"`
FromDevice string `json:"from_device"`
Text string `json:"text"`
SentAt int64 `json:"sent_at"`
CreatedAt int64 `json:"created_at"`
ExpiresAt int64 `json:"expires_at"`
}
type PushSubscription struct {
ID string `json:"id"`
UserID string `json:"user_id"`
+98
View File
@@ -0,0 +1,98 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: pending_messages.sql
package db
import (
"context"
)
const deleteExpiredPendingMessages = `-- name: DeleteExpiredPendingMessages :exec
DELETE FROM pending_messages
WHERE expires_at < ?
`
func (q *Queries) DeleteExpiredPendingMessages(ctx context.Context, expiresAt int64) error {
_, err := q.db.ExecContext(ctx, deleteExpiredPendingMessages, expiresAt)
return err
}
const insertPendingMessage = `-- name: InsertPendingMessage :exec
INSERT INTO pending_messages (id, user_id, to_device, from_device, text, sent_at, created_at, expires_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
`
type InsertPendingMessageParams struct {
ID string `json:"id"`
UserID string `json:"user_id"`
ToDevice string `json:"to_device"`
FromDevice string `json:"from_device"`
Text string `json:"text"`
SentAt int64 `json:"sent_at"`
CreatedAt int64 `json:"created_at"`
ExpiresAt int64 `json:"expires_at"`
}
// pending_messages: offline message queue. A text message to a device with no live
// SSE connection is queued here and delivered once when that device next polls.
// NOTE: keep this file pure ASCII; sqlc v1.31.1 drifts byte offsets on multibyte
// runes in query files, corrupting the generated SQL.
func (q *Queries) InsertPendingMessage(ctx context.Context, arg InsertPendingMessageParams) error {
_, err := q.db.ExecContext(ctx, insertPendingMessage,
arg.ID,
arg.UserID,
arg.ToDevice,
arg.FromDevice,
arg.Text,
arg.SentAt,
arg.CreatedAt,
arg.ExpiresAt,
)
return err
}
const popPendingMessages = `-- name: PopPendingMessages :many
DELETE FROM pending_messages
WHERE user_id = ? AND to_device = ?
RETURNING id, user_id, to_device, from_device, text, sent_at, created_at, expires_at
`
type PopPendingMessagesParams struct {
UserID string `json:"user_id"`
ToDevice string `json:"to_device"`
}
func (q *Queries) PopPendingMessages(ctx context.Context, arg PopPendingMessagesParams) ([]PendingMessage, error) {
rows, err := q.db.QueryContext(ctx, popPendingMessages, arg.UserID, arg.ToDevice)
if err != nil {
return nil, err
}
defer rows.Close()
var items []PendingMessage
for rows.Next() {
var i PendingMessage
if err := rows.Scan(
&i.ID,
&i.UserID,
&i.ToDevice,
&i.FromDevice,
&i.Text,
&i.SentAt,
&i.CreatedAt,
&i.ExpiresAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Close(); err != nil {
return nil, err
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
+17
View File
@@ -0,0 +1,17 @@
-- pending_messages: offline message queue. A text message to a device with no live
-- SSE connection is queued here and delivered once when that device next polls.
-- NOTE: keep this file pure ASCII; sqlc v1.31.1 drifts byte offsets on multibyte
-- runes in query files, corrupting the generated SQL.
-- name: InsertPendingMessage :exec
INSERT INTO pending_messages (id, user_id, to_device, from_device, text, sent_at, created_at, expires_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?);
-- name: PopPendingMessages :many
DELETE FROM pending_messages
WHERE user_id = ? AND to_device = ?
RETURNING id, user_id, to_device, from_device, text, sent_at, created_at, expires_at;
-- name: DeleteExpiredPendingMessages :exec
DELETE FROM pending_messages
WHERE expires_at < ?;
+60 -15
View File
@@ -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).
+1 -1
View File
@@ -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
View File
@@ -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)
}
+17 -5
View File
@@ -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")
+2
View File
@@ -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)
+6 -1
View File
@@ -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)
}
}
}
}
+69 -53
View File
@@ -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)
}
}
+12
View File
@@ -44,6 +44,10 @@ const (
KindTransferDone = "transfer:done"
KindTransferFailed = "transfer:failed"
KindMessage = "message"
// KindSessionRevoked tells a device it was logged out by another device (cross-device
// revoke). The client clears its local session on receipt — immediate even when its page /
// app is closed, instead of waiting for the next request to 401.
KindSessionRevoked = "session:revoked"
)
// Notification is an intent to notify; the sender localizes it per subscription.
@@ -206,18 +210,24 @@ var notifyStrings = map[string]map[string]string{
"incoming.body": "%s 发来 %s",
"done.title": "传输完成",
"failed.title": "传输失败",
"revoked.title": "已退出登录",
"revoked.body": "此设备已被其他设备移除,需重新登录",
},
"zh-TW": {
"incoming.title": "收到檔案",
"incoming.body": "%s 傳來 %s",
"done.title": "傳輸完成",
"failed.title": "傳輸失敗",
"revoked.title": "已登出",
"revoked.body": "此裝置已被其他裝置移除,需重新登入",
},
"en-US": {
"incoming.title": "Incoming file",
"incoming.body": "%s is sending %s",
"done.title": "Transfer complete",
"failed.title": "Transfer failed",
"revoked.title": "Signed out",
"revoked.body": "This device was removed by another device; sign in again",
},
}
@@ -254,6 +264,8 @@ func Localize(typ string, params map[string]string, locale string) (title, body
return t["done.title"], params["filename"]
case KindTransferFailed:
return t["failed.title"], params["filename"]
case KindSessionRevoked:
return t["revoked.title"], t["revoked.body"]
default:
return params["title"], params["body"]
}