Files
Commilitia-Drop/internal/httpapi/sessions.go
T
admin 018a77b13a 登录子系统:OIDC 统一自签 token + 吊销即时生效 + 设备并入会话列表 + 应用内扫码 + 禁则修复
接续 90a3790(扫码 A0+A1+B + step-up 雏形)。蓝本见 AUTH.md。

OIDC 统一到 cdrop 自签 token
- /auth/exchange 先 JWKS 验 id_token 签名(自签 token 的唯一信任锚)再签 cdrop
  自签 HS256 access token(绑 sid),不再把 IdP RS256 下发浏览器;验签失败仅告警
  并回退 RS256(会话仍建、下次 refresh 自愈),登录不中断
- /auth/refresh oidc 路径仍打 IdP 轮换 refresh_token + 探测 IdP 侧吊销,但同样回
  自签 token;createWebSession 改返回行 id
- verify 链保留 RS256 分支仅供桌面端 loopback(其即时吊销留后续)

吊销即时生效 + 被吊销设备自知回退
- verifySelfToken 每请求按 sid 查 web_sessions 行,行删即拒 → 吊销在被吊销设备
  下一次请求即生效(不等 TTL),oidc / self / guest 一致
- 前端仅在「服务端以 401 确证会话失效」时 forceLogout 清登录态、回登录页;短期连接
  失败(5xx / 网络)一律保留登录态(refreshTokens 改三态 refreshed/invalid/transient,
  cookieRefresh 改 discriminated 结果)
- __root 反应式守卫:prod 下失登录态且非认证路由即跳登录页;新增 auth.sessionLost.* 三语

设备列表并入会话列表 + 孤儿自动清除
- GET /api/auth/sessions 统一 web_sessions 与原生客户端设备(桌面 / iOS,自 devices
  登记表呈现,native=true,离线也列);同名不重复列出,排除 shortcut 与无会话 browser
- 吊销网页会话连带删其设备登记(无同名在用会话时);原生「登出」走
  DELETE /api/devices/{name}(同要求 step-up)
- 新增 DeleteOrphanBrowserDevices(browser 型且无存活 web_session),接入设备清扫器(1h)

应用内扫码 + 聚珍崩溃 / CJK 禁则修复
- 登录页内置 getUserMedia + jsqr 扫码,不再外跳系统应用(避免开错浏览器)
- 修聚珍(cjk-autospace)MutationObserver 与 React 重渲染同子树冲突致的 insertBefore
  崩溃:扫码 / 显码 / 批准三状态机页整页跳过聚珍(data-jz-skip)
- 修流动正文未跑 CJK 禁则(jinze 为段落级、须 opt-in):设置 / 快捷指令 / 桌面页一批
  hint 补 data-jz-level="paragraph" + justify,短标签 / 状态仍留文本级

step-up 完善
- auth_time 改可选(Casdoor 不下发,原强制致死循环);stepped_up_at 按会话绑定、
  StepUpMaxAgeSeconds 窗口内不复要求;新增 POST /api/auth/stepup
- 批准页 persist 编进 step-up returnTo 防整页跳转丢失;scope 随档绑定(信任=full /
  仅此次=guest),默认偏安全的「仅此次」

文档与测试
- AUTH.md:折中架构、accounts 薄表、令牌架构、扫码流程、step-up、§4.4 统一会话列表
- 新增 Go 测试:OIDC 自签验证、verifySelfToken 吊销即拒、会话吊销连带删设备、
  统一会话列表(含原生 / 不含 shortcut / 不重复)、孤儿清扫、删设备需 step-up
2026-06-22 11:55:02 +08:00

219 lines
7.8 KiB
Go

package httpapi
import (
"context"
"encoding/json"
"log/slog"
"net/http"
"time"
"github.com/go-chi/chi/v5"
"commilitia.net/cdrop/internal/db"
"commilitia.net/cdrop/internal/jwtauth"
)
// Session management (AUTH.md §1, §6): list the caller's logins with their
// capability level, and really revoke one (delete the row → its access token can
// no longer refresh and dies within its short TTL). Revocation is a sensitive
// action, so it requires a recent step-up. A standalone step-up endpoint lets the
// UI establish that re-auth once (per session/device) and reuse it across actions
// within the window — the same session isn't re-prompted repeatedly (#3).
type stepUpReq struct {
Code string `json:"code"`
Verifier string `json:"verifier"`
}
// handleStepUp exchanges a fresh prompt=login code and, on success, stamps the
// caller's session as stepped-up (per-session, cookie-keyed). Sensitive actions
// within StepUpMaxAgeSeconds then skip re-auth. 403 on failure; 204 when step-up
// is disabled (nothing to establish).
func (s *Server) handleStepUp(w http.ResponseWriter, r *http.Request) {
if !s.cfg.StepUpEnabled {
w.WriteHeader(http.StatusNoContent)
return
}
claims, _ := jwtauth.ClaimsFromContext(r.Context())
var body stepUpReq
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 8192)).Decode(&body); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid json"})
return
}
if !s.verifyStepUp(r, claims.UserID, body.Code, body.Verifier) {
writeJSON(w, http.StatusForbidden, map[string]string{"error": "step_up_required"})
return
}
s.recordStepUp(r)
w.WriteHeader(http.StatusNoContent)
}
type sessionView struct {
ID string `json:"id"`
DeviceName string `json:"device_name"`
Kind string `json:"kind"` // oidc | self | guest | macos | windows | linux | ios
Scope string `json:"scope"` // full | guest
Current bool `json:"current"`
Online bool `json:"online"` // device currently connected (SSE) — UI sorts online first
// Native marks a device that authenticates with an IdP token and keeps no
// web_session row (desktop / iOS). It is surfaced from the devices registry so
// the session list covers every device; its "logout" routes to the device
// endpoint rather than the web-session one.
Native bool `json:"native"`
CreatedAt int64 `json:"created_at"`
LastUsedAt int64 `json:"last_used_at"`
ExpiresAt int64 `json:"expires_at"`
}
// isNativeDeviceType reports whether a device type is a real native client (one
// that authenticates via the IdP and keeps no web_session). browser devices are
// expected to carry a web_session; "shortcut" tokens have their own panel.
func isNativeDeviceType(t string) bool {
switch t {
case "macos", "windows", "linux", "ios":
return true
default:
return false
}
}
// handleSessionsList returns the caller's login sessions with their scope, so the
// UI can show the permission level (完整 / 受限访客) and offer real logout. The list
// is unified: web_sessions (browser / scan-login) PLUS native client devices
// (desktop / iOS) that have no web_session of their own — so every logged-in
// device appears in one place and orphaned device rows fall away (AUTH.md §4).
func (s *Server) handleSessionsList(w http.ResponseWriter, r *http.Request) {
claims, _ := jwtauth.ClaimsFromContext(r.Context())
now := time.Now().Unix()
rows, err := s.queries.ListWebSessionsByUser(r.Context(), claims.UserID)
if err != nil {
slog.Error("list sessions failed", "err", err, "user", claims.UserID)
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "db"})
return
}
current := ""
if c, err := r.Cookie(sessionCookieName); err == nil && c.Value != "" {
current = sessionID(c.Value)
}
// Cookieless callers (native apps) can't match by cookie; fall back to their
// own device name to mark the "current" row.
callerDevice, _ := jwtauth.DeviceNameFromContext(r.Context())
out := make([]sessionView, 0, len(rows))
named := make(map[string]struct{}, len(rows))
for _, row := range rows {
if row.ExpiresAt < now {
continue // hide expired sessions (reaped separately)
}
if row.DeviceName != "" {
named[row.DeviceName] = struct{}{}
}
out = append(out, sessionView{
ID: row.ID,
DeviceName: row.DeviceName,
Kind: row.Kind,
Scope: row.Scope,
Current: row.ID == current || (current == "" && row.DeviceName != "" && row.DeviceName == callerDevice),
Online: row.DeviceName != "" && s.hub.Online(claims.UserID, row.DeviceName),
CreatedAt: row.CreatedAt,
LastUsedAt: row.LastUsedAt,
ExpiresAt: row.ExpiresAt,
})
}
// Native clients keep no web_session — surface them from the devices registry,
// skipping any whose name already has a web_session (no double-listing).
if devs, derr := s.queries.ListDevicesByUser(r.Context(), claims.UserID); derr == nil {
for _, d := range devs {
if !isNativeDeviceType(d.Type) {
continue
}
if _, ok := named[d.Name]; ok {
continue
}
out = append(out, sessionView{
ID: "device:" + d.Name,
DeviceName: d.Name,
Kind: d.Type,
Scope: "full",
Native: true,
Current: current == "" && d.Name != "" && d.Name == callerDevice,
Online: s.hub.Online(claims.UserID, d.Name),
CreatedAt: d.LastSeen,
LastUsedAt: d.LastSeen,
ExpiresAt: 0,
})
}
}
writeJSON(w, http.StatusOK, map[string]any{"sessions": out})
}
// deviceNameHasLiveSession reports whether the user still has a non-expired
// web_session bound to deviceName — used to avoid deleting a device that another
// live session (e.g. a re-login that left the old row) still depends on.
func (s *Server) deviceNameHasLiveSession(ctx context.Context, userID, deviceName string) bool {
rows, err := s.queries.ListWebSessionsByUser(ctx, userID)
if err != nil {
return false
}
now := time.Now().Unix()
for _, ws := range rows {
if ws.DeviceName == deviceName && ws.ExpiresAt >= now {
return true
}
}
return false
}
// handleSessionRevoke deletes a session row (scoped to its owner), really
// invalidating that login. Requires a recent step-up (403 step_up_required
// otherwise). Kicks the device's live SSE so it drops immediately.
func (s *Server) handleSessionRevoke(w http.ResponseWriter, r *http.Request) {
if s.cfg.StepUpEnabled && !s.sessionRecentlySteppedUp(r) {
writeJSON(w, http.StatusForbidden, map[string]string{"error": "step_up_required"})
return
}
claims, _ := jwtauth.ClaimsFromContext(r.Context())
id := chi.URLParam(r, "id")
if id == "" {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "missing id"})
return
}
// Read the device name before deletion so we can kick its SSE.
deviceName := ""
if sess, err := s.queries.GetWebSession(r.Context(), id); err == nil && sess.UserID == claims.UserID {
deviceName = sess.DeviceName
}
n, err := s.queries.DeleteWebSessionForUser(r.Context(), db.DeleteWebSessionForUserParams{
ID: id,
UserID: claims.UserID,
})
if err != nil {
slog.Error("revoke session failed", "err", err)
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "db"})
return
}
if n == 0 {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "not found"})
return
}
if deviceName != "" {
// Drop the device registration too, so a revoked device disappears from the
// device list at once (we no longer remove devices by hand) — unless another
// live session still uses this name.
if !s.deviceNameHasLiveSession(r.Context(), claims.UserID, deviceName) {
if _, derr := s.queries.DeleteDevice(r.Context(), db.DeleteDeviceParams{
UserID: claims.UserID,
Name: deviceName,
}); derr != nil {
slog.Warn("delete device on session revoke failed", "err", derr)
}
}
s.hub.Kick(claims.UserID, deviceName)
s.hub.PublishPresence(r.Context(), claims.UserID)
}
w.WriteHeader(http.StatusNoContent)
}