package httpapi import ( "encoding/json" "errors" "net/http" "os" "strconv" "strings" "sync" "time" "github.com/miaopanel/miaopanel/internal/plugins" "github.com/miaopanel/miaopanel/internal/store" ) // pluginItem is a catalog entry plus local install state. type pluginItem struct { plugins.CatalogEntry Installed bool `json:"installed"` InstalledVersion string `json:"installed_version"` Status string `json:"status"` Update bool `json:"update"` Available string `json:"available"` Revoked bool `json:"revoked"` Reason string `json:"reason"` AutoUpdate bool `json:"auto_update"` PermissionView []plugins.Permission `json:"permission_view"` } func (s *Server) pluginService() (*plugins.Service, error) { if s.plugins == nil { return nil, Errorf(http.StatusServiceUnavailable, "插件系统未初始化") } return s.plugins, nil } func (s *Server) handlePlugins(w http.ResponseWriter, r *http.Request) { svc, err := s.pluginService() if err != nil { writeErr(w, err) return } refresh := r.URL.Query().Get("refresh") == "1" cat, cerr := svc.Catalog(r.Context(), refresh) installed, _ := svc.InstalledViews(r.Context()) if cat == nil { // The control plane may be unreachable (offline server, older release). // Return local state so the operator can still uninstall. items := make([]pluginItem, 0, len(installed)) for _, iv := range installed { items = append(items, pluginItem{ CatalogEntry: plugins.CatalogEntry{Slug: iv.Slug, Name: iv.Name, Summary: "离线:仅显示已安装状态"}, Installed: true, InstalledVersion: iv.Version, Status: iv.Status, Revoked: iv.Revoked, Reason: iv.Reason, AutoUpdate: iv.AutoUpdate, }) } msg := "" if cerr != nil { msg = cerr.Error() } writeOK(w, map[string]any{ "plugins": items, "tasks": svc.Tasks(10), "offline": true, "error": msg, "updated_at": time.Now().Unix(), }) return } out := make([]pluginItem, 0, len(cat.Plugins)) seen := map[string]bool{} for _, e := range cat.Plugins { item := pluginItem{CatalogEntry: e} for _, iv := range installed { if iv.Slug == e.Slug { item.Installed = true item.InstalledVersion = iv.Version item.Status = iv.Status item.Update = iv.Update item.Available = iv.Available item.Revoked = iv.Revoked item.Reason = iv.Reason item.AutoUpdate = iv.AutoUpdate } } item.PermissionView = plugins.ParsePermissions(e.Permissions) out = append(out, item) seen[e.Slug] = true } // Installed plugins that disappeared from the catalog (yanked/suspended) // must stay visible so the operator can uninstall them. for _, iv := range installed { if seen[iv.Slug] { continue } out = append(out, pluginItem{ CatalogEntry: plugins.CatalogEntry{ Slug: iv.Slug, Name: iv.Name, Summary: "该插件已从市场下架", }, Installed: true, InstalledVersion: iv.Version, Status: iv.Status, Revoked: iv.Revoked, Reason: iv.Reason, AutoUpdate: iv.AutoUpdate, }) } msg := "" if cerr != nil { msg = cerr.Error() } writeOK(w, map[string]any{ "plugins": out, "tasks": svc.Tasks(10), "updated_at": time.Now().Unix(), "offline": cerr != nil, "error": msg, }) } type pluginConfigReq struct { RepoURL string `json:"repo_url"` AutoUpdate bool `json:"auto_update"` } // handlePluginConfig reads or updates the catalog endpoint. func (s *Server) handlePluginConfig(w http.ResponseWriter, r *http.Request) { if r.Method == http.MethodGet { writeOK(w, map[string]any{ "repo_url": s.cfg.PluginRepoURL, "auto_update": s.cfg.PluginAutoUpdate, }) return } var req pluginConfigReq if err := decodeJSON(w, r, &req, 8<<10); err != nil { writeErr(w, err) return } raw := strings.TrimRight(strings.TrimSpace(req.RepoURL), "/") if raw == "" || (!strings.HasPrefix(raw, "https://") && !strings.HasPrefix(raw, "http://")) { writeJSON(w, http.StatusBadRequest, Envelope{Code: 400, Msg: "插件服务器必须是 http(s) 地址"}) return } s.cfg.PluginRepoURL = raw s.cfg.PluginAutoUpdate = req.AutoUpdate if err := s.cfg.Save(); err != nil { writeErr(w, err) return } if s.plugins != nil { s.plugins.InvalidateCatalog() } s.audit(r, "plugins", "config", raw, "ok", time.Now()) writeOK(w, map[string]any{"repo_url": s.cfg.PluginRepoURL, "auto_update": s.cfg.PluginAutoUpdate}) } // handlePluginResetKey forgets the pinned platform signing key so the next // catalog fetch pins the current one (key rotation). func (s *Server) handlePluginResetKey(w http.ResponseWriter, r *http.Request) { svc, err := s.pluginService() if err != nil { writeErr(w, err) return } if err := svc.ResetPlatformKey(r.Context()); err != nil { writeErr(w, err) return } svc.InvalidateCatalog() s.audit(r, "plugins", "reset_platform_key", "", "ok", time.Now()) writeOK(w, map[string]any{"reset": true}) } func (s *Server) handlePluginTasks(w http.ResponseWriter, r *http.Request) { svc, err := s.pluginService() if err != nil { writeErr(w, err) return } limit, _ := strconv.Atoi(r.URL.Query().Get("limit")) writeOK(w, svc.Tasks(limit)) } func (s *Server) handlePluginTask(w http.ResponseWriter, r *http.Request) { svc, err := s.pluginService() if err != nil { writeErr(w, err) return } task, ok := svc.Task(r.PathValue("id")) if !ok { writeJSON(w, http.StatusNotFound, Envelope{Code: 404, Msg: "任务不存在"}) return } writeOK(w, task) } type pluginVersionReq struct { Version string `json:"version"` Confirm string `json:"confirm"` } func (s *Server) handlePluginInstall(w http.ResponseWriter, r *http.Request) { svc, err := s.pluginService() if err != nil { writeErr(w, err) return } var req pluginVersionReq if err := decodeJSON(w, r, &req, 8<<10); err != nil { writeErr(w, err) return } slug := r.PathValue("slug") started := time.Now() task, err := svc.Install(r.Context(), slug, req.Version, req.Confirm, false) if err != nil { s.writePluginError(w, err) return } dropProxyCache(slug) s.audit(r, "plugins", "install", slug+"@"+req.Version, "started", started) writeOK(w, task) } type pluginUninstallReq struct { Confirm string `json:"confirm"` Purge bool `json:"purge"` Force bool `json:"force"` } func (s *Server) handlePluginUninstall(w http.ResponseWriter, r *http.Request) { svc, err := s.pluginService() if err != nil { writeErr(w, err) return } var req pluginUninstallReq if err := decodeJSON(w, r, &req, 8<<10); err != nil { writeErr(w, err) return } slug := r.PathValue("slug") started := time.Now() task, err := svc.Uninstall(r.Context(), slug, req.Confirm, req.Purge, req.Force) if err != nil { s.writePluginError(w, err) return } dropProxyCache(slug) s.audit(r, "plugins", "uninstall", slug, "started", started) writeOK(w, task) } type pluginActionReq struct { Action string `json:"action"` } func (s *Server) handlePluginAction(w http.ResponseWriter, r *http.Request) { svc, err := s.pluginService() if err != nil { writeErr(w, err) return } var req pluginActionReq if err := decodeJSON(w, r, &req, 4<<10); err != nil { writeErr(w, err) return } slug := r.PathValue("slug") if err := svc.Action(r.Context(), slug, req.Action); err != nil { s.writePluginError(w, err) return } s.audit(r, "plugins", req.Action, slug, "ok", time.Now()) writeOK(w, map[string]any{"slug": slug, "action": req.Action}) } type pluginAutoReq struct { AutoUpdate bool `json:"auto_update"` } func (s *Server) handlePluginAutoUpdate(w http.ResponseWriter, r *http.Request) { svc, err := s.pluginService() if err != nil { writeErr(w, err) return } var req pluginAutoReq if err := decodeJSON(w, r, &req, 4<<10); err != nil { writeErr(w, err) return } slug := r.PathValue("slug") if err := svc.SetAutoUpdate(r.Context(), slug, req.AutoUpdate); err != nil { s.writePluginError(w, err) return } writeOK(w, map[string]any{"slug": slug, "auto_update": req.AutoUpdate}) } func (s *Server) handlePluginSettings(w http.ResponseWriter, r *http.Request) { svc, err := s.pluginService() if err != nil { writeErr(w, err) return } slug := r.PathValue("slug") p, err := s.db.PluginBySlug(r.Context(), slug) if err != nil { writeJSON(w, http.StatusNotFound, Envelope{Code: 404, Msg: "插件未安装"}) return } if r.Method == http.MethodGet { values, _ := svc.Settings(r.Context(), slug) writeOK(w, map[string]any{ "slug": slug, "values": values, "schema": uiSchema(p.Manifest), }) return } var req struct { Values map[string]string `json:"values"` } if err := decodeJSON(w, r, &req, 1<<20); err != nil { writeErr(w, err) return } if req.Values == nil { req.Values = map[string]string{} } if err := svc.SaveSettings(r.Context(), slug, req.Values); err != nil { s.writePluginError(w, err) return } s.audit(r, "plugins", "settings", slug, "ok", time.Now()) writeOK(w, map[string]any{"slug": slug, "saved": len(req.Values)}) } // uiSchema extracts the declarative form definition from the manifest. func uiSchema(rawManifest string) any { m, err := plugins.Parse([]byte(rawManifest)) if err != nil || len(m.UI) == 0 { return nil } var schema any if err := json.Unmarshal(m.UI, &schema); err != nil { return nil } if obj, ok := schema.(map[string]any); ok { if t, _ := obj["type"].(string); t != "declarative" { return nil } } return schema } func (s *Server) handlePluginEvents(w http.ResponseWriter, r *http.Request) { slug := r.URL.Query().Get("slug") events, err := s.db.PluginEvents(r.Context(), slug, 80) if err != nil { writeErr(w, err) return } writeOK(w, events) } type proxyCacheEntry struct { handler http.Handler at time.Time } // proxyCacheTTL bounds how long a cached handler may outlive the plugin it // points at: uninstall, reinstall or an upgrade moves the socket, and a // permanent cache kept forwarding to the stale path until a restart. const proxyCacheTTL = 30 * time.Second var ( proxyCacheMu sync.Mutex proxyCache = map[string]proxyCacheEntry{} ) func dropProxyCache(slug string) { proxyCacheMu.Lock() delete(proxyCache, slug) proxyCacheMu.Unlock() } // handlePluginProxy forwards service plugin API calls to its unix socket. func (s *Server) handlePluginProxy(w http.ResponseWriter, r *http.Request) { svc, err := s.pluginService() if err != nil { writeErr(w, err) return } slug := r.PathValue("slug") proxyCacheMu.Lock() entry, ok := proxyCache[slug] proxyCacheMu.Unlock() var handler http.Handler if ok && time.Since(entry.at) < proxyCacheTTL { handler = entry.handler } if handler == nil { h, err := svc.ProxyHandler(slug) if err != nil { writeJSON(w, http.StatusBadRequest, Envelope{Code: 400, Msg: err.Error()}) return } proxyCacheMu.Lock() proxyCache[slug] = proxyCacheEntry{handler: h, at: time.Now()} proxyCacheMu.Unlock() handler = h } handler.ServeHTTP(w, r) } func (s *Server) writePluginError(w http.ResponseWriter, err error) { switch { case errors.Is(err, plugins.ErrTaskRunning): writeJSON(w, http.StatusConflict, Envelope{Code: 409, Msg: err.Error()}) case errors.Is(err, store.ErrNotFound): writeJSON(w, http.StatusNotFound, Envelope{Code: 404, Msg: "插件不存在"}) case errors.Is(err, os.ErrPermission): writeJSON(w, http.StatusForbidden, Envelope{Code: 403, Msg: "需要 Linux root 权限"}) default: if s.log != nil { s.log.Error("plugin operation failed", "error", err) } writeJSON(w, http.StatusBadRequest, Envelope{Code: 400, Msg: err.Error()}) } }