History

Merge pull request #3818 from router-for-me/Plugin-stone

feat(pluginstore): add lightweight plugin store installer APIs

Luis Pater committed 5 months ago

Commit 0626b222 parents 9dbf4cd e38ba2825 files · +2031 −103Browse files

Unified · Split

25 files
  1. config.example.yaml +3 −3
  2. internal/api/handlers/management/handler.go +17 −14
  3. internal/api/handlers/management/plugin_store.go +286 −0
  4. internal/api/handlers/management/plugin_store_test.go +258 −0
  5. internal/api/server.go +2 −0
  6. internal/httpfetch/httpfetch.go +62 −0
  7. internal/httpfetch/httpfetch_test.go +67 −0
  8. internal/managementasset/updater.go +10 −41
  9. internal/pluginhost/adapters_test.go +11 −11
  10. internal/pluginhost/command_line_test.go +7 −7
  11. internal/pluginhost/host.go +15 −0
  12. internal/pluginhost/host_test.go +49 −0
  13. internal/pluginhost/platform.go +5 −0
  14. internal/pluginstore/checksum.go +45 −0
  15. internal/pluginstore/github.go +130 −0
  16. internal/pluginstore/github_test.go +93 −0
  17. internal/pluginstore/install.go +277 −0
  18. internal/pluginstore/install_test.go +241 −0
  19. internal/pluginstore/registry.go +156 −0
  20. internal/pluginstore/registry_test.go +167 −0
  21. internal/pluginstore/version.go +69 −0
  22. internal/pluginstore/version_test.go +34 −0
  23. internal/thinking/validate.go +1 −1
  24. sdk/cliproxy/auth/oauth_model_alias_test.go +13 −13
  25. sdk/cliproxy/service_oauth_model_alias_test.go +13 −13
config.example.yaml+3−3
@@ -392,9 +392,9 @@ nonstream-keepalive-interval: 0 · 391 unmodified lines
392392 # xai:
393393 # - name: "grok-4.3"
394394 # alias: "grok-latest"
395−# qoder: # plugin provider keys are supported for OAuth plugins
396−# - name: "qmodel_latest"
397−# alias: "qlatest"
395+# sample-provider: # plugin provider keys are supported for OAuth plugins
396+# - name: "sample-model-latest"
397+# alias: "sample-latest"
398398
399399 # OAuth provider excluded models
400400 # oauth-excluded-models:
internal/api/handlers/management/handler.go+17−14
@@ -16,6 +16,7 @@ import ( · 15 unmodified lines
1616 "github.com/router-for-me/CLIProxyAPI/v7/internal/buildinfo"
1717 "github.com/router-for-me/CLIProxyAPI/v7/internal/config"
1818 "github.com/router-for-me/CLIProxyAPI/v7/internal/pluginhost"
19+ "github.com/router-for-me/CLIProxyAPI/v7/internal/pluginstore"
1920 sdkAuth "github.com/router-for-me/CLIProxyAPI/v7/sdk/auth"
2021 coreauth "github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy/auth"
2122 "golang.org/x/crypto/bcrypt"
@@ -35,20 +36,22 @@ const attemptMaxIdleTime = 2 * time.Hour · 13 unmodified lines
3536
3637 // Handler aggregates config reference, persistence path and helpers.
3738 type Handler struct {
38− cfg *config.Config
39− configFilePath string
40− mu sync.Mutex
41− attemptsMu sync.Mutex
42− failedAttempts map[string]*attemptInfo // keyed by client IP
43− authManager *coreauth.Manager
44− tokenStore coreauth.Store
45− localPassword string
46− allowRemoteOverride bool
47− envSecret string
48− logDir string
49− postAuthHook coreauth.PostAuthHook
50− postAuthPersistHook coreauth.PostAuthHook
51− pluginHost *pluginhost.Host
39+ cfg *config.Config
40+ configFilePath string
41+ mu sync.Mutex
42+ attemptsMu sync.Mutex
43+ failedAttempts map[string]*attemptInfo // keyed by client IP
44+ authManager *coreauth.Manager
45+ tokenStore coreauth.Store
46+ localPassword string
47+ allowRemoteOverride bool
48+ envSecret string
49+ logDir string
50+ postAuthHook coreauth.PostAuthHook
51+ postAuthPersistHook coreauth.PostAuthHook
52+ pluginHost *pluginhost.Host
53+ pluginStoreRegistryURL string
54+ pluginStoreHTTPClient pluginstore.HTTPDoer
5255 }
5356
5457 // NewHandler creates a new management handler instance.
internal/api/handlers/management/plugin_store.go+286−0
@@ -0,0 +1,286 @@
1+package management
2+
3+import (
4+ "errors"
5+ "fmt"
6+ "net/http"
7+ "runtime"
8+ "strings"
9+
10+ "github.com/gin-gonic/gin"
11+ "github.com/router-for-me/CLIProxyAPI/v7/internal/config"
12+ "github.com/router-for-me/CLIProxyAPI/v7/internal/pluginhost"
13+ "github.com/router-for-me/CLIProxyAPI/v7/internal/pluginstore"
14+ "github.com/router-for-me/CLIProxyAPI/v7/internal/util"
15+ sdkconfig "github.com/router-for-me/CLIProxyAPI/v7/sdk/config"
16+)
17+
18+type pluginStoreListResponse struct {
19+ PluginsEnabled bool `json:"plugins_enabled"`
20+ PluginsDir string `json:"plugins_dir"`
21+ Plugins []pluginStoreListEntry `json:"plugins"`
22+}
23+
24+type pluginStoreListEntry struct {
25+ ID string `json:"id"`
26+ Name string `json:"name"`
27+ Description string `json:"description"`
28+ Author string `json:"author"`
29+ Version string `json:"version"`
30+ Repository string `json:"repository"`
31+ Logo string `json:"logo,omitempty"`
32+ Homepage string `json:"homepage,omitempty"`
33+ License string `json:"license,omitempty"`
34+ Tags []string `json:"tags,omitempty"`
35+ Installed bool `json:"installed"`
36+ InstalledVersion string `json:"installed_version"`
37+ Path string `json:"path"`
38+ Configured bool `json:"configured"`
39+ Registered bool `json:"registered"`
40+ Enabled bool `json:"enabled"`
41+ EffectiveEnabled bool `json:"effective_enabled"`
42+ UpdateAvailable bool `json:"update_available"`
43+}
44+
45+type pluginInstallResponse struct {
46+ Status string `json:"status"`
47+ ID string `json:"id"`
48+ Version string `json:"version"`
49+ Path string `json:"path"`
50+ PluginsEnabled bool `json:"plugins_enabled"`
51+ RestartRequired bool `json:"restart_required"`
52+}
53+
54+type pluginLocalStatus struct {
55+ Installed bool
56+ InstalledVersion string
57+ Path string
58+ Configured bool
59+ Registered bool
60+ Enabled bool
61+ EffectiveEnabled bool
62+}
63+
64+func (h *Handler) ListPluginStore(c *gin.Context) {
65+ pluginsEnabled, pluginsDir, proxyURL, configs, host := h.pluginStoreSnapshot()
66+ client := h.newPluginStoreClient(proxyURL)
67+ registry, errRegistry := client.FetchRegistry(c.Request.Context())
68+ if errRegistry != nil {
69+ c.JSON(http.StatusBadGateway, gin.H{"error": "plugin_store_registry_failed", "message": errRegistry.Error()})
70+ return
71+ }
72+ statuses, errStatus := pluginLocalStatuses(pluginsEnabled, pluginsDir, configs, host)
73+ if errStatus != nil {
74+ c.JSON(http.StatusInternalServerError, gin.H{"error": "plugin_discovery_failed", "message": errStatus.Error()})
75+ return
76+ }
77+
78+ entries := make([]pluginStoreListEntry, 0, len(registry.Plugins))
79+ for _, plugin := range registry.Plugins {
80+ status := statuses[plugin.ID]
81+ installedVersion := status.InstalledVersion
82+ entries = append(entries, pluginStoreListEntry{
83+ ID: plugin.ID,
84+ Name: plugin.Name,
85+ Description: plugin.Description,
86+ Author: plugin.Author,
87+ Version: plugin.Version,
88+ Repository: plugin.Repository,
89+ Logo: plugin.Logo,
90+ Homepage: plugin.Homepage,
91+ License: plugin.License,
92+ Tags: append([]string{}, plugin.Tags...),
93+ Installed: status.Installed,
94+ InstalledVersion: installedVersion,
95+ Path: status.Path,
96+ Configured: status.Configured,
97+ Registered: status.Registered,
98+ Enabled: status.Enabled,
99+ EffectiveEnabled: status.EffectiveEnabled,
100+ UpdateAvailable: pluginstore.UpdateAvailable(installedVersion, plugin.Version),
101+ })
102+ }
103+
104+ c.JSON(http.StatusOK, pluginStoreListResponse{
105+ PluginsEnabled: pluginsEnabled,
106+ PluginsDir: pluginsDir,
107+ Plugins: entries,
108+ })
109+}
110+
111+func (h *Handler) InstallPluginFromStore(c *gin.Context) {
112+ h.installPluginFromStore(c, runtime.GOOS, runtime.GOARCH)
113+}
114+
115+func (h *Handler) installPluginFromStore(c *gin.Context, goos, goarch string) {
116+ id, okID := pluginIDFromRequest(c)
117+ if !okID {
118+ return
119+ }
120+ pluginsEnabled, pluginsDir, proxyURL, _, host := h.pluginStoreSnapshot()
121+ client := h.newPluginStoreClient(proxyURL)
122+ registry, errRegistry := client.FetchRegistry(c.Request.Context())
123+ if errRegistry != nil {
124+ c.JSON(http.StatusBadGateway, gin.H{"error": "plugin_store_registry_failed", "message": errRegistry.Error()})
125+ return
126+ }
127+ plugin, okPlugin := registry.PluginByID(id)
128+ if !okPlugin {
129+ c.JSON(http.StatusNotFound, gin.H{"error": "plugin_not_found", "message": "plugin not found in registry"})
130+ return
131+ }
132+
133+ pluginIsLoaded := func() bool { return pluginLoaded(host, id) }
134+ result, errInstall := client.Install(c.Request.Context(), plugin, pluginstore.InstallOptions{
135+ PluginsDir: pluginsDir,
136+ GOOS: goos,
137+ GOARCH: goarch,
138+ PluginLoaded: pluginIsLoaded,
139+ })
140+ if errInstall != nil {
141+ if errors.Is(errInstall, pluginstore.ErrLoadedPluginLocked) {
142+ c.JSON(http.StatusConflict, gin.H{
143+ "error": "plugin_update_requires_restart",
144+ "message": "loaded Windows plugins cannot be overwritten while the server is running",
145+ "restart_required": true,
146+ })
147+ return
148+ }
149+ c.JSON(http.StatusBadGateway, gin.H{"error": "plugin_install_failed", "message": errInstall.Error()})
150+ return
151+ }
152+ // Sample after the install so the response reflects the library state at
153+ // the time the new file landed on disk.
154+ restartRequired := pluginIsLoaded()
155+
156+ h.mu.Lock()
157+ defer h.mu.Unlock()
158+ if h.cfg == nil {
159+ c.JSON(http.StatusInternalServerError, gin.H{
160+ "error": "config_unavailable",
161+ "message": fmt.Sprintf("plugin file installed at %s but config is unavailable to enable it", result.Path),
162+ "path": result.Path,
163+ })
164+ return
165+ }
166+ if errEnable := h.enablePluginConfigLocked(id); errEnable != nil {
167+ c.JSON(http.StatusInternalServerError, gin.H{
168+ "error": "config_update_failed",
169+ "message": fmt.Sprintf("plugin file installed at %s but enabling it in config failed: %s", result.Path, errEnable.Error()),
170+ "path": result.Path,
171+ })
172+ return
173+ }
174+ if errSave := config.SaveConfigPreserveComments(h.configFilePath, h.cfg); errSave != nil {
175+ c.JSON(http.StatusInternalServerError, gin.H{
176+ "error": "config_save_failed",
177+ "message": fmt.Sprintf("plugin file installed at %s but saving config failed: %s", result.Path, errSave.Error()),
178+ "path": result.Path,
179+ })
180+ return
181+ }
182+
183+ c.JSON(http.StatusOK, pluginInstallResponse{
184+ Status: "installed",
185+ ID: result.ID,
186+ Version: result.Version,
187+ Path: result.Path,
188+ PluginsEnabled: pluginsEnabled,
189+ RestartRequired: restartRequired,
190+ })
191+}
192+
193+// enablePluginConfigLocked sets plugins.configs.<id>.enabled to true while preserving
194+// the rest of the plugin's raw configuration. Callers must hold h.mu.
195+func (h *Handler) enablePluginConfigLocked(id string) error {
196+ ensurePluginConfigMap(h.cfg)
197+ node := pluginConfigNode(h.cfg.Plugins.Configs[id])
198+ setYAMLMappingValue(node, "enabled", boolYAMLNode(true))
199+ updated, errConfig := pluginInstanceConfigFromNode(node)
200+ if errConfig != nil {
201+ return fmt.Errorf("decode plugin config: %w", errConfig)
202+ }
203+ h.cfg.Plugins.Configs[id] = updated
204+ return nil
205+}
206+
207+func (h *Handler) pluginStoreSnapshot() (bool, string, string, map[string]config.PluginInstanceConfig, *pluginhost.Host) {
208+ if h == nil || h.cfg == nil {
209+ return false, "plugins", "", map[string]config.PluginInstanceConfig{}, nil
210+ }
211+ h.mu.Lock()
212+ defer h.mu.Unlock()
213+ pluginsEnabled := h.cfg.Plugins.Enabled
214+ pluginsDir := normalizedPluginsDir(h.cfg.Plugins.Dir)
215+ proxyURL := strings.TrimSpace(h.cfg.ProxyURL)
216+ configs := make(map[string]config.PluginInstanceConfig, len(h.cfg.Plugins.Configs))
217+ for id, item := range h.cfg.Plugins.Configs {
218+ configs[id] = item
219+ }
220+ return pluginsEnabled, pluginsDir, proxyURL, configs, h.pluginHost
221+}
222+
223+func (h *Handler) newPluginStoreClient(proxyURL string) pluginstore.Client {
224+ registryURL := ""
225+ var httpClient pluginstore.HTTPDoer
226+ if h != nil {
227+ registryURL = strings.TrimSpace(h.pluginStoreRegistryURL)
228+ httpClient = h.pluginStoreHTTPClient
229+ }
230+ if registryURL == "" {
231+ registryURL = pluginstore.DefaultRegistryURL
232+ }
233+ if httpClient != nil {
234+ return pluginstore.Client{HTTPClient: httpClient, RegistryURL: registryURL}
235+ }
236+ client := &http.Client{}
237+ if strings.TrimSpace(proxyURL) != "" {
238+ util.SetProxy(&sdkconfig.SDKConfig{ProxyURL: strings.TrimSpace(proxyURL)}, client)
239+ }
240+ return pluginstore.Client{HTTPClient: client, RegistryURL: registryURL}
241+}
242+
243+func pluginLocalStatuses(pluginsEnabled bool, pluginsDir string, configs map[string]config.PluginInstanceConfig, host *pluginhost.Host) (map[string]pluginLocalStatus, error) {
244+ statuses := map[string]pluginLocalStatus{}
245+ files, errDiscover := pluginhost.DiscoverPluginFiles(pluginsDir)
246+ if errDiscover != nil {
247+ return nil, errDiscover
248+ }
249+ for _, file := range files {
250+ status := statuses[file.ID]
251+ status.Installed = true
252+ status.Path = file.Path
253+ status.Enabled = true
254+ statuses[file.ID] = status
255+ }
256+ for id, item := range configs {
257+ status := statuses[id]
258+ status.Configured = true
259+ status.Enabled = pluginInstanceEnabled(item)
260+ statuses[id] = status
261+ }
262+ if host != nil {
263+ for _, info := range host.RegisteredPlugins() {
264+ status := statuses[info.ID]
265+ status.Installed = true
266+ status.Registered = true
267+ status.InstalledVersion = strings.TrimSpace(info.Metadata.Version)
268+ if _, configured := configs[info.ID]; !configured && !status.Enabled {
269+ status.Enabled = true
270+ }
271+ statuses[info.ID] = status
272+ }
273+ }
274+ for id, status := range statuses {
275+ status.EffectiveEnabled = pluginsEnabled && status.Enabled && status.Registered
276+ statuses[id] = status
277+ }
278+ return statuses, nil
279+}
280+
281+func pluginLoaded(host *pluginhost.Host, id string) bool {
282+ if host == nil {
283+ return false
284+ }
285+ return host.PluginLoaded(id)
286+}
internal/api/handlers/management/plugin_store_test.go+258−0
@@ -0,0 +1,258 @@
1+package management
2+
3+import (
4+ "archive/zip"
5+ "bytes"
6+ "crypto/sha256"
7+ "encoding/hex"
8+ "encoding/json"
9+ "io"
10+ "net/http"
11+ "net/http/httptest"
12+ "os"
13+ "path/filepath"
14+ "runtime"
15+ "strings"
16+ "testing"
17+
18+ "github.com/gin-gonic/gin"
19+ "github.com/router-for-me/CLIProxyAPI/v7/internal/config"
20+)
21+
22+func TestListPluginStoreMergesInstalledStatus(t *testing.T) {
23+ t.Parallel()
24+ gin.SetMode(gin.TestMode)
25+
26+ pluginsDir := writeManagementPluginFile(t, "sample-provider")
27+ h := &Handler{
28+ cfg: &config.Config{
29+ Plugins: config.PluginsConfig{
30+ Enabled: true,
31+ Dir: pluginsDir,
32+ Configs: map[string]config.PluginInstanceConfig{
33+ "sample-provider": pluginConfigFromYAML(t, "enabled: true\nmode: fast\n"),
34+ },
35+ },
36+ },
37+ configFilePath: writeTestConfigFile(t),
38+ pluginStoreRegistryURL: "https://registry.example/registry.json",
39+ pluginStoreHTTPClient: fakePluginStoreHTTPClient{
40+ "https://registry.example/registry.json": registryJSON(t),
41+ },
42+ }
43+
44+ rec := httptest.NewRecorder()
45+ c, _ := gin.CreateTestContext(rec)
46+ c.Request = httptest.NewRequest(http.MethodGet, "/v0/management/plugin-store", nil)
47+
48+ h.ListPluginStore(c)
49+
50+ if rec.Code != http.StatusOK {
51+ t.Fatalf("status = %d, want %d; body=%s", rec.Code, http.StatusOK, rec.Body.String())
52+ }
53+ var body pluginStoreListResponse
54+ if errDecode := json.Unmarshal(rec.Body.Bytes(), &body); errDecode != nil {
55+ t.Fatalf("Unmarshal() error = %v; body=%s", errDecode, rec.Body.String())
56+ }
57+ if !body.PluginsEnabled {
58+ t.Fatal("plugins_enabled = false, want true")
59+ }
60+ if len(body.Plugins) != 1 {
61+ t.Fatalf("plugins len = %d, want 1", len(body.Plugins))
62+ }
63+ entry := body.Plugins[0]
64+ if !entry.Installed || !entry.Configured || !entry.Enabled {
65+ t.Fatalf("store entry status = %#v, want installed configured enabled", entry)
66+ }
67+ if entry.Registered || entry.EffectiveEnabled {
68+ t.Fatalf("runtime status = registered %v effective %v, want false false", entry.Registered, entry.EffectiveEnabled)
69+ }
70+ if entry.InstalledVersion != "" {
71+ t.Fatalf("installed_version = %q, want empty for unregistered plugin", entry.InstalledVersion)
72+ }
73+ if entry.UpdateAvailable {
74+ t.Fatal("update_available = true, want false when installed version is unknown")
75+ }
76+ if entry.Path == "" {
77+ t.Fatal("path is empty")
78+ }
79+}
80+
81+func TestInstallPluginFromStoreWritesFileAndEnablesConfig(t *testing.T) {
82+ t.Parallel()
83+ gin.SetMode(gin.TestMode)
84+
85+ pluginsDir := t.TempDir()
86+ archiveData := makeManagementPluginStoreZip(t, "sample-provider"+managementPluginExtension(runtime.GOOS), "library-data")
87+ archiveName := "sample-provider_0.1.0_" + runtime.GOOS + "_" + runtime.GOARCH + ".zip"
88+ checksum := sha256.Sum256(archiveData)
89+ h := &Handler{
90+ cfg: &config.Config{
91+ Plugins: config.PluginsConfig{
92+ Enabled: false,
93+ Dir: pluginsDir,
94+ Configs: map[string]config.PluginInstanceConfig{
95+ "sample-provider": pluginConfigFromYAML(t, "enabled: false\nmode: fast\n"),
96+ },
97+ },
98+ },
99+ configFilePath: writeTestConfigFile(t),
100+ pluginStoreRegistryURL: "https://registry.example/registry.json",
101+ pluginStoreHTTPClient: fakePluginStoreHTTPClient{
102+ "https://registry.example/registry.json": registryJSON(t),
103+ "https://api.github.com/repos/author-name/cliproxy-sample-provider-plugin/releases/tags/v0.1.0": []byte(`{
104+ "tag_name": "v0.1.0",
105+ "assets": [
106+ {"name": "` + archiveName + `", "browser_download_url": "https://downloads.example/` + archiveName + `"},
107+ {"name": "checksums.txt", "browser_download_url": "https://downloads.example/checksums.txt"}
108+ ]
109+ }`),
110+ "https://downloads.example/" + archiveName: archiveData,
111+ "https://downloads.example/checksums.txt": []byte(hex.EncodeToString(checksum[:]) + " " + archiveName + "\n"),
112+ },
113+ }
114+
115+ rec := httptest.NewRecorder()
116+ c, _ := gin.CreateTestContext(rec)
117+ c.Params = gin.Params{{Key: "id", Value: "sample-provider"}}
118+ c.Request = httptest.NewRequest(http.MethodPost, "/v0/management/plugin-store/sample-provider/install", nil)
119+
120+ h.InstallPluginFromStore(c)
121+
122+ if rec.Code != http.StatusOK {
123+ t.Fatalf("status = %d, want %d; body=%s", rec.Code, http.StatusOK, rec.Body.String())
124+ }
125+ var body pluginInstallResponse
126+ if errDecode := json.Unmarshal(rec.Body.Bytes(), &body); errDecode != nil {
127+ t.Fatalf("Unmarshal() error = %v; body=%s", errDecode, rec.Body.String())
128+ }
129+ if body.Status != "installed" || body.ID != "sample-provider" || body.Version != "0.1.0" {
130+ t.Fatalf("install response = %#v", body)
131+ }
132+ if body.PluginsEnabled {
133+ t.Fatal("plugins_enabled = true, want false")
134+ }
135+ if body.RestartRequired {
136+ t.Fatal("restart_required = true, want false")
137+ }
138+ targetPath := filepath.Join(pluginsDir, runtime.GOOS, runtime.GOARCH, "sample-provider"+managementPluginExtension(runtime.GOOS))
139+ data, errRead := os.ReadFile(targetPath)
140+ if errRead != nil {
141+ t.Fatalf("ReadFile(%s) error = %v", targetPath, errRead)
142+ }
143+ if string(data) != "library-data" {
144+ t.Fatalf("installed file = %q, want library-data", data)
145+ }
146+ item := h.cfg.Plugins.Configs["sample-provider"]
147+ if item.Enabled == nil || !*item.Enabled {
148+ t.Fatalf("plugin enabled = %#v, want true", item.Enabled)
149+ }
150+ if h.cfg.Plugins.Enabled {
151+ t.Fatal("global plugins.enabled changed to true")
152+ }
153+ raw := marshalPluginRaw(t, item)
154+ if !strings.Contains(raw, "mode: fast") {
155+ t.Fatalf("plugin raw config lost custom field:\n%s", raw)
156+ }
157+}
158+
159+func TestEnablePluginConfigLockedPreservesExistingFields(t *testing.T) {
160+ t.Parallel()
161+
162+ h := &Handler{
163+ cfg: &config.Config{
164+ Plugins: config.PluginsConfig{
165+ Enabled: false,
166+ Configs: map[string]config.PluginInstanceConfig{
167+ "sample-provider": pluginConfigFromYAML(t, "enabled: false\npriority: 5\nmode: fast\n"),
168+ },
169+ },
170+ },
171+ }
172+
173+ if errEnable := h.enablePluginConfigLocked("sample-provider"); errEnable != nil {
174+ t.Fatalf("enablePluginConfigLocked() error = %v", errEnable)
175+ }
176+ if h.cfg.Plugins.Enabled {
177+ t.Fatal("global Plugins.Enabled changed to true")
178+ }
179+ item := h.cfg.Plugins.Configs["sample-provider"]
180+ if item.Enabled == nil || !*item.Enabled {
181+ t.Fatalf("plugin enabled = %#v, want true", item.Enabled)
182+ }
183+ if item.Priority != 5 {
184+ t.Fatalf("plugin priority = %d, want 5", item.Priority)
185+ }
186+ raw := marshalPluginRaw(t, item)
187+ if !strings.Contains(raw, "mode: fast") {
188+ t.Fatalf("plugin raw config lost custom field:\n%s", raw)
189+ }
190+}
191+
192+func TestEnablePluginConfigLockedCreatesMissingConfig(t *testing.T) {
193+ t.Parallel()
194+
195+ h := &Handler{cfg: &config.Config{}}
196+ if errEnable := h.enablePluginConfigLocked("sample-provider"); errEnable != nil {
197+ t.Fatalf("enablePluginConfigLocked() error = %v", errEnable)
198+ }
199+ item := h.cfg.Plugins.Configs["sample-provider"]
200+ if item.Enabled == nil || !*item.Enabled {
201+ t.Fatalf("plugin enabled = %#v, want true", item.Enabled)
202+ }
203+}
204+
205+type fakePluginStoreHTTPClient map[string][]byte
206+
207+func (c fakePluginStoreHTTPClient) Do(req *http.Request) (*http.Response, error) {
208+ body, ok := c[req.URL.String()]
209+ if !ok {
210+ return &http.Response{
211+ StatusCode: http.StatusNotFound,
212+ Body: io.NopCloser(strings.NewReader("not found")),
213+ Header: make(http.Header),
214+ Request: req,
215+ }, nil
216+ }
217+ return &http.Response{
218+ StatusCode: http.StatusOK,
219+ Body: io.NopCloser(bytes.NewReader(body)),
220+ Header: make(http.Header),
221+ Request: req,
222+ }, nil
223+}
224+
225+func registryJSON(t *testing.T) []byte {
226+ t.Helper()
227+
228+ return []byte(`{
229+ "schema_version": 1,
230+ "plugins": [{
231+ "id": "sample-provider",
232+ "name": "Sample Provider",
233+ "description": "Adds sample provider support.",
234+ "author": "author-name",
235+ "version": "0.1.0",
236+ "repository": "https://github.com/author-name/cliproxy-sample-provider-plugin",
237+ "tags": ["provider"]
238+ }]
239+ }`)
240+}
241+
242+func makeManagementPluginStoreZip(t *testing.T, name string, content string) []byte {
243+ t.Helper()
244+
245+ var buffer bytes.Buffer
246+ writer := zip.NewWriter(&buffer)
247+ file, errCreate := writer.Create(name)
248+ if errCreate != nil {
249+ t.Fatalf("Create(%s) error = %v", name, errCreate)
250+ }
251+ if _, errWrite := file.Write([]byte(content)); errWrite != nil {
252+ t.Fatalf("Write(%s) error = %v", name, errWrite)
253+ }
254+ if errClose := writer.Close(); errClose != nil {
255+ t.Fatalf("Close() error = %v", errClose)
256+ }
257+ return buffer.Bytes()
258+}
internal/api/server.go+2−0
@@ -603,6 +603,8 @@ func (s *Server) registerManagementRoutes() { · 602 unmodified lines
603603 mgmt.PUT("/config.yaml", s.mgmt.PutConfigYAML)
604604 mgmt.GET("/latest-version", s.mgmt.GetLatestVersion)
605605 mgmt.GET("/plugins", s.mgmt.ListPlugins)
606+ mgmt.GET("/plugin-store", s.mgmt.ListPluginStore)
607+ mgmt.POST("/plugin-store/:id/install", s.mgmt.InstallPluginFromStore)
606608 mgmt.PATCH("/plugins/:id/enabled", s.mgmt.PatchPluginEnabled)
607609 mgmt.PUT("/plugins/:id/config", s.mgmt.PutPluginConfig)
608610 mgmt.PATCH("/plugins/:id/config", s.mgmt.PatchPluginConfig)
internal/httpfetch/httpfetch.go+62−0
@@ -0,0 +1,62 @@
1+package httpfetch
2+
3+import (
4+ "context"
5+ "fmt"
6+ "io"
7+ "net/http"
8+ "strings"
9+
10+ log "github.com/sirupsen/logrus"
11+)
12+
13+// Doer abstracts the HTTP client used to execute requests.
14+type Doer interface {
15+ Do(*http.Request) (*http.Response, error)
16+}
17+
18+// GetBytes performs a GET request with the supplied headers, requires a
19+// success status, and returns the response body. When maxSize is positive
20+// the body is rejected once it exceeds maxSize bytes.
21+func GetBytes(ctx context.Context, client Doer, requestURL string, headers map[string]string, maxSize int64) ([]byte, error) {
22+ if client == nil {
23+ client = http.DefaultClient
24+ }
25+ req, errRequest := http.NewRequestWithContext(ctx, http.MethodGet, requestURL, nil)
26+ if errRequest != nil {
27+ return nil, fmt.Errorf("create request: %w", errRequest)
28+ }
29+ for key, value := range headers {
30+ if value != "" {
31+ req.Header.Set(key, value)
32+ }
33+ }
34+
35+ resp, errDo := client.Do(req)
36+ if errDo != nil {
37+ return nil, fmt.Errorf("request failed: %w", errDo)
38+ }
39+ defer func() {
40+ if errClose := resp.Body.Close(); errClose != nil {
41+ log.WithError(errClose).Debug("failed to close response body")
42+ }
43+ }()
44+
45+ if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
46+ body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
47+ return nil, fmt.Errorf("unexpected status %d: %s", resp.StatusCode, strings.TrimSpace(string(body)))
48+ }
49+
50+ reader := io.Reader(resp.Body)
51+ if maxSize > 0 {
52+ reader = io.LimitReader(resp.Body, maxSize+1)
53+ }
54+ data, errRead := io.ReadAll(reader)
55+ if errRead != nil {
56+ return nil, fmt.Errorf("read response: %w", errRead)
57+ }
58+ if maxSize > 0 && int64(len(data)) > maxSize {
59+ return nil, fmt.Errorf("response exceeds maximum allowed size of %d bytes", maxSize)
60+ }
61+ return data, nil
62+}
internal/httpfetch/httpfetch_test.go+67−0
@@ -0,0 +1,67 @@
1+package httpfetch
2+
3+import (
4+ "context"
5+ "net/http"
6+ "net/http/httptest"
7+ "strings"
8+ "testing"
9+)
10+
11+func TestGetBytesReturnsBodyAndSendsHeaders(t *testing.T) {
12+ t.Parallel()
13+
14+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
15+ if r.Header.Get("User-Agent") != "agent" || r.Header.Get("Accept") != "application/json" {
16+ http.Error(w, "missing headers", http.StatusBadRequest)
17+ return
18+ }
19+ _, _ = w.Write([]byte("payload"))
20+ }))
21+ t.Cleanup(server.Close)
22+
23+ data, errGet := GetBytes(context.Background(), server.Client(), server.URL, map[string]string{
24+ "User-Agent": "agent",
25+ "Accept": "application/json",
26+ }, 0)
27+ if errGet != nil {
28+ t.Fatalf("GetBytes() error = %v", errGet)
29+ }
30+ if string(data) != "payload" {
31+ t.Fatalf("GetBytes() = %q, want payload", data)
32+ }
33+}
34+
35+func TestGetBytesRejectsErrorStatus(t *testing.T) {
36+ t.Parallel()
37+
38+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
39+ http.Error(w, "missing", http.StatusNotFound)
40+ }))
41+ t.Cleanup(server.Close)
42+
43+ _, errGet := GetBytes(context.Background(), server.Client(), server.URL, nil, 0)
44+ if errGet == nil {
45+ t.Fatal("GetBytes() error = nil")
46+ }
47+ if !strings.Contains(errGet.Error(), "unexpected status 404") {
48+ t.Fatalf("GetBytes() error = %v, want status 404", errGet)
49+ }
50+}
51+
52+func TestGetBytesEnforcesMaxSize(t *testing.T) {
53+ t.Parallel()
54+
55+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
56+ _, _ = w.Write([]byte("0123456789"))
57+ }))
58+ t.Cleanup(server.Close)
59+
60+ _, errGet := GetBytes(context.Background(), server.Client(), server.URL, nil, 4)
61+ if errGet == nil {
62+ t.Fatal("GetBytes() error = nil")
63+ }
64+ if !strings.Contains(errGet.Error(), "maximum allowed size") {
65+ t.Fatalf("GetBytes() error = %v, want size limit error", errGet)
66+ }
67+}
internal/managementasset/updater.go+10−41
@@ -18,6 +18,7 @@ import ( · 17 unmodified lines
1818 "time"
1919
2020 "github.com/router-for-me/CLIProxyAPI/v7/internal/config"
21+ "github.com/router-for-me/CLIProxyAPI/v7/internal/httpfetch"
2122 "github.com/router-for-me/CLIProxyAPI/v7/internal/util"
2223 sdkconfig "github.com/router-for-me/CLIProxyAPI/v7/sdk/config"
2324 log "github.com/sirupsen/logrus"
@@ -345,32 +346,22 @@ func fetchLatestAsset(ctx context.Context, client *http.Client, releaseURL strin · 321 unmodified lines
345346 releaseURL = defaultManagementReleaseURL
346347 }
347348
348− req, err := http.NewRequestWithContext(ctx, http.MethodGet, releaseURL, nil)
349− if err != nil {
350− return nil, "", fmt.Errorf("create release request: %w", err)
349+ headers := map[string]string{
350+ "Accept": "application/vnd.github+json",
351+ "User-Agent": httpUserAgent,
351352 }
352− req.Header.Set("Accept", "application/vnd.github+json")
353− req.Header.Set("User-Agent", httpUserAgent)
354353 gitURL := strings.ToLower(strings.TrimSpace(os.Getenv("GITSTORE_GIT_URL")))
355354 if tok := strings.TrimSpace(os.Getenv("GITSTORE_GIT_TOKEN")); tok != "" && strings.Contains(gitURL, "github.com") {
356− req.Header.Set("Authorization", "Bearer "+tok)
355+ headers["Authorization"] = "Bearer " + tok
357356 }
358357
359− resp, err := client.Do(req)
358+ data, err := httpfetch.GetBytes(ctx, client, releaseURL, headers, 0)
360359 if err != nil {
361− return nil, "", fmt.Errorf("execute release request: %w", err)
362− }
363− defer func() {
364− _ = resp.Body.Close()
365− }()
366−
367− if resp.StatusCode != http.StatusOK {
368− body, _ := io.ReadAll(io.LimitReader(resp.Body, 1024))
369− return nil, "", fmt.Errorf("unexpected release status %d: %s", resp.StatusCode, strings.TrimSpace(string(body)))
360+ return nil, "", fmt.Errorf("fetch release: %w", err)
370361 }
371362
372363 var release releaseResponse
373− if err = json.NewDecoder(resp.Body).Decode(&release); err != nil {
364+ if err = json.Unmarshal(data, &release); err != nil {
374365 return nil, "", fmt.Errorf("decode release response: %w", err)
375366 }
376367
@@ -390,31 +381,9 @@ func downloadAsset(ctx context.Context, client *http.Client, downloadURL string) · 13 unmodified lines
390381 return nil, "", fmt.Errorf("empty download url")
391382 }
392383
393− req, err := http.NewRequestWithContext(ctx, http.MethodGet, downloadURL, nil)
394− if err != nil {
395− return nil, "", fmt.Errorf("create download request: %w", err)
396− }
397− req.Header.Set("User-Agent", httpUserAgent)
398−
399− resp, err := client.Do(req)
384+ data, err := httpfetch.GetBytes(ctx, client, downloadURL, map[string]string{"User-Agent": httpUserAgent}, maxAssetDownloadSize)
400385 if err != nil {
401− return nil, "", fmt.Errorf("execute download request: %w", err)
402− }
403− defer func() {
404− _ = resp.Body.Close()
405− }()
406−
407− if resp.StatusCode != http.StatusOK {
408− body, _ := io.ReadAll(io.LimitReader(resp.Body, 1024))
409− return nil, "", fmt.Errorf("unexpected download status %d: %s", resp.StatusCode, strings.TrimSpace(string(body)))
410− }
411−
412− data, err := io.ReadAll(io.LimitReader(resp.Body, maxAssetDownloadSize+1))
413− if err != nil {
414− return nil, "", fmt.Errorf("read download body: %w", err)
415− }
416− if int64(len(data)) > maxAssetDownloadSize {
417− return nil, "", fmt.Errorf("download exceeds maximum allowed size of %d bytes", maxAssetDownloadSize)
386+ return nil, "", fmt.Errorf("download asset: %w", err)
418387 }
419388
420389 sum := sha256.Sum256(data)
internal/pluginhost/adapters_test.go+11−11
@@ -623,25 +623,25 @@ func TestRegisterExecutorsOAuthScopeSkipsStaticModelClientButRegistersExecutor(t · 622 unmodified lines
623623 manager := newFakeExecutorManager()
624624 staticCalled := false
625625 host := newHostWithRecords(capabilityRecord{
626− id: "qoder",
626+ id: "sample-provider",
627627 plugin: pluginapi.Plugin{Capabilities: pluginapi.Capabilities{
628− AuthProvider: fakeAuthProvider{identifier: "qoder"},
628+ AuthProvider: fakeAuthProvider{identifier: "sample-provider"},
629629 ModelProvider: modelProviderFunc{
630630 staticModels: func(ctx context.Context, req pluginapi.StaticModelRequest) (pluginapi.ModelResponse, error) {
631631 staticCalled = true
632632 return pluginapi.ModelResponse{
633− Provider: "qoder",
633+ Provider: "sample-provider",
634634 Models: []pluginapi.ModelInfo{{ID: "static-model"}},
635635 }, nil
636636 },
637637 modelsForAuth: func(ctx context.Context, req pluginapi.AuthModelRequest) (pluginapi.ModelResponse, error) {
638638 return pluginapi.ModelResponse{
639− Provider: "qoder",
639+ Provider: "sample-provider",
640640 Models: []pluginapi.ModelInfo{{ID: "oauth-model"}},
641641 }, nil
642642 },
643643 },
644− Executor: &fakeExecutor{identifier: "qoder"},
644+ Executor: &fakeExecutor{identifier: "sample-provider"},
645645 ExecutorModelScope: pluginapi.ExecutorModelScopeOAuth,
646646 }},
647647 })
@@ -652,21 +652,21 @@ func TestRegisterExecutorsOAuthScopeSkipsStaticModelClientButRegistersExecutor(t · 4 unmodified lines
652652 if staticCalled {
653653 t.Fatal("StaticModels was called for an OAuth-only executor")
654654 }
655− if _, okExecutor := manager.executors["qoder"]; !okExecutor {
655+ if _, okExecutor := manager.executors["sample-provider"]; !okExecutor {
656656 t.Fatal("OAuth-only executor was not registered")
657657 }
658− if _, okClient := modelRegistry.clients[pluginExecutorModelClientID("qoder", "qoder")]; okClient {
658+ if _, okClient := modelRegistry.clients[pluginExecutorModelClientID("sample-provider", "sample-provider")]; okClient {
659659 t.Fatal("OAuth-only executor registered a static model client")
660660 }
661− if got := host.ModelsForProvider("qoder"); len(got) != 0 {
661+ if got := host.ModelsForProvider("sample-provider"); len(got) != 0 {
662662 t.Fatalf("OAuth-only provider models = %#v, want none", got)
663663 }
664664
665665 result := host.ModelsForAuth(context.Background(), &coreauth.Auth{
666− ID: "qoder-auth",
667− Provider: "qoder",
666+ ID: "sample-provider-auth",
667+ Provider: "sample-provider",
668668 })
669− if !result.Handled || result.Provider != "qoder" || len(result.Models) != 1 || result.Models[0].ID != "oauth-model" {
669+ if !result.Handled || result.Provider != "sample-provider" || len(result.Models) != 1 || result.Models[0].ID != "oauth-model" {
670670 t.Fatalf("OAuth model result = %#v, want oauth-model", result)
671671 }
672672 }
internal/pluginhost/command_line_test.go+7−7
@@ -127,16 +127,16 @@ func TestExecuteCommandLinePersistsReturnedAuths(t *testing.T) { · 126 unmodified lines
127127 response: pluginapi.CommandLineExecutionResponse{
128128 Stdout: []byte("login ok\n"),
129129 Auths: []pluginapi.AuthData{{
130− Provider: "Qoder",
131− ID: "qoder.json",
132− FileName: "qoder.json",
130+ Provider: "Sample-Provider",
131+ ID: "sample-provider.json",
132+ FileName: "sample-provider.json",
133133 Label: "Luis",
134134 StorageJSON: []byte(`{"token":"secret"}`),
135135 }},
136136 },
137137 }
138138 host := newHostWithRecords(capabilityRecord{
139− id: "qoder",
139+ id: "sample-provider",
140140 plugin: pluginapi.Plugin{Capabilities: pluginapi.Capabilities{CommandLinePlugin: plugin}},
141141 })
142142 host.runtimeConfig = &config.Config{AuthDir: authDir}
@@ -160,13 +160,13 @@ func TestExecuteCommandLinePersistsReturnedAuths(t *testing.T) { · 17 unmodified lines
160160 t.Fatalf("saved auths = %d, want 1", len(store.saved))
161161 }
162162 saved := store.saved[0]
163− if saved.Provider != "qoder" || saved.ID != "qoder.json" || saved.FileName != "qoder.json" {
164− t.Fatalf("saved auth = %#v, want normalized qoder auth", saved)
163+ if saved.Provider != "sample-provider" || saved.ID != "sample-provider.json" || saved.FileName != "sample-provider.json" {
164+ t.Fatalf("saved auth = %#v, want normalized sample provider auth", saved)
165165 }
166166 if saved.Storage == nil {
167167 t.Fatal("saved auth storage = nil, want plugin token storage")
168168 }
169− if store.paths[0] != filepath.Join(authDir, "qoder.json") {
169+ if store.paths[0] != filepath.Join(authDir, "sample-provider.json") {
170170 t.Fatalf("saved path = %q, want auth dir path", store.paths[0])
171171 }
172172 }
internal/pluginhost/host.go+15−0
@@ -114,6 +114,21 @@ func (h *Host) Snapshot() *Snapshot { · 113 unmodified lines
114114 return emptySnapshot()
115115 }
116116
117+// PluginLoaded reports whether a plugin dynamic library is still loaded by the host.
118+func (h *Host) PluginLoaded(id string) bool {
119+ if h == nil {
120+ return false
121+ }
122+ id = strings.TrimSpace(id)
123+ if id == "" {
124+ return false
125+ }
126+ h.mu.Lock()
127+ defer h.mu.Unlock()
128+ _, ok := h.loaded[id]
129+ return ok
130+}
131+
117132 func (h *Host) ApplyConfig(ctx context.Context, cfg *config.Config) {
118133 if h == nil {
119134 return
internal/pluginhost/host_test.go+49−0
@@ -64,6 +64,55 @@ func TestHostApplyConfig_DisabledPluginSkipsCapability(t *testing.T) { · 63 unmodified lines
6464 }
6565 }
6666
67+func TestPluginLoadedTracksLoadedPluginAfterDisabled(t *testing.T) {
68+ disabled := false
69+ loader := newTestSymbolLoader()
70+ plugin := &testPlugin{
71+ registerResult: validTestPlugin("alpha"),
72+ reconfigureResult: validTestPlugin("alpha"),
73+ }
74+ loader.lookups["alpha"] = newTestSymbolLookup(plugin)
75+ h := NewForTest(loader)
76+ t.Cleanup(h.ShutdownAll)
77+ pluginsDir := makePluginDir(t, "alpha")
78+
79+ h.ApplyConfig(context.Background(), &config.Config{
80+ Plugins: config.PluginsConfig{
81+ Enabled: true,
82+ Dir: pluginsDir,
83+ },
84+ })
85+
86+ if !h.PluginLoaded("alpha") {
87+ t.Fatal("PluginLoaded(alpha) = false, want true after load")
88+ }
89+ if len(h.RegisteredPlugins()) != 1 {
90+ t.Fatalf("RegisteredPlugins() len = %d, want 1", len(h.RegisteredPlugins()))
91+ }
92+
93+ h.ApplyConfig(context.Background(), &config.Config{
94+ Plugins: config.PluginsConfig{
95+ Enabled: true,
96+ Dir: pluginsDir,
97+ Configs: map[string]config.PluginInstanceConfig{
98+ "alpha": {Enabled: &disabled},
99+ },
100+ },
101+ })
102+
103+ if len(h.RegisteredPlugins()) != 0 {
104+ t.Fatalf("RegisteredPlugins() len = %d, want 0 after disable", len(h.RegisteredPlugins()))
105+ }
106+ if !h.PluginLoaded("alpha") {
107+ t.Fatal("PluginLoaded(alpha) = false, want true while library remains loaded")
108+ }
109+
110+ h.ShutdownAll()
111+ if h.PluginLoaded("alpha") {
112+ t.Fatal("PluginLoaded(alpha) = true, want false after ShutdownAll")
113+ }
114+}
115+
67116 func TestHostApplyConfigRegistersPluginThinkingApplier(t *testing.T) {
68117 loader := newTestSymbolLoader()
69118 plugin := &testPlugin{
internal/pluginhost/platform.go+5−0
@@ -44,6 +44,11 @@ func pluginIDFromPath(path string) string { · 43 unmodified lines
4444 return base
4545 }
4646
47+// PluginExtension returns the dynamic library file extension used for goos.
48+func PluginExtension(goos string) string {
49+ return pluginExtension(goos)
50+}
51+
4752 func pluginExtension(goos string) string {
4853 switch goos {
4954 case "darwin":
internal/pluginstore/checksum.go+45−0
@@ -0,0 +1,45 @@
1+package pluginstore
2+
3+import (
4+ "crypto/sha256"
5+ "encoding/hex"
6+ "fmt"
7+ "strings"
8+)
9+
10+func ParseChecksums(data []byte) (map[string]string, error) {
11+ out := map[string]string{}
12+ for lineNumber, rawLine := range strings.Split(string(data), "\n") {
13+ line := strings.TrimSpace(rawLine)
14+ if line == "" || strings.HasPrefix(line, "#") {
15+ continue
16+ }
17+ fields := strings.Fields(line)
18+ if len(fields) < 2 {
19+ return nil, fmt.Errorf("line %d: invalid checksum entry", lineNumber+1)
20+ }
21+ hash := strings.ToLower(strings.TrimSpace(fields[0]))
22+ if len(hash) != sha256.Size*2 {
23+ return nil, fmt.Errorf("line %d: invalid sha256 length", lineNumber+1)
24+ }
25+ if _, errDecode := hex.DecodeString(hash); errDecode != nil {
26+ return nil, fmt.Errorf("line %d: invalid sha256: %w", lineNumber+1, errDecode)
27+ }
28+ name := strings.TrimPrefix(strings.TrimSpace(fields[1]), "*")
29+ out[name] = hash
30+ }
31+ return out, nil
32+}
33+
34+func VerifyChecksum(name string, data []byte, checksums map[string]string) error {
35+ expected := strings.ToLower(strings.TrimSpace(checksums[name]))
36+ if expected == "" {
37+ return fmt.Errorf("checksum for %s not found", name)
38+ }
39+ actualBytes := sha256.Sum256(data)
40+ actual := hex.EncodeToString(actualBytes[:])
41+ if actual != expected {
42+ return fmt.Errorf("checksum mismatch for %s", name)
43+ }
44+ return nil
45+}
internal/pluginstore/github.go+130−0
@@ -0,0 +1,130 @@
1+package pluginstore
2+
3+import (
4+ "context"
5+ "encoding/json"
6+ "fmt"
7+ "net/http"
8+ "net/url"
9+ "strings"
10+
11+ "github.com/router-for-me/CLIProxyAPI/v7/internal/httpfetch"
12+)
13+
14+const userAgent = "CLIProxyAPI"
15+
16+// HTTPDoer abstracts the HTTP client used to execute requests.
17+type HTTPDoer = httpfetch.Doer
18+
19+type Client struct {
20+ HTTPClient HTTPDoer
21+ RegistryURL string
22+ UserAgent string
23+}
24+
25+type Release struct {
26+ TagName string `json:"tag_name"`
27+ Assets []ReleaseAsset `json:"assets"`
28+}
29+
30+type ReleaseAsset struct {
31+ Name string `json:"name"`
32+ BrowserDownloadURL string `json:"browser_download_url"`
33+}
34+
35+func (c Client) FetchRegistry(ctx context.Context) (Registry, error) {
36+ registryURL := strings.TrimSpace(c.RegistryURL)
37+ if registryURL == "" {
38+ registryURL = DefaultRegistryURL
39+ }
40+ data, errDownload := c.get(ctx, registryURL, "application/json")
41+ if errDownload != nil {
42+ return Registry{}, errDownload
43+ }
44+ registry, errParse := ParseRegistry(data)
45+ if errParse != nil {
46+ return Registry{}, errParse
47+ }
48+ return registry, nil
49+}
50+
51+func (c Client) FetchRelease(ctx context.Context, plugin Plugin) (Release, error) {
52+ owner, repo, errRepository := GitHubRepositoryParts(plugin.Repository)
53+ if errRepository != nil {
54+ return Release{}, errRepository
55+ }
56+ releaseURL := fmt.Sprintf(
57+ "https://api.github.com/repos/%s/%s/releases/tags/%s",
58+ url.PathEscape(owner),
59+ url.PathEscape(repo),
60+ url.PathEscape("v"+strings.TrimSpace(plugin.Version)),
61+ )
62+ data, errDownload := c.get(ctx, releaseURL, "application/vnd.github+json")
63+ if errDownload != nil {
64+ return Release{}, errDownload
65+ }
66+ var release Release
67+ if errDecode := json.Unmarshal(data, &release); errDecode != nil {
68+ return Release{}, fmt.Errorf("decode release: %w", errDecode)
69+ }
70+ return release, nil
71+}
72+
73+func (c Client) DownloadAsset(ctx context.Context, asset ReleaseAsset) ([]byte, error) {
74+ if strings.TrimSpace(asset.BrowserDownloadURL) == "" {
75+ return nil, fmt.Errorf("asset %q missing browser_download_url", asset.Name)
76+ }
77+ return c.get(ctx, asset.BrowserDownloadURL, "application/octet-stream")
78+}
79+
80+func (c Client) get(ctx context.Context, requestURL string, accept string) ([]byte, error) {
81+ return httpfetch.GetBytes(ctx, c.httpClient(), requestURL, map[string]string{
82+ "Accept": accept,
83+ "User-Agent": c.userAgent(),
84+ }, 0)
85+}
86+
87+func (c Client) httpClient() HTTPDoer {
88+ if c.HTTPClient != nil {
89+ return c.HTTPClient
90+ }
91+ return http.DefaultClient
92+}
93+
94+func (c Client) userAgent() string {
95+ if strings.TrimSpace(c.UserAgent) != "" {
96+ return strings.TrimSpace(c.UserAgent)
97+ }
98+ return userAgent
99+}
100+
101+func SelectReleaseAssets(release Release, id, version, goos, goarch string) (ReleaseAsset, ReleaseAsset, error) {
102+ archiveName := ArchiveName(id, version, goos, goarch)
103+ var archiveAsset ReleaseAsset
104+ var checksumAsset ReleaseAsset
105+ for _, asset := range release.Assets {
106+ switch strings.TrimSpace(asset.Name) {
107+ case archiveName:
108+ archiveAsset = asset
109+ case "checksums.txt":
110+ checksumAsset = asset
111+ }
112+ }
113+ if strings.TrimSpace(archiveAsset.Name) == "" {
114+ return ReleaseAsset{}, ReleaseAsset{}, fmt.Errorf("release asset %s not found", archiveName)
115+ }
116+ if strings.TrimSpace(checksumAsset.Name) == "" {
117+ return ReleaseAsset{}, ReleaseAsset{}, fmt.Errorf("release asset checksums.txt not found")
118+ }
119+ return archiveAsset, checksumAsset, nil
120+}
121+
122+func ArchiveName(id, version, goos, goarch string) string {
123+ return fmt.Sprintf(
124+ "%s_%s_%s_%s.zip",
125+ strings.TrimSpace(id),
126+ strings.TrimSpace(version),
127+ strings.TrimSpace(goos),
128+ strings.TrimSpace(goarch),
129+ )
130+}
internal/pluginstore/github_test.go+93−0
@@ -0,0 +1,93 @@
1+package pluginstore
2+
3+import (
4+ "crypto/sha256"
5+ "encoding/hex"
6+ "strings"
7+ "testing"
8+)
9+
10+func TestSelectReleaseAssets(t *testing.T) {
11+ t.Parallel()
12+
13+ release := Release{Assets: []ReleaseAsset{
14+ {Name: "sample-provider_0.1.0_darwin_arm64.zip", BrowserDownloadURL: "https://example.com/sample-provider.zip"},
15+ {Name: "checksums.txt", BrowserDownloadURL: "https://example.com/checksums.txt"},
16+ }}
17+ archiveAsset, checksumAsset, errSelect := SelectReleaseAssets(release, "sample-provider", "0.1.0", "darwin", "arm64")
18+ if errSelect != nil {
19+ t.Fatalf("SelectReleaseAssets() error = %v", errSelect)
20+ }
21+ if archiveAsset.BrowserDownloadURL != "https://example.com/sample-provider.zip" {
22+ t.Fatalf("archive URL = %q", archiveAsset.BrowserDownloadURL)
23+ }
24+ if checksumAsset.BrowserDownloadURL != "https://example.com/checksums.txt" {
25+ t.Fatalf("checksum URL = %q", checksumAsset.BrowserDownloadURL)
26+ }
27+}
28+
29+func TestSelectReleaseAssetsRejectsMissingAssets(t *testing.T) {
30+ t.Parallel()
31+
32+ tests := []struct {
33+ name string
34+ release Release
35+ wantErr string
36+ }{
37+ {
38+ name: "missing zip",
39+ release: Release{Assets: []ReleaseAsset{
40+ {Name: "checksums.txt", BrowserDownloadURL: "https://example.com/checksums.txt"},
41+ }},
42+ wantErr: "sample-provider_0.1.0_darwin_arm64.zip",
43+ },
44+ {
45+ name: "missing checksum",
46+ release: Release{Assets: []ReleaseAsset{
47+ {Name: "sample-provider_0.1.0_darwin_arm64.zip", BrowserDownloadURL: "https://example.com/sample-provider.zip"},
48+ }},
49+ wantErr: "checksums.txt",
50+ },
51+ }
52+ for _, tt := range tests {
53+ t.Run(tt.name, func(t *testing.T) {
54+ t.Parallel()
55+
56+ _, _, errSelect := SelectReleaseAssets(tt.release, "sample-provider", "0.1.0", "darwin", "arm64")
57+ if errSelect == nil {
58+ t.Fatal("SelectReleaseAssets() error = nil")
59+ }
60+ if !strings.Contains(errSelect.Error(), tt.wantErr) {
61+ t.Fatalf("SelectReleaseAssets() error = %v, want substring %q", errSelect, tt.wantErr)
62+ }
63+ })
64+ }
65+}
66+
67+func TestParseChecksumsAndVerifyChecksum(t *testing.T) {
68+ t.Parallel()
69+
70+ data := []byte("zip-data")
71+ sum := sha256.Sum256(data)
72+ checksumText := hex.EncodeToString(sum[:]) + " sample-provider_0.1.0_darwin_arm64.zip\n"
73+ checksums, errParse := ParseChecksums([]byte(checksumText))
74+ if errParse != nil {
75+ t.Fatalf("ParseChecksums() error = %v", errParse)
76+ }
77+ if errVerify := VerifyChecksum("sample-provider_0.1.0_darwin_arm64.zip", data, checksums); errVerify != nil {
78+ t.Fatalf("VerifyChecksum() error = %v", errVerify)
79+ }
80+}
81+
82+func TestVerifyChecksumRejectsMissingAndMismatch(t *testing.T) {
83+ t.Parallel()
84+
85+ sum := sha256.Sum256([]byte("zip-data"))
86+ checksums := map[string]string{"sample-provider.zip": hex.EncodeToString(sum[:])}
87+ if errVerify := VerifyChecksum("missing.zip", []byte("zip-data"), checksums); errVerify == nil {
88+ t.Fatal("VerifyChecksum() missing checksum error = nil")
89+ }
90+ if errVerify := VerifyChecksum("sample-provider.zip", []byte("other"), checksums); errVerify == nil {
91+ t.Fatal("VerifyChecksum() mismatch error = nil")
92+ }
93+}
internal/pluginstore/install.go+277−0
@@ -0,0 +1,277 @@
1+package pluginstore
2+
3+import (
4+ "archive/zip"
5+ "bytes"
6+ "context"
7+ "errors"
8+ "fmt"
9+ "io"
10+ "os"
11+ "path"
12+ "path/filepath"
13+ "runtime"
14+ "strings"
15+
16+ "github.com/router-for-me/CLIProxyAPI/v7/internal/pluginhost"
17+ log "github.com/sirupsen/logrus"
18+)
19+
20+type InstallOptions struct {
21+ PluginsDir string
22+ GOOS string
23+ GOARCH string
24+ // PluginLoaded reports whether the plugin's dynamic library is currently
25+ // loaded by the running host. Loaded libraries cannot be overwritten on
26+ // Windows, so installs targeting Windows are rejected while it returns true.
27+ PluginLoaded func() bool
28+}
29+
30+// ErrLoadedPluginLocked is returned when an install would overwrite a plugin
31+// library that is loaded by the running process on Windows.
32+var ErrLoadedPluginLocked = errors.New("loaded plugin library cannot be overwritten while the server is running")
33+
34+type InstallResult struct {
35+ ID string `json:"id"`
36+ Version string `json:"version"`
37+ Path string `json:"path"`
38+ Overwritten bool `json:"overwritten"`
39+}
40+
41+func (c Client) Install(ctx context.Context, plugin Plugin, options InstallOptions) (InstallResult, error) {
42+ if errValidate := ValidatePlugin(plugin); errValidate != nil {
43+ return InstallResult{}, errValidate
44+ }
45+ options = normalizeInstallOptions(options)
46+ if loadedPluginInstallBlocked(options) {
47+ return InstallResult{}, ErrLoadedPluginLocked
48+ }
49+ release, errRelease := c.FetchRelease(ctx, plugin)
50+ if errRelease != nil {
51+ return InstallResult{}, errRelease
52+ }
53+ archiveAsset, checksumAsset, errAssets := SelectReleaseAssets(release, plugin.ID, plugin.Version, options.GOOS, options.GOARCH)
54+ if errAssets != nil {
55+ return InstallResult{}, errAssets
56+ }
57+ archiveData, errArchive := c.DownloadAsset(ctx, archiveAsset)
58+ if errArchive != nil {
59+ return InstallResult{}, fmt.Errorf("download %s: %w", archiveAsset.Name, errArchive)
60+ }
61+ checksumData, errChecksum := c.DownloadAsset(ctx, checksumAsset)
62+ if errChecksum != nil {
63+ return InstallResult{}, fmt.Errorf("download checksums.txt: %w", errChecksum)
64+ }
65+ checksums, errParse := ParseChecksums(checksumData)
66+ if errParse != nil {
67+ return InstallResult{}, errParse
68+ }
69+ if errVerify := VerifyChecksum(archiveAsset.Name, archiveData, checksums); errVerify != nil {
70+ return InstallResult{}, errVerify
71+ }
72+ return InstallArchive(archiveData, plugin, options)
73+}
74+
75+func InstallArchive(archiveData []byte, plugin Plugin, options InstallOptions) (InstallResult, error) {
76+ options = normalizeInstallOptions(options)
77+ id := strings.TrimSpace(plugin.ID)
78+ if !pluginhost.ValidatePluginID(id) {
79+ return InstallResult{}, fmt.Errorf("invalid plugin id %q", plugin.ID)
80+ }
81+ reader, errZip := zip.NewReader(bytes.NewReader(archiveData), int64(len(archiveData)))
82+ if errZip != nil {
83+ return InstallResult{}, fmt.Errorf("open zip: %w", errZip)
84+ }
85+
86+ libraryData, mode, errLibrary := readTargetLibrary(reader, id, options.GOOS)
87+ if errLibrary != nil {
88+ return InstallResult{}, errLibrary
89+ }
90+
91+ targetPath, errTarget := installTargetPath(options, id)
92+ if errTarget != nil {
93+ return InstallResult{}, errTarget
94+ }
95+ overwritten := false
96+ if _, errStat := os.Stat(targetPath); errStat == nil {
97+ overwritten = true
98+ } else if !errors.Is(errStat, os.ErrNotExist) {
99+ return InstallResult{}, fmt.Errorf("stat target plugin: %w", errStat)
100+ }
101+ // Re-check immediately before writing: the plugin may have been loaded
102+ // while the archive was being downloaded and verified.
103+ if loadedPluginInstallBlocked(options) {
104+ return InstallResult{}, ErrLoadedPluginLocked
105+ }
106+ if errWrite := writeFileAtomic(targetPath, libraryData, mode); errWrite != nil {
107+ return InstallResult{}, errWrite
108+ }
109+ return InstallResult{
110+ ID: id,
111+ Version: strings.TrimSpace(plugin.Version),
112+ Path: targetPath,
113+ Overwritten: overwritten,
114+ }, nil
115+}
116+
117+func installTargetPath(options InstallOptions, id string) (string, error) {
118+ defaultPath := filepath.Join(options.PluginsDir, options.GOOS, options.GOARCH, id+pluginhost.PluginExtension(options.GOOS))
119+ if options.GOOS != runtime.GOOS || options.GOARCH != runtime.GOARCH {
120+ return defaultPath, nil
121+ }
122+ files, errDiscover := pluginhost.DiscoverPluginFiles(options.PluginsDir)
123+ if errDiscover != nil {
124+ return "", fmt.Errorf("discover current plugin files: %w", errDiscover)
125+ }
126+ for _, file := range files {
127+ if file.ID == id && strings.TrimSpace(file.Path) != "" {
128+ return file.Path, nil
129+ }
130+ }
131+ return defaultPath, nil
132+}
133+
134+func readTargetLibrary(reader *zip.Reader, id string, goos string) ([]byte, os.FileMode, error) {
135+ targetName := strings.TrimSpace(id) + pluginhost.PluginExtension(goos)
136+ var target *zip.File
137+ for _, file := range reader.File {
138+ cleanedName, errClean := cleanZipName(file.Name)
139+ if errClean != nil {
140+ return nil, 0, errClean
141+ }
142+ if file.FileInfo().IsDir() {
143+ continue
144+ }
145+ if !regularZipFile(file) {
146+ return nil, 0, fmt.Errorf("zip entry %s is not a regular file", file.Name)
147+ }
148+ if !hasDynamicLibraryExtension(cleanedName) {
149+ continue
150+ }
151+ if cleanedName != targetName {
152+ if path.Base(cleanedName) == targetName {
153+ return nil, 0, fmt.Errorf("target dynamic library must be at zip root")
154+ }
155+ return nil, 0, fmt.Errorf("dynamic library filename must be %s", targetName)
156+ }
157+ if target != nil {
158+ return nil, 0, fmt.Errorf("zip contains multiple target dynamic libraries")
159+ }
160+ target = file
161+ }
162+ if target == nil {
163+ return nil, 0, fmt.Errorf("zip does not contain %s", targetName)
164+ }
165+
166+ handle, errOpen := target.Open()
167+ if errOpen != nil {
168+ return nil, 0, fmt.Errorf("open %s: %w", targetName, errOpen)
169+ }
170+ defer func() {
171+ if errClose := handle.Close(); errClose != nil {
172+ log.WithError(errClose).Debug("failed to close plugin archive entry")
173+ }
174+ }()
175+ data, errRead := io.ReadAll(handle)
176+ if errRead != nil {
177+ return nil, 0, fmt.Errorf("read %s: %w", targetName, errRead)
178+ }
179+ mode := target.FileInfo().Mode().Perm()
180+ if mode == 0 {
181+ mode = 0o755
182+ }
183+ return data, mode, nil
184+}
185+
186+func cleanZipName(name string) (string, error) {
187+ if strings.TrimSpace(name) == "" {
188+ return "", fmt.Errorf("zip entry has empty name")
189+ }
190+ if strings.Contains(name, `\`) {
191+ return "", fmt.Errorf("zip entry %s uses backslash path separators", name)
192+ }
193+ if path.IsAbs(name) {
194+ return "", fmt.Errorf("zip entry %s is absolute", name)
195+ }
196+ cleaned := path.Clean(name)
197+ if cleaned == "." || cleaned == ".." || strings.HasPrefix(cleaned, "../") {
198+ return "", fmt.Errorf("zip entry %s escapes archive root", name)
199+ }
200+ return cleaned, nil
201+}
202+
203+func regularZipFile(file *zip.File) bool {
204+ mode := file.FileInfo().Mode()
205+ return mode.IsRegular() || mode.Type() == 0
206+}
207+
208+func hasDynamicLibraryExtension(name string) bool {
209+ lowerName := strings.ToLower(name)
210+ return strings.HasSuffix(lowerName, ".dylib") || strings.HasSuffix(lowerName, ".so") || strings.HasSuffix(lowerName, ".dll")
211+}
212+
213+func writeFileAtomic(targetPath string, data []byte, mode os.FileMode) error {
214+ targetDir := filepath.Dir(targetPath)
215+ if errMkdir := os.MkdirAll(targetDir, 0o755); errMkdir != nil {
216+ return fmt.Errorf("create plugin directory: %w", errMkdir)
217+ }
218+
219+ temp, errTemp := os.CreateTemp(targetDir, "."+filepath.Base(targetPath)+".tmp-*")
220+ if errTemp != nil {
221+ return fmt.Errorf("create temp plugin file: %w", errTemp)
222+ }
223+ tempPath := temp.Name()
224+ removeTemp := true
225+ closed := false
226+ defer func() {
227+ if !closed {
228+ if errClose := temp.Close(); errClose != nil {
229+ log.WithError(errClose).Debug("failed to close temp plugin file")
230+ }
231+ }
232+ if removeTemp {
233+ if errRemove := os.Remove(tempPath); errRemove != nil && !errors.Is(errRemove, os.ErrNotExist) {
234+ log.WithError(errRemove).Debug("failed to remove temp plugin file")
235+ }
236+ }
237+ }()
238+
239+ if errChmod := temp.Chmod(mode); errChmod != nil {
240+ return fmt.Errorf("chmod temp plugin file: %w", errChmod)
241+ }
242+ if _, errWrite := temp.Write(data); errWrite != nil {
243+ return fmt.Errorf("write temp plugin file: %w", errWrite)
244+ }
245+ if errSync := temp.Sync(); errSync != nil {
246+ return fmt.Errorf("sync temp plugin file: %w", errSync)
247+ }
248+ if errClose := temp.Close(); errClose != nil {
249+ return fmt.Errorf("close temp plugin file: %w", errClose)
250+ }
251+ closed = true
252+ if errRename := os.Rename(tempPath, targetPath); errRename != nil {
253+ return fmt.Errorf("install plugin file: %w", errRename)
254+ }
255+ removeTemp = false
256+ return nil
257+}
258+
259+func loadedPluginInstallBlocked(options InstallOptions) bool {
260+ return options.PluginLoaded != nil && strings.EqualFold(options.GOOS, "windows") && options.PluginLoaded()
261+}
262+
263+func normalizeInstallOptions(options InstallOptions) InstallOptions {
264+ options.PluginsDir = strings.TrimSpace(options.PluginsDir)
265+ if options.PluginsDir == "" {
266+ options.PluginsDir = "plugins"
267+ }
268+ options.GOOS = strings.TrimSpace(options.GOOS)
269+ if options.GOOS == "" {
270+ options.GOOS = runtime.GOOS
271+ }
272+ options.GOARCH = strings.TrimSpace(options.GOARCH)
273+ if options.GOARCH == "" {
274+ options.GOARCH = runtime.GOARCH
275+ }
276+ return options
277+}
internal/pluginstore/install_test.go+241−0
@@ -0,0 +1,241 @@
1+package pluginstore
2+
3+import (
4+ "archive/zip"
5+ "bytes"
6+ "context"
7+ "errors"
8+ "net/http"
9+ "os"
10+ "path/filepath"
11+ "runtime"
12+ "strings"
13+ "testing"
14+
15+ "github.com/router-for-me/CLIProxyAPI/v7/internal/pluginhost"
16+)
17+
18+func TestInstallBlocksLoadedWindowsPlugin(t *testing.T) {
19+ t.Parallel()
20+
21+ tests := []struct {
22+ name string
23+ goos string
24+ loaded bool
25+ wantBlocked bool
26+ }{
27+ {name: "windows loaded", goos: "windows", loaded: true, wantBlocked: true},
28+ {name: "windows not loaded", goos: "windows", loaded: false, wantBlocked: false},
29+ {name: "linux loaded", goos: "linux", loaded: true, wantBlocked: false},
30+ {name: "darwin loaded", goos: "darwin", loaded: true, wantBlocked: false},
31+ }
32+ for _, tt := range tests {
33+ t.Run(tt.name, func(t *testing.T) {
34+ t.Parallel()
35+
36+ _, errInstall := Client{HTTPClient: failingHTTPDoer{}}.Install(context.Background(), testPlugin(), InstallOptions{
37+ PluginsDir: t.TempDir(),
38+ GOOS: tt.goos,
39+ GOARCH: "amd64",
40+ PluginLoaded: func() bool { return tt.loaded },
41+ })
42+ if errInstall == nil {
43+ t.Fatal("Install() error = nil")
44+ }
45+ if gotBlocked := errors.Is(errInstall, ErrLoadedPluginLocked); gotBlocked != tt.wantBlocked {
46+ t.Fatalf("Install() error = %v, blocked = %v, want %v", errInstall, gotBlocked, tt.wantBlocked)
47+ }
48+ })
49+ }
50+}
51+
52+func TestInstallArchiveBlocksLoadedWindowsPluginBeforeWrite(t *testing.T) {
53+ t.Parallel()
54+
55+ _, errInstall := InstallArchive(makeZip(t, map[string]string{
56+ "sample-provider.dll": "library-data",
57+ }), testPlugin(), InstallOptions{
58+ PluginsDir: t.TempDir(),
59+ GOOS: "windows",
60+ GOARCH: "amd64",
61+ PluginLoaded: func() bool { return true },
62+ })
63+ if !errors.Is(errInstall, ErrLoadedPluginLocked) {
64+ t.Fatalf("InstallArchive() error = %v, want ErrLoadedPluginLocked", errInstall)
65+ }
66+}
67+
68+func TestInstallArchiveWritesPlatformPlugin(t *testing.T) {
69+ t.Parallel()
70+
71+ root := t.TempDir()
72+ result, errInstall := InstallArchive(makeZip(t, map[string]string{
73+ "README.md": "ignored",
74+ "sample-provider.dylib": "library-data",
75+ }), testPlugin(), InstallOptions{PluginsDir: root, GOOS: "darwin", GOARCH: "arm64"})
76+ if errInstall != nil {
77+ t.Fatalf("InstallArchive() error = %v", errInstall)
78+ }
79+ wantPath := filepath.Join(root, "darwin", "arm64", "sample-provider.dylib")
80+ if result.Path != wantPath {
81+ t.Fatalf("Path = %q, want %q", result.Path, wantPath)
82+ }
83+ data, errRead := os.ReadFile(wantPath)
84+ if errRead != nil {
85+ t.Fatalf("ReadFile() error = %v", errRead)
86+ }
87+ if string(data) != "library-data" {
88+ t.Fatalf("installed data = %q", data)
89+ }
90+}
91+
92+func TestInstallArchiveReportsOverwrite(t *testing.T) {
93+ t.Parallel()
94+
95+ root := t.TempDir()
96+ targetDir := filepath.Join(root, "darwin", "arm64")
97+ if errMkdir := os.MkdirAll(targetDir, 0o755); errMkdir != nil {
98+ t.Fatalf("MkdirAll() error = %v", errMkdir)
99+ }
100+ if errWrite := os.WriteFile(filepath.Join(targetDir, "sample-provider.dylib"), []byte("old"), 0o644); errWrite != nil {
101+ t.Fatalf("WriteFile() error = %v", errWrite)
102+ }
103+ result, errInstall := InstallArchive(makeZip(t, map[string]string{
104+ "sample-provider.dylib": "new",
105+ }), testPlugin(), InstallOptions{PluginsDir: root, GOOS: "darwin", GOARCH: "arm64"})
106+ if errInstall != nil {
107+ t.Fatalf("InstallArchive() error = %v", errInstall)
108+ }
109+ if !result.Overwritten {
110+ t.Fatal("Overwritten = false, want true")
111+ }
112+}
113+
114+func TestInstallArchiveOverwritesRuntimeSelectedPlugin(t *testing.T) {
115+ t.Parallel()
116+
117+ root := t.TempDir()
118+ existingPath := filepath.Join(root, "sample-provider"+pluginhost.PluginExtension(runtime.GOOS))
119+ if errWrite := os.WriteFile(existingPath, []byte("old"), 0o644); errWrite != nil {
120+ t.Fatalf("WriteFile() error = %v", errWrite)
121+ }
122+
123+ result, errInstall := InstallArchive(makeZip(t, map[string]string{
124+ "sample-provider" + pluginhost.PluginExtension(runtime.GOOS): "new",
125+ }), testPlugin(), InstallOptions{PluginsDir: root, GOOS: runtime.GOOS, GOARCH: runtime.GOARCH})
126+ if errInstall != nil {
127+ t.Fatalf("InstallArchive() error = %v", errInstall)
128+ }
129+ if result.Path != existingPath {
130+ t.Fatalf("Path = %q, want selected runtime plugin %q", result.Path, existingPath)
131+ }
132+ if !result.Overwritten {
133+ t.Fatal("Overwritten = false, want true")
134+ }
135+ data, errRead := os.ReadFile(existingPath)
136+ if errRead != nil {
137+ t.Fatalf("ReadFile() error = %v", errRead)
138+ }
139+ if string(data) != "new" {
140+ t.Fatalf("installed data = %q, want new", data)
141+ }
142+}
143+
144+func TestInstallArchiveRejectsUnsafeArchives(t *testing.T) {
145+ t.Parallel()
146+
147+ tests := []struct {
148+ name string
149+ files map[string]string
150+ wantErr string
151+ }{
152+ {
153+ name: "zip slip",
154+ files: map[string]string{"../sample-provider.dylib": "library"},
155+ wantErr: "escapes archive root",
156+ },
157+ {
158+ name: "absolute path",
159+ files: map[string]string{"/sample-provider.dylib": "library"},
160+ wantErr: "is absolute",
161+ },
162+ {
163+ name: "nested target",
164+ files: map[string]string{"nested/sample-provider.dylib": "library"},
165+ wantErr: "zip root",
166+ },
167+ {
168+ name: "extension mismatch",
169+ files: map[string]string{"sample-provider.so": "library"},
170+ wantErr: "sample-provider.dylib",
171+ },
172+ {
173+ name: "filename mismatch",
174+ files: map[string]string{"other.dylib": "library"},
175+ wantErr: "sample-provider.dylib",
176+ },
177+ {
178+ name: "missing target",
179+ files: map[string]string{"README.md": "library"},
180+ wantErr: "does not contain",
181+ },
182+ {
183+ name: "multiple targets",
184+ files: map[string]string{
185+ "sample-provider.dylib": "library",
186+ "copy.dylib": "library",
187+ },
188+ wantErr: "sample-provider.dylib",
189+ },
190+ }
191+ for _, tt := range tests {
192+ t.Run(tt.name, func(t *testing.T) {
193+ t.Parallel()
194+
195+ _, errInstall := InstallArchive(makeZip(t, tt.files), testPlugin(), InstallOptions{PluginsDir: t.TempDir(), GOOS: "darwin", GOARCH: "arm64"})
196+ if errInstall == nil {
197+ t.Fatal("InstallArchive() error = nil")
198+ }
199+ if !strings.Contains(errInstall.Error(), tt.wantErr) {
200+ t.Fatalf("InstallArchive() error = %v, want substring %q", errInstall, tt.wantErr)
201+ }
202+ })
203+ }
204+}
205+
206+func makeZip(t *testing.T, files map[string]string) []byte {
207+ t.Helper()
208+
209+ var buffer bytes.Buffer
210+ writer := zip.NewWriter(&buffer)
211+ for name, content := range files {
212+ file, errCreate := writer.Create(name)
213+ if errCreate != nil {
214+ t.Fatalf("Create(%s) error = %v", name, errCreate)
215+ }
216+ if _, errWrite := file.Write([]byte(content)); errWrite != nil {
217+ t.Fatalf("Write(%s) error = %v", name, errWrite)
218+ }
219+ }
220+ if errClose := writer.Close(); errClose != nil {
221+ t.Fatalf("Close() error = %v", errClose)
222+ }
223+ return buffer.Bytes()
224+}
225+
226+type failingHTTPDoer struct{}
227+
228+func (failingHTTPDoer) Do(*http.Request) (*http.Response, error) {
229+ return nil, errors.New("network unavailable")
230+}
231+
232+func testPlugin() Plugin {
233+ return Plugin{
234+ ID: "sample-provider",
235+ Name: "Sample Provider",
236+ Description: "Adds sample provider support.",
237+ Author: "author-name",
238+ Version: "0.1.0",
239+ Repository: "https://github.com/author-name/cliproxy-sample-provider-plugin",
240+ }
241+}
internal/pluginstore/registry.go+156−0
@@ -0,0 +1,156 @@
1+package pluginstore
2+
3+import (
4+ "bytes"
5+ "encoding/json"
6+ "fmt"
7+ "net/url"
8+ "regexp"
9+ "strings"
10+
11+ "github.com/router-for-me/CLIProxyAPI/v7/internal/pluginhost"
12+)
13+
14+const (
15+ DefaultRegistryURL = "https://raw.githubusercontent.com/router-for-me/CLIProxyAPI-Plugins-Store/main/registry.json"
16+ SchemaVersion = 1
17+)
18+
19+var pluginVersionPattern = regexp.MustCompile(`^[0-9][0-9A-Za-z.+-]*$`)
20+
21+type Registry struct {
22+ SchemaVersion int `json:"schema_version"`
23+ Plugins []Plugin `json:"plugins"`
24+}
25+
26+type Plugin struct {
27+ ID string `json:"id"`
28+ Name string `json:"name"`
29+ Description string `json:"description"`
30+ Author string `json:"author"`
31+ Version string `json:"version"`
32+ Repository string `json:"repository"`
33+ Logo string `json:"logo,omitempty"`
34+ Homepage string `json:"homepage,omitempty"`
35+ License string `json:"license,omitempty"`
36+ Tags []string `json:"tags,omitempty"`
37+}
38+
39+func ParseRegistry(data []byte) (Registry, error) {
40+ var registry Registry
41+ decoder := json.NewDecoder(bytes.NewReader(data))
42+ if errDecode := decoder.Decode(&registry); errDecode != nil {
43+ return Registry{}, fmt.Errorf("decode registry: %w", errDecode)
44+ }
45+ normalizeRegistry(&registry)
46+ if errValidate := ValidateRegistry(registry); errValidate != nil {
47+ return Registry{}, errValidate
48+ }
49+ return registry, nil
50+}
51+
52+func normalizeRegistry(registry *Registry) {
53+ if registry == nil {
54+ return
55+ }
56+ for index := range registry.Plugins {
57+ plugin := &registry.Plugins[index]
58+ plugin.ID = strings.TrimSpace(plugin.ID)
59+ plugin.Name = strings.TrimSpace(plugin.Name)
60+ plugin.Description = strings.TrimSpace(plugin.Description)
61+ plugin.Author = strings.TrimSpace(plugin.Author)
62+ plugin.Version = strings.TrimSpace(plugin.Version)
63+ plugin.Repository = strings.TrimSpace(plugin.Repository)
64+ plugin.Logo = strings.TrimSpace(plugin.Logo)
65+ plugin.Homepage = strings.TrimSpace(plugin.Homepage)
66+ plugin.License = strings.TrimSpace(plugin.License)
67+ for tagIndex := range plugin.Tags {
68+ plugin.Tags[tagIndex] = strings.TrimSpace(plugin.Tags[tagIndex])
69+ }
70+ }
71+}
72+
73+func ValidateRegistry(registry Registry) error {
74+ if registry.SchemaVersion != SchemaVersion {
75+ return fmt.Errorf("unsupported schema_version %d", registry.SchemaVersion)
76+ }
77+ seen := make(map[string]struct{}, len(registry.Plugins))
78+ for index, plugin := range registry.Plugins {
79+ if errValidate := ValidatePlugin(plugin); errValidate != nil {
80+ return fmt.Errorf("plugins[%d]: %w", index, errValidate)
81+ }
82+ id := strings.TrimSpace(plugin.ID)
83+ if _, exists := seen[id]; exists {
84+ return fmt.Errorf("plugins[%d]: duplicate plugin id %q", index, id)
85+ }
86+ seen[id] = struct{}{}
87+ }
88+ return nil
89+}
90+
91+func ValidatePlugin(plugin Plugin) error {
92+ required := map[string]string{
93+ "id": plugin.ID,
94+ "name": plugin.Name,
95+ "description": plugin.Description,
96+ "author": plugin.Author,
97+ "version": plugin.Version,
98+ "repository": plugin.Repository,
99+ }
100+ for field, value := range required {
101+ if strings.TrimSpace(value) == "" {
102+ return fmt.Errorf("missing required field %s", field)
103+ }
104+ }
105+ if !pluginhost.ValidatePluginID(strings.TrimSpace(plugin.ID)) {
106+ return fmt.Errorf("invalid plugin id %q", plugin.ID)
107+ }
108+ if !validPluginVersion(strings.TrimSpace(plugin.Version)) {
109+ return fmt.Errorf("invalid plugin version %q", plugin.Version)
110+ }
111+ if _, _, errRepository := GitHubRepositoryParts(plugin.Repository); errRepository != nil {
112+ return errRepository
113+ }
114+ return nil
115+}
116+
117+func validPluginVersion(version string) bool {
118+ return version != "" && !strings.HasPrefix(version, "v") && pluginVersionPattern.MatchString(version)
119+}
120+
121+func GitHubRepositoryParts(repository string) (string, string, error) {
122+ repository = strings.TrimSpace(repository)
123+ parsed, errParse := url.Parse(repository)
124+ if errParse != nil {
125+ return "", "", fmt.Errorf("invalid repository URL: %w", errParse)
126+ }
127+ if parsed.Scheme != "https" || parsed.Host != "github.com" || parsed.RawQuery != "" || parsed.Fragment != "" {
128+ return "", "", fmt.Errorf("repository must be https://github.com/{owner}/{repo}")
129+ }
130+ segments := strings.Split(strings.Trim(parsed.EscapedPath(), "/"), "/")
131+ if len(segments) != 2 || segments[0] == "" || segments[1] == "" {
132+ return "", "", fmt.Errorf("repository must be https://github.com/{owner}/{repo}")
133+ }
134+ owner, errOwner := url.PathUnescape(segments[0])
135+ if errOwner != nil {
136+ return "", "", fmt.Errorf("invalid repository owner: %w", errOwner)
137+ }
138+ repo, errRepo := url.PathUnescape(segments[1])
139+ if errRepo != nil {
140+ return "", "", fmt.Errorf("invalid repository name: %w", errRepo)
141+ }
142+ if strings.HasSuffix(repo, ".git") {
143+ return "", "", fmt.Errorf("repository must be https://github.com/{owner}/{repo}")
144+ }
145+ return owner, repo, nil
146+}
147+
148+func (r Registry) PluginByID(id string) (Plugin, bool) {
149+ id = strings.TrimSpace(id)
150+ for _, plugin := range r.Plugins {
151+ if strings.TrimSpace(plugin.ID) == id {
152+ return plugin, true
153+ }
154+ }
155+ return Plugin{}, false
156+}
internal/pluginstore/registry_test.go+167−0
@@ -0,0 +1,167 @@
1+package pluginstore
2+
3+import (
4+ "strings"
5+ "testing"
6+)
7+
8+func TestParseRegistryValidatesRegistry(t *testing.T) {
9+ t.Parallel()
10+
11+ registry, errParse := ParseRegistry([]byte(`{
12+ "schema_version": 1,
13+ "plugins": [{
14+ "id": "sample-provider",
15+ "name": "Sample Provider",
16+ "description": "Adds sample provider support.",
17+ "author": "author-name",
18+ "version": "0.1.0",
19+ "repository": "https://github.com/author-name/cliproxy-sample-provider-plugin",
20+ "logo": "https://example.com/logo.png",
21+ "homepage": "https://github.com/author-name/cliproxy-sample-provider-plugin",
22+ "license": "MIT",
23+ "tags": ["provider"]
24+ }]
25+ }`))
26+ if errParse != nil {
27+ t.Fatalf("ParseRegistry() error = %v", errParse)
28+ }
29+ plugin, ok := registry.PluginByID("sample-provider")
30+ if !ok {
31+ t.Fatal("PluginByID(sample-provider) missing")
32+ }
33+ if plugin.Version != "0.1.0" {
34+ t.Fatalf("plugin version = %q, want 0.1.0", plugin.Version)
35+ }
36+}
37+
38+func TestParseRegistryNormalizesPluginFields(t *testing.T) {
39+ t.Parallel()
40+
41+ registry, errParse := ParseRegistry([]byte(`{
42+ "schema_version": 1,
43+ "plugins": [{
44+ "id": " sample-provider ",
45+ "name": " Sample Provider ",
46+ "description": " Adds sample provider support. ",
47+ "author": " author-name ",
48+ "version": " 0.1.0 ",
49+ "repository": " https://github.com/author-name/cliproxy-sample-provider-plugin ",
50+ "logo": " https://example.com/logo.png ",
51+ "homepage": " https://github.com/author-name/cliproxy-sample-provider-plugin ",
52+ "license": " MIT ",
53+ "tags": [" provider "]
54+ }]
55+ }`))
56+ if errParse != nil {
57+ t.Fatalf("ParseRegistry() error = %v", errParse)
58+ }
59+ plugin, ok := registry.PluginByID("sample-provider")
60+ if !ok {
61+ t.Fatal("PluginByID(sample-provider) missing")
62+ }
63+ if plugin.ID != "sample-provider" || plugin.Version != "0.1.0" || plugin.Repository != "https://github.com/author-name/cliproxy-sample-provider-plugin" {
64+ t.Fatalf("plugin not normalized: %#v", plugin)
65+ }
66+ if plugin.Name != "Sample Provider" || plugin.Tags[0] != "provider" {
67+ t.Fatalf("plugin display fields not normalized: %#v", plugin)
68+ }
69+}
70+
71+func TestValidateRegistryRejectsInvalidEntries(t *testing.T) {
72+ t.Parallel()
73+
74+ valid := Plugin{
75+ ID: "sample-provider",
76+ Name: "Sample Provider",
77+ Description: "Adds sample provider support.",
78+ Author: "author-name",
79+ Version: "0.1.0",
80+ Repository: "https://github.com/author-name/cliproxy-sample-provider-plugin",
81+ }
82+ tests := []struct {
83+ name string
84+ mutate func(*Registry)
85+ wantErr string
86+ }{
87+ {
88+ name: "schema version",
89+ mutate: func(registry *Registry) {
90+ registry.SchemaVersion = 2
91+ },
92+ wantErr: "unsupported schema_version",
93+ },
94+ {
95+ name: "missing required field",
96+ mutate: func(registry *Registry) {
97+ registry.Plugins[0].Name = ""
98+ },
99+ wantErr: "missing required field name",
100+ },
101+ {
102+ name: "duplicate id",
103+ mutate: func(registry *Registry) {
104+ registry.Plugins = append(registry.Plugins, valid)
105+ },
106+ wantErr: "duplicate plugin id",
107+ },
108+ {
109+ name: "invalid id",
110+ mutate: func(registry *Registry) {
111+ registry.Plugins[0].ID = "../sample-provider"
112+ },
113+ wantErr: "invalid plugin id",
114+ },
115+ {
116+ name: "v-prefixed version",
117+ mutate: func(registry *Registry) {
118+ registry.Plugins[0].Version = "v0.1.0"
119+ },
120+ wantErr: "invalid plugin version",
121+ },
122+ {
123+ name: "invalid repository",
124+ mutate: func(registry *Registry) {
125+ registry.Plugins[0].Repository = "https://example.com/author/repo"
126+ },
127+ wantErr: "repository must be",
128+ },
129+ }
130+
131+ for _, tt := range tests {
132+ t.Run(tt.name, func(t *testing.T) {
133+ t.Parallel()
134+
135+ registry := Registry{SchemaVersion: 1, Plugins: []Plugin{valid}}
136+ tt.mutate(&registry)
137+ errValidate := ValidateRegistry(registry)
138+ if errValidate == nil {
139+ t.Fatal("ValidateRegistry() error = nil")
140+ }
141+ if !strings.Contains(errValidate.Error(), tt.wantErr) {
142+ t.Fatalf("ValidateRegistry() error = %v, want substring %q", errValidate, tt.wantErr)
143+ }
144+ })
145+ }
146+}
147+
148+func TestGitHubRepositoryPartsRejectsNonRepositoryURLs(t *testing.T) {
149+ t.Parallel()
150+
151+ tests := []string{
152+ "http://github.com/owner/repo",
153+ "https://github.com/owner",
154+ "https://github.com/owner/repo/issues",
155+ "https://github.com/owner/repo.git",
156+ "https://github.com/owner/repo?tab=readme",
157+ }
158+ for _, repository := range tests {
159+ t.Run(repository, func(t *testing.T) {
160+ t.Parallel()
161+
162+ if _, _, errParse := GitHubRepositoryParts(repository); errParse == nil {
163+ t.Fatalf("GitHubRepositoryParts(%q) error = nil", repository)
164+ }
165+ })
166+ }
167+}
internal/pluginstore/version.go+69−0
@@ -0,0 +1,69 @@
1+package pluginstore
2+
3+import (
4+ "strconv"
5+ "strings"
6+)
7+
8+// UpdateAvailable reports whether latest should be offered as an upgrade over
9+// installed. A leading "v"/"V" is ignored on both sides. Versions are compared
10+// numerically when both are dotted release numbers, so an installed version
11+// newer than the registry one is not reported as an update; otherwise any
12+// difference counts as an update.
13+func UpdateAvailable(installed, latest string) bool {
14+ installed = normalizeVersion(installed)
15+ latest = normalizeVersion(latest)
16+ if installed == "" || latest == "" || installed == latest {
17+ return false
18+ }
19+ comparison, comparable := compareVersions(installed, latest)
20+ if !comparable {
21+ return true
22+ }
23+ return comparison < 0
24+}
25+
26+func normalizeVersion(version string) string {
27+ version = strings.TrimSpace(version)
28+ if len(version) > 1 && (version[0] == 'v' || version[0] == 'V') {
29+ version = version[1:]
30+ }
31+ return version
32+}
33+
34+// compareVersions compares dotted numeric versions segment by segment, with
35+// missing segments treated as zero. It reports false when either version
36+// contains a non-numeric segment.
37+func compareVersions(a, b string) (int, bool) {
38+ segmentsA := strings.Split(a, ".")
39+ segmentsB := strings.Split(b, ".")
40+ length := len(segmentsA)
41+ if len(segmentsB) > length {
42+ length = len(segmentsB)
43+ }
44+ for index := 0; index < length; index++ {
45+ numberA, okA := versionSegment(segmentsA, index)
46+ numberB, okB := versionSegment(segmentsB, index)
47+ if !okA || !okB {
48+ return 0, false
49+ }
50+ if numberA != numberB {
51+ if numberA < numberB {
52+ return -1, true
53+ }
54+ return 1, true
55+ }
56+ }
57+ return 0, true
58+}
59+
60+func versionSegment(segments []string, index int) (int64, bool) {
61+ if index >= len(segments) {
62+ return 0, true
63+ }
64+ number, errParse := strconv.ParseInt(segments[index], 10, 64)
65+ if errParse != nil || number < 0 {
66+ return 0, false
67+ }
68+ return number, true
69+}
internal/pluginstore/version_test.go+34−0
@@ -0,0 +1,34 @@
1+package pluginstore
2+
3+import "testing"
4+
5+func TestUpdateAvailable(t *testing.T) {
6+ t.Parallel()
7+
8+ tests := []struct {
9+ name string
10+ installed string
11+ latest string
12+ want bool
13+ }{
14+ {name: "unknown installed", installed: "", latest: "0.2.0", want: false},
15+ {name: "same version", installed: "0.1.0", latest: "0.1.0", want: false},
16+ {name: "same version with v prefix", installed: "v0.1.0", latest: "0.1.0", want: false},
17+ {name: "newer registry version", installed: "0.1.0", latest: "0.2.0", want: true},
18+ {name: "newer registry version with v prefix", installed: "v0.1.0", latest: "0.2.0", want: true},
19+ {name: "numeric not lexicographic", installed: "0.1.9", latest: "0.1.10", want: true},
20+ {name: "installed newer than registry", installed: "0.2.0", latest: "0.1.0", want: false},
21+ {name: "missing segments treated as zero", installed: "0.1", latest: "0.1.0", want: false},
22+ {name: "prerelease falls back to inequality", installed: "0.1.0-rc1", latest: "0.1.0", want: true},
23+ {name: "non numeric falls back to inequality", installed: "dev", latest: "0.1.0", want: true},
24+ }
25+ for _, tt := range tests {
26+ t.Run(tt.name, func(t *testing.T) {
27+ t.Parallel()
28+
29+ if got := UpdateAvailable(tt.installed, tt.latest); got != tt.want {
30+ t.Fatalf("UpdateAvailable(%q, %q) = %v, want %v", tt.installed, tt.latest, got, tt.want)
31+ }
32+ })
33+ }
34+}
internal/thinking/validate.go+1−1
@@ -339,7 +339,7 @@ func normalizeLevels(levels []string) []string { · 338 unmodified lines
339339 // These providers may also support level-based thinking (hybrid models).
340340 func isBudgetCapableProvider(provider string) bool {
341341 switch provider {
342− case "gemini", "gemini-cli", "antigravity", "claude", "qoder":
342+ case "gemini", "gemini-cli", "antigravity", "claude":
343343 return true
344344 default:
345345 return false
sdk/cliproxy/auth/oauth_model_alias_test.go+13−13
@@ -175,10 +175,10 @@ func TestOAuthModelAliasChannel_Kimi(t *testing.T) { · 174 unmodified lines
175175 func TestOAuthModelAliasChannel_PluginProvider(t *testing.T) {
176176 t.Parallel()
177177
178− if got := OAuthModelAliasChannel(" Qoder ", "oauth"); got != "qoder" {
179− t.Fatalf("OAuthModelAliasChannel() = %q, want %q", got, "qoder")
178+ if got := OAuthModelAliasChannel(" Sample-Provider ", "oauth"); got != "sample-provider" {
179+ t.Fatalf("OAuthModelAliasChannel() = %q, want %q", got, "sample-provider")
180180 }
181− if got := OAuthModelAliasChannel("qoder", "api_key"); got != "" {
181+ if got := OAuthModelAliasChannel("sample-provider", "api_key"); got != "" {
182182 t.Fatalf("OAuthModelAliasChannel() = %q, want empty channel for API key", got)
183183 }
184184 }
@@ -206,18 +206,18 @@ func TestApplyOAuthModelAlias_PluginProvider(t *testing.T) { · 21 unmodified lines
206206 t.Parallel()
207207
208208 aliases := map[string][]internalconfig.OAuthModelAlias{
209− "qoder": {{Name: "qmodel_latest", Alias: "qlatest"}},
209+ "sample-provider": {{Name: "sample-model-latest", Alias: "sample-latest"}},
210210 }
211211
212212 mgr := NewManager(nil, nil, nil)
213213 mgr.SetConfig(&internalconfig.Config{})
214214 mgr.SetOAuthModelAlias(aliases)
215215
216− auth := &Auth{ID: "qoder-auth", Provider: "qoder", Attributes: map[string]string{"auth_kind": "oauth"}}
216+ auth := &Auth{ID: "sample-provider-auth", Provider: "sample-provider", Attributes: map[string]string{"auth_kind": "oauth"}}
217217
218− resolvedModel := mgr.applyOAuthModelAlias(auth, "qlatest")
219− if resolvedModel != "qmodel_latest" {
220− t.Errorf("applyOAuthModelAlias() model = %q, want %q", resolvedModel, "qmodel_latest")
218+ resolvedModel := mgr.applyOAuthModelAlias(auth, "sample-latest")
219+ if resolvedModel != "sample-model-latest" {
220+ t.Errorf("applyOAuthModelAlias() model = %q, want %q", resolvedModel, "sample-model-latest")
221221 }
222222 }
223223
@@ -225,17 +225,17 @@ func TestApplyOAuthModelAlias_PluginProviderSkipsAPIKey(t *testing.T) { · 1 unmodified line
225225 t.Parallel()
226226
227227 aliases := map[string][]internalconfig.OAuthModelAlias{
228− "qoder": {{Name: "qmodel_latest", Alias: "qlatest"}},
228+ "sample-provider": {{Name: "sample-model-latest", Alias: "sample-latest"}},
229229 }
230230
231231 mgr := NewManager(nil, nil, nil)
232232 mgr.SetConfig(&internalconfig.Config{})
233233 mgr.SetOAuthModelAlias(aliases)
234234
235− auth := &Auth{ID: "qoder-auth", Provider: "qoder", Attributes: map[string]string{"auth_kind": "api_key"}}
235+ auth := &Auth{ID: "sample-provider-auth", Provider: "sample-provider", Attributes: map[string]string{"auth_kind": "api_key"}}
236236
237− resolvedModel := mgr.applyOAuthModelAlias(auth, "qlatest")
238− if resolvedModel != "qlatest" {
239− t.Errorf("applyOAuthModelAlias() model = %q, want %q", resolvedModel, "qlatest")
237+ resolvedModel := mgr.applyOAuthModelAlias(auth, "sample-latest")
238+ if resolvedModel != "sample-latest" {
239+ t.Errorf("applyOAuthModelAlias() model = %q, want %q", resolvedModel, "sample-latest")
240240 }
241241 }
sdk/cliproxy/service_oauth_model_alias_test.go+13−13
@@ -94,41 +94,41 @@ func TestApplyOAuthModelAlias_ForkAddsMultipleAliases(t *testing.T) { · 93 unmodified lines
9494 func TestApplyOAuthModelAlias_PluginProvider(t *testing.T) {
9595 cfg := &config.Config{
9696 OAuthModelAlias: map[string][]config.OAuthModelAlias{
97− "qoder": {
98− {Name: "qmodel_latest", Alias: "qlatest"},
97+ "sample-provider": {
98+ {Name: "sample-model-latest", Alias: "sample-latest"},
9999 },
100100 },
101101 }
102102 models := []*ModelInfo{
103− {ID: "qmodel_latest", Name: "models/qmodel_latest"},
103+ {ID: "sample-model-latest", Name: "models/sample-model-latest"},
104104 }
105105
106− out := applyOAuthModelAlias(cfg, "qoder", "oauth", models)
106+ out := applyOAuthModelAlias(cfg, "sample-provider", "oauth", models)
107107 if len(out) != 1 {
108108 t.Fatalf("expected 1 model, got %d", len(out))
109109 }
110− if out[0].ID != "qlatest" {
111− t.Fatalf("expected plugin alias id %q, got %q", "qlatest", out[0].ID)
110+ if out[0].ID != "sample-latest" {
111+ t.Fatalf("expected plugin alias id %q, got %q", "sample-latest", out[0].ID)
112112 }
113− if out[0].Name != "models/qlatest" {
114− t.Fatalf("expected plugin alias name %q, got %q", "models/qlatest", out[0].Name)
113+ if out[0].Name != "models/sample-latest" {
114+ t.Fatalf("expected plugin alias name %q, got %q", "models/sample-latest", out[0].Name)
115115 }
116116 }
117117
118118 func TestApplyOAuthModelAlias_PluginProviderSkipsAPIKey(t *testing.T) {
119119 cfg := &config.Config{
120120 OAuthModelAlias: map[string][]config.OAuthModelAlias{
121− "qoder": {
122− {Name: "qmodel_latest", Alias: "qlatest"},
121+ "sample-provider": {
122+ {Name: "sample-model-latest", Alias: "sample-latest"},
123123 },
124124 },
125125 }
126126 models := []*ModelInfo{
127− {ID: "qmodel_latest", Name: "models/qmodel_latest"},
127+ {ID: "sample-model-latest", Name: "models/sample-model-latest"},
128128 }
129129
130− out := applyOAuthModelAlias(cfg, "qoder", "api_key", models)
131− if len(out) != 1 || out[0].ID != "qmodel_latest" {
130+ out := applyOAuthModelAlias(cfg, "sample-provider", "api_key", models)
131+ if len(out) != 1 || out[0].ID != "sample-model-latest" {
132132 t.Fatalf("expected API key plugin model to remain unchanged, got %#v", out)
133133 }
134134 }

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

Select next item
j↓
Select previous item
k↑
Open selected item
Enter
Dismiss filters or clear selection
Esc

Repository code

Go to file
t