package httpapi import ( "crypto/subtle" "net/http" "strings" "time" "github.com/miaopanel/miaopanel/internal/security" "github.com/miaopanel/miaopanel/internal/store" ) // QR code login hands one browser session over to a phone that is already // signed in to the panel app: // // 浏览器 POST /auth/qr/create → ticket + secret + payload(二维码内容) // 手机 POST /auth/qr/scan → 标记「已扫码」,回传浏览器 IP/UA 供人工核对 // 手机 POST /auth/qr/approve → 允许 / 拒绝 // 浏览器 POST /auth/qr/exchange → 用 ticket+secret 换会话 Cookie // // The ticket is single use and short lived; the secret never leaves the two // parties that already know it, so a leaked ticket alone cannot mint a session. const ( qrTicketTTL = 2 * time.Minute // qrPollInterval is what the login page should use between status reads. qrPollInterval = 1500 // ms // qrMaxCreatePerMinute throttles QR creation per address so an attacker // cannot flood the table. Logins behind one NAT share this budget, so keep // it comfortably above what a small workgroup needs. qrMaxCreatePerMinute = 30 qrPayloadScheme = "miaopanel://qrlogin" ) type qrCreateResp struct { Ticket string `json:"ticket"` Secret string `json:"secret"` Payload string `json:"payload"` ExpiresAt int64 `json:"expires_at"` PollInterval int `json:"poll_interval"` Entry string `json:"entry"` } type qrStatusResp struct { Status string `json:"status"` ExpiresAt int64 `json:"expires_at"` Username string `json:"username,omitempty"` ApprovedAt int64 `json:"approved_at,omitempty"` } type qrTicketReq struct { Ticket string `json:"ticket"` } type qrConfirmReq struct { Ticket string `json:"ticket"` // Approve must be explicit: a missing field would otherwise mean "deny", // and a typo in the client would silently reject a legitimate login. Approve *bool `json:"approve"` } type qrExchangeReq struct { Ticket string `json:"ticket"` Secret string `json:"secret"` } // buildQRPayload is the exact string encoded into the QR image. The app parses // it back, so keep it a boring query string rather than JSON. Values are written // verbatim (no percent-encoding) because every field is already restricted to a // URL safe alphabet; that keeps the phone side parser tiny. func buildQRPayload(host, entry, ticket, secret string) string { return qrPayloadScheme + "?t=" + ticket + "&s=" + secret + "&h=" + qrSafeValue(host) + "&e=" + qrSafeValue(entry) } // qrSafeValue keeps only characters that can appear in a host or the security // entry, so a crafted value cannot inject extra query parameters. func qrSafeValue(v string) string { var b strings.Builder for _, c := range v { switch { case c >= 'a' && c <= 'z', c >= 'A' && c <= 'Z', c >= '0' && c <= '9', c == '.', c == '-', c == ':', c == '[', c == ']': b.WriteRune(c) } } out := b.String() if len(out) > 120 { return out[:120] } return out } // qrCreateAllowed is a fixed window limiter over ticket creation. QR login is a // public endpoint, so it needs at least a token effort against scripted abuse. func (s *Server) qrCreateAllowed(ip string) bool { now := time.Now() s.qrMu.Lock() defer s.qrMu.Unlock() if s.qrHits == nil { s.qrHits = map[string]*qrRateWindow{} } for k, v := range s.qrHits { if now.After(v.reset) { delete(s.qrHits, k) } } w := s.qrHits[ip] if w == nil { w = &qrRateWindow{reset: now.Add(time.Minute)} s.qrHits[ip] = w } if w.count >= qrMaxCreatePerMinute { return false } w.count++ return true } // handleQRCreate starts a challenge for the browser that is showing the login // page. It returns the payload to render as a QR code. func (s *Server) handleQRCreate(w http.ResponseWriter, r *http.Request) { ip := clientIP(r, s.cfg.TrustProxy) if !s.qrCreateAllowed(ip) { writeJSON(w, http.StatusTooManyRequests, Envelope{ Code: 429, Msg: "二维码申请过于频繁,请稍后再试", }) return } ticket, ticketHash, err := security.Token(32) if err != nil { writeErr(w, err) return } secret, secretHash, err := security.Token(32) if err != nil { writeErr(w, err) return } now := time.Now() t := &store.QRTicket{ ID: ticketHash, SecretHash: secretHash, Status: store.QRStatusPending, IP: ip, UA: truncate(r.UserAgent(), 255), CreatedAt: now.Unix(), ExpiresAt: now.Add(qrTicketTTL).Unix(), UpdatedAt: now.Unix(), } if err := s.db.CreateQRTicket(r.Context(), t); err != nil { writeErr(w, err) return } // Opportunistic cleanup keeps the table bounded without another cron job. _, _ = s.db.PurgeQRTickets(r.Context(), now.Unix()) host := strings.TrimSpace(r.Host) if host == "" { host = s.cfg.Addr } entry := s.currentEntry() writeOK(w, qrCreateResp{ Ticket: ticket, Secret: secret, Payload: buildQRPayload(host, entry, ticket, secret), ExpiresAt: t.ExpiresAt, PollInterval: qrPollInterval, Entry: entry, }) } // handleQRStatus is polled by the login page. Unknown tickets answer with the // "invalid" status instead of an error so the client has one code path. func (s *Server) handleQRStatus(w http.ResponseWriter, r *http.Request) { ticket := strings.TrimSpace(r.URL.Query().Get("ticket")) if ticket == "" { writeJSON(w, http.StatusBadRequest, Envelope{Code: 400, Msg: "缺少二维码票据"}) return } now := time.Now().Unix() t, err := s.db.QRTicketByID(r.Context(), security.HashToken(ticket)) if err != nil { writeOK(w, qrStatusResp{Status: "invalid"}) return } status := t.Status // Expiry wins over every state that has not produced a session yet; the // exchange endpoint enforces the same deadline. if t.ExpiresAt <= now && status != store.QRStatusConsumed { status = "expired" } resp := qrStatusResp{Status: status, ExpiresAt: t.ExpiresAt} if status == store.QRStatusConfirmed || status == store.QRStatusConsumed { resp.ApprovedAt = t.UpdatedAt if user, err := s.db.UserByID(r.Context(), t.UserID); err == nil { resp.Username = user.Username } } writeOK(w, resp) } // handleQRExchange turns an approved ticket into a browser session. It is // public because the browser is not signed in yet; the secret plus the single // use consume keep it from being replayable. // // The secret, not the client address, is what binds the exchange to the browser // that showed the code: clients behind NAT or rotating IPv6 addresses would // otherwise break, and an attacker who only learns the ticket from a log still // cannot mint a session. func (s *Server) handleQRExchange(w http.ResponseWriter, r *http.Request) { var req qrExchangeReq if err := decodeJSON(w, r, &req, 8<<10); err != nil { writeErr(w, err) return } req.Ticket = strings.TrimSpace(req.Ticket) req.Secret = strings.TrimSpace(req.Secret) if req.Ticket == "" || req.Secret == "" { writeJSON(w, http.StatusBadRequest, Envelope{Code: 400, Msg: "缺少二维码票据"}) return } now := time.Now().Unix() t, err := s.db.QRTicketByID(r.Context(), security.HashToken(req.Ticket)) if err != nil { writeJSON(w, http.StatusGone, Envelope{Code: 410, Msg: "二维码已失效,请刷新后重试"}) return } if subtle.ConstantTimeCompare([]byte(security.HashToken(req.Secret)), []byte(t.SecretHash)) != 1 { writeJSON(w, http.StatusForbidden, Envelope{Code: 403, Msg: "二维码校验失败,请刷新后重试"}) return } if t.ExpiresAt <= now { writeJSON(w, http.StatusGone, Envelope{Code: 410, Msg: "二维码已过期,请刷新后重试"}) return } switch t.Status { case store.QRStatusConfirmed: // fallthrough to consume case store.QRStatusDenied: writeJSON(w, http.StatusForbidden, Envelope{Code: 403, Msg: "该登录请求已在手机上拒绝"}) return case store.QRStatusConsumed: writeJSON(w, http.StatusConflict, Envelope{Code: 409, Msg: "二维码已被使用,请刷新后重试"}) return default: writeJSON(w, http.StatusConflict, Envelope{Code: 409, Msg: "尚未在手机上确认登录"}) return } ok, err := s.db.ConsumeQRTicket(r.Context(), t.ID, now) if err != nil { writeErr(w, err) return } if !ok { writeJSON(w, http.StatusConflict, Envelope{Code: 409, Msg: "二维码已被使用,请刷新后重试"}) return } user, err := s.db.UserByID(r.Context(), t.UserID) if err != nil || user.Status != 1 { writeJSON(w, http.StatusUnauthorized, Envelope{Code: 401, Msg: "账号不可用"}) return } s.issueSessionAs(w, r, user, "qr_login") } // handleQRScan is called by the app right after reading the code. It only marks // the ticket as scanned and echoes what the browser looks like, so the operator // can judge the request before approving it. func (s *Server) handleQRScan(w http.ResponseWriter, r *http.Request) { if _, err := requireUser(r); err != nil { writeErr(w, err) return } var req qrTicketReq if err := decodeJSON(w, r, &req, 8<<10); err != nil { writeErr(w, err) return } req.Ticket = strings.TrimSpace(req.Ticket) if req.Ticket == "" { writeJSON(w, http.StatusBadRequest, Envelope{Code: 400, Msg: "缺少二维码票据"}) return } now := time.Now().Unix() t, err := s.db.QRTicketByID(r.Context(), security.HashToken(req.Ticket)) if err != nil { writeJSON(w, http.StatusNotFound, Envelope{Code: 404, Msg: "二维码无效,请确认它来自本面板"}) return } if t.ExpiresAt <= now { writeJSON(w, http.StatusGone, Envelope{Code: 410, Msg: "二维码已过期,请让浏览器刷新"}) return } if t.Status != store.QRStatusPending && t.Status != store.QRStatusScanned { writeJSON(w, http.StatusConflict, Envelope{Code: 409, Msg: "该二维码已处理,请让浏览器刷新"}) return } ip := clientIP(r, s.cfg.TrustProxy) // Several phones may open the same code; only the first scan flips the // state, but the others may still look at the details and decide. What must // not happen is showing a printable request for a ticket that was already // approved or rejected elsewhere. if ok, markErr := s.db.MarkQRTicketScanned(r.Context(), t.ID, ip, truncate(r.UserAgent(), 255), now); !ok || markErr != nil { latest, err := s.db.QRTicketByID(r.Context(), t.ID) if err != nil { writeJSON(w, http.StatusNotFound, Envelope{Code: 404, Msg: "二维码无效,请确认它来自本面板"}) return } if latest.Status != store.QRStatusPending && latest.Status != store.QRStatusScanned { writeJSON(w, http.StatusConflict, Envelope{Code: 409, Msg: "该二维码已被处理,请让浏览器刷新"}) return } } writeOK(w, map[string]any{ "status": store.QRStatusScanned, "expires_at": t.ExpiresAt, "created_at": t.CreatedAt, "ip": t.IP, "ua": t.UA, }) } // handleQRApprove is the actual consent step on the phone. func (s *Server) handleQRApprove(w http.ResponseWriter, r *http.Request) { user, err := requireUser(r) if err != nil { writeErr(w, err) return } var req qrConfirmReq if err := decodeJSON(w, r, &req, 8<<10); err != nil { writeErr(w, err) return } if req.Approve == nil { writeJSON(w, http.StatusBadRequest, Envelope{Code: 400, Msg: "缺少确认结果"}) return } req.Ticket = strings.TrimSpace(req.Ticket) if req.Ticket == "" { writeJSON(w, http.StatusBadRequest, Envelope{Code: 400, Msg: "缺少二维码票据"}) return } now := time.Now().Unix() t, err := s.db.QRTicketByID(r.Context(), security.HashToken(req.Ticket)) if err != nil { writeJSON(w, http.StatusNotFound, Envelope{Code: 404, Msg: "二维码无效,请确认它来自本面板"}) return } if t.ExpiresAt <= now { writeJSON(w, http.StatusGone, Envelope{Code: 410, Msg: "二维码已过期,请让浏览器刷新"}) return } ip := clientIP(r, s.cfg.TrustProxy) ok, err := s.db.DecideQRTicket(r.Context(), t.ID, user.ID, *req.Approve, ip, truncate(r.UserAgent(), 255), now) if err != nil { writeErr(w, err) return } if !ok { writeJSON(w, http.StatusConflict, Envelope{Code: 409, Msg: "该二维码已处理或已过期,请让浏览器刷新"}) return } status := store.QRStatusDenied action := "qr_deny" if *req.Approve { status = store.QRStatusConfirmed action = "qr_approve" } _ = s.db.Audit(r.Context(), store.AuditEntry{ UserID: user.ID, Username: user.Username, IP: ip, UA: truncate(r.UserAgent(), 255), Module: "auth", Action: action, Target: t.IP, Result: "ok", }) writeOK(w, map[string]any{"status": status, "expires_at": t.ExpiresAt}) }