Files
Commilitia-Drop/internal/httpapi/qr.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

533 lines
18 KiB
Go

package httpapi
import (
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"encoding/json"
"errors"
"log/slog"
"net"
"net/http"
"net/url"
"strings"
"time"
"commilitia.net/cdrop/internal/db"
"commilitia.net/cdrop/internal/jwtauth"
)
// Scan-login (QR), AUTH.md §4. A new device shows a QR; an already-logged-in
// phone scans and approves it into the user's account as a restricted guest
// session. Three secrets are kept apart so the QR — which can be photographed —
// only lets someone *request* approval, never collect the session:
//
// - request_id : public handle, in the QR.
// - approval_code : in the QR; binds the authed approver to this request.
// - poll_secret : returned ONCE to the new device, never in the QR; only its
// SHA-256 is stored. The session is delivered solely on the connection that
// proves the plaintext, so a QR photographer (no poll_secret, not logged in)
// fails twice.
//
// The session row is created when the new device collects it (handleQRStatus),
// not at approve time, so the cookie secret is generated on and returned to the
// new device's own TLS connection and never travels through the phone.
// qrStatusPollWindow caps how long one status long-poll blocks before returning
// "pending" for the client to re-poll. var (not const) so tests can shrink it.
var qrStatusPollWindow = 25 * time.Second
type qrStartReq struct {
DeviceName string `json:"device_name"`
DeviceType string `json:"device_type"`
}
type qrStartResp struct {
RequestID string `json:"request_id"`
PollSecret string `json:"poll_secret"`
QRPayload string `json:"qr_payload"`
ExpiresAt int64 `json:"expires_at"`
}
type qrStatusResp struct {
Status string `json:"status"` // pending | approved | denied | expired
AccessToken string `json:"access_token,omitempty"`
ExpiresIn int `json:"expires_in,omitempty"`
User *userResp `json:"user,omitempty"`
DeviceName string `json:"device_name,omitempty"`
}
type qrRequestResp struct {
DeviceName string `json:"device_name"`
DeviceType string `json:"device_type"`
RequestIP string `json:"request_ip"`
ExpiresAt int64 `json:"expires_at"`
Status string `json:"status"`
// StepUp tells the approver UI a fresh re-auth is required before approving.
StepUp bool `json:"step_up"`
}
type qrApproveReq struct {
RequestID string `json:"request_id"`
ApprovalCode string `json:"approval_code"`
Scope string `json:"scope"` // full | guest (this milestone always guest)
Persist string `json:"persist"` // once | persist
// Step-up (when CDROP_STEP_UP_ENABLED): a fresh prompt=login PKCE code+verifier
// the backend exchanges and checks for a recent auth_time (AUTH.md §6).
StepUpCode string `json:"step_up_code"`
StepUpVerifier string `json:"step_up_verifier"`
}
type qrDenyReq struct {
RequestID string `json:"request_id"`
ApprovalCode string `json:"approval_code"`
}
// handleQRStart (public, rate-limited) opens a scan-login request for a new
// device and returns the QR payload plus the device-private poll secret.
func (s *Server) handleQRStart(w http.ResponseWriter, r *http.Request) {
if !s.cfg.QRLoginOn() {
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "scan login disabled"})
return
}
var req qrStartReq
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4096)).Decode(&req); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid json"})
return
}
deviceName := jwtauth.SanitizeDeviceName(req.DeviceName)
if deviceName == "" {
deviceName = "New device"
}
requestID, err1 := randB64(16)
approvalCode, err2 := randB64(9)
pollSecret, err3 := randB64(32)
if err := errors.Join(err1, err2, err3); err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "id gen"})
return
}
now := time.Now()
expires := now.Add(time.Duration(s.cfg.QRRequestTTLSeconds) * time.Second)
if err := s.queries.CreateLoginRequest(r.Context(), db.CreateLoginRequestParams{
ID: requestID,
PollSecret: sessionID(pollSecret), // store only the hash
ApprovalCode: approvalCode,
NewDeviceName: deviceName,
NewDeviceType: qrDeviceType(req.DeviceType),
UserAgent: truncate(r.UserAgent(), 256),
RequestIp: clientIP(r),
CreatedAt: now.Unix(),
ExpiresAt: expires.Unix(),
}); err != nil {
slog.Error("create login request failed", "err", err)
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "db"})
return
}
writeJSON(w, http.StatusOK, qrStartResp{
RequestID: requestID,
PollSecret: pollSecret,
QRPayload: s.qrPayload(r, requestID, approvalCode),
ExpiresAt: expires.Unix(),
})
}
// handleQRStatus (public, rate-limited) is the new device's long-poll. It proves
// the poll_secret, then reports pending until the request is approved/denied/
// expired. On approval it creates the session, sets the cookie on THIS response,
// mints the first access token, and marks the request consumed (single use).
func (s *Server) handleQRStatus(w http.ResponseWriter, r *http.Request) {
if !s.cfg.QRLoginOn() {
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "scan login disabled"})
return
}
requestID := r.URL.Query().Get("request_id")
pollSecret := r.Header.Get("X-Poll-Secret")
if requestID == "" || pollSecret == "" {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "missing request_id or poll secret"})
return
}
pollHash := sessionID(pollSecret)
deadline := time.Now().Add(qrStatusPollWindow)
for {
req, err := s.queries.GetLoginRequest(r.Context(), requestID)
if err != nil {
// Unknown / reaped → treat as expired without leaking existence.
writeJSON(w, http.StatusOK, qrStatusResp{Status: "expired"})
return
}
if subtle.ConstantTimeCompare([]byte(req.PollSecret), []byte(pollHash)) != 1 {
writeJSON(w, http.StatusForbidden, map[string]string{"error": "bad poll secret"})
return
}
if req.ExpiresAt < time.Now().Unix() {
writeJSON(w, http.StatusOK, qrStatusResp{Status: "expired"})
return
}
switch req.Status {
case "approved":
s.collectQRSession(w, r, req)
return
case "denied":
writeJSON(w, http.StatusOK, qrStatusResp{Status: "denied"})
return
case "consumed":
writeJSON(w, http.StatusOK, qrStatusResp{Status: "expired"})
return
default: // pending
if time.Now().After(deadline) {
writeJSON(w, http.StatusOK, qrStatusResp{Status: "pending"})
return
}
select {
case <-r.Context().Done():
return
case <-time.After(time.Second):
}
}
}
}
// collectQRSession turns an approved request into a live session for the new
// device. ConsumeLoginRequest is the single-use guard: only the poll that flips
// approved→consumed proceeds, so a duplicated/raced poll can't mint a second
// session.
func (s *Server) collectQRSession(w http.ResponseWriter, r *http.Request, req db.LoginRequest) {
n, err := s.queries.ConsumeLoginRequest(r.Context(), req.ID)
if err != nil {
slog.Error("consume login request failed", "err", err)
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "db"})
return
}
if n == 0 {
// Lost the race to another poll; the winner already has the session.
writeJSON(w, http.StatusOK, qrStatusResp{Status: "expired"})
return
}
raw, id, err := newSessionToken()
if err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "id gen"})
return
}
scope := req.GrantScope
if scope != "full" {
scope = "guest"
}
// Persistent borrows slide their window (kind self); one-time borrows are kind
// guest with a fixed short expiry that refresh never extends (AUTH.md §3.1).
now := time.Now()
kind := "guest"
exp := now.Add(time.Duration(s.cfg.QRGuestTTLSeconds) * time.Second)
if req.GrantPersist == "persist" {
kind = "self"
exp = now.Add(time.Duration(s.cfg.QRPersistTTLHours) * time.Hour)
}
if err := s.queries.CreateSelfSession(r.Context(), db.CreateSelfSessionParams{
ID: id,
UserID: req.ApproverUserID,
DeviceName: req.NewDeviceName,
UserAgent: req.UserAgent,
Kind: kind,
Scope: scope,
GrantedBy: "qr",
CreatedAt: now.Unix(),
LastUsedAt: now.Unix(),
ExpiresAt: exp.Unix(),
}); err != nil {
slog.Error("create self session failed", "err", err)
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "db"})
return
}
token, expiresIn, err := s.mintSessionToken(req.ApproverUserID, id, scope)
if err != nil {
slog.Error("mint session token failed", "err", err)
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "mint failed"})
return
}
setSessionCookie(w, raw)
user := userResp{ID: req.ApproverUserID, Name: req.ApproverUserID}
if acct, err := s.queries.GetAccount(r.Context(), req.ApproverUserID); err == nil {
if acct.DisplayName != "" {
user.Name = acct.DisplayName
}
user.Avatar = acct.AvatarUrl
}
writeJSON(w, http.StatusOK, qrStatusResp{
Status: "approved",
AccessToken: token,
ExpiresIn: expiresIn,
User: &user,
DeviceName: req.NewDeviceName,
})
}
// handleQRRequest (full session) lets the approver see what they are about to
// authorise. The approval_code (from the QR) gates the lookup, so only someone
// who scanned the code can read the request's device info.
func (s *Server) handleQRRequest(w http.ResponseWriter, r *http.Request) {
if !s.cfg.QRLoginOn() {
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "scan login disabled"})
return
}
req, ok := s.lookupQRRequest(w, r, r.URL.Query().Get("request_id"), r.URL.Query().Get("code"))
if !ok {
return
}
writeJSON(w, http.StatusOK, qrRequestResp{
DeviceName: req.NewDeviceName,
DeviceType: req.NewDeviceType,
RequestIP: req.RequestIp,
ExpiresAt: req.ExpiresAt,
Status: req.Status,
// Tell the approver UI to re-auth only if step-up is on AND this session
// hasn't recently stepped up (within the window) — no repeated prompts (#3).
StepUp: s.cfg.StepUpEnabled && !s.sessionRecentlySteppedUp(r),
})
}
// handleQRApprove (full session) binds the request to the caller and records the
// granted scope/persistence. The new device's poll then collects the session.
func (s *Server) handleQRApprove(w http.ResponseWriter, r *http.Request) {
if !s.cfg.QRLoginOn() {
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "scan login disabled"})
return
}
var body qrApproveReq
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4096)).Decode(&body); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid json"})
return
}
req, ok := s.lookupQRRequest(w, r, body.RequestID, body.ApprovalCode)
if !ok {
return
}
claims, _ := jwtauth.ClaimsFromContext(r.Context())
// Step-up: approving a new device into your account is sensitive. When enabled,
// require a fresh prompt=login re-auth (the provider's 2FA, if configured, is
// enforced during that exchange) — UNLESS this session already stepped up within
// the freshness window, so the same session isn't re-prompted repeatedly (#3).
if s.cfg.StepUpEnabled && !s.sessionRecentlySteppedUp(r) {
if !s.verifyStepUp(r, claims.UserID, body.StepUpCode, body.StepUpVerifier) {
writeJSON(w, http.StatusForbidden, map[string]string{"error": "step_up_required"})
return
}
s.recordStepUp(r)
}
scope := "guest" // this milestone grants restricted guest sessions only
if body.Scope == "full" {
scope = "full"
}
persist := "once"
if body.Persist == "persist" {
persist = "persist"
}
now := time.Now()
n, err := s.queries.ApproveLoginRequest(r.Context(), db.ApproveLoginRequestParams{
ApproverUserID: claims.UserID,
GrantScope: scope,
GrantPersist: persist,
ApprovedAt: ptrInt64(now.Unix()),
ID: req.ID,
})
if err != nil {
slog.Error("approve login request failed", "err", err)
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "db"})
return
}
if n == 0 {
// Raced to denied/consumed/expired between lookup and update.
writeJSON(w, http.StatusConflict, map[string]string{"error": "request no longer pending"})
return
}
w.WriteHeader(http.StatusNoContent)
}
// handleQRDeny (full session) rejects a pending request.
func (s *Server) handleQRDeny(w http.ResponseWriter, r *http.Request) {
if !s.cfg.QRLoginOn() {
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "scan login disabled"})
return
}
var body qrDenyReq
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4096)).Decode(&body); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid json"})
return
}
req, ok := s.lookupQRRequest(w, r, body.RequestID, body.ApprovalCode)
if !ok {
return
}
if _, err := s.queries.DenyLoginRequest(r.Context(), req.ID); err != nil {
slog.Error("deny login request failed", "err", err)
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "db"})
return
}
w.WriteHeader(http.StatusNoContent)
}
// sessionFromCookie resolves the caller's web_session row from the cdrop_session
// cookie. The scan-approval endpoints live under /api/auth/*, which the cookie's
// Path covers, so both OIDC and self sessions can be located here.
func (s *Server) sessionFromCookie(r *http.Request) (db.WebSession, bool) {
c, err := r.Cookie(sessionCookieName)
if err != nil || c.Value == "" {
return db.WebSession{}, false
}
sess, err := s.queries.GetWebSession(r.Context(), sessionID(c.Value))
if err != nil {
return db.WebSession{}, false
}
return sess, true
}
// sessionRecentlySteppedUp reports whether the caller's session passed step-up
// within StepUpMaxAgeSeconds — so a sensitive action skips re-auth and the same
// session isn't re-prompted repeatedly (#3, AUTH.md §6).
func (s *Server) sessionRecentlySteppedUp(r *http.Request) bool {
sess, ok := s.sessionFromCookie(r)
if !ok || sess.SteppedUpAt == 0 {
return false
}
window := int64(s.cfg.StepUpMaxAgeSeconds)
if window <= 0 {
window = 300
}
return time.Now().Unix()-sess.SteppedUpAt <= window
}
// recordStepUp stamps the caller's session as freshly stepped-up.
func (s *Server) recordStepUp(r *http.Request) {
sess, ok := s.sessionFromCookie(r)
if !ok {
return
}
if err := s.queries.SetSessionSteppedUp(r.Context(), db.SetSessionSteppedUpParams{
SteppedUpAt: time.Now().Unix(),
ID: sess.ID,
}); err != nil {
slog.Warn("record step-up failed", "err", err)
}
}
// verifyStepUp exchanges a fresh prompt=login authorization code and confirms it
// proves a recent interactive re-authentication by the same user: the id_token's
// signature validates (JWKS), its sub matches the caller, and its auth_time is
// within StepUpMaxAgeSeconds. Any failure → false (the caller answers 403). The
// code is single-use at the IdP, so it can't be replayed (AUTH.md §6).
func (s *Server) verifyStepUp(r *http.Request, userID, code, verifier string) bool {
if code == "" || verifier == "" || s.cfg.OIDCTokenURL == "" {
return false
}
form := url.Values{}
form.Set("grant_type", "authorization_code")
form.Set("code", code)
form.Set("code_verifier", verifier)
form.Set("client_id", s.cfg.OIDCClientID)
form.Set("redirect_uri", s.cfg.OIDCRedirectURI)
if s.cfg.OIDCClientSecret != "" {
form.Set("client_secret", s.cfg.OIDCClientSecret)
}
tr, err := postOIDCToken(r.Context(), s.cfg.OIDCTokenURL, form)
if err != nil {
slog.Warn("step-up exchange failed", "err", err)
return false
}
if tr.IDToken == "" {
return false
}
sub, authTime, err := s.auth.VerifyIDToken(r.Context(), tr.IDToken)
if err != nil {
slog.Warn("step-up id_token invalid", "err", err)
return false
}
if sub != userID {
return false
}
// Enforce the freshness window only when the IdP supplied auth_time (Casdoor
// omits it). When absent, the fresh single-use prompt=login code — exchanged
// once, just now — is itself the bound on how recent the re-auth was.
if authTime > 0 {
maxAge := int64(s.cfg.StepUpMaxAgeSeconds)
if maxAge <= 0 {
maxAge = 300
}
if time.Now().Unix()-authTime > maxAge {
return false
}
}
return true
}
// lookupQRRequest fetches a request and verifies the approval_code in constant
// time. It writes the error response itself and returns ok=false on any failure
// (missing args, unknown request, bad code, expired), so callers just early-return.
func (s *Server) lookupQRRequest(w http.ResponseWriter, r *http.Request, requestID, code string) (db.LoginRequest, bool) {
if requestID == "" || code == "" {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "missing request_id or code"})
return db.LoginRequest{}, false
}
req, err := s.queries.GetLoginRequest(r.Context(), requestID)
if err != nil {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "request not found"})
return db.LoginRequest{}, false
}
if subtle.ConstantTimeCompare([]byte(req.ApprovalCode), []byte(code)) != 1 {
writeJSON(w, http.StatusForbidden, map[string]string{"error": "bad approval code"})
return db.LoginRequest{}, false
}
if req.ExpiresAt < time.Now().Unix() {
writeJSON(w, http.StatusGone, map[string]string{"error": "request expired"})
return db.LoginRequest{}, false
}
return req, true
}
// qrPayload builds the URL encoded into the QR: the approver opens it on their
// phone. Prefers the configured site origin; falls back to the request's own
// scheme/host for dev.
func (s *Server) qrPayload(r *http.Request, requestID, approvalCode string) string {
origin := s.siteOrigin
if origin == "" {
scheme := "https"
if r.TLS == nil && r.Header.Get("X-Forwarded-Proto") == "" {
scheme = "http"
}
origin = scheme + "://" + r.Host
}
return origin + "/link?r=" + requestID + "&c=" + approvalCode
}
func qrDeviceType(raw string) string {
switch t := strings.ToLower(strings.TrimSpace(raw)); t {
case "macos", "windows", "linux", "ios", "browser":
return t
default:
return "browser"
}
}
func clientIP(r *http.Request) string {
if host, _, err := net.SplitHostPort(r.RemoteAddr); err == nil {
return host
}
return r.RemoteAddr
}
func ptrInt64(v int64) *int64 { return &v }
func randB64(n int) (string, error) {
b := make([]byte, n)
if _, err := rand.Read(b); err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(b), nil
}