Files
Reims-Go/internal/plugin/market.go
T
千川白浪 0830bf5856 feat(market): show all channels with Alpha tag, version picker, sorting, and title links (#176)
* feat(market): show all channels with Alpha tag, version picker, sorting, and title links

* fix(market): merge multi-channel releases and default picker to card version
2026-12-04 23:12:24 +08:00

934 lines
29 KiB
Go

package plugin
import (
"context"
_ "embed"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"time"
"github.com/Nwflower/reims-go/internal/atomicfile"
"github.com/Nwflower/reims-go/internal/fetch"
"github.com/Nwflower/reims-go/internal/netproxy"
)
//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 = 5 * time.Minute
defaultMarketStallTimeout = 45 * time.Second
maxMarketIndexBytes = 4 << 20 // 4 MiB ceiling for lightweight index.json
)
// MarketRelease describes one selectable release version of a plugin in the market index.
type MarketRelease struct {
Version string `json:"version"`
Channel string `json:"channel,omitempty"` // "stable" | "alpha"
DownloadURL string `json:"download_url"`
SHA256 string `json:"sha256"`
SizeBytes int64 `json:"size_bytes,omitempty"`
PublishedAt string `json:"published_at,omitempty"`
Changelog LocalizedText `json:"changelog,omitempty"`
}
// 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"`
Icon *PluginIcon `json:"icon,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"`
Releases []MarketRelease `json:"releases,omitempty"`
Tags []string `json:"tags,omitempty"`
// Locales lists the UI languages a locale pack provides. When absent,
// they are inferred from tags and translated names (MarketEntryLocales).
Locales []string `json:"locales,omitempty"`
Stars int `json:"stars,omitempty"`
Downloads int `json:"downloads,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"`
Risks []string `json:"risks,omitempty"`
}
// MarketKindFacet counts listings of one kind, so the GUI builds its category
// filter from the index instead of a fixed list.
type MarketKindFacet struct {
Kind string `json:"kind"`
Count int `json:"count"`
}
// 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"`
Kinds []MarketKindFacet `json:"kinds"`
WithdrawnInstalled []MarketWithdrawal `json:"withdrawn_installed,omitempty"`
}
// Install phases reported through MarketInstallOptions.OnPhase.
const (
MarketPhaseDownload = "download"
MarketPhaseInstall = "install"
)
// MarketInstallOptions controls InstallFromMarket.
type MarketInstallOptions struct {
Version string
IncludeAlpha bool
ForceRefresh bool
Keyring []SigningKey
OnProgress fetch.Progress
// OnPhase is called when the install moves to a new phase.
OnPhase func(phase string)
}
// MarketClientOptions configures MarketClient.
type MarketClientOptions struct {
Layout PluginsLayout
HostVersion string
URLs []string
HTTPClient *http.Client
DownloadClient *http.Client
CacheTTL time.Duration
DownloadStallTimeout time.Duration
AllowInsecureLocalhost bool
// FirstParty marks URLs as the project's own index, whose trust levels
// carry over to installs. The built-in default URLs always are.
FirstParty 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
downloadStallTimeout time.Duration
allowInsecureLocalhost bool
firstParty bool
mu sync.RWMutex
memIndex *MarketIndex
memLoaded time.Time
// memFetched is true when memIndex came over the network in this
// session and is not stale.
memFetched bool
// memStale is true after the most recent remote fetch failed in this session.
memStale bool
memFetchErr error
diskCacheMu sync.Mutex
}
// 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
}
stallTimeout := opts.DownloadStallTimeout
if stallTimeout <= 0 {
stallTimeout = defaultMarketStallTimeout
}
checkRedirect := func(req *http.Request, via []*http.Request) error {
if len(via) >= 10 {
return errors.New("stopped after 10 redirects")
}
return validateMarketURL(req.URL.String(), opts.AllowInsecureLocalhost)
}
hc := opts.HTTPClient
if hc == nil {
hc = &http.Client{
Transport: netproxy.NewTransport(),
Timeout: 20 * time.Second,
CheckRedirect: checkRedirect,
}
}
dc := opts.DownloadClient
if dc == nil {
dc = &http.Client{
Transport: netproxy.NewTransport(),
CheckRedirect: checkRedirect,
}
}
return &MarketClient{
layout: opts.Layout,
hostVersion: opts.HostVersion,
urls: urls,
httpClient: hc,
downloadClient: dc,
cacheTTL: ttl,
downloadStallTimeout: stallTimeout,
allowInsecureLocalhost: opts.AllowInsecureLocalhost,
firstParty: opts.FirstParty || isDefaultMarketURLs(urls),
}
}
// 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 && !c.memStale && 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, false, false, nil)
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, true, false, nil)
_ = 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.
// Clear memFetched and memLoaded so stale data never vouches for trust
// and subsequent non-forced Browse/Install calls retry immediately once online.
c.mu.Lock()
c.memStale = true
c.memFetched = false
c.memFetchErr = fetchErr
c.memLoaded = time.Time{}
if c.memIndex != nil {
cp := cloneMarketIndex(*c.memIndex)
c.mu.Unlock()
return cp, "cache", true, fetchErr
}
c.mu.Unlock()
if disk, err := c.readDiskCache(); err == nil {
c.storeMem(disk, false, true, fetchErr)
return disk, "cache", true, fetchErr
}
return cloneMarketIndex(EmbeddedFallbackMarketIndex), "fallback", true, fetchErr
}
// CachedIndex returns the index from memory, the disk cache or the embedded
// fallback without touching the network, so the GUI can paint at once and
// revalidate in the background.
func (c *MarketClient) CachedIndex() (idx MarketIndex, source string) {
idx, source, _, _ = c.cachedSnapshot()
return idx, source
}
func (c *MarketClient) cachedSnapshot() (idx MarketIndex, source string, stale bool, fetchErr error) {
c.mu.RLock()
if c.memIndex != nil {
cp := cloneMarketIndex(*c.memIndex)
st := c.memStale
fe := c.memFetchErr
c.mu.RUnlock()
return cp, "cache", st, fe
}
st := c.memStale
fe := c.memFetchErr
c.mu.RUnlock()
if disk, err := c.readDiskCache(); err == nil {
c.mu.Lock()
if c.memIndex == nil {
cp := cloneMarketIndex(disk)
c.memIndex = &cp
c.memFetched = false
// Not fetched in this session: leave memLoaded zero so the next
// Browse still goes to the network.
}
st = c.memStale
fe = c.memFetchErr
c.mu.Unlock()
return disk, "cache", st, fe
}
return cloneMarketIndex(EmbeddedFallbackMarketIndex), "fallback", st, fe
}
// Peek is Browse over CachedIndex: no network I/O.
func (c *MarketClient) Peek(installed []PluginInfo, opts MarketBrowseOptions) MarketBrowseResult {
idx, source, stale, fetchErr := c.cachedSnapshot()
return c.browseIndex(idx, source, stale, fetchErr, installed, opts, c.vouches(source, stale))
}
// 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)
return c.browseIndex(idx, source, stale, fetchErr, installed, opts, c.vouches(source, stale))
}
func (c *MarketClient) browseIndex(idx MarketIndex, source string, stale bool, fetchErr error, installed []PluginInfo, opts MarketBrowseOptions, vouched bool) MarketBrowseResult {
res := MarketBrowseResult{
Source: source,
Stale: stale,
UpdatedAt: idx.UpdatedAt,
Items: []MarketCatalogItem{},
Kinds: []MarketKindFacet{},
}
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))
kindCounts := map[string]int{}
for _, entry := range selected {
if q != "" && !marketEntryMatchesQuery(entry, q) {
continue
}
if k := strings.ToLower(strings.TrimSpace(entry.Kind)); k != "" {
kindCounts[k]++
}
if kindFilter != "" && !strings.EqualFold(entry.Kind, kindFilter) {
continue
}
if !vouched && entry.Trust != TrustCommunity {
// An index that cannot vouch (third-party or stale cache) must show
// the trust its packages will actually install with.
entry.Trust = TrustCommunity
}
compat, incompatReason := CheckMarketCompatibility(entry, c.hostVersion)
item := MarketCatalogItem{
Entry: entry,
Compatible: compat,
IncompatibleReason: incompatReason,
HighRiskPermissions: HighRiskPermissions(entry.Permissions),
Risks: MarketEntryRisks(entry),
}
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
})
for k, n := range kindCounts {
res.Kinds = append(res.Kinds, MarketKindFacet{Kind: k, Count: n})
}
sort.Slice(res.Kinds, func(i, j int) bool {
if res.Kinds[i].Count != res.Kinds[j].Count {
return res.Kinds[i].Count > res.Kinds[j].Count
}
return res.Kinds[i].Kind < res.Kinds[j].Kind
})
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, stale, fetchErr := c.LoadIndex(ctx, opts.ForceRefresh)
vouched := c.vouches(source, stale)
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 || strings.TrimSpace(opts.Version) != "")
entry, ok := selected[pluginID]
if !ok {
return nil, fmt.Errorf("plugin %q not found in market index", pluginID)
}
if reqVer := strings.TrimSpace(opts.Version); reqVer != "" && reqVer != entry.Version {
matched := false
for _, candidate := range idx.Plugins {
if candidate.ID != pluginID {
continue
}
if strings.TrimSpace(candidate.Version) == reqVer {
entry = candidate
matched = true
break
}
for _, rel := range candidate.Releases {
if strings.TrimSpace(rel.Version) == reqVer {
entry = candidate
entry.Version = rel.Version
if rel.Channel != "" {
entry.Channel = rel.Channel
}
entry.DownloadURL = rel.DownloadURL
entry.SHA256 = rel.SHA256
entry.SizeBytes = rel.SizeBytes
matched = true
break
}
}
if matched {
break
}
}
if !matched {
return nil, fmt.Errorf("version %q of plugin %q not found in market index", reqVer, 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 version, archive size, SHA-256, and download URL before touching the network or disk.
if entry.Version == "" || strings.TrimSpace(entry.Version) != entry.Version ||
strings.ContainsAny(entry.Version, `/\`) || strings.Contains(entry.Version, "..") {
return nil, fmt.Errorf("market entry %s has invalid version %q", entry.ID, entry.Version)
}
if _, err := ParseSemVer(entry.Version); err != nil {
return nil, fmt.Errorf("market entry %s has invalid version %q: %w", entry.ID, entry.Version, err)
}
if entry.SizeBytes < 0 || entry.SizeBytes > maxPluginArchiveBytes {
return nil, fmt.Errorf("market entry %s@%s declares invalid archive size %d", entry.ID, entry.Version, entry.SizeBytes)
}
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, err := safeJoin(c.layout.TmpDir(), archiveName)
if err != nil {
return nil, fmt.Errorf("invalid market archive path for %s@%s: %w", entry.ID, entry.Version, err)
}
defer func() {
_ = os.Remove(archivePath)
_ = os.Remove(archivePath + ".part")
}()
if opts.OnPhase != nil {
opts.OnPhase(MarketPhaseDownload)
}
maxBytes := maxPluginArchiveBytes
if entry.SizeBytes > 0 && entry.SizeBytes < maxBytes {
maxBytes = entry.SizeBytes
}
if _, err := fetch.ResumeDirect(ctx, c.downloadClient, entry.DownloadURL, archivePath, entry.SizeBytes, wantSum, opts.OnProgress, fetch.ResumeOptions{
BypassDownloader: true,
MaxBytes: maxBytes,
StallTimeout: c.downloadStallTimeout,
}); err != nil {
return nil, err
}
if opts.OnPhase != nil {
opts.OnPhase(MarketPhaseInstall)
}
return mgr.InstallArchiveWithSource(ctx, archivePath, SourceMarket, PackageInstallOptions{
ExpectedID: entry.ID,
ExpectedVersion: entry.Version,
HostVersion: c.hostVersion,
Keyring: opts.Keyring,
AllowUnsigned: true,
IndexTrust: indexTrust(entry, vouched),
})
}
// CheckMarketCompatibility verifies platform and engines constraints before downloading.
func CheckMarketCompatibility(entry MarketEntry, hostVersion string) (bool, string) {
return checkHostCompatibility(entry.Platforms, entry.Engines, hostVersion)
}
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 {
return validateMarketURL(rawURL, c.allowInsecureLocalhost)
}
func validateMarketURL(rawURL string, allowInsecureLocalhost bool) 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 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, fetched, stale bool, fetchErr error) {
cp := cloneMarketIndex(idx)
c.mu.Lock()
c.memIndex = &cp
if stale {
c.memLoaded = time.Time{}
} else {
c.memLoaded = time.Now()
}
c.memFetched = fetched && !stale
c.memStale = stale
c.memFetchErr = fetchErr
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
}
c.diskCacheMu.Lock()
defer c.diskCacheMu.Unlock()
cachePath := c.layout.IndexCachePath()
if err := os.MkdirAll(filepath.Dir(cachePath), 0o755); err != nil {
return err
}
return atomicfile.WriteJSON(cachePath, idx, 0o600)
}
func selectChannelEntries(entries []MarketEntry, includeAlpha bool) map[string]MarketEntry {
out := make(map[string]MarketEntry, len(entries))
mergedReleases := make(map[string][]MarketRelease, len(entries))
seenVer := make(map[string]map[string]bool, len(entries))
addRelease := func(id string, rel MarketRelease) {
v := strings.TrimSpace(rel.Version)
if v == "" {
return
}
if seenVer[id] == nil {
seenVer[id] = map[string]bool{}
}
if seenVer[id][v] {
return
}
seenVer[id][v] = true
if strings.TrimSpace(rel.Channel) == "" {
rel.Channel = "stable"
}
mergedReleases[id] = append(mergedReleases[id], rel)
}
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
}
e.Channel = ch
addRelease(e.ID, MarketRelease{
Version: e.Version,
Channel: ch,
DownloadURL: e.DownloadURL,
SHA256: e.SHA256,
SizeBytes: e.SizeBytes,
PublishedAt: e.UpdatedAt,
Changelog: e.Changelog,
})
for _, r := range e.Releases {
rch := strings.ToLower(strings.TrimSpace(r.Channel))
if rch == "" {
rch = ch
}
if rch != "stable" && !includeAlpha {
continue
}
r.Channel = rch
addRelease(e.ID, r)
}
if prev, exists := out[e.ID]; exists {
if !isVersionNewer(e.Version, prev.Version) {
continue
}
}
out[e.ID] = e
}
for id, e := range out {
if rels := mergedReleases[id]; len(rels) > 1 {
sort.Slice(rels, func(i, j int) bool {
return isVersionNewer(rels[i].Version, rels[j].Version)
})
e.Releases = rels
out[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 _, v := range e.Name.Extra {
if strings.Contains(strings.ToLower(v), q) {
return true
}
}
for _, v := range e.Description.Extra {
if strings.Contains(strings.ToLower(v), 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
}
// vouches reports whether the index LoadIndex just returned can vouch for
// the packages it lists: it must be the project's own index, fetched over
// HTTPS in this session (or embedded in the binary), not a stale or
// disk-cached copy. Otherwise installs keep the trust their signature gives.
func (c *MarketClient) vouches(source string, stale bool) bool {
if !c.firstParty || stale {
return false
}
switch source {
case "remote", "fallback":
return true
case "cache":
c.mu.RLock()
defer c.mu.RUnlock()
return c.memFetched
}
return false
}
// indexTrust is the trust an install inherits from a vouching index.
func indexTrust(entry MarketEntry, vouched bool) TrustLevel {
if !vouched {
return ""
}
if entry.Trust == TrustOfficial || entry.Trust == TrustVerified {
return entry.Trust
}
return ""
}
func isDefaultMarketURLs(urls []string) bool {
if len(urls) == 0 {
return false
}
for _, u := range urls {
if u != DefaultMarketIndexURL && u != DefaultMarketMirrorURL {
return false
}
}
return true
}