From 2c107dc80a4edee78e2fc6e1a277808e22ebc06f Mon Sep 17 00:00:00 2001 From: Sycun <165354365+Sycun@users.noreply.github.com> Date: Sat, 28 Nov 2026 20:43:06 +0800 Subject: [PATCH] feat(pluginhub): support adding, deleting, and restoring market catalog entries --- internal/database/plugin_catalog.go | 81 +++++++ internal/database/schemas/application.sql | 12 + internal/handler/plugins.go | 53 ++++- internal/handler/plugins_test.go | 24 ++ internal/pluginhub/catalog/catalog.go | 14 +- internal/pluginhub/catalog_store.go | 176 ++++++++++++++ internal/pluginhub/catalog_store_test.go | 135 +++++++++++ internal/pluginhub/planning.go | 3 +- internal/security/rbac_middleware.go | 6 +- web/frontend/src/pages/plugin-hub/Drawers.jsx | 214 +++++++++++++++++- web/frontend/src/pages/plugin-hub/api.js | 4 + web/frontend/src/pages/plugin-hub/index.jsx | 103 ++++++++- ...PuXMx4.js => AssetEditorModal-BEZxqgxe.js} | 2 +- ...cun4T.js => agents-management-Dc8cfsKK.js} | 2 +- ...-docs-Ct8ppDxE.js => api-docs-C9mgfNVV.js} | 2 +- ...-n7tD2oRA.js => asset-library-Cx4WauFD.js} | 2 +- ...BCDioECx.js => asset-overview-BcrOahpV.js} | 2 +- ...ents--E-TMcWA.js => c2-events-wyQwRxwo.js} | 2 +- ...s-DG2YKGmu.js => c2-listeners-Db41NAPb.js} | 2 +- ...ds-C5S-G8Nv.js => c2-payloads-B55bhMwV.js} | 2 +- ...es-DeCq3zSk.js => c2-profiles-BS7Ltblj.js} | 2 +- ...ns-CPg-wdnb.js => c2-sessions-GX4yfPDz.js} | 2 +- ...ared-ChrAHhKB.js => c2-shared-CsmBGia3.js} | 2 +- ...ared-CYdOx-YS.js => c2-shared-DNv0OQHb.js} | 2 +- ...tasks-CofE5lbz.js => c2-tasks-6xM547kO.js} | 2 +- .../{chat-DcZlFiwm.js => chat-ClVpg1U3.js} | 2 +- ...les-9vNKnz9A.js => chat-files-BNVzNP7B.js} | 2 +- ...oard-CevUeofU.js => dashboard-DXgcxUQj.js} | 2 +- ...a2u--7.js => deep-assessments-COCEQmQD.js} | 2 +- .../{hitl-BWSwvNOF.js => hitl-Id7QulFl.js} | 2 +- .../{index-CKro0ye9.js => index-B3TlLo8G.js} | 4 +- ...t-CUvlCygk.js => info-collect-CptOHPKp.js} | 2 +- ...DY.js => knowledge-management-Iwt3xopD.js} | 2 +- ...s => knowledge-retrieval-logs-BxYtvGe3.js} | 2 +- ...BWbzUsaI.js => mcp-management-D3SuCdcS.js} | 2 +- ...or-CJgC2C-z.js => mcp-monitor-Cc2dBV9i.js} | 2 +- ...-BlFlD0Rf.js => platform-rbac-C0-ocSH4.js} | 2 +- web/static/app/assets/plugin-hub-BUVWIN0m.js | 3 + web/static/app/assets/plugin-hub-Cwo3gy3v.js | 3 - ...m-BKErgX2t.js => project-form-Z4A6P7_8.js} | 2 +- ...jects-Da3r2wEW.js => projects-D2bGTn9g.js} | 2 +- ...pMOkXZ.js => roles-management-eLTgkMp6.js} | 2 +- ...tings-WKt89Atw.js => settings-KJYz4E6U.js} | 2 +- ...EZxt2.js => skills-management-Cypf8GSB.js} | 2 +- ...DBUZ6Cuu.js => skills-monitor-Be9DdFa9.js} | 2 +- .../{tasks-DKUq31wQ.js => tasks-m8084w-D.js} | 2 +- ...ard-DALbrGtS.js => tool-guard-DaTdUHek.js} | 2 +- ...cpNrjSf.js => vulnerabilities-BWF1ATYl.js} | 2 +- ...shell-CgprwKxz.js => webshell-8Sjh_Kpl.js} | 2 +- ...lows-DXneq5Cp.js => workflows-Dkuw22Xz.js} | 2 +- web/static/app/index.html | 2 +- web/static/i18n/ar-SA.json | 32 ++- web/static/i18n/en-US.json | 32 ++- web/static/i18n/ru-RU.json | 32 ++- web/static/i18n/zh-CN.json | 32 ++- 55 files changed, 974 insertions(+), 61 deletions(-) create mode 100644 internal/database/plugin_catalog.go create mode 100644 internal/pluginhub/catalog_store.go create mode 100644 internal/pluginhub/catalog_store_test.go rename web/static/app/assets/{AssetEditorModal-0cPuXMx4.js => AssetEditorModal-BEZxqgxe.js} (98%) rename web/static/app/assets/{agents-management-C17cun4T.js => agents-management-Dc8cfsKK.js} (97%) rename web/static/app/assets/{api-docs-Ct8ppDxE.js => api-docs-C9mgfNVV.js} (98%) rename web/static/app/assets/{asset-library-n7tD2oRA.js => asset-library-Cx4WauFD.js} (99%) rename web/static/app/assets/{asset-overview-BCDioECx.js => asset-overview-BcrOahpV.js} (98%) rename web/static/app/assets/{c2-events--E-TMcWA.js => c2-events-wyQwRxwo.js} (95%) rename web/static/app/assets/{c2-listeners-DG2YKGmu.js => c2-listeners-Db41NAPb.js} (97%) rename web/static/app/assets/{c2-payloads-C5S-G8Nv.js => c2-payloads-B55bhMwV.js} (97%) rename web/static/app/assets/{c2-profiles-DeCq3zSk.js => c2-profiles-BS7Ltblj.js} (98%) rename web/static/app/assets/{c2-sessions-CPg-wdnb.js => c2-sessions-GX4yfPDz.js} (98%) rename web/static/app/assets/{c2-shared-ChrAHhKB.js => c2-shared-CsmBGia3.js} (96%) rename web/static/app/assets/{c2-shared-CYdOx-YS.js => c2-shared-DNv0OQHb.js} (94%) rename web/static/app/assets/{c2-tasks-CofE5lbz.js => c2-tasks-6xM547kO.js} (97%) rename web/static/app/assets/{chat-DcZlFiwm.js => chat-ClVpg1U3.js} (99%) rename web/static/app/assets/{chat-files-9vNKnz9A.js => chat-files-BNVzNP7B.js} (99%) rename web/static/app/assets/{dashboard-CevUeofU.js => dashboard-DXgcxUQj.js} (99%) rename web/static/app/assets/{deep-assessments-D_a2u--7.js => deep-assessments-COCEQmQD.js} (99%) rename web/static/app/assets/{hitl-BWSwvNOF.js => hitl-Id7QulFl.js} (99%) rename web/static/app/assets/{index-CKro0ye9.js => index-B3TlLo8G.js} (96%) rename web/static/app/assets/{info-collect-CUvlCygk.js => info-collect-CptOHPKp.js} (99%) rename web/static/app/assets/{knowledge-management-uk7eamDY.js => knowledge-management-Iwt3xopD.js} (98%) rename web/static/app/assets/{knowledge-retrieval-logs-C3heed_N.js => knowledge-retrieval-logs-BxYtvGe3.js} (96%) rename web/static/app/assets/{mcp-management-BWbzUsaI.js => mcp-management-D3SuCdcS.js} (99%) rename web/static/app/assets/{mcp-monitor-CJgC2C-z.js => mcp-monitor-Cc2dBV9i.js} (99%) rename web/static/app/assets/{platform-rbac-BlFlD0Rf.js => platform-rbac-C0-ocSH4.js} (99%) create mode 100644 web/static/app/assets/plugin-hub-BUVWIN0m.js delete mode 100644 web/static/app/assets/plugin-hub-Cwo3gy3v.js rename web/static/app/assets/{project-form-BKErgX2t.js => project-form-Z4A6P7_8.js} (94%) rename web/static/app/assets/{projects-Da3r2wEW.js => projects-D2bGTn9g.js} (99%) rename web/static/app/assets/{roles-management-h2pMOkXZ.js => roles-management-eLTgkMp6.js} (99%) rename web/static/app/assets/{settings-WKt89Atw.js => settings-KJYz4E6U.js} (99%) rename web/static/app/assets/{skills-management-CAqEZxt2.js => skills-management-Cypf8GSB.js} (97%) rename web/static/app/assets/{skills-monitor-DBUZ6Cuu.js => skills-monitor-Be9DdFa9.js} (95%) rename web/static/app/assets/{tasks-DKUq31wQ.js => tasks-m8084w-D.js} (99%) rename web/static/app/assets/{tool-guard-DALbrGtS.js => tool-guard-DaTdUHek.js} (99%) rename web/static/app/assets/{vulnerabilities-CcpNrjSf.js => vulnerabilities-BWF1ATYl.js} (99%) rename web/static/app/assets/{webshell-CgprwKxz.js => webshell-8Sjh_Kpl.js} (99%) rename web/static/app/assets/{workflows-DXneq5Cp.js => workflows-Dkuw22Xz.js} (99%) diff --git a/internal/database/plugin_catalog.go b/internal/database/plugin_catalog.go new file mode 100644 index 00000000..1af5f2dc --- /dev/null +++ b/internal/database/plugin_catalog.go @@ -0,0 +1,81 @@ +package database + +import ( + "context" + "time" +) + +type PluginCatalogRecord struct { + ID string + Title string + Repository string + Revision string + Summary string + ManifestJSON string + Source string // "custom" | "builtin_hidden" + CreatedAt time.Time + UpdatedAt time.Time +} + +func (db *DB) ListPluginCatalogRecords(ctx context.Context) ([]PluginCatalogRecord, error) { + rows, err := db.QueryContext(ctx, `SELECT id, title, repository, revision, summary, manifest_json, source, created_at, updated_at + FROM plugin_catalog_entries ORDER BY updated_at DESC, id ASC`) + if err != nil { + return nil, err + } + defer rows.Close() + out := []PluginCatalogRecord{} + for rows.Next() { + var r PluginCatalogRecord + if err := rows.Scan(&r.ID, &r.Title, &r.Repository, &r.Revision, &r.Summary, &r.ManifestJSON, &r.Source, &r.CreatedAt, &r.UpdatedAt); err != nil { + return nil, err + } + out = append(out, r) + } + return out, rows.Err() +} + +func (db *DB) GetPluginCatalogRecord(ctx context.Context, id string) (PluginCatalogRecord, error) { + var r PluginCatalogRecord + err := db.QueryRowContext(ctx, `SELECT id, title, repository, revision, summary, manifest_json, source, created_at, updated_at + FROM plugin_catalog_entries WHERE id = ?`, id). + Scan(&r.ID, &r.Title, &r.Repository, &r.Revision, &r.Summary, &r.ManifestJSON, &r.Source, &r.CreatedAt, &r.UpdatedAt) + return r, err +} + +func (db *DB) UpsertPluginCatalogRecord(ctx context.Context, r PluginCatalogRecord) error { + now := time.Now().UTC() + if r.Source == "" { + r.Source = "custom" + } + _, err := db.ExecContext(ctx, `INSERT INTO plugin_catalog_entries + (id, title, repository, revision, summary, manifest_json, source, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(id) DO UPDATE SET + title=excluded.title, + repository=excluded.repository, + revision=excluded.revision, + summary=excluded.summary, + manifest_json=excluded.manifest_json, + source=excluded.source, + updated_at=excluded.updated_at`, + r.ID, r.Title, r.Repository, r.Revision, r.Summary, r.ManifestJSON, r.Source, now, now) + return err +} + +func (db *DB) DeletePluginCatalogRecord(ctx context.Context, id string) (bool, error) { + res, err := db.ExecContext(ctx, `DELETE FROM plugin_catalog_entries WHERE id = ?`, id) + if err != nil { + return false, err + } + n, err := res.RowsAffected() + return n > 0, err +} + +func (db *DB) RestoreHiddenBuiltinCatalog(ctx context.Context) (int64, error) { + res, err := db.ExecContext(ctx, `DELETE FROM plugin_catalog_entries WHERE source = 'builtin_hidden'`) + if err != nil { + return 0, err + } + return res.RowsAffected() +} diff --git a/internal/database/schemas/application.sql b/internal/database/schemas/application.sql index 3d45366d..b06adbb9 100644 --- a/internal/database/schemas/application.sql +++ b/internal/database/schemas/application.sql @@ -1227,6 +1227,18 @@ CREATE TABLE IF NOT EXISTS plugin_operations ( CREATE UNIQUE INDEX IF NOT EXISTS idx_plugin_operations_active ON plugin_operations(install_id) WHERE status IN ('queued', 'running'); +CREATE TABLE IF NOT EXISTS plugin_catalog_entries ( + id TEXT PRIMARY KEY, + title TEXT NOT NULL, + repository TEXT NOT NULL, + revision TEXT NOT NULL DEFAULT '', + summary TEXT NOT NULL DEFAULT '', + manifest_json TEXT NOT NULL DEFAULT '', + source TEXT NOT NULL DEFAULT 'custom' CHECK(source IN ('custom','builtin_hidden')), + created_at DATETIME NOT NULL, + updated_at DATETIME NOT NULL +); + CREATE TABLE IF NOT EXISTS plugin_runtime_leases ( id INTEGER PRIMARY KEY CHECK(id = 1), owner TEXT NOT NULL, diff --git a/internal/handler/plugins.go b/internal/handler/plugins.go index 023f8735..b2558503 100644 --- a/internal/handler/plugins.go +++ b/internal/handler/plugins.go @@ -16,7 +16,6 @@ import ( "cyberstrike-ai/internal/audit" "cyberstrike-ai/internal/database" "cyberstrike-ai/internal/pluginhub" - "cyberstrike-ai/internal/pluginhub/catalog" "cyberstrike-ai/internal/pluginhub/llmgateway" "cyberstrike-ai/internal/pluginhub/manifest" "cyberstrike-ai/internal/pluginhub/source" @@ -54,6 +53,9 @@ func (h *PluginHandler) Register(group *gin.RouterGroup) { c.Next() }) group.GET("/catalog", h.listCatalog) + group.POST("/catalog", h.saveCatalog) + group.DELETE("/catalog/:id", h.deleteCatalog) + group.POST("/catalog/restore", h.restoreCatalog) group.GET("/schemas/:name", h.schema) group.GET("/llm/channels", h.listLLMChannels) group.GET("/installs", h.listInstalls) @@ -111,7 +113,54 @@ func (h *PluginHandler) patchLLM(c *gin.Context) { } func (h *PluginHandler) listCatalog(c *gin.Context) { - c.JSON(http.StatusOK, gin.H{"items": catalog.Entries()}) + items, hiddenBuiltins, err := h.hub.ListCatalog(c.Request.Context()) + if err != nil { + pluginError(c, http.StatusInternalServerError, "plugin_storage_error") + return + } + c.JSON(http.StatusOK, gin.H{"items": items, "hidden_builtins": hiddenBuiltins}) +} + +func (h *PluginHandler) saveCatalog(c *gin.Context) { + var input pluginhub.CatalogInput + if !bindPluginRequest(c, &input) { + return + } + entry, err := h.hub.SaveCatalogEntry(c.Request.Context(), input) + if err != nil { + pluginLifecycleError(c, err) + return + } + if h.audit != nil { + h.audit.RecordOK(c, "plugins", "catalog_save", "Plugin catalog entry saved", "plugin_catalog", entry.ID, + map[string]interface{}{"repository": entry.Repository, "availability": entry.Availability}) + } + c.JSON(http.StatusCreated, gin.H{"item": entry}) +} + +func (h *PluginHandler) deleteCatalog(c *gin.Context) { + id := c.Param("id") + if err := h.hub.DeleteCatalogEntry(c.Request.Context(), id); err != nil { + pluginLifecycleError(c, err) + return + } + if h.audit != nil { + h.audit.RecordOK(c, "plugins", "catalog_delete", "Plugin catalog entry removed", "plugin_catalog", id, nil) + } + c.JSON(http.StatusOK, gin.H{"deleted": id}) +} + +func (h *PluginHandler) restoreCatalog(c *gin.Context) { + restored, err := h.hub.RestoreBuiltinCatalog(c.Request.Context()) + if err != nil { + pluginError(c, http.StatusInternalServerError, "plugin_storage_error") + return + } + if h.audit != nil { + h.audit.RecordOK(c, "plugins", "catalog_restore", "Built-in plugin catalog entries restored", "plugin_catalog", "builtin", + map[string]interface{}{"restored": restored}) + } + c.JSON(http.StatusOK, gin.H{"restored": restored}) } func (h *PluginHandler) schema(c *gin.Context) { diff --git a/internal/handler/plugins_test.go b/internal/handler/plugins_test.go index 37eedddc..c6a9c2c0 100644 --- a/internal/handler/plugins_test.go +++ b/internal/handler/plugins_test.go @@ -123,6 +123,30 @@ func TestPluginManagementPreviewAndRBAC(t *testing.T) { request(http.MethodGet, "/catalog", "cookie:"+admin, "", http.StatusUnauthorized) request(http.MethodGet, "/catalog", reader, "", http.StatusOK) request(http.MethodGet, "/catalog", userWithoutPlugins, "", http.StatusForbidden) + // Catalog CRUD & RBAC + customBody := `{"id":"custom-tool","title":"Custom Tool","repository":"https://github.com/example/custom-tool","revision":"main","summary":"Custom market entry"}` + request(http.MethodPost, "/catalog", reader, customBody, http.StatusForbidden) + request(http.MethodPost, "/catalog", scopedManager, customBody, http.StatusForbidden) + request(http.MethodPost, "/catalog", admin, customBody, http.StatusCreated) + catalogRaw := request(http.MethodGet, "/catalog", reader, "", http.StatusOK) + if !strings.Contains(string(catalogRaw), `"custom-tool"`) { + t.Fatalf("expected custom-tool in catalog: %s", catalogRaw) + } + request(http.MethodDelete, "/catalog/custom-tool", reader, "", http.StatusForbidden) + request(http.MethodDelete, "/catalog/custom-tool", admin, "", http.StatusOK) + request(http.MethodDelete, "/catalog/custom-tool", admin, "", http.StatusNotFound) + // Hiding and restoring a built-in catalog entry + request(http.MethodDelete, "/catalog/artex", admin, "", http.StatusOK) + hiddenRaw := request(http.MethodGet, "/catalog", reader, "", http.StatusOK) + if strings.Contains(string(hiddenRaw), `"id":"artex"`) || !strings.Contains(string(hiddenRaw), `"hidden_builtins":1`) { + t.Fatalf("expected artex hidden with hidden_builtins=1: %s", hiddenRaw) + } + request(http.MethodPost, "/catalog/restore", reader, `{}`, http.StatusForbidden) + request(http.MethodPost, "/catalog/restore", admin, `{}`, http.StatusOK) + restoredRaw := request(http.MethodGet, "/catalog", reader, "", http.StatusOK) + if !strings.Contains(string(restoredRaw), `"id":"artex"`) || !strings.Contains(string(restoredRaw), `"hidden_builtins":0`) { + t.Fatalf("expected artex restored: %s", restoredRaw) + } request(http.MethodGet, "/schemas/manifest-v1", reader, "", http.StatusOK) body := `{"repository":"https://github.com/example/review","revision":"v1.0.0"}` request(http.MethodPost, "/imports/inspect", reader, body, http.StatusForbidden) diff --git a/internal/pluginhub/catalog/catalog.go b/internal/pluginhub/catalog/catalog.go index cebf33b9..5bec114c 100644 --- a/internal/pluginhub/catalog/catalog.go +++ b/internal/pluginhub/catalog/catalog.go @@ -16,6 +16,7 @@ type Entry struct { Revision string `json:"revision"` Summary string `json:"summary"` Availability string `json:"availability"` + Builtin bool `json:"builtin"` } func Entries() []Entry { @@ -26,18 +27,29 @@ func Entries() []Entry { Repository: "https://github.com/RuoJi6/ARTEX", Summary: "AI autonomous penetration testing platform (Go + Next.js + PostgreSQL) with CSAI LLM gateway reuse.", Availability: "plan_available", + Builtin: true, }, {ID: "static-web", Title: "Static Web Runtime Check", Repository: "https://github.com/nginx/docker-nginx-unprivileged", - Summary: "Unprivileged static WebUI for lifecycle verification.", Availability: "plan_available"}, + Summary: "Unprivileged static WebUI for lifecycle verification.", Availability: "plan_available", Builtin: true}, { ID: "librechat", Title: "LibreChat", Repository: "https://github.com/LibreChat-AI/LibreChat", Revision: "566e20b613389600a7975fd8f7c1bffbe54f06c8", Summary: "Self-hosted chat WebUI used for plugin platform interoperability verification.", Availability: "inspection_only", + Builtin: true, }, } } +func HasBuiltin(id string) bool { + for _, entry := range Entries() { + if entry.ID == id { + return true + } + } + return false +} + func Manifest(id string) ([]byte, bool) { switch id { case "artex": diff --git a/internal/pluginhub/catalog_store.go b/internal/pluginhub/catalog_store.go new file mode 100644 index 00000000..b493c524 --- /dev/null +++ b/internal/pluginhub/catalog_store.go @@ -0,0 +1,176 @@ +package pluginhub + +import ( + "context" + "database/sql" + "regexp" + "strings" + + "cyberstrike-ai/internal/database" + "cyberstrike-ai/internal/pluginhub/catalog" + "cyberstrike-ai/internal/pluginhub/manifest" + "cyberstrike-ai/internal/pluginhub/source" +) + +var catalogIDPattern = regexp.MustCompile(`^[a-z][a-z0-9-]{1,47}$`) + +type CatalogInput struct { + ID string `json:"id"` + Title string `json:"title"` + Repository string `json:"repository"` + Revision string `json:"revision"` + Summary string `json:"summary"` + Manifest string `json:"manifest"` // Optional YAML or JSON manifest for one-click install +} + +func (m *Manager) ListCatalog(ctx context.Context) ([]catalog.Entry, int, error) { + records, err := m.db.ListPluginCatalogRecords(ctx) + if err != nil { + return nil, 0, err + } + byID := make(map[string]database.PluginCatalogRecord, len(records)) + hiddenBuiltins := 0 + for _, r := range records { + byID[r.ID] = r + if r.Source == "builtin_hidden" && catalog.HasBuiltin(r.ID) { + hiddenBuiltins++ + } + } + result := make([]catalog.Entry, 0, len(catalog.Entries())+len(records)) + seen := map[string]bool{} + for _, entry := range catalog.Entries() { + seen[entry.ID] = true + if override, ok := byID[entry.ID]; ok { + if override.Source == "builtin_hidden" { + continue + } + avail := "inspection_only" + if strings.TrimSpace(override.ManifestJSON) != "" { + avail = "plan_available" + } + result = append(result, catalog.Entry{ + ID: override.ID, Title: override.Title, Repository: override.Repository, + Revision: override.Revision, Summary: override.Summary, Availability: avail, Builtin: false, + }) + continue + } + result = append(result, entry) + } + for _, r := range records { + if seen[r.ID] || r.Source != "custom" { + continue + } + avail := "inspection_only" + if strings.TrimSpace(r.ManifestJSON) != "" { + avail = "plan_available" + } + result = append(result, catalog.Entry{ + ID: r.ID, Title: r.Title, Repository: r.Repository, + Revision: r.Revision, Summary: r.Summary, Availability: avail, Builtin: false, + }) + } + return result, hiddenBuiltins, nil +} + +func (m *Manager) CatalogManifest(ctx context.Context, id string) ([]byte, bool) { + if r, err := m.db.GetPluginCatalogRecord(ctx, id); err == nil { + if r.Source == "builtin_hidden" { + return nil, false + } + if strings.TrimSpace(r.ManifestJSON) != "" { + return []byte(r.ManifestJSON), true + } + return nil, false + } + return catalog.Manifest(id) +} + +func (m *Manager) SaveCatalogEntry(ctx context.Context, input CatalogInput) (catalog.Entry, error) { + id := strings.TrimSpace(input.ID) + title := strings.TrimSpace(input.Title) + repoRaw := strings.TrimSpace(input.Repository) + rev := strings.TrimSpace(input.Revision) + summary := strings.TrimSpace(input.Summary) + manifestRaw := strings.TrimSpace(input.Manifest) + + var manifestCanonical string + var manifestRepo string + if manifestRaw != "" { + decl, err := manifest.DecodeDeclaration([]byte(manifestRaw)) + if err != nil { + return catalog.Entry{}, ErrInvalidManifest + } + manifestCanonical = string(decl.Canonical) + manifestRepo = decl.Metadata.Repository + if id == "" { + id = decl.Metadata.ID + } else if id != decl.Metadata.ID { + return catalog.Entry{}, ErrInvalidManifest + } + if title == "" { + title = decl.Metadata.Title + } + if repoRaw == "" { + repoRaw = decl.Metadata.Repository + } + if summary == "" { + summary = decl.Metadata.Summary + } + } + + if !catalogIDPattern.MatchString(id) || title == "" || len(title) > 100 || len(summary) > 500 { + return catalog.Entry{}, ErrInvalidRequest + } + repo, err := source.NormalizeGitHubRepository(repoRaw) + if err != nil { + return catalog.Entry{}, ErrSourceMismatch + } + if manifestRepo != "" { + if normManifestRepo, err := source.NormalizeGitHubRepository(manifestRepo); err == nil && normManifestRepo != repo { + return catalog.Entry{}, ErrSourceMismatch + } + } + if rev != "" && manifest.ValidateGitRef(rev) != nil { + return catalog.Entry{}, ErrInvalidRequest + } + if err := m.db.UpsertPluginCatalogRecord(ctx, database.PluginCatalogRecord{ + ID: id, Title: title, Repository: repo, Revision: rev, Summary: summary, + ManifestJSON: manifestCanonical, Source: "custom", + }); err != nil { + return catalog.Entry{}, err + } + avail := "inspection_only" + if manifestCanonical != "" { + avail = "plan_available" + } + return catalog.Entry{ + ID: id, Title: title, Repository: repo, Revision: rev, + Summary: summary, Availability: avail, Builtin: false, + }, nil +} + +func (m *Manager) DeleteCatalogEntry(ctx context.Context, id string) error { + id = strings.TrimSpace(id) + if !catalogIDPattern.MatchString(id) { + return ErrInvalidRequest + } + if catalog.HasBuiltin(id) { + // Hide built-in catalog entries via tombstone so they disappear from the market + // while remaining restorable if the operator chooses to restore defaults. + return m.db.UpsertPluginCatalogRecord(ctx, database.PluginCatalogRecord{ + ID: id, Title: id, Repository: "", Source: "builtin_hidden", + }) + } + deleted, err := m.db.DeletePluginCatalogRecord(ctx, id) + if err != nil { + return err + } + if !deleted { + return sql.ErrNoRows + } + return nil +} + +func (m *Manager) RestoreBuiltinCatalog(ctx context.Context) (int64, error) { + return m.db.RestoreHiddenBuiltinCatalog(ctx) +} diff --git a/internal/pluginhub/catalog_store_test.go b/internal/pluginhub/catalog_store_test.go new file mode 100644 index 00000000..24126563 --- /dev/null +++ b/internal/pluginhub/catalog_store_test.go @@ -0,0 +1,135 @@ +package pluginhub + +import ( + "context" + "database/sql" + "errors" + "os" + "path/filepath" + "strings" + "testing" + + "cyberstrike-ai/internal/config" + "cyberstrike-ai/internal/database" + + "go.uber.org/zap" +) + +func TestCatalogStoreCRUDAndRestore(t *testing.T) { + ctx := context.Background() + db, err := database.NewDB(filepath.Join(t.TempDir(), "catalog.db"), zap.NewNop()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Close() }) + + mgr, err := New(db, config.PluginsConfig{}, t.TempDir(), zap.NewNop()) + if err != nil { + t.Fatal(err) + } + + // Built-in entries present initially + initial, hidden, err := mgr.ListCatalog(ctx) + if err != nil { + t.Fatal(err) + } + if len(initial) < 3 || hidden != 0 { + t.Fatalf("expected >=3 built-ins and 0 hidden, got %d / %d", len(initial), hidden) + } + + // Add custom inspection-only entry + entry, err := mgr.SaveCatalogEntry(ctx, CatalogInput{ + ID: "my-scanner", + Title: "My Scanner", + Repository: "https://github.com/example/my-scanner.git", + Revision: "main", + Summary: "Custom security scanner", + }) + if err != nil { + t.Fatalf("save inspection-only entry: %v", err) + } + if entry.ID != "my-scanner" || entry.Repository != "https://github.com/example/my-scanner" || entry.Availability != "inspection_only" || entry.Builtin { + t.Fatalf("unexpected saved entry: %+v", entry) + } + + // Add custom entry with YAML manifest -> plan_available + raw, err := os.ReadFile("manifest/testdata/web-plugin.yaml") + if err != nil { + t.Fatal(err) + } + rawStr := strings.ReplaceAll(string(raw), "https://git.example.org/examples/log-review-demo.git", "https://github.com/example/log-review-demo") + withManifest, err := mgr.SaveCatalogEntry(ctx, CatalogInput{ + Manifest: rawStr, + }) + if err != nil { + t.Fatalf("save manifest entry: %v", err) + } + if withManifest.ID != "log-review" || withManifest.Availability != "plan_available" { + t.Fatalf("unexpected manifest entry: %+v", withManifest) + } + if rawManifest, ok := mgr.CatalogManifest(ctx, "log-review"); !ok || len(rawManifest) == 0 { + t.Fatalf("expected CatalogManifest to resolve custom manifest") + } + + // Mismatched repository vs manifest must fail + if _, err := mgr.SaveCatalogEntry(ctx, CatalogInput{ + Repository: "https://github.com/other/repo", + Manifest: rawStr, + }); !errors.Is(err, ErrSourceMismatch) { + t.Fatalf("expected ErrSourceMismatch, got %v", err) + } + + // Delete custom entry -> hard deleted + if err := mgr.DeleteCatalogEntry(ctx, "my-scanner"); err != nil { + t.Fatalf("delete custom entry: %v", err) + } + if err := mgr.DeleteCatalogEntry(ctx, "my-scanner"); !errors.Is(err, sql.ErrNoRows) { + t.Fatalf("expected sql.ErrNoRows on second delete, got %v", err) + } + + // Delete built-in entry -> hidden tombstone, hidden_builtins increments, manifest inaccessible + if err := mgr.DeleteCatalogEntry(ctx, "artex"); err != nil { + t.Fatalf("hide built-in entry: %v", err) + } + afterHide, hidden, err := mgr.ListCatalog(ctx) + if err != nil { + t.Fatal(err) + } + if hidden != 1 { + t.Fatalf("expected hidden_builtins=1, got %d", hidden) + } + for _, item := range afterHide { + if item.ID == "artex" { + t.Fatalf("expected artex to be hidden") + } + } + if _, ok := mgr.CatalogManifest(ctx, "artex"); ok { + t.Fatalf("expected hidden built-in manifest to be unavailable") + } + + // Restore hidden built-ins + restored, err := mgr.RestoreBuiltinCatalog(ctx) + if err != nil { + t.Fatal(err) + } + if restored != 1 { + t.Fatalf("expected 1 restored, got %d", restored) + } + afterRestore, hidden, err := mgr.ListCatalog(ctx) + if err != nil { + t.Fatal(err) + } + if hidden != 0 { + t.Fatalf("expected hidden_builtins=0 after restore, got %d", hidden) + } + foundArtex := false + for _, item := range afterRestore { + if item.ID == "artex" { + foundArtex = true + break + } + } + if !foundArtex { + t.Fatalf("expected artex to reappear after restore") + } +} diff --git a/internal/pluginhub/planning.go b/internal/pluginhub/planning.go index c9c81e7d..c0b4935f 100644 --- a/internal/pluginhub/planning.go +++ b/internal/pluginhub/planning.go @@ -13,7 +13,6 @@ import ( "cyberstrike-ai/internal/config" "cyberstrike-ai/internal/database" - "cyberstrike-ai/internal/pluginhub/catalog" "cyberstrike-ai/internal/pluginhub/manifest" "cyberstrike-ai/internal/pluginhub/source" @@ -73,7 +72,7 @@ func (m *Manager) CreatePlan(ctx context.Context, request PlanRequest) (PlanResu if len(request.Manifest) != 0 { return PlanResult{}, ErrInvalidRequest } - data, ok := catalog.Manifest(request.CatalogID) + data, ok := m.CatalogManifest(ctx, request.CatalogID) if !ok { return PlanResult{}, ErrCatalogManifest } diff --git a/internal/security/rbac_middleware.go b/internal/security/rbac_middleware.go index 07221ad6..61471e36 100644 --- a/internal/security/rbac_middleware.go +++ b/internal/security/rbac_middleware.go @@ -222,7 +222,11 @@ func pluginPermission(method, path string) string { switch path { case "/plugins/installs/:id/embed-sessions": return "plugins:use" - case "/plugins/imports/inspect", "/plugins/install-plans", "/plugins/installs", "/plugins/installs/:id/operations": + case "/plugins/catalog", "/plugins/catalog/restore", "/plugins/imports/inspect", "/plugins/install-plans", "/plugins/installs", "/plugins/installs/:id/operations": + return "plugins:manage" + } + case http.MethodDelete: + if path == "/plugins/catalog/:id" { return "plugins:manage" } case http.MethodPatch: diff --git a/web/frontend/src/pages/plugin-hub/Drawers.jsx b/web/frontend/src/pages/plugin-hub/Drawers.jsx index ab8c1156..074af32e 100644 --- a/web/frontend/src/pages/plugin-hub/Drawers.jsx +++ b/web/frontend/src/pages/plugin-hub/Drawers.jsx @@ -165,7 +165,184 @@ export function PlanApprovalDrawer({ planResponse, channels, visible, onCancel, ); } -export function ImportGitDrawer({ visible, onCancel, onPlanReady }) { +export function AddCatalogDrawer({ visible, onCancel, onSaved }) { + const t = useT(); + const [repository, setRepository] = useState(''); + const [revision, setRevision] = useState(''); + const [id, setId] = useState(''); + const [title, setTitle] = useState(''); + const [summary, setSummary] = useState(''); + const [manifestText, setManifestText] = useState(''); + const [inspecting, setInspecting] = useState(false); + const [saving, setSaving] = useState(false); + + useEffect(() => { + if (visible) { + setRepository(''); + setRevision(''); + setId(''); + setTitle(''); + setSummary(''); + setManifestText(''); + } + }, [visible]); + + const inferFromRepo = repoValue => { + const cleaned = String(repoValue || '').trim().replace(/\.git$/i, '').replace(/\/+$/, ''); + const seg = cleaned.split('/').pop() || ''; + const slug = seg.toLowerCase().replace(/[^a-z0-9-]+/g, '-').replace(/^-+|-+$/g, ''); + return { seg, slug }; + }; + + const handleRepoChange = value => { + setRepository(value); + const { seg, slug } = inferFromRepo(value); + if (!id && slug && /^[a-z]/.test(slug)) setId(slug); + if (!title && seg) setTitle(seg); + }; + + const handleProbe = async () => { + if (!repository.trim()) return; + setInspecting(true); + try { + const res = await pluginApi.inspectGit(repository, revision); + const info = res?.inspection; + if (info?.repository) setRepository(info.repository); + if (info?.manifest) { + const m = info.manifest; + if (m.metadata?.id) setId(m.metadata.id); + if (m.metadata?.title) setTitle(m.metadata.title); + if (m.metadata?.summary) setSummary(m.metadata.summary); + setManifestText(JSON.stringify(m, null, 2)); + toastSuccess(t('pluginHub.catalogProbeWithManifest', null, '已探测到仓库自带 Manifest,保存后支持一键安装')); + } else { + const { seg, slug } = inferFromRepo(info?.repository || repository); + if (!id && slug && /^[a-z]/.test(slug)) setId(slug); + if (!title && seg) setTitle(seg); + toastSuccess(t('pluginHub.catalogProbeSuccess', null, '仓库只读探测完成,已自动填充基础信息')); + } + } catch (err) { + toastError(pluginErrorText(t, err, t('pluginHub.inspectFailed', null, '探测仓库失败'))); + } finally { + setInspecting(false); + } + }; + + const handleSave = async () => { + if (!repository.trim() && !manifestText.trim()) { + toastError(t('pluginHub.catalogRepoRequired', null, '请填写 GitHub 仓库地址或提供 Manifest')); + return; + } + setSaving(true); + try { + const res = await pluginApi.saveCatalog({ + id: id.trim(), + title: title.trim(), + repository: repository.trim(), + revision: revision.trim(), + summary: summary.trim(), + manifest: manifestText.trim() + }); + toastSuccess(t('pluginHub.catalogSaved', null, '已保存到能力市场')); + onSaved?.(res?.item); + } catch (err) { + toastError(pluginErrorText(t, err, t('pluginHub.catalogSaveFailed', null, '保存到能力市场失败'))); + } finally { + setSaving(false); + } + }; + + return ( + + + + + } + > +
+ + {t('pluginHub.addCatalogDesc', null, '将公开 GitHub 仓库收录到本机能力市场。留空 Manifest 将以「支持探测导入」模式展示;提供合法 YAML/JSON Manifest 后将直接支持「一键下载安装」。')} + + +
+ {t('pluginHub.repositoryURL', null, 'GitHub 仓库地址')} + +
+
+ {t('pluginHub.revisionOptional', null, '分支 / Tag(可选)')} + +
+ +
+ + +
+ {t('pluginHub.pluginId', null, '插件标识 ID')} + +
+
+ {t('pluginHub.pluginTitle', null, '显示名称')} + +
+
+ +
+ {t('pluginHub.catalogSummaryLabel', null, '功能简介')} + +
+ +
+ {t('pluginHub.catalogManifestOptional', null, '插件 Manifest(可选,支持 YAML 或 JSON)')} +