miaopanel
1package plugins
2
3import (
4 "context"
5 "encoding/json"
6 "errors"
7 "fmt"
8 "io"
9 "net/http"
10 "net/url"
11 "os"
12 "path/filepath"
13 "runtime"
14 "strings"
15 "time"
16
17 "github.com/miaopanel/miaopanel/internal/semver"
18 "github.com/miaopanel/miaopanel/internal/store"
19)
20
21// CatalogVersion is one published artifact.
22type CatalogVersion struct {
23 Version string `json:"version"`
24 Channel string `json:"channel"`
25 Arch string `json:"arch"`
26 Size int64 `json:"size"`
27 SHA256 string `json:"sha256"`
28 MinPanel string `json:"min_panel"`
29 MaxPanel string `json:"max_panel"`
30 Downloads int64 `json:"downloads"`
31 PublishedAt int64 `json:"published_at"`
32}
33
34// CatalogEntry is one plugin in the public catalog.
35type CatalogEntry struct {
36 Slug string `json:"slug"`
37 Name string `json:"name"`
38 Summary string `json:"summary"`
39 Category string `json:"category"`
40 License string `json:"license"`
41 Homepage string `json:"homepage"`
42 Icon string `json:"icon"`
43 Author string `json:"author"`
44 Downloads int64 `json:"downloads"`
45 Permissions []string `json:"permissions"`
46 Latest *CatalogVersion `json:"latest"`
47 Versions []CatalogVersion `json:"versions"`
48}
49
50// Catalog is the signed list served by the control plane.
51type Catalog struct {
52 API int `json:"api"`
53 UpdatedAt int64 `json:"updated_at"`
54 Plugins []CatalogEntry `json:"plugins"`
55}
56
57// catalogResponse is the envelope of GET /api/v1/plugins.
58type catalogResponse struct {
59 API int `json:"api"`
60 UpdatedAt int64 `json:"updated_at"`
61 Plugins []CatalogEntry `json:"plugins"`
62}
63
64// ManifestDoc is the signed manifest plus artifact metadata.
65type ManifestDoc struct {
66 Slug string `json:"slug"`
67 Version string `json:"version"`
68 Arch string `json:"arch"`
69 Manifest string `json:"manifest"`
70 PlatformSig string `json:"platform_sig"`
71 PlatformPubkey string `json:"platform_pubkey"`
72 DevSig string `json:"dev_sig"`
73 Artifact struct {
74 URL string `json:"url"`
75 SHA256 string `json:"sha256"`
76 Size int64 `json:"size"`
77 Arch string `json:"arch"`
78 } `json:"artifact"`
79}
80
81func (s *Service) repoURL() string {
82 return strings.TrimRight(s.cfg.PluginRepoURL, "/")
83}
84
85func (s *Service) catalogCachePath() string {
86 return filepath.Join(s.cfg.DataDir, "plugins", "catalog.json")
87}
88
89// Catalog returns the cached catalog, refreshing it at most once an hour.
90func (s *Service) Catalog(ctx context.Context, refresh bool) (*Catalog, error) {
91 s.mu.Lock()
92 defer s.mu.Unlock()
93 if !refresh && s.catalog != nil && time.Since(s.catalogAt) < time.Hour {
94 return s.catalog, nil
95 }
96 cat, err := s.fetchCatalog(ctx)
97 if err != nil {
98 if cached, cerr := s.loadCachedCatalog(); cerr == nil {
99 s.catalog, s.catalogAt = cached, time.Now().Add(-30*time.Minute)
100 return cached, nil
101 }
102 return nil, err
103 }
104 s.catalog, s.catalogAt = cat, time.Now()
105 s.saveCachedCatalog(cat)
106 return cat, nil
107}
108
109func (s *Service) fetchCatalog(ctx context.Context) (*Catalog, error) {
110 q := url.Values{}
111 q.Set("api", "1")
112 q.Set("panel", strings.TrimPrefix(s.version, "v"))
113 q.Set("arch", runtime.GOARCH)
114 q.Set("os", "linux")
115 var raw catalogResponse
116 if err := s.apiGet(ctx, "/api/v1/plugins?"+q.Encode(), &raw); err != nil {
117 return nil, err
118 }
119 cat := &Catalog{API: raw.API, UpdatedAt: raw.UpdatedAt, Plugins: raw.Plugins}
120 return cat, nil
121}
122
123func (s *Service) saveCachedCatalog(cat *Catalog) {
124 path := s.catalogCachePath()
125 if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
126 return
127 }
128 body, err := json.Marshal(cat)
129 if err != nil {
130 return
131 }
132 _ = os.WriteFile(path, body, 0o644)
133}
134
135func (s *Service) loadCachedCatalog() (*Catalog, error) {
136 raw, err := os.ReadFile(s.catalogCachePath())
137 if err != nil {
138 return nil, err
139 }
140 var cat Catalog
141 if err := json.Unmarshal(raw, &cat); err != nil {
142 return nil, err
143 }
144 return &cat, nil
145}
146
147// Entry returns one catalog entry by slug.
148func (s *Service) Entry(ctx context.Context, slug string) (*CatalogEntry, error) {
149 cat, err := s.Catalog(ctx, false)
150 if err != nil {
151 return nil, err
152 }
153 for i := range cat.Plugins {
154 if cat.Plugins[i].Slug == slug {
155 return &cat.Plugins[i], nil
156 }
157 }
158 return nil, store.ErrNotFound
159}
160
161// VersionInfo returns one published version of an entry.
162func (e *CatalogEntry) VersionInfo(version, arch string) (*CatalogVersion, error) {
163 for i := range e.Versions {
164 if e.Versions[i].Version == version && e.Versions[i].Arch == arch {
165 return &e.Versions[i], nil
166 }
167 }
168 if version == "" && e.Latest != nil {
169 return e.Latest, nil
170 }
171 return nil, errors.New("指定版本不存在")
172}
173
174// ManifestDoc fetches and returns the signed document for a version.
175func (s *Service) ManifestDoc(ctx context.Context, slug, version, arch string) (*ManifestDoc, error) {
176 if arch == "" {
177 arch = runtime.GOARCH
178 }
179 path := fmt.Sprintf("/api/v1/plugins/%s/%s/manifest?arch=%s",
180 url.PathEscape(slug), url.PathEscape(version), url.QueryEscape(arch))
181 var doc ManifestDoc
182 if err := s.apiGet(ctx, path, &doc); err != nil {
183 return nil, err
184 }
185 return &doc, nil
186}
187
188// apiGet performs a bounded JSON request against the control plane and unwraps
189// the {code,msg,data} envelope.
190func (s *Service) apiGet(ctx context.Context, path string, out any) error {
191 req, err := http.NewRequestWithContext(ctx, http.MethodGet, s.repoURL()+path, nil)
192 if err != nil {
193 return err
194 }
195 req.Header.Set("User-Agent", "miaopanel/"+s.version)
196 req.Header.Set("Accept", "application/json")
197 res, err := s.client.Do(req)
198 if err != nil {
199 return fmt.Errorf("连接插件服务器失败: %w", err)
200 }
201 defer res.Body.Close()
202 body, err := io.ReadAll(io.LimitReader(res.Body, 8<<20))
203 if err != nil {
204 return err
205 }
206 if res.StatusCode == http.StatusNotFound {
207 return errors.New("插件服务器未提供该接口,请确认发布服务器已升级到支持插件市场的版本")
208 }
209 var env struct {
210 Code int `json:"code"`
211 Msg string `json:"msg"`
212 Data json.RawMessage `json:"data"`
213 }
214 if err := json.Unmarshal(body, &env); err != nil {
215 return fmt.Errorf("插件服务器返回异常 (HTTP %d)", res.StatusCode)
216 }
217 if env.Code != 0 {
218 msg := env.Msg
219 if msg == "" {
220 msg = fmt.Sprintf("插件服务器返回错误码 %d", env.Code)
221 }
222 return errors.New(msg)
223 }
224 if len(env.Data) == 0 {
225 return errors.New("插件服务器返回空数据")
226 }
227 return json.Unmarshal(env.Data, out)
228}
229
230// InstalledViews merges the catalog with local install state for the UI.
231func (s *Service) InstalledViews(ctx context.Context) ([]InstalledView, error) {
232 installed, err := s.db.Plugins(ctx)
233 if err != nil {
234 return nil, err
235 }
236 cat, _ := s.Catalog(ctx, false)
237 out := make([]InstalledView, 0, len(installed))
238 for _, p := range installed {
239 v := InstalledView{Plugin: *p}
240 if cat != nil {
241 for i := range cat.Plugins {
242 if cat.Plugins[i].Slug != p.Slug {
243 continue
244 }
245 if cat.Plugins[i].Latest != nil {
246 v.Available = cat.Plugins[i].Latest.Version
247 v.Update = semver.Compare(cat.Plugins[i].Latest.Version, p.Version) > 0
248 }
249 }
250 }
251 if rv, err := s.db.RevocationFor(ctx, p.Slug, p.Version); err == nil {
252 v.Revoked = true
253 v.Reason = rv.Reason
254 }
255 out = append(out, v)
256 }
257 return out, nil
258}