miaopanel
1package httpapi
2
3import (
4 "encoding/json"
5 "errors"
6 "net/http"
7 "os"
8 "strconv"
9 "strings"
10 "sync"
11 "time"
12
13 "github.com/miaopanel/miaopanel/internal/plugins"
14 "github.com/miaopanel/miaopanel/internal/store"
15)
16
17// pluginItem is a catalog entry plus local install state.
18type pluginItem struct {
19 plugins.CatalogEntry
20 Installed bool `json:"installed"`
21 InstalledVersion string `json:"installed_version"`
22 Status string `json:"status"`
23 Update bool `json:"update"`
24 Available string `json:"available"`
25 Revoked bool `json:"revoked"`
26 Reason string `json:"reason"`
27 AutoUpdate bool `json:"auto_update"`
28 PermissionView []plugins.Permission `json:"permission_view"`
29}
30
31func (s *Server) pluginService() (*plugins.Service, error) {
32 if s.plugins == nil {
33 return nil, Errorf(http.StatusServiceUnavailable, "插件系统未初始化")
34 }
35 return s.plugins, nil
36}
37
38func (s *Server) handlePlugins(w http.ResponseWriter, r *http.Request) {
39 svc, err := s.pluginService()
40 if err != nil {
41 writeErr(w, err)
42 return
43 }
44 refresh := r.URL.Query().Get("refresh") == "1"
45 cat, cerr := svc.Catalog(r.Context(), refresh)
46 installed, _ := svc.InstalledViews(r.Context())
47 if cat == nil {
48 // The control plane may be unreachable (offline server, older release).
49 // Return local state so the operator can still uninstall.
50 items := make([]pluginItem, 0, len(installed))
51 for _, iv := range installed {
52 items = append(items, pluginItem{
53 CatalogEntry: plugins.CatalogEntry{Slug: iv.Slug, Name: iv.Name, Summary: "离线:仅显示已安装状态"},
54 Installed: true, InstalledVersion: iv.Version, Status: iv.Status,
55 Revoked: iv.Revoked, Reason: iv.Reason, AutoUpdate: iv.AutoUpdate,
56 })
57 }
58 msg := ""
59 if cerr != nil {
60 msg = cerr.Error()
61 }
62 writeOK(w, map[string]any{
63 "plugins": items, "tasks": svc.Tasks(10), "offline": true,
64 "error": msg, "updated_at": time.Now().Unix(),
65 })
66 return
67 }
68 out := make([]pluginItem, 0, len(cat.Plugins))
69 seen := map[string]bool{}
70 for _, e := range cat.Plugins {
71 item := pluginItem{CatalogEntry: e}
72 for _, iv := range installed {
73 if iv.Slug == e.Slug {
74 item.Installed = true
75 item.InstalledVersion = iv.Version
76 item.Status = iv.Status
77 item.Update = iv.Update
78 item.Available = iv.Available
79 item.Revoked = iv.Revoked
80 item.Reason = iv.Reason
81 item.AutoUpdate = iv.AutoUpdate
82 }
83 }
84 item.PermissionView = plugins.ParsePermissions(e.Permissions)
85 out = append(out, item)
86 seen[e.Slug] = true
87 }
88 // Installed plugins that disappeared from the catalog (yanked/suspended)
89 // must stay visible so the operator can uninstall them.
90 for _, iv := range installed {
91 if seen[iv.Slug] {
92 continue
93 }
94 out = append(out, pluginItem{
95 CatalogEntry: plugins.CatalogEntry{
96 Slug: iv.Slug, Name: iv.Name, Summary: "该插件已从市场下架",
97 },
98 Installed: true, InstalledVersion: iv.Version, Status: iv.Status,
99 Revoked: iv.Revoked, Reason: iv.Reason, AutoUpdate: iv.AutoUpdate,
100 })
101 }
102 msg := ""
103 if cerr != nil {
104 msg = cerr.Error()
105 }
106 writeOK(w, map[string]any{
107 "plugins": out,
108 "tasks": svc.Tasks(10),
109 "updated_at": time.Now().Unix(),
110 "offline": cerr != nil,
111 "error": msg,
112 })
113}
114
115type pluginConfigReq struct {
116 RepoURL string `json:"repo_url"`
117 AutoUpdate bool `json:"auto_update"`
118}
119
120// handlePluginConfig reads or updates the catalog endpoint.
121func (s *Server) handlePluginConfig(w http.ResponseWriter, r *http.Request) {
122 if r.Method == http.MethodGet {
123 writeOK(w, map[string]any{
124 "repo_url": s.cfg.PluginRepoURL,
125 "auto_update": s.cfg.PluginAutoUpdate,
126 })
127 return
128 }
129 var req pluginConfigReq
130 if err := decodeJSON(w, r, &req, 8<<10); err != nil {
131 writeErr(w, err)
132 return
133 }
134 raw := strings.TrimRight(strings.TrimSpace(req.RepoURL), "/")
135 if raw == "" || (!strings.HasPrefix(raw, "https://") && !strings.HasPrefix(raw, "http://")) {
136 writeJSON(w, http.StatusBadRequest, Envelope{Code: 400, Msg: "插件服务器必须是 http(s) 地址"})
137 return
138 }
139 s.cfg.PluginRepoURL = raw
140 s.cfg.PluginAutoUpdate = req.AutoUpdate
141 if err := s.cfg.Save(); err != nil {
142 writeErr(w, err)
143 return
144 }
145 if s.plugins != nil {
146 s.plugins.InvalidateCatalog()
147 }
148 s.audit(r, "plugins", "config", raw, "ok", time.Now())
149 writeOK(w, map[string]any{"repo_url": s.cfg.PluginRepoURL, "auto_update": s.cfg.PluginAutoUpdate})
150}
151
152// handlePluginResetKey forgets the pinned platform signing key so the next
153// catalog fetch pins the current one (key rotation).
154func (s *Server) handlePluginResetKey(w http.ResponseWriter, r *http.Request) {
155 svc, err := s.pluginService()
156 if err != nil {
157 writeErr(w, err)
158 return
159 }
160 if err := svc.ResetPlatformKey(r.Context()); err != nil {
161 writeErr(w, err)
162 return
163 }
164 svc.InvalidateCatalog()
165 s.audit(r, "plugins", "reset_platform_key", "", "ok", time.Now())
166 writeOK(w, map[string]any{"reset": true})
167}
168
169func (s *Server) handlePluginTasks(w http.ResponseWriter, r *http.Request) {
170 svc, err := s.pluginService()
171 if err != nil {
172 writeErr(w, err)
173 return
174 }
175 limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
176 writeOK(w, svc.Tasks(limit))
177}
178
179func (s *Server) handlePluginTask(w http.ResponseWriter, r *http.Request) {
180 svc, err := s.pluginService()
181 if err != nil {
182 writeErr(w, err)
183 return
184 }
185 task, ok := svc.Task(r.PathValue("id"))
186 if !ok {
187 writeJSON(w, http.StatusNotFound, Envelope{Code: 404, Msg: "任务不存在"})
188 return
189 }
190 writeOK(w, task)
191}
192
193type pluginVersionReq struct {
194 Version string `json:"version"`
195 Confirm string `json:"confirm"`
196}
197
198func (s *Server) handlePluginInstall(w http.ResponseWriter, r *http.Request) {
199 svc, err := s.pluginService()
200 if err != nil {
201 writeErr(w, err)
202 return
203 }
204 var req pluginVersionReq
205 if err := decodeJSON(w, r, &req, 8<<10); err != nil {
206 writeErr(w, err)
207 return
208 }
209 slug := r.PathValue("slug")
210 started := time.Now()
211 task, err := svc.Install(r.Context(), slug, req.Version, req.Confirm, false)
212 if err != nil {
213 s.writePluginError(w, err)
214 return
215 }
216 dropProxyCache(slug)
217 s.audit(r, "plugins", "install", slug+"@"+req.Version, "started", started)
218 writeOK(w, task)
219}
220
221type pluginUninstallReq struct {
222 Confirm string `json:"confirm"`
223 Purge bool `json:"purge"`
224 Force bool `json:"force"`
225}
226
227func (s *Server) handlePluginUninstall(w http.ResponseWriter, r *http.Request) {
228 svc, err := s.pluginService()
229 if err != nil {
230 writeErr(w, err)
231 return
232 }
233 var req pluginUninstallReq
234 if err := decodeJSON(w, r, &req, 8<<10); err != nil {
235 writeErr(w, err)
236 return
237 }
238 slug := r.PathValue("slug")
239 started := time.Now()
240 task, err := svc.Uninstall(r.Context(), slug, req.Confirm, req.Purge, req.Force)
241 if err != nil {
242 s.writePluginError(w, err)
243 return
244 }
245 dropProxyCache(slug)
246 s.audit(r, "plugins", "uninstall", slug, "started", started)
247 writeOK(w, task)
248}
249
250type pluginActionReq struct {
251 Action string `json:"action"`
252}
253
254func (s *Server) handlePluginAction(w http.ResponseWriter, r *http.Request) {
255 svc, err := s.pluginService()
256 if err != nil {
257 writeErr(w, err)
258 return
259 }
260 var req pluginActionReq
261 if err := decodeJSON(w, r, &req, 4<<10); err != nil {
262 writeErr(w, err)
263 return
264 }
265 slug := r.PathValue("slug")
266 if err := svc.Action(r.Context(), slug, req.Action); err != nil {
267 s.writePluginError(w, err)
268 return
269 }
270 s.audit(r, "plugins", req.Action, slug, "ok", time.Now())
271 writeOK(w, map[string]any{"slug": slug, "action": req.Action})
272}
273
274type pluginAutoReq struct {
275 AutoUpdate bool `json:"auto_update"`
276}
277
278func (s *Server) handlePluginAutoUpdate(w http.ResponseWriter, r *http.Request) {
279 svc, err := s.pluginService()
280 if err != nil {
281 writeErr(w, err)
282 return
283 }
284 var req pluginAutoReq
285 if err := decodeJSON(w, r, &req, 4<<10); err != nil {
286 writeErr(w, err)
287 return
288 }
289 slug := r.PathValue("slug")
290 if err := svc.SetAutoUpdate(r.Context(), slug, req.AutoUpdate); err != nil {
291 s.writePluginError(w, err)
292 return
293 }
294 writeOK(w, map[string]any{"slug": slug, "auto_update": req.AutoUpdate})
295}
296
297func (s *Server) handlePluginSettings(w http.ResponseWriter, r *http.Request) {
298 svc, err := s.pluginService()
299 if err != nil {
300 writeErr(w, err)
301 return
302 }
303 slug := r.PathValue("slug")
304 p, err := s.db.PluginBySlug(r.Context(), slug)
305 if err != nil {
306 writeJSON(w, http.StatusNotFound, Envelope{Code: 404, Msg: "插件未安装"})
307 return
308 }
309 if r.Method == http.MethodGet {
310 values, _ := svc.Settings(r.Context(), slug)
311 writeOK(w, map[string]any{
312 "slug": slug, "values": values, "schema": uiSchema(p.Manifest),
313 })
314 return
315 }
316 var req struct {
317 Values map[string]string `json:"values"`
318 }
319 if err := decodeJSON(w, r, &req, 1<<20); err != nil {
320 writeErr(w, err)
321 return
322 }
323 if req.Values == nil {
324 req.Values = map[string]string{}
325 }
326 if err := svc.SaveSettings(r.Context(), slug, req.Values); err != nil {
327 s.writePluginError(w, err)
328 return
329 }
330 s.audit(r, "plugins", "settings", slug, "ok", time.Now())
331 writeOK(w, map[string]any{"slug": slug, "saved": len(req.Values)})
332}
333
334// uiSchema extracts the declarative form definition from the manifest.
335func uiSchema(rawManifest string) any {
336 m, err := plugins.Parse([]byte(rawManifest))
337 if err != nil || len(m.UI) == 0 {
338 return nil
339 }
340 var schema any
341 if err := json.Unmarshal(m.UI, &schema); err != nil {
342 return nil
343 }
344 if obj, ok := schema.(map[string]any); ok {
345 if t, _ := obj["type"].(string); t != "declarative" {
346 return nil
347 }
348 }
349 return schema
350}
351
352func (s *Server) handlePluginEvents(w http.ResponseWriter, r *http.Request) {
353 slug := r.URL.Query().Get("slug")
354 events, err := s.db.PluginEvents(r.Context(), slug, 80)
355 if err != nil {
356 writeErr(w, err)
357 return
358 }
359 writeOK(w, events)
360}
361
362type proxyCacheEntry struct {
363 handler http.Handler
364 at time.Time
365}
366
367// proxyCacheTTL bounds how long a cached handler may outlive the plugin it
368// points at: uninstall, reinstall or an upgrade moves the socket, and a
369// permanent cache kept forwarding to the stale path until a restart.
370const proxyCacheTTL = 30 * time.Second
371
372var (
373 proxyCacheMu sync.Mutex
374 proxyCache = map[string]proxyCacheEntry{}
375)
376
377func dropProxyCache(slug string) {
378 proxyCacheMu.Lock()
379 delete(proxyCache, slug)
380 proxyCacheMu.Unlock()
381}
382
383// handlePluginProxy forwards service plugin API calls to its unix socket.
384func (s *Server) handlePluginProxy(w http.ResponseWriter, r *http.Request) {
385 svc, err := s.pluginService()
386 if err != nil {
387 writeErr(w, err)
388 return
389 }
390 slug := r.PathValue("slug")
391 proxyCacheMu.Lock()
392 entry, ok := proxyCache[slug]
393 proxyCacheMu.Unlock()
394 var handler http.Handler
395 if ok && time.Since(entry.at) < proxyCacheTTL {
396 handler = entry.handler
397 }
398 if handler == nil {
399 h, err := svc.ProxyHandler(slug)
400 if err != nil {
401 writeJSON(w, http.StatusBadRequest, Envelope{Code: 400, Msg: err.Error()})
402 return
403 }
404 proxyCacheMu.Lock()
405 proxyCache[slug] = proxyCacheEntry{handler: h, at: time.Now()}
406 proxyCacheMu.Unlock()
407 handler = h
408 }
409 handler.ServeHTTP(w, r)
410}
411
412func (s *Server) writePluginError(w http.ResponseWriter, err error) {
413 switch {
414 case errors.Is(err, plugins.ErrTaskRunning):
415 writeJSON(w, http.StatusConflict, Envelope{Code: 409, Msg: err.Error()})
416 case errors.Is(err, store.ErrNotFound):
417 writeJSON(w, http.StatusNotFound, Envelope{Code: 404, Msg: "插件不存在"})
418 case errors.Is(err, os.ErrPermission):
419 writeJSON(w, http.StatusForbidden, Envelope{Code: 403, Msg: "需要 Linux root 权限"})
420 default:
421 if s.log != nil {
422 s.log.Error("plugin operation failed", "error", err)
423 }
424 writeJSON(w, http.StatusBadRequest, Envelope{Code: 400, Msg: err.Error()})
425 }
426}