package plugins import ( "context" "encoding/json" "errors" "fmt" "io" "net/http" "net/url" "os" "path/filepath" "runtime" "strings" "time" "github.com/miaopanel/miaopanel/internal/semver" "github.com/miaopanel/miaopanel/internal/store" ) // CatalogVersion is one published artifact. type CatalogVersion struct { Version string `json:"version"` Channel string `json:"channel"` Arch string `json:"arch"` Size int64 `json:"size"` SHA256 string `json:"sha256"` MinPanel string `json:"min_panel"` MaxPanel string `json:"max_panel"` Downloads int64 `json:"downloads"` PublishedAt int64 `json:"published_at"` } // CatalogEntry is one plugin in the public catalog. type CatalogEntry struct { Slug string `json:"slug"` Name string `json:"name"` Summary string `json:"summary"` Category string `json:"category"` License string `json:"license"` Homepage string `json:"homepage"` Icon string `json:"icon"` Author string `json:"author"` Downloads int64 `json:"downloads"` Permissions []string `json:"permissions"` Latest *CatalogVersion `json:"latest"` Versions []CatalogVersion `json:"versions"` } // Catalog is the signed list served by the control plane. type Catalog struct { API int `json:"api"` UpdatedAt int64 `json:"updated_at"` Plugins []CatalogEntry `json:"plugins"` } // catalogResponse is the envelope of GET /api/v1/plugins. type catalogResponse struct { API int `json:"api"` UpdatedAt int64 `json:"updated_at"` Plugins []CatalogEntry `json:"plugins"` } // ManifestDoc is the signed manifest plus artifact metadata. type ManifestDoc struct { Slug string `json:"slug"` Version string `json:"version"` Arch string `json:"arch"` Manifest string `json:"manifest"` PlatformSig string `json:"platform_sig"` PlatformPubkey string `json:"platform_pubkey"` DevSig string `json:"dev_sig"` Artifact struct { URL string `json:"url"` SHA256 string `json:"sha256"` Size int64 `json:"size"` Arch string `json:"arch"` } `json:"artifact"` } func (s *Service) repoURL() string { return strings.TrimRight(s.cfg.PluginRepoURL, "/") } func (s *Service) catalogCachePath() string { return filepath.Join(s.cfg.DataDir, "plugins", "catalog.json") } // Catalog returns the cached catalog, refreshing it at most once an hour. func (s *Service) Catalog(ctx context.Context, refresh bool) (*Catalog, error) { s.mu.Lock() defer s.mu.Unlock() if !refresh && s.catalog != nil && time.Since(s.catalogAt) < time.Hour { return s.catalog, nil } cat, err := s.fetchCatalog(ctx) if err != nil { if cached, cerr := s.loadCachedCatalog(); cerr == nil { s.catalog, s.catalogAt = cached, time.Now().Add(-30*time.Minute) return cached, nil } return nil, err } s.catalog, s.catalogAt = cat, time.Now() s.saveCachedCatalog(cat) return cat, nil } func (s *Service) fetchCatalog(ctx context.Context) (*Catalog, error) { q := url.Values{} q.Set("api", "1") q.Set("panel", strings.TrimPrefix(s.version, "v")) q.Set("arch", runtime.GOARCH) q.Set("os", "linux") var raw catalogResponse if err := s.apiGet(ctx, "/api/v1/plugins?"+q.Encode(), &raw); err != nil { return nil, err } cat := &Catalog{API: raw.API, UpdatedAt: raw.UpdatedAt, Plugins: raw.Plugins} return cat, nil } func (s *Service) saveCachedCatalog(cat *Catalog) { path := s.catalogCachePath() if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { return } body, err := json.Marshal(cat) if err != nil { return } _ = os.WriteFile(path, body, 0o644) } func (s *Service) loadCachedCatalog() (*Catalog, error) { raw, err := os.ReadFile(s.catalogCachePath()) if err != nil { return nil, err } var cat Catalog if err := json.Unmarshal(raw, &cat); err != nil { return nil, err } return &cat, nil } // Entry returns one catalog entry by slug. func (s *Service) Entry(ctx context.Context, slug string) (*CatalogEntry, error) { cat, err := s.Catalog(ctx, false) if err != nil { return nil, err } for i := range cat.Plugins { if cat.Plugins[i].Slug == slug { return &cat.Plugins[i], nil } } return nil, store.ErrNotFound } // VersionInfo returns one published version of an entry. func (e *CatalogEntry) VersionInfo(version, arch string) (*CatalogVersion, error) { for i := range e.Versions { if e.Versions[i].Version == version && e.Versions[i].Arch == arch { return &e.Versions[i], nil } } if version == "" && e.Latest != nil { return e.Latest, nil } return nil, errors.New("指定版本不存在") } // ManifestDoc fetches and returns the signed document for a version. func (s *Service) ManifestDoc(ctx context.Context, slug, version, arch string) (*ManifestDoc, error) { if arch == "" { arch = runtime.GOARCH } path := fmt.Sprintf("/api/v1/plugins/%s/%s/manifest?arch=%s", url.PathEscape(slug), url.PathEscape(version), url.QueryEscape(arch)) var doc ManifestDoc if err := s.apiGet(ctx, path, &doc); err != nil { return nil, err } return &doc, nil } // apiGet performs a bounded JSON request against the control plane and unwraps // the {code,msg,data} envelope. func (s *Service) apiGet(ctx context.Context, path string, out any) error { req, err := http.NewRequestWithContext(ctx, http.MethodGet, s.repoURL()+path, nil) if err != nil { return err } req.Header.Set("User-Agent", "miaopanel/"+s.version) req.Header.Set("Accept", "application/json") res, err := s.client.Do(req) if err != nil { return fmt.Errorf("连接插件服务器失败: %w", err) } defer res.Body.Close() body, err := io.ReadAll(io.LimitReader(res.Body, 8<<20)) if err != nil { return err } if res.StatusCode == http.StatusNotFound { return errors.New("插件服务器未提供该接口,请确认发布服务器已升级到支持插件市场的版本") } var env struct { Code int `json:"code"` Msg string `json:"msg"` Data json.RawMessage `json:"data"` } if err := json.Unmarshal(body, &env); err != nil { return fmt.Errorf("插件服务器返回异常 (HTTP %d)", res.StatusCode) } if env.Code != 0 { msg := env.Msg if msg == "" { msg = fmt.Sprintf("插件服务器返回错误码 %d", env.Code) } return errors.New(msg) } if len(env.Data) == 0 { return errors.New("插件服务器返回空数据") } return json.Unmarshal(env.Data, out) } // InstalledViews merges the catalog with local install state for the UI. func (s *Service) InstalledViews(ctx context.Context) ([]InstalledView, error) { installed, err := s.db.Plugins(ctx) if err != nil { return nil, err } cat, _ := s.Catalog(ctx, false) out := make([]InstalledView, 0, len(installed)) for _, p := range installed { v := InstalledView{Plugin: *p} if cat != nil { for i := range cat.Plugins { if cat.Plugins[i].Slug != p.Slug { continue } if cat.Plugins[i].Latest != nil { v.Available = cat.Plugins[i].Latest.Version v.Update = semver.Compare(cat.Plugins[i].Latest.Version, p.Version) > 0 } } } if rv, err := s.db.RevocationFor(ctx, p.Slug, p.Version); err == nil { v.Revoked = true v.Reason = rv.Reason } out = append(out, v) } return out, nil }