package httpapi import ( "context" "crypto/x509" "encoding/pem" "errors" "fmt" "net" "net/http" "os" "path/filepath" "strconv" "strings" "time" "github.com/miaopanel/miaopanel/internal/paneltls" "github.com/miaopanel/miaopanel/internal/webserver" ) // settingsPayload is what the settings page renders. type settingsPayload struct { Entry string `json:"entry"` SessionTTLMinutes int `json:"session_ttl_minutes"` HTTPS bool `json:"https"` AppDomain string `json:"app_domain"` CertPath string `json:"cert_path"` CertIssuer string `json:"cert_issuer"` CertNotAfter int64 `json:"cert_not_after"` CertSelfSigned bool `json:"cert_self_signed"` Port string `json:"port"` Version string `json:"version"` } func (s *Server) settingsSnapshot() settingsPayload { issuer, notAfter, selfSigned := certificateInfo(s.cfg.HTTPSCert) if s.cfg.HTTPSCert == "" { issuer, notAfter, selfSigned = certificateInfo(filepath.Join(s.cfg.SelfSignedDir(), "panel.crt")) } return settingsPayload{ Entry: s.cfg.Entry, SessionTTLMinutes: s.cfg.SessionTTLMinutes, HTTPS: s.cfg.HTTPSEnabled(), AppDomain: s.cfg.AppDomain, CertPath: s.cfg.HTTPSCert, CertIssuer: issuer, CertNotAfter: notAfter, CertSelfSigned: selfSigned, Port: portOf(s.cfg.Addr), Version: s.version, } } func certificateInfo(certPath string) (string, int64, bool) { if certPath == "" { return "", 0, false } raw, err := os.ReadFile(certPath) if err != nil { return "", 0, false } block, _ := pem.Decode(raw) if block == nil { return "", 0, false } crt, err := x509.ParseCertificate(block.Bytes) if err != nil { return "", 0, false } return crt.Issuer.String(), crt.NotAfter.Unix(), crt.Issuer.String() == crt.Subject.String() } func portOf(addr string) string { if i := strings.LastIndex(addr, ":"); i >= 0 { return addr[i+1:] } return "8888" } // portSuffix is the ":8888" part of an app URL; empty for the default 443. func portSuffix(addr string) string { port := portOf(addr) if port == "" || port == "443" { return "" } return ":" + port } func (s *Server) handleSettingsGet(w http.ResponseWriter, r *http.Request) { writeOK(w, s.settingsSnapshot()) } type entryReq struct { Entry string `json:"entry"` } func (s *Server) handleSettingsEntry(w http.ResponseWriter, r *http.Request) { var req entryReq if err := decodeJSON(w, r, &req, 4<<10); err != nil { writeErr(w, err) return } entry := strings.ToLower(strings.Trim(strings.TrimSpace(req.Entry), "/")) if !validEntry(entry) { writeJSON(w, http.StatusBadRequest, Envelope{ Code: 400, Msg: "安全入口需为 4-32 位小写字母或数字", }) return } started := time.Now() old := s.cfg.Entry s.cfg.Entry = entry if err := s.cfg.Save(); err != nil { s.cfg.Entry = old writeErr(w, err) return } s.setEntry(entry) // Rotating the entry is a credential change: sessions obtained with the old // entry (including Bearer tokens, which ignore the cookie Path) must die, // not just look logged out in the browser. if user, err := requireUser(r); err == nil { _, _ = s.db.DeleteOtherSessions(r.Context(), user.ID, "") } s.audit(r, "settings", "entry", entry, "ok", started) // The old cookie Path no longer matches, so the browser must re-login at // the new prefix. The response tells the UI where to go. writeOK(w, map[string]any{"entry": entry, "relogin": true}) } func validEntry(entry string) bool { if len(entry) < 4 || len(entry) > 32 { return false } for _, c := range entry { if (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') { continue } return false } // The SPA serves /assets and /api from the root handler; using one of them // as the entry would shadow the frontend and lock the operator out. switch entry { case "assets", "api", "static", "favicon": return false } return true } type sessionReq struct { Minutes int `json:"minutes"` } func (s *Server) handleSettingsSession(w http.ResponseWriter, r *http.Request) { var req sessionReq if err := decodeJSON(w, r, &req, 4<<10); err != nil { writeErr(w, err) return } if req.Minutes < 1 || req.Minutes > 10080 { writeJSON(w, http.StatusBadRequest, Envelope{Code: 400, Msg: "登录有效期需在 1 到 10080 分钟之间"}) return } started := time.Now() old := s.cfg.SessionTTLMinutes s.cfg.SessionTTLMinutes = req.Minutes if err := s.cfg.Save(); err != nil { s.cfg.SessionTTLMinutes = old writeErr(w, err) return } s.audit(r, "settings", "session_ttl", strconv.Itoa(req.Minutes), "ok", started) writeOK(w, s.settingsSnapshot()) } type appAccessReq struct { Domain string `json:"domain"` Staging bool `json:"staging"` } // handleAppAccessEnable issues a publicly trusted certificate for the domain // the operator pointed at this server, so the mobile app can use real HTTPS // instead of a self signed certificate the system will not trust. func (s *Server) handleAppAccessEnable(w http.ResponseWriter, r *http.Request) { if s.sslSvc == nil { writeJSON(w, http.StatusServiceUnavailable, Envelope{Code: 503, Msg: "证书服务不可用"}) return } if s.tls == nil { writeJSON(w, http.StatusServiceUnavailable, Envelope{Code: 503, Msg: "面板未启用 HTTPS,请先在配置中开启 https"}) return } var req appAccessReq if err := decodeJSON(w, r, &req, 4<<10); err != nil { writeErr(w, err) return } domain := strings.ToLower(strings.TrimSpace(req.Domain)) domain = strings.TrimPrefix(strings.TrimPrefix(domain, "https://"), "http://") domain = strings.TrimSuffix(domain, "/") if !validDomainName(domain) { writeJSON(w, http.StatusBadRequest, Envelope{Code: 400, Msg: "请填写一个已解析到本机的域名,例如 panel.example.com"}) return } started := time.Now() // Keep the challenge files outside DataDir: that directory is 0700 so the // nginx worker cannot traverse into it, and the ACME probe would 403. webRoot := filepath.Join(s.cfg.PanelDir, "acme-web") outDir := filepath.Join(s.cfg.SelfSignedDir(), "domain") // Detach from the request context: clicking refresh must not abort an // issuance that Let's Encrypt has already started, otherwise the account // burns rate limit for nothing. The ACME call keeps its own timeout. issueCtx := context.WithoutCancel(r.Context()) // The HTTP-01 challenge must be reachable on port 80. Prefer a temporary // listener; fall back to a throwaway nginx server block when nginx owns 80. stop, err := s.startChallengeServer(issueCtx, domain, webRoot) if err != nil { writeJSON(w, http.StatusBadRequest, Envelope{Code: 400, Msg: err.Error()}) return } defer stop() result, err := s.sslSvc.IssuePanelCert(issueCtx, domain, webRoot, outDir, req.Staging) if err != nil { s.audit(r, "settings", "app_access", domain, "failed", started) writeJSON(w, http.StatusBadRequest, Envelope{Code: 400, Msg: friendlyACMEError(err)}) return } // A staging certificate is untrusted by design; use it only to prove the // challenge path works, never to serve the panel. if req.Staging { s.audit(r, "settings", "app_access_staging", domain, "ok", started) writeOK(w, map[string]any{ "domain": domain, "issuer": result.Issuer, "notAfter": result.NotAfter, "daysLeft": result.DaysLeft, "url": "", "staging": true, "message": "测试证书已签发,说明 80 端口通道正常。请取消「测试模式」再申请一次正式证书。", }) return } certPath := filepath.Join(outDir, "fullchain.pem") keyPath := filepath.Join(outDir, "privkey.pem") oldCert, oldKey, oldDomain := s.cfg.HTTPSCert, s.cfg.HTTPSKey, s.cfg.AppDomain s.cfg.HTTPSCert = certPath s.cfg.HTTPSKey = keyPath s.cfg.AppDomain = domain if !containsFold(s.cfg.HTTPSHosts, domain) { s.cfg.HTTPSHosts = append(s.cfg.HTTPSHosts, domain) } if err := s.cfg.Save(); err != nil { s.cfg.HTTPSCert, s.cfg.HTTPSKey, s.cfg.AppDomain = oldCert, oldKey, oldDomain writeErr(w, err) return } if err := s.tls.Reload(certPath, keyPath); err != nil { writeJSON(w, http.StatusInternalServerError, Envelope{ Code: 500, Msg: "证书已签发但加载失败:" + err.Error(), }) return } s.audit(r, "settings", "app_access", domain, "ok", started) writeOK(w, map[string]any{ "domain": domain, "issuer": result.Issuer, "notAfter": result.NotAfter, "daysLeft": result.DaysLeft, "url": "https://" + domain + portSuffix(s.cfg.Addr) + "/" + s.cfg.Entry + "/", }) } func (s *Server) handleAppAccessDisable(w http.ResponseWriter, r *http.Request) { if s.tls == nil { writeJSON(w, http.StatusServiceUnavailable, Envelope{Code: 503, Msg: "面板未启用 HTTPS"}) return } started := time.Now() oldCert, oldKey, oldDomain := s.cfg.HTTPSCert, s.cfg.HTTPSKey, s.cfg.AppDomain s.cfg.HTTPSCert = "" s.cfg.HTTPSKey = "" s.cfg.AppDomain = "" if err := s.cfg.Save(); err != nil { s.cfg.HTTPSCert, s.cfg.HTTPSKey, s.cfg.AppDomain = oldCert, oldKey, oldDomain writeErr(w, err) return } // Fall back to the self signed certificate so HTTPS keeps working. hosts := paneltls.LocalHosts() hosts = append(hosts, s.cfg.HTTPSHosts...) if material, err := paneltls.Ensure(s.cfg.SelfSignedDir(), hosts); err == nil { _ = s.tls.Reload(material.CertPath, material.KeyPath) } s.audit(r, "settings", "app_access_off", oldDomain, "ok", started) writeOK(w, s.settingsSnapshot()) } // friendlyACMEError turns the terse RFC 8555 payload into something an // operator can act on. func friendlyACMEError(err error) string { msg := err.Error() low := strings.ToLower(msg) if strings.Contains(low, "ratelimited") || strings.Contains(low, "too many failed authorizations") { return "该域名近期验证失败次数过多,Let's Encrypt 已临时拒绝签发(通常需等待 1 小时)。" + "请先确认 80 端口能从公网访问,再用「测试模式」重试,避免继续消耗正式额度。原始信息:" + msg } return msg } func containsFold(list []string, want string) bool { for _, v := range list { if strings.EqualFold(strings.TrimSpace(v), want) { return true } } return false } func validDomainName(domain string) bool { if len(domain) < 4 || len(domain) > 253 || !strings.Contains(domain, ".") { return false } if strings.HasPrefix(domain, ".") || strings.HasSuffix(domain, ".") || strings.Contains(domain, "..") { return false } for _, c := range domain { if (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '.' || c == '-' { continue } return false } return true } // startChallengeServer makes http:///.well-known/acme-challenge/ work // for the duration of the issuance. Returns a stop function. func (s *Server) startChallengeServer(ctx context.Context, domain, webRoot string) (func(), error) { challengeDir := filepath.Join(webRoot, ".well-known", "acme-challenge") if err := os.MkdirAll(challengeDir, 0o755); err != nil { return nil, fmt.Errorf("创建验证目录失败: %w", err) } // nginx runs as an unprivileged user; make sure it can actually walk down // to the token file even if a previous umask created the dirs tighter. for _, dir := range []string{webRoot, filepath.Join(webRoot, ".well-known"), challengeDir} { _ = os.Chmod(dir, 0o755) } // A fixed probe file lets the operator verify the public path themselves // while an issuance is running: http:///.well-known/acme-challenge/test.txt _ = os.WriteFile(filepath.Join(challengeDir, "test.txt"), []byte("miaopanel-acme-ok"), 0o644) s.logInfo("面板证书:验证目录 " + challengeDir) if ln, err := net.Listen("tcp", ":80"); err == nil { s.logInfo("面板证书:临时监听 80 端口处理 ACME 验证") srv := &http.Server{ Handler: http.FileServer(http.Dir(webRoot)), ReadHeaderTimeout: 10 * time.Second, } go func() { _ = srv.Serve(ln) }() return func() { shutdownCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second) defer cancel() _ = srv.Shutdown(shutdownCtx) }, nil } else { s.logInfo("面板证书:80 端口被占用,改用 nginx 临时 vhost(" + err.Error() + ")") } // Port 80 is taken: borrow nginx until Let's Encrypt is done verifying. if s.nginx == nil || !s.nginx.Available() { return nil, errors.New("80 端口被占用且 nginx 不可用,无法完成域名验证") } confPath := filepath.Join(s.cfg.Nginx.VhostDir, "panel-acme.conf") conf := fmt.Sprintf(`# MiaoPanel 临时 ACME 验证配置,申请结束后自动删除 server { listen 80; server_name %s; location ^~ /.well-known/acme-challenge/ { root %s; default_type text/plain; } location / { return 404; } } `, domain, webRoot) // Never block the request forever on a stuck nginx -t or reload. applyCtx, cancel := context.WithTimeout(ctx, 30*time.Second) defer cancel() if err := s.nginx.Apply(applyCtx, &webserver.Render{ Files: map[string][]byte{confPath: []byte(conf)}, }); err != nil { s.logInfo("面板证书:写入临时 nginx 配置失败:" + err.Error()) return nil, fmt.Errorf("写入临时 nginx 配置失败: %w", err) } s.logInfo("面板证书:已写入临时 nginx 配置 " + confPath) return func() { cleanupCtx, done := context.WithTimeout(context.Background(), 30*time.Second) defer done() _ = s.nginx.Apply(cleanupCtx, &webserver.Render{ Remove: []string{confPath}, }) }, nil } func (s *Server) logInfo(msg string) { if s.log != nil { s.log.Info(msg) } }