Files
Reims-Go/internal/plugin/market.go
T

644 lines
20 KiB
Go

package plugin
import (
"context"
_ "embed"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path/filepath"
"runtime"
"sort"
"strings"
"sync"
"time"
"github.com/Nwflower/reims-go/internal/fetch"
)
//go:embed market_fallback.json
var embeddedMarketFallbackJSON []byte
const (
// EnvPluginMarketURL overrides the remote plugin market index URL(s).
// Accepts a single HTTPS URL, a comma-separated list of mirror URLs, or
// "off"/"offline" to use the embedded fallback only.
EnvPluginMarketURL = "REIMS_GO_PLUGIN_MARKET_URL"
// DefaultMarketIndexURL is the primary static plugin market index published
// from the reims-go/plugins dist branch (never fetched on app startup).
DefaultMarketIndexURL = "https://raw.githubusercontent.com/reims-go/plugins/dist/index.json"
// DefaultMarketMirrorURL is the CDN mirror automatically tried when the
// primary GitHub raw endpoint is unreachable or blocked.
DefaultMarketMirrorURL = "https://cdn.jsdelivr.net/gh/reims-go/plugins@dist/index.json"
defaultMarketCacheTTL = 10 * time.Minute
maxMarketIndexBytes = 4 << 20 // 4 MiB ceiling for lightweight index.json
)
// MarketEntry describes one plugin published in the remote/embedded market index (§9).
type MarketEntry struct {
ID string `json:"id"`
Version string `json:"version"`
Name LocalizedText `json:"name"`
Description LocalizedText `json:"description"`
Publisher string `json:"publisher"`
License string `json:"license"`
Channel string `json:"channel"` // "stable" | "alpha"
Trust TrustLevel `json:"trust"`
Kind string `json:"kind,omitempty"` // "theme" | "locale" | "driver" | "tool" | "template" | "runtime"
Tier Tier `json:"tier,omitempty"`
Homepage string `json:"homepage,omitempty"`
ReadmeURL string `json:"readme_url,omitempty"`
Engines Engines `json:"engines"`
Platforms []string `json:"platforms,omitempty"`
Permissions []string `json:"permissions,omitempty"`
DownloadURL string `json:"download_url"`
SHA256 string `json:"sha256"`
SizeBytes int64 `json:"size_bytes,omitempty"`
Signer string `json:"signer,omitempty"`
Changelog LocalizedText `json:"changelog,omitempty"`
Tags []string `json:"tags,omitempty"`
UpdatedAt string `json:"updated_at,omitempty"`
}
// MarketWithdrawal represents a soft-withdrawn plugin: new installs are refused,
// while already-installed users keep running with a replacement advisory.
type MarketWithdrawal struct {
ID string `json:"id"`
Reason LocalizedText `json:"reason"`
InsteadID string `json:"instead_id,omitempty"`
InsteadName string `json:"instead_name,omitempty"`
WithdrawnAt string `json:"withdrawn_at,omitempty"`
}
// MarketIndex is the static index.json structure (§9).
type MarketIndex struct {
Schema int `json:"schema"`
UpdatedAt string `json:"updated_at"`
Plugins []MarketEntry `json:"plugins"`
Withdrawn []MarketWithdrawal `json:"withdrawn,omitempty"`
}
// EmbeddedFallbackMarketIndex is shipped as a zero-network fallback (§9).
var EmbeddedFallbackMarketIndex MarketIndex
func init() {
if err := json.Unmarshal(embeddedMarketFallbackJSON, &EmbeddedFallbackMarketIndex); err != nil {
EmbeddedFallbackMarketIndex = MarketIndex{
Schema: 1,
UpdatedAt: "2026-11-30T00:00:00Z",
Plugins: []MarketEntry{},
}
}
}
// MarketCatalogItem pairs a MarketEntry with local install/compatibility state.
type MarketCatalogItem struct {
Entry MarketEntry `json:"entry"`
Installed bool `json:"installed"`
InstalledVersion string `json:"installed_version,omitempty"`
UpdateAvailable bool `json:"update_available"`
Compatible bool `json:"compatible"`
IncompatibleReason string `json:"incompatible_reason,omitempty"`
Withdrawn *MarketWithdrawal `json:"withdrawn,omitempty"`
HighRiskPermissions []string `json:"high_risk_permissions,omitempty"`
}
// MarketBrowseOptions filters and controls market index browsing.
type MarketBrowseOptions struct {
Query string `json:"query,omitempty"`
Kind string `json:"kind,omitempty"`
IncludeAlpha bool `json:"include_alpha,omitempty"`
ForceRefresh bool `json:"force_refresh,omitempty"`
}
// MarketBrowseResult is returned by MarketClient.Browse for GUI & CLI consumption.
type MarketBrowseResult struct {
Source string `json:"source"` // "remote" | "cache" | "fallback"
Stale bool `json:"stale"`
FetchError string `json:"fetch_error,omitempty"`
UpdatedAt string `json:"updated_at,omitempty"`
Items []MarketCatalogItem `json:"items"`
WithdrawnInstalled []MarketWithdrawal `json:"withdrawn_installed,omitempty"`
}
// MarketInstallOptions controls InstallFromMarket.
type MarketInstallOptions struct {
IncludeAlpha bool
ForceRefresh bool
Keyring []SigningKey
OnProgress fetch.Progress
}
// MarketClientOptions configures MarketClient.
type MarketClientOptions struct {
Layout PluginsLayout
HostVersion string
URLs []string
HTTPClient *http.Client
DownloadClient *http.Client
CacheTTL time.Duration
AllowInsecureLocalhost bool
}
// MarketClient lazily fetches, caches, searches, and installs plugins from the
// static remote market index with disk-cache + embedded fallback (§9).
type MarketClient struct {
layout PluginsLayout
hostVersion string
urls []string
httpClient *http.Client
downloadClient *http.Client
cacheTTL time.Duration
allowInsecureLocalhost bool
mu sync.RWMutex
memIndex *MarketIndex
memLoaded time.Time
}
// DefaultMarketURLs resolves market index URL(s) from REIMS_GO_PLUGIN_MARKET_URL
// or falls back to DefaultMarketIndexURL + DefaultMarketMirrorURL. Returning nil
// means offline mode.
func DefaultMarketURLs() []string {
raw := strings.TrimSpace(os.Getenv(EnvPluginMarketURL))
if raw == "" {
return []string{DefaultMarketIndexURL, DefaultMarketMirrorURL}
}
low := strings.ToLower(raw)
if low == "off" || low == "offline" || low == "none" || low == "0" {
return nil
}
var out []string
for _, part := range strings.Split(raw, ",") {
u := strings.TrimSpace(part)
if u != "" {
out = append(out, u)
}
}
return out
}
// NewMarketClient constructs a lazy MarketClient (performs zero network I/O until queried).
func NewMarketClient(opts MarketClientOptions) *MarketClient {
urls := opts.URLs
if urls == nil {
urls = DefaultMarketURLs()
}
ttl := opts.CacheTTL
if ttl <= 0 {
ttl = defaultMarketCacheTTL
}
hc := opts.HTTPClient
if hc == nil {
hc = &http.Client{Timeout: 20 * time.Second}
}
dc := opts.DownloadClient
if dc == nil {
dc = &http.Client{Timeout: 5 * time.Minute}
}
return &MarketClient{
layout: opts.Layout,
hostVersion: opts.HostVersion,
urls: urls,
httpClient: hc,
downloadClient: dc,
cacheTTL: ttl,
allowInsecureLocalhost: opts.AllowInsecureLocalhost,
}
}
// LoadIndex retrieves the market index using memory cache → remote mirrors →
// disk cache → embedded fallback. Network failures never wipe a valid cache.
func (c *MarketClient) LoadIndex(ctx context.Context, forceRefresh bool) (idx MarketIndex, source string, stale bool, fetchErr error) {
if !forceRefresh {
c.mu.RLock()
if c.memIndex != nil && time.Since(c.memLoaded) < c.cacheTTL {
cp := cloneMarketIndex(*c.memIndex)
c.mu.RUnlock()
return cp, "cache", false, nil
}
c.mu.RUnlock()
}
if len(c.urls) == 0 {
if disk, err := c.readDiskCache(); err == nil {
c.storeMem(disk)
return disk, "cache", false, nil
}
return cloneMarketIndex(EmbeddedFallbackMarketIndex), "fallback", false, nil
}
var errs []string
for _, u := range c.urls {
fetched, err := c.fetchRemoteIndex(ctx, u)
if err == nil {
c.storeMem(fetched)
_ = c.writeDiskCache(fetched)
return fetched, "remote", false, nil
}
errs = append(errs, fmt.Sprintf("%s: %v", u, err))
}
fetchErr = errors.New(strings.Join(errs, "; "))
// Remote failed: fall back gracefully without overwriting valid caches.
c.mu.RLock()
if c.memIndex != nil {
cp := cloneMarketIndex(*c.memIndex)
c.mu.RUnlock()
return cp, "cache", true, fetchErr
}
c.mu.RUnlock()
if disk, err := c.readDiskCache(); err == nil {
c.storeMem(disk)
return disk, "cache", true, fetchErr
}
return cloneMarketIndex(EmbeddedFallbackMarketIndex), "fallback", true, fetchErr
}
// Browse filters the market index and annotates compatibility, local install
// state, available updates, and soft-withdrawal advisories.
func (c *MarketClient) Browse(ctx context.Context, installed []PluginInfo, opts MarketBrowseOptions) MarketBrowseResult {
idx, source, stale, fetchErr := c.LoadIndex(ctx, opts.ForceRefresh)
res := MarketBrowseResult{
Source: source,
Stale: stale,
UpdatedAt: idx.UpdatedAt,
Items: []MarketCatalogItem{},
}
if fetchErr != nil {
res.FetchError = fetchErr.Error()
}
instMap := make(map[string]PluginInfo, len(installed))
for _, info := range installed {
instMap[info.ID] = info
}
withdrawnMap := make(map[string]MarketWithdrawal, len(idx.Withdrawn))
for _, w := range idx.Withdrawn {
withdrawnMap[w.ID] = w
if _, ok := instMap[w.ID]; ok {
res.WithdrawnInstalled = append(res.WithdrawnInstalled, w)
}
}
sort.Slice(res.WithdrawnInstalled, func(i, j int) bool {
return res.WithdrawnInstalled[i].ID < res.WithdrawnInstalled[j].ID
})
// Pick best eligible channel entry per plugin ID.
selected := selectChannelEntries(idx.Plugins, opts.IncludeAlpha)
q := strings.ToLower(strings.TrimSpace(opts.Query))
kindFilter := strings.ToLower(strings.TrimSpace(opts.Kind))
for _, entry := range selected {
if kindFilter != "" && !strings.EqualFold(entry.Kind, kindFilter) {
continue
}
if q != "" && !marketEntryMatchesQuery(entry, q) {
continue
}
compat, incompatReason := CheckMarketCompatibility(entry, c.hostVersion)
item := MarketCatalogItem{
Entry: entry,
Compatible: compat,
IncompatibleReason: incompatReason,
HighRiskPermissions: HighRiskPermissions(entry.Permissions),
}
if w, ok := withdrawnMap[entry.ID]; ok {
wCopy := w
item.Withdrawn = &wCopy
}
if inst, ok := instMap[entry.ID]; ok {
item.Installed = true
item.InstalledVersion = inst.Version
if isVersionNewer(entry.Version, inst.Version) {
item.UpdateAvailable = true
}
}
res.Items = append(res.Items, item)
}
sort.Slice(res.Items, func(i, j int) bool {
a, b := res.Items[i], res.Items[j]
if a.UpdateAvailable != b.UpdateAvailable {
return a.UpdateAvailable
}
ra, rb := trustSortRank(a.Entry.Trust), trustSortRank(b.Entry.Trust)
if ra != rb {
return ra > rb
}
return a.Entry.ID < b.Entry.ID
})
return res
}
// CheckUpdates returns installed plugins that have a compatible, non-withdrawn
// newer version available in the market.
func (c *MarketClient) CheckUpdates(ctx context.Context, installed []PluginInfo, includeAlpha, forceRefresh bool) ([]MarketCatalogItem, MarketBrowseResult) {
browse := c.Browse(ctx, installed, MarketBrowseOptions{
IncludeAlpha: includeAlpha,
ForceRefresh: forceRefresh,
})
var updates []MarketCatalogItem
for _, it := range browse.Items {
if it.Installed && it.UpdateAvailable && it.Compatible && it.Withdrawn == nil {
updates = append(updates, it)
}
}
return updates, browse
}
// InstallFromMarket downloads, verifies SHA-256, static-scans, and
// transactionally installs pluginID from the market index.
func (c *MarketClient) InstallFromMarket(ctx context.Context, mgr *Manager, pluginID string, opts MarketInstallOptions) (*PluginInfo, error) {
if mgr == nil {
return nil, errors.New("plugin manager is nil")
}
pluginID = strings.TrimSpace(pluginID)
if !reReverseDomainID.MatchString(pluginID) {
return nil, fmt.Errorf("invalid plugin id %q", pluginID)
}
idx, source, _, fetchErr := c.LoadIndex(ctx, opts.ForceRefresh)
if fetchErr != nil && source == "fallback" && len(idx.Plugins) == 0 {
return nil, fmt.Errorf("failed to fetch plugin market index: %w", fetchErr)
}
// Enforce soft withdrawal: refuse new installs and point to replacement.
for _, w := range idx.Withdrawn {
if w.ID == pluginID {
reason := w.Reason.Get("en-US")
if reason == "" {
reason = w.Reason.Get("zh-CN")
}
if w.InsteadID != "" {
return nil, fmt.Errorf("plugin %q has been withdrawn (%s); use %q instead", pluginID, reason, w.InsteadID)
}
return nil, fmt.Errorf("plugin %q has been withdrawn (%s)", pluginID, reason)
}
}
selected := selectChannelEntries(idx.Plugins, opts.IncludeAlpha)
entry, ok := selected[pluginID]
if !ok {
return nil, fmt.Errorf("plugin %q not found in market index", pluginID)
}
// Pre-download compatibility gate (engines + platform).
if compat, reason := CheckMarketCompatibility(entry, c.hostVersion); !compat {
return nil, fmt.Errorf("plugin %s@%s is incompatible with this host: %s", entry.ID, entry.Version, reason)
}
// Validate SHA-256 and download URL before touching the network.
wantSum := strings.ToLower(strings.TrimSpace(entry.SHA256))
if len(wantSum) != 64 {
return nil, fmt.Errorf("market entry %s@%s is missing a valid 64-char SHA-256 checksum", entry.ID, entry.Version)
}
if _, err := hex.DecodeString(wantSum); err != nil {
return nil, fmt.Errorf("market entry %s@%s has invalid SHA-256 checksum", entry.ID, entry.Version)
}
if err := c.validateDownloadURL(entry.DownloadURL); err != nil {
return nil, fmt.Errorf("market entry %s@%s has unsafe download URL: %w", entry.ID, entry.Version, err)
}
if err := os.MkdirAll(c.layout.TmpDir(), 0o755); err != nil {
return nil, err
}
archiveName := fmt.Sprintf("market-%s-%s.zip", entry.ID, entry.Version)
archivePath := filepath.Join(c.layout.TmpDir(), archiveName)
defer func() {
_ = os.Remove(archivePath)
_ = os.Remove(archivePath + ".part")
}()
if _, err := fetch.Resume(ctx, c.downloadClient, entry.DownloadURL, archivePath, entry.SizeBytes, wantSum, opts.OnProgress); err != nil {
return nil, err
}
return mgr.InstallArchiveWithSource(ctx, archivePath, SourceMarket, PackageInstallOptions{
ExpectedID: entry.ID,
ExpectedVersion: entry.Version,
HostVersion: c.hostVersion,
Keyring: opts.Keyring,
AllowUnsigned: true,
})
}
// CheckMarketCompatibility verifies platform and engines constraints before downloading.
func CheckMarketCompatibility(entry MarketEntry, hostVersion string) (bool, string) {
if len(entry.Platforms) > 0 {
cur := runtime.GOOS + "/" + runtime.GOARCH
matched := false
for _, p := range entry.Platforms {
if p == cur || p == "*" {
matched = true
break
}
}
if !matched {
return false, fmt.Sprintf("platform %s not supported (requires %s)", cur, strings.Join(entry.Platforms, ", "))
}
}
if entry.Engines.PluginAPI != "" && !MatchesRange(PluginAPIVersion, entry.Engines.PluginAPI) {
return false, fmt.Sprintf("requires pluginApi %s (host has %s)", entry.Engines.PluginAPI, PluginAPIVersion)
}
if entry.Engines.UIAPI != "" && !MatchesRange(UIAPIVersion, entry.Engines.UIAPI) {
return false, fmt.Sprintf("requires uiApi %s (host has %s)", entry.Engines.UIAPI, UIAPIVersion)
}
if hostVersion != "" && entry.Engines.ReimsGo != "" && !MatchesRange(hostVersion, entry.Engines.ReimsGo) {
return false, fmt.Sprintf("requires reims-go %s (host has %s)", entry.Engines.ReimsGo, hostVersion)
}
return true, ""
}
func (c *MarketClient) fetchRemoteIndex(ctx context.Context, rawURL string) (MarketIndex, error) {
if err := c.validateDownloadURL(rawURL); err != nil {
return MarketIndex{}, err
}
req, err := fetch.NewRequest(ctx, rawURL)
if err != nil {
return MarketIndex{}, err
}
resp, err := c.httpClient.Do(req)
if err != nil {
return MarketIndex{}, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return MarketIndex{}, fmt.Errorf("HTTP %d", resp.StatusCode)
}
data, err := io.ReadAll(io.LimitReader(resp.Body, maxMarketIndexBytes+1))
if err != nil {
return MarketIndex{}, err
}
if int64(len(data)) > maxMarketIndexBytes {
return MarketIndex{}, fmt.Errorf("market index exceeds %d byte limit", maxMarketIndexBytes)
}
var idx MarketIndex
if err := json.Unmarshal(data, &idx); err != nil {
return MarketIndex{}, fmt.Errorf("parse index JSON: %w", err)
}
if idx.Schema != 1 {
return MarketIndex{}, fmt.Errorf("unsupported market index schema %d", idx.Schema)
}
if idx.Plugins == nil {
idx.Plugins = []MarketEntry{}
}
return idx, nil
}
func (c *MarketClient) validateDownloadURL(rawURL string) error {
u, err := url.Parse(strings.TrimSpace(rawURL))
if err != nil || u.Host == "" {
return errors.New("malformed URL")
}
switch strings.ToLower(u.Scheme) {
case "https":
return nil
case "http":
if c.allowInsecureLocalhost {
host := strings.ToLower(u.Hostname())
if host == "127.0.0.1" || host == "localhost" || host == "::1" {
return nil
}
}
return errors.New("only HTTPS market URLs are permitted")
default:
return fmt.Errorf("unsupported URL scheme %q", u.Scheme)
}
}
func (c *MarketClient) storeMem(idx MarketIndex) {
cp := cloneMarketIndex(idx)
c.mu.Lock()
c.memIndex = &cp
c.memLoaded = time.Now()
c.mu.Unlock()
}
func (c *MarketClient) readDiskCache() (MarketIndex, error) {
if c.layout.Root == "" {
return MarketIndex{}, os.ErrNotExist
}
raw, err := os.ReadFile(c.layout.IndexCachePath())
if err != nil {
return MarketIndex{}, err
}
var idx MarketIndex
if err := json.Unmarshal(raw, &idx); err != nil {
return MarketIndex{}, err
}
if idx.Schema != 1 {
return MarketIndex{}, fmt.Errorf("unsupported cached schema %d", idx.Schema)
}
if idx.Plugins == nil {
idx.Plugins = []MarketEntry{}
}
return idx, nil
}
func (c *MarketClient) writeDiskCache(idx MarketIndex) error {
if c.layout.Root == "" {
return nil
}
cachePath := c.layout.IndexCachePath()
if err := os.MkdirAll(filepath.Dir(cachePath), 0o755); err != nil {
return err
}
raw, err := json.MarshalIndent(idx, "", " ")
if err != nil {
return err
}
tmp := cachePath + ".tmp"
if err := os.WriteFile(tmp, raw, 0o644); err != nil {
return err
}
return os.Rename(tmp, cachePath)
}
func selectChannelEntries(entries []MarketEntry, includeAlpha bool) map[string]MarketEntry {
out := make(map[string]MarketEntry, len(entries))
for _, e := range entries {
if e.ID == "" || e.Version == "" {
continue
}
ch := strings.ToLower(strings.TrimSpace(e.Channel))
if ch == "" {
ch = "stable"
}
if ch != "stable" && !includeAlpha {
continue
}
if prev, exists := out[e.ID]; exists {
if !isVersionNewer(e.Version, prev.Version) {
continue
}
}
e.Channel = ch
out[e.ID] = e
}
return out
}
func isVersionNewer(candidate, current string) bool {
vc, err1 := ParseSemVer(candidate)
vcur, err2 := ParseSemVer(current)
if err1 != nil || err2 != nil {
return candidate != current && candidate > current
}
return vc.Compare(vcur) > 0
}
func marketEntryMatchesQuery(e MarketEntry, q string) bool {
if strings.Contains(strings.ToLower(e.ID), q) ||
strings.Contains(strings.ToLower(e.Publisher), q) ||
strings.Contains(strings.ToLower(e.Kind), q) ||
strings.Contains(strings.ToLower(e.Name.ZhCN), q) ||
strings.Contains(strings.ToLower(e.Name.EnUS), q) ||
strings.Contains(strings.ToLower(e.Description.ZhCN), q) ||
strings.Contains(strings.ToLower(e.Description.EnUS), q) {
return true
}
for _, tag := range e.Tags {
if strings.Contains(strings.ToLower(tag), q) {
return true
}
}
return false
}
func trustSortRank(t TrustLevel) int {
switch t {
case TrustOfficial:
return 3
case TrustVerified:
return 2
case TrustCommunity:
return 1
default:
return 0
}
}
func cloneMarketIndex(idx MarketIndex) MarketIndex {
cp := MarketIndex{
Schema: idx.Schema,
UpdatedAt: idx.UpdatedAt,
Plugins: append([]MarketEntry(nil), idx.Plugins...),
Withdrawn: append([]MarketWithdrawal(nil), idx.Withdrawn...),
}
if cp.Plugins == nil {
cp.Plugins = []MarketEntry{}
}
return cp
}