仰望星辰工作室

miaopanel

miaopanel/ internal/httpapi/qrlogin.go 12.2 KB · 371 行 原始文件
1package httpapi
2
3import (
4 "crypto/subtle"
5 "net/http"
6 "strings"
7 "time"
8
9 "github.com/miaopanel/miaopanel/internal/security"
10 "github.com/miaopanel/miaopanel/internal/store"
11)
12
13// QR code login hands one browser session over to a phone that is already
14// signed in to the panel app:
15//
16// 浏览器 POST /auth/qr/create → ticket + secret + payload(二维码内容)
17// 手机 POST /auth/qr/scan → 标记「已扫码」,回传浏览器 IP/UA 供人工核对
18// 手机 POST /auth/qr/approve → 允许 / 拒绝
19// 浏览器 POST /auth/qr/exchange → 用 ticket+secret 换会话 Cookie
20//
21// The ticket is single use and short lived; the secret never leaves the two
22// parties that already know it, so a leaked ticket alone cannot mint a session.
23const (
24 qrTicketTTL = 2 * time.Minute
25 // qrPollInterval is what the login page should use between status reads.
26 qrPollInterval = 1500 // ms
27 // qrMaxCreatePerMinute throttles QR creation per address so an attacker
28 // cannot flood the table. Logins behind one NAT share this budget, so keep
29 // it comfortably above what a small workgroup needs.
30 qrMaxCreatePerMinute = 30
31 qrPayloadScheme = "miaopanel://qrlogin"
32)
33
34type qrCreateResp struct {
35 Ticket string `json:"ticket"`
36 Secret string `json:"secret"`
37 Payload string `json:"payload"`
38 ExpiresAt int64 `json:"expires_at"`
39 PollInterval int `json:"poll_interval"`
40 Entry string `json:"entry"`
41}
42
43type qrStatusResp struct {
44 Status string `json:"status"`
45 ExpiresAt int64 `json:"expires_at"`
46 Username string `json:"username,omitempty"`
47 ApprovedAt int64 `json:"approved_at,omitempty"`
48}
49
50type qrTicketReq struct {
51 Ticket string `json:"ticket"`
52}
53
54type qrConfirmReq struct {
55 Ticket string `json:"ticket"`
56 // Approve must be explicit: a missing field would otherwise mean "deny",
57 // and a typo in the client would silently reject a legitimate login.
58 Approve *bool `json:"approve"`
59}
60
61type qrExchangeReq struct {
62 Ticket string `json:"ticket"`
63 Secret string `json:"secret"`
64}
65
66// buildQRPayload is the exact string encoded into the QR image. The app parses
67// it back, so keep it a boring query string rather than JSON. Values are written
68// verbatim (no percent-encoding) because every field is already restricted to a
69// URL safe alphabet; that keeps the phone side parser tiny.
70func buildQRPayload(host, entry, ticket, secret string) string {
71 return qrPayloadScheme + "?t=" + ticket + "&s=" + secret +
72 "&h=" + qrSafeValue(host) + "&e=" + qrSafeValue(entry)
73}
74
75// qrSafeValue keeps only characters that can appear in a host or the security
76// entry, so a crafted value cannot inject extra query parameters.
77func qrSafeValue(v string) string {
78 var b strings.Builder
79 for _, c := range v {
80 switch {
81 case c >= 'a' && c <= 'z', c >= 'A' && c <= 'Z', c >= '0' && c <= '9',
82 c == '.', c == '-', c == ':', c == '[', c == ']':
83 b.WriteRune(c)
84 }
85 }
86 out := b.String()
87 if len(out) > 120 {
88 return out[:120]
89 }
90 return out
91}
92
93// qrCreateAllowed is a fixed window limiter over ticket creation. QR login is a
94// public endpoint, so it needs at least a token effort against scripted abuse.
95func (s *Server) qrCreateAllowed(ip string) bool {
96 now := time.Now()
97 s.qrMu.Lock()
98 defer s.qrMu.Unlock()
99 if s.qrHits == nil {
100 s.qrHits = map[string]*qrRateWindow{}
101 }
102 for k, v := range s.qrHits {
103 if now.After(v.reset) {
104 delete(s.qrHits, k)
105 }
106 }
107 w := s.qrHits[ip]
108 if w == nil {
109 w = &qrRateWindow{reset: now.Add(time.Minute)}
110 s.qrHits[ip] = w
111 }
112 if w.count >= qrMaxCreatePerMinute {
113 return false
114 }
115 w.count++
116 return true
117}
118
119// handleQRCreate starts a challenge for the browser that is showing the login
120// page. It returns the payload to render as a QR code.
121func (s *Server) handleQRCreate(w http.ResponseWriter, r *http.Request) {
122 ip := clientIP(r, s.cfg.TrustProxy)
123 if !s.qrCreateAllowed(ip) {
124 writeJSON(w, http.StatusTooManyRequests, Envelope{
125 Code: 429, Msg: "二维码申请过于频繁,请稍后再试",
126 })
127 return
128 }
129 ticket, ticketHash, err := security.Token(32)
130 if err != nil {
131 writeErr(w, err)
132 return
133 }
134 secret, secretHash, err := security.Token(32)
135 if err != nil {
136 writeErr(w, err)
137 return
138 }
139 now := time.Now()
140 t := &store.QRTicket{
141 ID: ticketHash, SecretHash: secretHash, Status: store.QRStatusPending,
142 IP: ip, UA: truncate(r.UserAgent(), 255),
143 CreatedAt: now.Unix(), ExpiresAt: now.Add(qrTicketTTL).Unix(),
144 UpdatedAt: now.Unix(),
145 }
146 if err := s.db.CreateQRTicket(r.Context(), t); err != nil {
147 writeErr(w, err)
148 return
149 }
150 // Opportunistic cleanup keeps the table bounded without another cron job.
151 _, _ = s.db.PurgeQRTickets(r.Context(), now.Unix())
152
153 host := strings.TrimSpace(r.Host)
154 if host == "" {
155 host = s.cfg.Addr
156 }
157 entry := s.currentEntry()
158 writeOK(w, qrCreateResp{
159 Ticket: ticket, Secret: secret,
160 Payload: buildQRPayload(host, entry, ticket, secret),
161 ExpiresAt: t.ExpiresAt,
162 PollInterval: qrPollInterval,
163 Entry: entry,
164 })
165}
166
167// handleQRStatus is polled by the login page. Unknown tickets answer with the
168// "invalid" status instead of an error so the client has one code path.
169func (s *Server) handleQRStatus(w http.ResponseWriter, r *http.Request) {
170 ticket := strings.TrimSpace(r.URL.Query().Get("ticket"))
171 if ticket == "" {
172 writeJSON(w, http.StatusBadRequest, Envelope{Code: 400, Msg: "缺少二维码票据"})
173 return
174 }
175 now := time.Now().Unix()
176 t, err := s.db.QRTicketByID(r.Context(), security.HashToken(ticket))
177 if err != nil {
178 writeOK(w, qrStatusResp{Status: "invalid"})
179 return
180 }
181 status := t.Status
182 // Expiry wins over every state that has not produced a session yet; the
183 // exchange endpoint enforces the same deadline.
184 if t.ExpiresAt <= now && status != store.QRStatusConsumed {
185 status = "expired"
186 }
187 resp := qrStatusResp{Status: status, ExpiresAt: t.ExpiresAt}
188 if status == store.QRStatusConfirmed || status == store.QRStatusConsumed {
189 resp.ApprovedAt = t.UpdatedAt
190 if user, err := s.db.UserByID(r.Context(), t.UserID); err == nil {
191 resp.Username = user.Username
192 }
193 }
194 writeOK(w, resp)
195}
196
197// handleQRExchange turns an approved ticket into a browser session. It is
198// public because the browser is not signed in yet; the secret plus the single
199// use consume keep it from being replayable.
200//
201// The secret, not the client address, is what binds the exchange to the browser
202// that showed the code: clients behind NAT or rotating IPv6 addresses would
203// otherwise break, and an attacker who only learns the ticket from a log still
204// cannot mint a session.
205func (s *Server) handleQRExchange(w http.ResponseWriter, r *http.Request) {
206 var req qrExchangeReq
207 if err := decodeJSON(w, r, &req, 8<<10); err != nil {
208 writeErr(w, err)
209 return
210 }
211 req.Ticket = strings.TrimSpace(req.Ticket)
212 req.Secret = strings.TrimSpace(req.Secret)
213 if req.Ticket == "" || req.Secret == "" {
214 writeJSON(w, http.StatusBadRequest, Envelope{Code: 400, Msg: "缺少二维码票据"})
215 return
216 }
217 now := time.Now().Unix()
218 t, err := s.db.QRTicketByID(r.Context(), security.HashToken(req.Ticket))
219 if err != nil {
220 writeJSON(w, http.StatusGone, Envelope{Code: 410, Msg: "二维码已失效,请刷新后重试"})
221 return
222 }
223 if subtle.ConstantTimeCompare([]byte(security.HashToken(req.Secret)), []byte(t.SecretHash)) != 1 {
224 writeJSON(w, http.StatusForbidden, Envelope{Code: 403, Msg: "二维码校验失败,请刷新后重试"})
225 return
226 }
227 if t.ExpiresAt <= now {
228 writeJSON(w, http.StatusGone, Envelope{Code: 410, Msg: "二维码已过期,请刷新后重试"})
229 return
230 }
231 switch t.Status {
232 case store.QRStatusConfirmed:
233 // fallthrough to consume
234 case store.QRStatusDenied:
235 writeJSON(w, http.StatusForbidden, Envelope{Code: 403, Msg: "该登录请求已在手机上拒绝"})
236 return
237 case store.QRStatusConsumed:
238 writeJSON(w, http.StatusConflict, Envelope{Code: 409, Msg: "二维码已被使用,请刷新后重试"})
239 return
240 default:
241 writeJSON(w, http.StatusConflict, Envelope{Code: 409, Msg: "尚未在手机上确认登录"})
242 return
243 }
244 ok, err := s.db.ConsumeQRTicket(r.Context(), t.ID, now)
245 if err != nil {
246 writeErr(w, err)
247 return
248 }
249 if !ok {
250 writeJSON(w, http.StatusConflict, Envelope{Code: 409, Msg: "二维码已被使用,请刷新后重试"})
251 return
252 }
253 user, err := s.db.UserByID(r.Context(), t.UserID)
254 if err != nil || user.Status != 1 {
255 writeJSON(w, http.StatusUnauthorized, Envelope{Code: 401, Msg: "账号不可用"})
256 return
257 }
258 s.issueSessionAs(w, r, user, "qr_login")
259}
260
261// handleQRScan is called by the app right after reading the code. It only marks
262// the ticket as scanned and echoes what the browser looks like, so the operator
263// can judge the request before approving it.
264func (s *Server) handleQRScan(w http.ResponseWriter, r *http.Request) {
265 if _, err := requireUser(r); err != nil {
266 writeErr(w, err)
267 return
268 }
269 var req qrTicketReq
270 if err := decodeJSON(w, r, &req, 8<<10); err != nil {
271 writeErr(w, err)
272 return
273 }
274 req.Ticket = strings.TrimSpace(req.Ticket)
275 if req.Ticket == "" {
276 writeJSON(w, http.StatusBadRequest, Envelope{Code: 400, Msg: "缺少二维码票据"})
277 return
278 }
279 now := time.Now().Unix()
280 t, err := s.db.QRTicketByID(r.Context(), security.HashToken(req.Ticket))
281 if err != nil {
282 writeJSON(w, http.StatusNotFound, Envelope{Code: 404, Msg: "二维码无效,请确认它来自本面板"})
283 return
284 }
285 if t.ExpiresAt <= now {
286 writeJSON(w, http.StatusGone, Envelope{Code: 410, Msg: "二维码已过期,请让浏览器刷新"})
287 return
288 }
289 if t.Status != store.QRStatusPending && t.Status != store.QRStatusScanned {
290 writeJSON(w, http.StatusConflict, Envelope{Code: 409, Msg: "该二维码已处理,请让浏览器刷新"})
291 return
292 }
293 ip := clientIP(r, s.cfg.TrustProxy)
294 // Several phones may open the same code; only the first scan flips the
295 // state, but the others may still look at the details and decide. What must
296 // not happen is showing a printable request for a ticket that was already
297 // approved or rejected elsewhere.
298 if ok, markErr := s.db.MarkQRTicketScanned(r.Context(), t.ID, ip, truncate(r.UserAgent(), 255), now); !ok || markErr != nil {
299 latest, err := s.db.QRTicketByID(r.Context(), t.ID)
300 if err != nil {
301 writeJSON(w, http.StatusNotFound, Envelope{Code: 404, Msg: "二维码无效,请确认它来自本面板"})
302 return
303 }
304 if latest.Status != store.QRStatusPending && latest.Status != store.QRStatusScanned {
305 writeJSON(w, http.StatusConflict, Envelope{Code: 409, Msg: "该二维码已被处理,请让浏览器刷新"})
306 return
307 }
308 }
309 writeOK(w, map[string]any{
310 "status": store.QRStatusScanned,
311 "expires_at": t.ExpiresAt,
312 "created_at": t.CreatedAt,
313 "ip": t.IP,
314 "ua": t.UA,
315 })
316}
317
318// handleQRApprove is the actual consent step on the phone.
319func (s *Server) handleQRApprove(w http.ResponseWriter, r *http.Request) {
320 user, err := requireUser(r)
321 if err != nil {
322 writeErr(w, err)
323 return
324 }
325 var req qrConfirmReq
326 if err := decodeJSON(w, r, &req, 8<<10); err != nil {
327 writeErr(w, err)
328 return
329 }
330 if req.Approve == nil {
331 writeJSON(w, http.StatusBadRequest, Envelope{Code: 400, Msg: "缺少确认结果"})
332 return
333 }
334 req.Ticket = strings.TrimSpace(req.Ticket)
335 if req.Ticket == "" {
336 writeJSON(w, http.StatusBadRequest, Envelope{Code: 400, Msg: "缺少二维码票据"})
337 return
338 }
339 now := time.Now().Unix()
340 t, err := s.db.QRTicketByID(r.Context(), security.HashToken(req.Ticket))
341 if err != nil {
342 writeJSON(w, http.StatusNotFound, Envelope{Code: 404, Msg: "二维码无效,请确认它来自本面板"})
343 return
344 }
345 if t.ExpiresAt <= now {
346 writeJSON(w, http.StatusGone, Envelope{Code: 410, Msg: "二维码已过期,请让浏览器刷新"})
347 return
348 }
349 ip := clientIP(r, s.cfg.TrustProxy)
350 ok, err := s.db.DecideQRTicket(r.Context(), t.ID, user.ID, *req.Approve, ip,
351 truncate(r.UserAgent(), 255), now)
352 if err != nil {
353 writeErr(w, err)
354 return
355 }
356 if !ok {
357 writeJSON(w, http.StatusConflict, Envelope{Code: 409, Msg: "该二维码已处理或已过期,请让浏览器刷新"})
358 return
359 }
360 status := store.QRStatusDenied
361 action := "qr_deny"
362 if *req.Approve {
363 status = store.QRStatusConfirmed
364 action = "qr_approve"
365 }
366 _ = s.db.Audit(r.Context(), store.AuditEntry{
367 UserID: user.ID, Username: user.Username, IP: ip, UA: truncate(r.UserAgent(), 255),
368 Module: "auth", Action: action, Target: t.IP, Result: "ok",
369 })
370 writeOK(w, map[string]any{"status": status, "expires_at": t.ExpiresAt})
371}