package httpapi import ( "bufio" "context" "errors" "fmt" "io/fs" "net" "net/http" "path" "runtime/debug" "strings" "time" "github.com/miaopanel/miaopanel/internal/security" "github.com/miaopanel/miaopanel/internal/store" ) const sessionCookie = "mp_sess" type ctxKey int const ( ctxKeySession ctxKey = iota ctxKeyUser ) var publicAPIPaths = map[string]bool{ "/api/v1/health": true, "/api/v1/auth/login": true, "/api/v1/auth/otp": true, "/api/v1/auth/qr/create": true, "/api/v1/auth/qr/status": true, "/api/v1/auth/qr/exchange": true, } func isPublicAPI(p string) bool { return publicAPIPaths[p] } func (s *Server) recoverer(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { defer func() { if rec := recover(); rec != nil { s.log.Error("panic recovered", "path", r.URL.Path, "panic", rec, "stack", string(debug.Stack())) if strings.HasPrefix(r.URL.Path, "/api/") { writeJSON(w, http.StatusInternalServerError, Envelope{Code: 500, Msg: "服务器内部错误"}) } else { http.Error(w, "internal error", http.StatusInternalServerError) } } }() next.ServeHTTP(w, r) }) } type statusWriter struct { http.ResponseWriter status int bytes int } func (w *statusWriter) WriteHeader(code int) { w.status = code w.ResponseWriter.WriteHeader(code) } func (w *statusWriter) Write(b []byte) (int, error) { if w.status == 0 { w.status = http.StatusOK } n, err := w.ResponseWriter.Write(b) w.bytes += n return n, err } // Hijack keeps WebSocket upgrades working: gorilla/websocket needs the // underlying connection, and a plain wrapper would break the handshake. func (w *statusWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { hijacker, ok := w.ResponseWriter.(http.Hijacker) if !ok { return nil, nil, fmt.Errorf("底层连接不支持 Hijack") } w.status = http.StatusSwitchingProtocols return hijacker.Hijack() } func (w *statusWriter) Flush() { if flusher, ok := w.ResponseWriter.(http.Flusher); ok { flusher.Flush() } } func (w *statusWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter } func (s *Server) accessLog(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { start := time.Now() sw := &statusWriter{ResponseWriter: w} next.ServeHTTP(sw, r) if strings.HasPrefix(r.URL.Path, "/api/") { s.log.Info("request", "method", r.Method, "path", r.URL.Path, "status", sw.status, "ms", time.Since(start).Milliseconds(), "ip", clientIP(r, s.cfg.TrustProxy)) } }) } func (s *Server) headers(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { h := w.Header() h.Set("X-Content-Type-Options", "nosniff") h.Set("X-Frame-Options", "DENY") h.Set("Referrer-Policy", "no-referrer") h.Set("X-Robots-Tag", "noindex, nofollow") h.Set("Content-Security-Policy", "default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; "+ "script-src 'self'; connect-src 'self'; font-src 'self' data:; frame-ancestors 'none'") if r.URL.Path == "/" || strings.HasPrefix(r.URL.Path, "/assets/") { h.Set("Cache-Control", "no-cache") } next.ServeHTTP(w, r) }) } // entryGuard adds response hardening for API traffic. Path level entry checks // happen in Handler before the mux is reached. func (s *Server) entryGuard(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if strings.HasPrefix(r.URL.Path, "/api/") { w.Header().Set("Cache-Control", "no-store") } next.ServeHTTP(w, r) }) } func (s *Server) authenticate(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if !strings.HasPrefix(r.URL.Path, "/api/") { next.ServeHTTP(w, r) return } if isPublicAPI(r.URL.Path) { if isMutating(r.Method) && !s.originAllowed(r) { writeJSON(w, http.StatusForbidden, Envelope{Code: 403, Msg: "来源校验失败"}) return } next.ServeHTTP(w, r) return } token, viaBearer := s.requestToken(r) if token == "" { writeJSON(w, http.StatusUnauthorized, Envelope{Code: 401, Msg: "未登录或会话已过期"}) return } ctx := r.Context() // Cookies carry the plain token; only its hash is persisted. sess, err := s.db.SessionByID(ctx, security.HashToken(token)) if err != nil { s.clearCookie(w, r) writeJSON(w, http.StatusUnauthorized, Envelope{Code: 401, Msg: "未登录或会话已过期"}) return } now := time.Now().Unix() if sess.ExpiresAt < now { _ = s.db.DeleteSession(ctx, sess.ID) s.clearCookie(w, r) writeJSON(w, http.StatusUnauthorized, Envelope{Code: 401, Msg: "会话已过期,请重新登录"}) return } user, err := s.db.UserByID(ctx, sess.UserID) if err != nil || user.Status != 1 { writeJSON(w, http.StatusUnauthorized, Envelope{Code: 401, Msg: "账号不可用"}) return } // Bearer tokens are only used by the native app, which cannot be the // target of a browser driven CSRF attack: such a credential is never // attached automatically by the client. if isMutating(r.Method) && !viaBearer { csrf := r.Header.Get("X-CSRF-Token") if csrf == "" || csrf != sess.CSRF { writeJSON(w, http.StatusForbidden, Envelope{Code: 403, Msg: "CSRF 校验失败,请刷新页面"}) return } if !s.originAllowed(r) { writeJSON(w, http.StatusForbidden, Envelope{Code: 403, Msg: "来源校验失败"}) return } } // Sliding expiry: activity extends the session. _ = s.db.TouchSession(ctx, sess.ID, now+int64(s.cfg.SessionTTL())) ctx = context.WithValue(ctx, ctxKeySession, sess) ctx = context.WithValue(ctx, ctxKeyUser, user) next.ServeHTTP(w, r.WithContext(ctx)) }) } // requestToken extracts the session token from the HttpOnly cookie, or from // the Authorization header for native clients that cannot store cookies. The // second return value reports the bearer path so CSRF checks can be skipped. func (s *Server) requestToken(r *http.Request) (string, bool) { if c, err := r.Cookie(sessionCookie); err == nil && c.Value != "" { return c.Value, false } const prefix = "bearer " h := strings.TrimSpace(r.Header.Get("Authorization")) if len(h) > len(prefix) && strings.EqualFold(h[:len(prefix)], prefix) { return strings.TrimSpace(h[len(prefix):]), true } return "", false } func isMutating(method string) bool { switch method { case http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete: return true } return false } func (s *Server) originAllowed(r *http.Request) bool { origin := r.Header.Get("Origin") if origin == "" { return true // non browser client; CSRF token still required } if origin == "null" { return false } host := r.Host for _, prefix := range []string{"http://", "https://"} { if strings.HasPrefix(origin, prefix) { return strings.TrimSuffix(strings.TrimPrefix(origin, prefix), "/") == host } } return false } func (s *Server) setCookie(w http.ResponseWriter, r *http.Request, token string) { http.SetCookie(w, &http.Cookie{ Name: sessionCookie, Value: token, Path: "/" + strings.Trim(s.cfg.Entry, "/"), HttpOnly: true, // The panel serves both schemes on one port, so the flag follows the // request: an https login never leaks the cookie over plain HTTP. Secure: s.cfg.SecureCookie || r.TLS != nil, SameSite: http.SameSiteStrictMode, MaxAge: s.cfg.SessionTTL(), }) } func (s *Server) clearCookie(w http.ResponseWriter, r *http.Request) { http.SetCookie(w, &http.Cookie{ Name: sessionCookie, Value: "", Path: "/" + strings.Trim(s.cfg.Entry, "/"), HttpOnly: true, Secure: s.cfg.SecureCookie || r.TLS != nil, SameSite: http.SameSiteStrictMode, MaxAge: -1, }) } func sessionFrom(r *http.Request) (*store.Session, *store.User, bool) { sess, ok := r.Context().Value(ctxKeySession).(*store.Session) if !ok { return nil, nil, false } user, ok := r.Context().Value(ctxKeyUser).(*store.User) if !ok { return nil, nil, false } return sess, user, true } // camouflage mimics a stock nginx 404 so the panel is invisible to scanners. func (s *Server) camouflage(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/html; charset=utf-8") w.Header().Set("Server", "nginx") w.WriteHeader(http.StatusNotFound) fmt.Fprint(w, `404 Not Found

404 Not Found


nginx
`) } func (s *Server) staticHandler() http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodGet && r.Method != http.MethodHead { http.Error(w, "method not allowed", http.StatusMethodNotAllowed) return } if s.web == nil { http.Error(w, "UI 未构建", http.StatusNotFound) return } p := strings.TrimPrefix(path.Clean(r.URL.Path), "/") if p == "" || p == "." { p = "index.html" } if f, err := s.web.Open(p); err == nil { _ = f.Close() http.FileServerFS(s.web).ServeHTTP(w, r) return } // SPA fallback index, err := fs.ReadFile(s.web, "index.html") if err != nil { http.Error(w, "UI 未构建", http.StatusNotFound) return } w.Header().Set("Content-Type", "text/html; charset=utf-8") w.Header().Set("Cache-Control", "no-cache") _, _ = w.Write(index) }) } // audit records a mutating operation; it never fails the request. func (s *Server) audit(r *http.Request, module, action, target, result string, started time.Time) { sess, user, ok := sessionFrom(r) if !ok { return } _ = s.db.Audit(r.Context(), store.AuditEntry{ UserID: user.ID, Username: user.Username, IP: clientIP(r, s.cfg.TrustProxy), UA: r.UserAgent(), Module: module, Action: action, Target: target, Result: result, CostMS: time.Since(started).Milliseconds(), }) _ = sess } // requireUser fetches the authenticated user or returns an APIError. func requireUser(r *http.Request) (*store.User, error) { _, user, ok := sessionFrom(r) if !ok { return nil, Errorf(http.StatusUnauthorized, "未登录") } return user, nil } var errNotFound = errors.New("not found")