diff --git a/docs/plugin-architecture.md b/docs/plugin-architecture.md index 9f6c31c..ac988f8 100644 --- a/docs/plugin-architecture.md +++ b/docs/plugin-architecture.md @@ -378,8 +378,8 @@ UI 槽位采用「声明即占有」:宿主预定义 `vm.toolbar`、`vm.card` - **安装来源**:本地包导入(首批)、市场索引(后续)、开发者模式本地目录链接。 - **随主程序附带的插件**:需要时可以标准插件包形式嵌入 `reims-go.exe`,信任等级为 `official`,版本跟随主程序;可启用/停用,不可卸载。 -- **事务安装**:下载到 `tmp` → 校验 `SHA256SUMS` 与签名 → 核对包内 `id` / `version` 与预期一致(防偷换)→ 兼容预检 → 原子 rename 到 `pkgs//` → 提交 `state.json`。任一步失败都不改变现状。 -- **市场索引**:独立仓库发布静态 `index.json`(GitHub Releases,复用运行时下载的代理逻辑),含版本、`engines`、下载地址、SHA-256 与签名者;主程序内嵌兜底副本。 +- **事务安装与静态准入门禁**:下载到 `tmp` → 校验 `SHA256SUMS` 与签名 → 核对包内 `id` / `version` 与预期一致(防偷换)→ 兼容预检 → 静态安全门禁(拦截 L1/L4 夹带可执行/系统脚本、L3 未声明二进制、SVG 主动脚本、`ui:script` 宿主逃逸或未声明联网、市场红线)→ 原子 rename 到 `pkgs//` → 提交 `state.json`。任一步失败都不改变现状。对 L3 原生程序不声称“代码扫描安全”,仅核对清单完整性与 SHA-256 并向用户如实展示完整当前 Windows 账户权限说明。 +- **市场索引与软撤回**:独立仓库发布轻量静态 `index.json`(二进制包托管在 GitHub Releases,复用运行时下载与代理逻辑;可通过 `REIMS_GO_PLUGIN_MARKET_URL` 配置镜像或 `off` 强制离线),含版本、`engines`、`platforms`、下载地址、SHA-256、签名者与软撤回列表(`withdrawn`,阻止新装并对存量用户展示替代建议);首次打开市场或执行市场 CLI 命令时惰性拉取,使用内存 + `/plugins/index-cache.json` 双层缓存与主程序内嵌兜底副本,网络失败不覆写有效缓存。 - **更新与回滚**:新旧版本并存、切换指针,保留最近若干版本;插件同样区分 `alpha` / `stable` 通道,默认只取 `stable`。 - **安全模式**:`reims-go --safe-mode` 跳过全部第三方插件,界面顶部显示横幅与插件管理入口;以启动哨兵文件检测上次插件初始化阶段异常退出,下次启动询问是否进入安全模式。 - **市场红线**:拒收含 Apple 专有文件、SMBIOS 真值或闭源固件的包;运行时包必须附源码与许可证。 @@ -390,8 +390,8 @@ UI 槽位采用「声明即占有」:宿主预定义 `vm.toolbar`、`vm.card` | 入口 | 内容 | | :--- | :--- | -| CLI | `reims-go plugin list / install / link / enable [--approve-high-risk] / disable / remove [--purge] / info / doctor / locale / run `;`vm create --driver ` | -| 应用设置 → 插件 | 分组展示内置插件与第三方插件:核心置顶、显示「始终启用」且无开关;其余显示来源与信任标签、权限摘要、启用开关、故障状态与日志入口;本地包导入 | +| CLI | `reims-go plugin list / search / install / update [id] / link / enable [--approve-high-risk] / disable / remove [--purge] / info / doctor [--json] [dir\|zip\|id] / locale / run `;`vm create --driver ` | +| 应用设置 → 插件 | 提供「已安装 / 插件市场」双视图(市场索引惰性加载):核心置顶、显示「始终启用」且无开关;其余显示来源与信任标签、权限摘要、安全扫描报告入口、启用开关、故障状态与日志入口;本地包导入前先展示三段式静态安全报告并执行硬门禁拦截 | | 插件设置页 | 由 `settings` Schema 渲染,复用现有设置控件,标注生效时机 | | VM 页面 | 按能力位显隐操作;`vm.toolbar` 菜单项支持 `when` 条件;`vm.card` 展示驱动或插件提供的键值信息 | | 创建向导 | 先选驱动,再按驱动 `CreateSchema` 渲染专属表单 | diff --git a/internal/app/plugins_flow.go b/internal/app/plugins_flow.go index f044b64..ac4f284 100644 --- a/internal/app/plugins_flow.go +++ b/internal/app/plugins_flow.go @@ -202,6 +202,7 @@ func (a *App) shutdownPlugins() { a.mu.Lock() mgr := a.pluginMgr a.pluginMgr = nil + a.pluginMarket = nil a.mu.Unlock() i18n.SetPluginCatalogs(nil) if mgr != nil { @@ -209,6 +210,23 @@ func (a *App) shutdownPlugins() { } } +func (a *App) getPluginMarket() *plugin.MarketClient { + a.mu.Lock() + defer a.mu.Unlock() + if a.pluginMarket != nil { + return a.pluginMarket + } + dataRoot := "" + if a.cfg != nil { + dataRoot = a.cfg.DataRoot + } + a.pluginMarket = plugin.NewMarketClient(plugin.MarketClientOptions{ + Layout: plugin.NewPluginsLayout(dataRoot), + HostVersion: version.Version, + }) + return a.pluginMarket +} + // reloadPlugins tears down the existing Plugin Manager (if running) and // re-initializes plugins and language packs against the current a.cfg.DataRoot. func (a *App) reloadPlugins() { @@ -826,6 +844,96 @@ func (a *App) DoctorPlugin(pluginID string) []plugin.DoctorFinding { return plugin.DoctorDirectory(info.InstallDir, version.Version, nil) } +// InspectPluginArchive runs the unified static security scanner on a local .zip +// package before installing it so the UI can display hard blockers, capabilities, +// and L3 native execution notices. +func (a *App) InspectPluginArchive(archivePath string) (plugin.ScanReport, error) { + a.mu.Lock() + mgr := a.pluginMgr + dataRoot := "" + if a.cfg != nil { + dataRoot = a.cfg.DataRoot + } + a.mu.Unlock() + tmpDir := plugin.NewPluginsLayout(dataRoot).TmpDir() + if mgr != nil { + tmpDir = mgr.Layout().TmpDir() + } + return plugin.ScanArchive(archivePath, tmpDir, version.Version, plugin.ScanOptions{}) +} + +// ScanInstalledPlugin runs the unified static risk report against an installed +// or dev-linked plugin directory. +func (a *App) ScanInstalledPlugin(pluginID string) (plugin.ScanReport, error) { + a.mu.Lock() + mgr := a.pluginMgr + a.mu.Unlock() + if mgr == nil { + return plugin.ScanReport{}, errors.New("plugin manager not initialized") + } + info, ok := mgr.Registry().Info(pluginID) + if !ok { + return plugin.ScanReport{}, fmt.Errorf("plugin %q not found", pluginID) + } + if info.InstallDir == "" { + return plugin.ScanReport{ + PluginID: info.ID, + Version: info.Version, + Name: info.Name, + Tier: info.Tier, + Trust: info.Trust, + Publisher: info.Publisher, + License: info.License, + Passed: true, + Headline: plugin.LocalizedText{ + ZhCN: "内置插件状态正常", + EnUS: "Built-in plugin is healthy", + }, + }, nil + } + rep := plugin.ScanDirectory(info.InstallDir, version.Version, plugin.ScanOptions{}) + if info.Trust == plugin.TrustDev { + rep.Trust = plugin.TrustDev + } + return rep, nil +} + +// BrowsePluginMarket lazily queries the remote/cached/fallback plugin market +// index (never called at app startup, §8.1, §9). +func (a *App) BrowsePluginMarket(query, kind string, includeAlpha, forceRefresh bool) plugin.MarketBrowseResult { + a.mu.Lock() + mgr := a.pluginMgr + a.mu.Unlock() + var installed []plugin.PluginInfo + if mgr != nil { + installed = mgr.Registry().List() + } + return a.getPluginMarket().Browse(context.Background(), installed, plugin.MarketBrowseOptions{ + Query: query, + Kind: kind, + IncludeAlpha: includeAlpha, + ForceRefresh: forceRefresh, + }) +} + +// InstallMarketPlugin downloads, verifies SHA-256, static-scans, and installs +// a plugin from the market index. +func (a *App) InstallMarketPlugin(pluginID string, includeAlpha bool) (*plugin.PluginInfo, error) { + a.mu.Lock() + mgr := a.pluginMgr + a.mu.Unlock() + if mgr == nil { + return nil, errors.New("plugin manager not initialized") + } + info, err := a.getPluginMarket().InstallFromMarket(context.Background(), mgr, pluginID, plugin.MarketInstallOptions{ + IncludeAlpha: includeAlpha, + }) + if err == nil && a.ctx != nil { + wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) + } + return info, err +} + // PanelBridgeCall handles permission-checked, rate-limited, redacted Host API // reads from sandboxed L4 iframe panels (§7.3). func (a *App) PanelBridgeCall(pluginID, method string, params map[string]any) (any, error) { diff --git a/internal/cli/plugin.go b/internal/cli/plugin.go index ed10053..a3395e8 100644 --- a/internal/cli/plugin.go +++ b/internal/cli/plugin.go @@ -74,12 +74,84 @@ func openCLIPluginManager(cfg *config.Config, safeMode bool) (*plugin.Manager, * return mgr, router, nil } +func openCLIMarketClient(cfg *config.Config) *plugin.MarketClient { + return plugin.NewMarketClient(plugin.MarketClientOptions{ + Layout: plugin.NewPluginsLayout(cfg.DataRoot), + HostVersion: version.Version, + }) +} + func cmdPlugin(cfg *config.Config, loc i18n.Locale, args []string) error { if len(args) == 0 { - return fmt.Errorf("usage: reims-go plugin ") + return fmt.Errorf("usage: reims-go plugin ") } ctx := context.Background() switch args[0] { + case "search": + fs := flag.NewFlagSet("plugin search", flag.ContinueOnError) + kind := fs.String("kind", "", "Filter by plugin kind (theme, locale, driver, tool, template, runtime)") + includeAlpha := fs.Bool("alpha", false, "Include alpha channel plugins") + refresh := fs.Bool("refresh", false, "Bypass cache and refresh market index") + asJSON := fs.Bool("json", false, "Output JSON") + if err := fs.Parse(args[1:]); err != nil { + return err + } + mgr, _, err := openCLIPluginManager(cfg, true) + if err != nil { + return err + } + defer mgr.Close() + mc := openCLIMarketClient(cfg) + query := strings.TrimSpace(strings.Join(fs.Args(), " ")) + res := mc.Browse(ctx, mgr.Registry().List(), plugin.MarketBrowseOptions{ + Query: query, + Kind: *kind, + IncludeAlpha: *includeAlpha, + ForceRefresh: *refresh, + }) + if *asJSON { + enc := json.NewEncoder(os.Stdout) + enc.SetIndent("", " ") + return enc.Encode(res) + } + if res.Stale && res.FetchError != "" { + fmt.Fprintf(os.Stderr, "[warn] %s (%s)\n", i18n.T(loc, "plugin.market.stale_warn"), res.FetchError) + } + for _, w := range res.WithdrawnInstalled { + fmt.Fprintf(os.Stderr, "[warn] %s: %s", w.ID, w.Reason.Get(string(loc))) + if w.InsteadID != "" { + fmt.Fprintf(os.Stderr, " -> %s", w.InsteadID) + } + fmt.Fprintln(os.Stderr) + } + if len(res.Items) == 0 { + fmt.Println(i18n.T(loc, "plugin.market.empty")) + return nil + } + for _, it := range res.Items { + status := it.Entry.Channel + switch { + case it.Withdrawn != nil: + status = "withdrawn" + case !it.Compatible: + status = "incompat" + case it.UpdateAvailable: + status = "update:" + it.InstalledVersion + "->" + it.Entry.Version + case it.Installed: + status = "installed" + } + kindLabel := it.Entry.Kind + if kindLabel == "" { + kindLabel = string(it.Entry.Tier) + } + if kindLabel == "" { + kindLabel = "-" + } + fmt.Printf("%-34s %-10s %-8s %-9s %-18s %s\n", + it.Entry.ID, it.Entry.Version, kindLabel, it.Entry.Trust, status, it.Entry.Name.Get(string(loc))) + } + return nil + case "list": fs := flag.NewFlagSet("plugin list", flag.ContinueOnError) asJSON := fs.Bool("json", false, "Output JSON") @@ -111,15 +183,39 @@ func cmdPlugin(cfg *config.Config, loc i18n.Locale, args []string) error { return nil case "install": - if len(args) < 2 { - return fmt.Errorf("usage: reims-go plugin install ") + fs := flag.NewFlagSet("plugin install", flag.ContinueOnError) + includeAlpha := fs.Bool("alpha", false, "Allow alpha channel when installing by market plugin ID") + refresh := fs.Bool("refresh", false, "Refresh market index before installing") + if err := fs.Parse(args[1:]); err != nil { + return err } + if fs.NArg() < 1 { + return fmt.Errorf("usage: reims-go plugin install [--alpha] [--refresh] ") + } + target := fs.Arg(0) mgr, _, err := openCLIPluginManager(cfg, false) if err != nil { return err } defer mgr.Close() - info, err := mgr.InstallLocalArchive(ctx, args[1], plugin.PackageInstallOptions{}) + + isLocalFile := false + if st, statErr := os.Stat(target); statErr == nil && !st.IsDir() { + isLocalFile = true + } else if strings.HasSuffix(strings.ToLower(target), ".zip") || strings.ContainsAny(target, `/\`) { + isLocalFile = true + } + + var info *plugin.PluginInfo + if isLocalFile { + info, err = mgr.InstallLocalArchive(ctx, target, plugin.PackageInstallOptions{}) + } else { + mc := openCLIMarketClient(cfg) + info, err = mc.InstallFromMarket(ctx, mgr, target, plugin.MarketInstallOptions{ + IncludeAlpha: *includeAlpha, + ForceRefresh: *refresh, + }) + } if err != nil { return err } @@ -129,6 +225,60 @@ func cmdPlugin(cfg *config.Config, loc i18n.Locale, args []string) error { } return nil + case "update": + fs := flag.NewFlagSet("plugin update", flag.ContinueOnError) + includeAlpha := fs.Bool("alpha", false, "Allow alpha channel updates") + refresh := fs.Bool("refresh", true, "Refresh market index before checking updates") + if err := fs.Parse(args[1:]); err != nil { + return err + } + mgr, _, err := openCLIPluginManager(cfg, false) + if err != nil { + return err + } + defer mgr.Close() + mc := openCLIMarketClient(cfg) + if fs.NArg() > 0 { + id := fs.Arg(0) + if _, ok := mgr.Registry().Info(id); !ok { + return fmt.Errorf("%s", i18n.T(loc, "plugin.not_found", id)) + } + info, uErr := mc.InstallFromMarket(ctx, mgr, id, plugin.MarketInstallOptions{ + IncludeAlpha: *includeAlpha, + ForceRefresh: *refresh, + }) + if uErr != nil { + return uErr + } + fmt.Println(i18n.T(loc, "plugin.installed", info.ID, info.Version, info.Trust, info.Tier)) + if info.NeedsApproval { + fmt.Println(i18n.T(loc, "plugin.needs_approval", info.ID)) + } + return nil + } + updates, browse := mc.CheckUpdates(ctx, mgr.Registry().List(), *includeAlpha, *refresh) + if browse.Stale && browse.FetchError != "" { + fmt.Fprintf(os.Stderr, "[warn] %s (%s)\n", i18n.T(loc, "plugin.market.stale_warn"), browse.FetchError) + } + if len(updates) == 0 { + fmt.Println(i18n.T(loc, "plugin.market.up_to_date")) + return nil + } + for _, up := range updates { + info, uErr := mc.InstallFromMarket(ctx, mgr, up.Entry.ID, plugin.MarketInstallOptions{ + IncludeAlpha: *includeAlpha, + ForceRefresh: false, + }) + if uErr != nil { + return fmt.Errorf("update %s: %w", up.Entry.ID, uErr) + } + fmt.Println(i18n.T(loc, "plugin.installed", info.ID, info.Version, info.Trust, info.Tier)) + if info.NeedsApproval { + fmt.Println(i18n.T(loc, "plugin.needs_approval", info.ID)) + } + } + return nil + case "link": if len(args) < 2 { return fmt.Errorf("usage: reims-go plugin link ") @@ -221,6 +371,7 @@ func cmdPlugin(cfg *config.Config, loc i18n.Locale, args []string) error { case "doctor": fs := flag.NewFlagSet("plugin doctor", flag.ContinueOnError) contractPath := fs.String("contract", "", "Optional path to ui-contract.json for CSS validation") + asJSON := fs.Bool("json", false, "Output structured ScanReport JSON") if err := fs.Parse(args[1:]); err != nil { return err } @@ -236,15 +387,26 @@ func cmdPlugin(cfg *config.Config, loc i18n.Locale, args []string) error { } contract = &c } + scanOpts := plugin.ScanOptions{Contract: contract} target := "" if fs.NArg() > 0 { target = fs.Arg(0) } - // If target is an existing directory, validate it directly (developer workflow, §5.1). + // Direct directory or .zip archive inspection (developer & market CI workflow, §5.1). if target != "" { - if st, err := os.Stat(target); err == nil && st.IsDir() { - findings := plugin.DoctorDirectory(target, version.Version, contract) - return printDoctorFindings(loc, findings) + if st, err := os.Stat(target); err == nil { + if st.IsDir() { + rep := plugin.ScanDirectory(target, version.Version, scanOpts) + return printScanReports(loc, []plugin.ScanReport{rep}, *asJSON) + } + if strings.HasSuffix(strings.ToLower(target), ".zip") { + layout := plugin.NewPluginsLayout(cfg.DataRoot) + rep, sErr := plugin.ScanArchive(target, layout.TmpDir(), version.Version, scanOpts) + if sErr != nil { + return sErr + } + return printScanReports(loc, []plugin.ScanReport{rep}, *asJSON) + } } } mgr, _, err := openCLIPluginManager(cfg, false) @@ -258,25 +420,46 @@ func cmdPlugin(cfg *config.Config, loc i18n.Locale, args []string) error { return fmt.Errorf("%s", i18n.T(loc, "plugin.target_not_found", target)) } if info.InstallDir == "" { + if *asJSON { + enc := json.NewEncoder(os.Stdout) + enc.SetIndent("", " ") + return enc.Encode(plugin.ScanReport{ + PluginID: info.ID, + Version: info.Version, + Name: info.Name, + Tier: info.Tier, + Trust: info.Trust, + Passed: true, + Headline: plugin.LocalizedText{ + ZhCN: "内置插件状态正常", + EnUS: "Built-in plugin is healthy", + }, + }) + } fmt.Printf("[ok] %s@%s (%s, state=%s)\n", info.ID, info.Version, info.Source, info.State) return nil } - return printDoctorFindings(loc, plugin.DoctorDirectory(info.InstallDir, version.Version, contract)) + rep := plugin.ScanDirectory(info.InstallDir, version.Version, scanOpts) + return printScanReports(loc, []plugin.ScanReport{rep}, *asJSON) } // Audit all installed external plugins. - var allFindings []plugin.DoctorFinding + var reports []plugin.ScanReport for _, info := range mgr.Registry().List() { if info.InstallDir != "" { - allFindings = append(allFindings, plugin.DoctorDirectory(info.InstallDir, version.Version, contract)...) - } else { - allFindings = append(allFindings, plugin.DoctorFinding{ - Severity: "ok", - Check: info.ID, - Message: fmt.Sprintf("%s@%s state=%s", info.ID, info.Version, info.State), - }) + reports = append(reports, plugin.ScanDirectory(info.InstallDir, version.Version, scanOpts)) } } - return printDoctorFindings(loc, allFindings) + if len(reports) == 0 { + if *asJSON { + fmt.Println("[]") + return nil + } + for _, info := range mgr.Registry().List() { + fmt.Printf("[ok] %s@%s (%s, state=%s)\n", info.ID, info.Version, info.Source, info.State) + } + return nil + } + return printScanReports(loc, reports, *asJSON) case "locale": return cmdPluginLocale(loc, args[1:]) @@ -311,6 +494,42 @@ func cmdPlugin(cfg *config.Config, loc i18n.Locale, args []string) error { } } +func printScanReports(loc i18n.Locale, reports []plugin.ScanReport, asJSON bool) error { + hasErr := false + for _, r := range reports { + if r.HardBlocked { + hasErr = true + } + } + if asJSON { + enc := json.NewEncoder(os.Stdout) + enc.SetIndent("", " ") + if len(reports) == 1 { + if err := enc.Encode(reports[0]); err != nil { + return err + } + } else { + if err := enc.Encode(reports); err != nil { + return err + } + } + if hasErr { + return fmt.Errorf("%s", i18n.T(loc, "plugin.doctor.errors")) + } + return nil + } + for i, r := range reports { + if i > 0 { + fmt.Println("---") + } + fmt.Println(r.SummaryText(string(loc))) + } + if hasErr { + return fmt.Errorf("%s", i18n.T(loc, "plugin.doctor.errors")) + } + return nil +} + func printDoctorFindings(loc i18n.Locale, findings []plugin.DoctorFinding) error { hasErr := false for _, f := range findings { diff --git a/internal/i18n/catalog_gen.go b/internal/i18n/catalog_gen.go index 41d2c25..72d8306 100644 --- a/internal/i18n/catalog_gen.go +++ b/internal/i18n/catalog_gen.go @@ -33,7 +33,7 @@ var catalog = map[Locale]map[string]string{ "cli.usage.cmd_inst_del": " installer delete <文件名> 删除已下载的安装包(正在使用或下载中的会被拒绝)", "cli.usage.cmd_inst_dl": " installer download <版本> 下载离线安装包(如 26.7.1、tahoe、latest;Ctrl+C 暂停,再次运行续传)", "cli.usage.cmd_inst_list": " installer list 列出 Apple 提供的离线安装包版本(需联网)", - "cli.usage.cmd_plugin": " plugin list|install|link|enable|disable|remove|info|doctor|locale|run\n 管理内置扩展、语言包与第三方插件", + "cli.usage.cmd_plugin": " plugin list|search|install|update|link|enable|disable|remove|info|doctor|locale|run\n 管理内置扩展、语言包、插件市场与静态安全检查", "cli.usage.cmd_rt_avail": " runtime available 列出 GitHub 上发布的运行时(--alpha 含 alpha 版)", "cli.usage.cmd_rt_fetch": " runtime fetch [commit] 在线下载、校验并安装运行时(默认最新;Ctrl+C 暂停,再次运行续传)", "cli.usage.cmd_rt_install": " runtime install 导入并校验本地运行时包(.tar.zst 或 .zip)", @@ -343,6 +343,9 @@ var catalog = map[Locale]map[string]string{ "plugin.enabled": "已启用 {id}", "plugin.installed": "已安装插件 {id}@{ver}(trust={trust},tier={tier})", "plugin.linked": "已链接本地开发插件 {id}@{ver} -> {dir}", + "plugin.market.empty": "当前插件市场暂无匹配插件", + "plugin.market.stale_warn": "远程插件市场索引暂不可达,已回退至本地缓存/内置索引", + "plugin.market.up_to_date": "所有已安装插件均已是最新版本", "plugin.needs_approval": "提示:此插件包含高危权限,启用前请运行:reims-go plugin enable --approve-high-risk {id}", "plugin.not_found": "未找到插件 \"{id}\"", "plugin.removed": "已卸载 {id}(purge={purge})", @@ -526,7 +529,7 @@ var catalog = map[Locale]map[string]string{ "cli.usage.cmd_inst_del": " installer delete Delete a downloaded installer (refused if in use or downloading)", "cli.usage.cmd_inst_dl": " installer download Download an offline installer (26.7.1, tahoe, latest; Ctrl+C pauses, rerun resumes)", "cli.usage.cmd_inst_list": " installer list List offline macOS installers Apple offers (needs network)", - "cli.usage.cmd_plugin": " plugin list|install|link|enable|disable|remove|info|doctor|locale|run\n Manage built-in extensions, language packs and third-party plugins", + "cli.usage.cmd_plugin": " plugin list|search|install|update|link|enable|disable|remove|info|doctor|locale|run\n Manage built-in extensions, language packs, plugin market and security checks", "cli.usage.cmd_rt_avail": " runtime available List runtimes published on GitHub (--alpha includes alpha builds)", "cli.usage.cmd_rt_fetch": " runtime fetch [commit] Download, verify and install a runtime (newest by default; Ctrl+C pauses)", "cli.usage.cmd_rt_install": " runtime install Verify and install a local runtime package (.tar.zst or .zip)", @@ -836,6 +839,9 @@ var catalog = map[Locale]map[string]string{ "plugin.enabled": "Enabled {id}", "plugin.installed": "Installed {id}@{ver} (trust={trust}, tier={tier})", "plugin.linked": "Linked dev plugin {id}@{ver} -> {dir}", + "plugin.market.empty": "No matching plugins found in the market index", + "plugin.market.stale_warn": "Remote plugin market unreachable; falling back to cached or embedded index", + "plugin.market.up_to_date": "All installed plugins are up to date", "plugin.needs_approval": "Note: plugin requires high-risk permission approval; run: reims-go plugin enable --approve-high-risk {id}", "plugin.not_found": "plugin \"{id}\" not found", "plugin.removed": "Removed {id} (purge={purge})", diff --git a/internal/plugin/manager.go b/internal/plugin/manager.go index 860e4de..5bb83ba 100644 --- a/internal/plugin/manager.go +++ b/internal/plugin/manager.go @@ -450,6 +450,15 @@ func (m *Manager) buildSidecarActivator(man Manifest, exePath string, blockingAl // InstallLocalArchive transactionally installs a local .zip plugin package and // records it in state.json (disabled by default until user enables/approves it). func (m *Manager) InstallLocalArchive(ctx context.Context, archivePath string, opts PackageInstallOptions) (*PluginInfo, error) { + return m.InstallArchiveWithSource(ctx, archivePath, SourceLocal, opts) +} + +// InstallArchiveWithSource transactionally installs a .zip plugin package and +// records its origin source (SourceLocal or SourceMarket) in state.json. +func (m *Manager) InstallArchiveWithSource(ctx context.Context, archivePath string, source SourceKind, opts PackageInstallOptions) (*PluginInfo, error) { + if source == "" { + source = SourceLocal + } if opts.HostVersion == "" { opts.HostVersion = m.opts.HostVersion } @@ -472,7 +481,7 @@ func (m *Manager) InstallLocalArchive(ctx context.Context, archivePath string, o if rec == nil { rec = &PluginRecord{ ID: installed.Manifest.ID, - Source: SourceLocal, + Source: source, Enabled: false, } m.state.Plugins[installed.Manifest.ID] = rec @@ -489,7 +498,7 @@ func (m *Manager) InstallLocalArchive(ctx context.Context, archivePath string, o rec.InstalledVersions = append(rec.InstalledVersions, installed.Manifest.Version) } rec.Version = installed.Manifest.Version - rec.Source = SourceLocal + rec.Source = source rec.Trust = installed.Trust rec.UpdatedAt = time.Now() diff --git a/internal/plugin/manager_sidecar_test.go b/internal/plugin/manager_sidecar_test.go index a00dea2..345c8d6 100644 --- a/internal/plugin/manager_sidecar_test.go +++ b/internal/plugin/manager_sidecar_test.go @@ -183,11 +183,11 @@ func TestTransactionalInstallSigningRedlinesAndThemeDoctor(t *testing.T) { }, }) validCSS := []byte(`.rg-p-sidebar { background: var(--surface-sidebar); }`) - svgWithScript := []byte(``) + cleanSVG := []byte(``) goodZip := makePluginZip(t, map[string][]byte{ "plugin.json": manifestJSON, "theme.css": validCSS, - "mascot.svg": svgWithScript, + "mascot.svg": cleanSVG, }, priv, false) info, err := mgr.InstallLocalArchive(context.Background(), goodZip, plugin.PackageInstallOptions{}) @@ -216,19 +216,6 @@ func TestTransactionalInstallSigningRedlinesAndThemeDoctor(t *testing.T) { t.Fatalf("wrong token status = %d, want 403", recBadTok.Code) } - reqSVG := httptest.NewRequest(http.MethodGet, mgr.Assets().AssetURL("test.theme.aurora", "mascot.svg"), nil) - recSVG := httptest.NewRecorder() - mgr.Assets().ServeHTTP(recSVG, reqSVG) - if recSVG.Code != http.StatusOK { - t.Fatalf("SVG fetch status = %d, want 200", recSVG.Code) - } - if strings.Contains(recSVG.Body.String(), "`) + if err := os.WriteFile(filepath.Join(info.InstallDir, "mascot.svg"), svgWithScript, 0o644); err != nil { + t.Fatalf("write tampered svg: %v", err) + } + reqSVG := httptest.NewRequest(http.MethodGet, mgr.Assets().AssetURL("test.theme.aurora", "mascot.svg"), nil) + recSVG := httptest.NewRecorder() + mgr.Assets().ServeHTTP(recSVG, reqSVG) + if recSVG.Code != http.StatusOK { + t.Fatalf("SVG fetch status = %d, want 200", recSVG.Code) + } + if strings.Contains(recSVG.Body.String(), " rb + } + return a.Entry.ID < b.Entry.ID + }) + return res +} + +// CheckUpdates returns installed plugins that have a compatible, non-withdrawn +// newer version available in the market. +func (c *MarketClient) CheckUpdates(ctx context.Context, installed []PluginInfo, includeAlpha, forceRefresh bool) ([]MarketCatalogItem, MarketBrowseResult) { + browse := c.Browse(ctx, installed, MarketBrowseOptions{ + IncludeAlpha: includeAlpha, + ForceRefresh: forceRefresh, + }) + var updates []MarketCatalogItem + for _, it := range browse.Items { + if it.Installed && it.UpdateAvailable && it.Compatible && it.Withdrawn == nil { + updates = append(updates, it) + } + } + return updates, browse +} + +// InstallFromMarket downloads, verifies SHA-256, static-scans, and +// transactionally installs pluginID from the market index. +func (c *MarketClient) InstallFromMarket(ctx context.Context, mgr *Manager, pluginID string, opts MarketInstallOptions) (*PluginInfo, error) { + if mgr == nil { + return nil, errors.New("plugin manager is nil") + } + pluginID = strings.TrimSpace(pluginID) + if !reReverseDomainID.MatchString(pluginID) { + return nil, fmt.Errorf("invalid plugin id %q", pluginID) + } + + idx, source, _, fetchErr := c.LoadIndex(ctx, opts.ForceRefresh) + if fetchErr != nil && source == "fallback" && len(idx.Plugins) == 0 { + return nil, fmt.Errorf("failed to fetch plugin market index: %w", fetchErr) + } + + // Enforce soft withdrawal: refuse new installs and point to replacement. + for _, w := range idx.Withdrawn { + if w.ID == pluginID { + reason := w.Reason.Get("en-US") + if reason == "" { + reason = w.Reason.Get("zh-CN") + } + if w.InsteadID != "" { + return nil, fmt.Errorf("plugin %q has been withdrawn (%s); use %q instead", pluginID, reason, w.InsteadID) + } + return nil, fmt.Errorf("plugin %q has been withdrawn (%s)", pluginID, reason) + } + } + + selected := selectChannelEntries(idx.Plugins, opts.IncludeAlpha) + entry, ok := selected[pluginID] + if !ok { + return nil, fmt.Errorf("plugin %q not found in market index", pluginID) + } + + // Pre-download compatibility gate (engines + platform). + if compat, reason := CheckMarketCompatibility(entry, c.hostVersion); !compat { + return nil, fmt.Errorf("plugin %s@%s is incompatible with this host: %s", entry.ID, entry.Version, reason) + } + + // Validate SHA-256 and download URL before touching the network. + wantSum := strings.ToLower(strings.TrimSpace(entry.SHA256)) + if len(wantSum) != 64 { + return nil, fmt.Errorf("market entry %s@%s is missing a valid 64-char SHA-256 checksum", entry.ID, entry.Version) + } + if _, err := hex.DecodeString(wantSum); err != nil { + return nil, fmt.Errorf("market entry %s@%s has invalid SHA-256 checksum", entry.ID, entry.Version) + } + if err := c.validateDownloadURL(entry.DownloadURL); err != nil { + return nil, fmt.Errorf("market entry %s@%s has unsafe download URL: %w", entry.ID, entry.Version, err) + } + + if err := os.MkdirAll(c.layout.TmpDir(), 0o755); err != nil { + return nil, err + } + archiveName := fmt.Sprintf("market-%s-%s.zip", entry.ID, entry.Version) + archivePath := filepath.Join(c.layout.TmpDir(), archiveName) + defer func() { + _ = os.Remove(archivePath) + _ = os.Remove(archivePath + ".part") + }() + + if _, err := fetch.Resume(ctx, c.downloadClient, entry.DownloadURL, archivePath, entry.SizeBytes, wantSum, opts.OnProgress); err != nil { + return nil, err + } + + return mgr.InstallArchiveWithSource(ctx, archivePath, SourceMarket, PackageInstallOptions{ + ExpectedID: entry.ID, + ExpectedVersion: entry.Version, + HostVersion: c.hostVersion, + Keyring: opts.Keyring, + AllowUnsigned: true, + }) +} + +// CheckMarketCompatibility verifies platform and engines constraints before downloading. +func CheckMarketCompatibility(entry MarketEntry, hostVersion string) (bool, string) { + if len(entry.Platforms) > 0 { + cur := runtime.GOOS + "/" + runtime.GOARCH + matched := false + for _, p := range entry.Platforms { + if p == cur || p == "*" { + matched = true + break + } + } + if !matched { + return false, fmt.Sprintf("platform %s not supported (requires %s)", cur, strings.Join(entry.Platforms, ", ")) + } + } + if entry.Engines.PluginAPI != "" && !MatchesRange(PluginAPIVersion, entry.Engines.PluginAPI) { + return false, fmt.Sprintf("requires pluginApi %s (host has %s)", entry.Engines.PluginAPI, PluginAPIVersion) + } + if entry.Engines.UIAPI != "" && !MatchesRange(UIAPIVersion, entry.Engines.UIAPI) { + return false, fmt.Sprintf("requires uiApi %s (host has %s)", entry.Engines.UIAPI, UIAPIVersion) + } + if hostVersion != "" && entry.Engines.ReimsGo != "" && !MatchesRange(hostVersion, entry.Engines.ReimsGo) { + return false, fmt.Sprintf("requires reims-go %s (host has %s)", entry.Engines.ReimsGo, hostVersion) + } + return true, "" +} + +func (c *MarketClient) fetchRemoteIndex(ctx context.Context, rawURL string) (MarketIndex, error) { + if err := c.validateDownloadURL(rawURL); err != nil { + return MarketIndex{}, err + } + req, err := fetch.NewRequest(ctx, rawURL) + if err != nil { + return MarketIndex{}, err + } + resp, err := c.httpClient.Do(req) + if err != nil { + return MarketIndex{}, err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return MarketIndex{}, fmt.Errorf("HTTP %d", resp.StatusCode) + } + data, err := io.ReadAll(io.LimitReader(resp.Body, maxMarketIndexBytes+1)) + if err != nil { + return MarketIndex{}, err + } + if int64(len(data)) > maxMarketIndexBytes { + return MarketIndex{}, fmt.Errorf("market index exceeds %d byte limit", maxMarketIndexBytes) + } + var idx MarketIndex + if err := json.Unmarshal(data, &idx); err != nil { + return MarketIndex{}, fmt.Errorf("parse index JSON: %w", err) + } + if idx.Schema != 1 { + return MarketIndex{}, fmt.Errorf("unsupported market index schema %d", idx.Schema) + } + if idx.Plugins == nil { + idx.Plugins = []MarketEntry{} + } + return idx, nil +} + +func (c *MarketClient) validateDownloadURL(rawURL string) error { + u, err := url.Parse(strings.TrimSpace(rawURL)) + if err != nil || u.Host == "" { + return errors.New("malformed URL") + } + switch strings.ToLower(u.Scheme) { + case "https": + return nil + case "http": + if c.allowInsecureLocalhost { + host := strings.ToLower(u.Hostname()) + if host == "127.0.0.1" || host == "localhost" || host == "::1" { + return nil + } + } + return errors.New("only HTTPS market URLs are permitted") + default: + return fmt.Errorf("unsupported URL scheme %q", u.Scheme) + } +} + +func (c *MarketClient) storeMem(idx MarketIndex) { + cp := cloneMarketIndex(idx) + c.mu.Lock() + c.memIndex = &cp + c.memLoaded = time.Now() + c.mu.Unlock() +} + +func (c *MarketClient) readDiskCache() (MarketIndex, error) { + if c.layout.Root == "" { + return MarketIndex{}, os.ErrNotExist + } + raw, err := os.ReadFile(c.layout.IndexCachePath()) + if err != nil { + return MarketIndex{}, err + } + var idx MarketIndex + if err := json.Unmarshal(raw, &idx); err != nil { + return MarketIndex{}, err + } + if idx.Schema != 1 { + return MarketIndex{}, fmt.Errorf("unsupported cached schema %d", idx.Schema) + } + if idx.Plugins == nil { + idx.Plugins = []MarketEntry{} + } + return idx, nil +} + +func (c *MarketClient) writeDiskCache(idx MarketIndex) error { + if c.layout.Root == "" { + return nil + } + cachePath := c.layout.IndexCachePath() + if err := os.MkdirAll(filepath.Dir(cachePath), 0o755); err != nil { + return err + } + raw, err := json.MarshalIndent(idx, "", " ") + if err != nil { + return err + } + tmp := cachePath + ".tmp" + if err := os.WriteFile(tmp, raw, 0o644); err != nil { + return err + } + return os.Rename(tmp, cachePath) +} + +func selectChannelEntries(entries []MarketEntry, includeAlpha bool) map[string]MarketEntry { + out := make(map[string]MarketEntry, len(entries)) + for _, e := range entries { + if e.ID == "" || e.Version == "" { + continue + } + ch := strings.ToLower(strings.TrimSpace(e.Channel)) + if ch == "" { + ch = "stable" + } + if ch != "stable" && !includeAlpha { + continue + } + if prev, exists := out[e.ID]; exists { + if !isVersionNewer(e.Version, prev.Version) { + continue + } + } + e.Channel = ch + out[e.ID] = e + } + return out +} + +func isVersionNewer(candidate, current string) bool { + vc, err1 := ParseSemVer(candidate) + vcur, err2 := ParseSemVer(current) + if err1 != nil || err2 != nil { + return candidate != current && candidate > current + } + return vc.Compare(vcur) > 0 +} + +func marketEntryMatchesQuery(e MarketEntry, q string) bool { + if strings.Contains(strings.ToLower(e.ID), q) || + strings.Contains(strings.ToLower(e.Publisher), q) || + strings.Contains(strings.ToLower(e.Kind), q) || + strings.Contains(strings.ToLower(e.Name.ZhCN), q) || + strings.Contains(strings.ToLower(e.Name.EnUS), q) || + strings.Contains(strings.ToLower(e.Description.ZhCN), q) || + strings.Contains(strings.ToLower(e.Description.EnUS), q) { + return true + } + for _, tag := range e.Tags { + if strings.Contains(strings.ToLower(tag), q) { + return true + } + } + return false +} + +func trustSortRank(t TrustLevel) int { + switch t { + case TrustOfficial: + return 3 + case TrustVerified: + return 2 + case TrustCommunity: + return 1 + default: + return 0 + } +} + +func cloneMarketIndex(idx MarketIndex) MarketIndex { + cp := MarketIndex{ + Schema: idx.Schema, + UpdatedAt: idx.UpdatedAt, + Plugins: append([]MarketEntry(nil), idx.Plugins...), + Withdrawn: append([]MarketWithdrawal(nil), idx.Withdrawn...), + } + if cp.Plugins == nil { + cp.Plugins = []MarketEntry{} + } + return cp +} diff --git a/internal/plugin/market_fallback.json b/internal/plugin/market_fallback.json new file mode 100644 index 0000000..835128a --- /dev/null +++ b/internal/plugin/market_fallback.json @@ -0,0 +1,6 @@ +{ + "schema": 1, + "updated_at": "2026-11-30T00:00:00Z", + "plugins": [], + "withdrawn": [] +} diff --git a/internal/plugin/market_test.go b/internal/plugin/market_test.go new file mode 100644 index 0000000..46f8ee6 --- /dev/null +++ b/internal/plugin/market_test.go @@ -0,0 +1,274 @@ +package plugin_test + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/Nwflower/reims-go/internal/fetch" + "github.com/Nwflower/reims-go/internal/plugin" +) + +func TestMarketFetchCacheAndFallback(t *testing.T) { + var fail atomic.Bool + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if fail.Load() { + w.WriteHeader(http.StatusServiceUnavailable) + return + } + idx := plugin.MarketIndex{ + Schema: 1, + UpdatedAt: "2026-11-30T00:00:00Z", + Plugins: []plugin.MarketEntry{{ + ID: "community.theme.nord", + Version: "1.2.0", + Name: plugin.LocalizedText{ZhCN: "北欧主题", EnUS: "Nord Theme"}, + Description: plugin.LocalizedText{EnUS: "Cool blue palette"}, + Publisher: "nord", + License: "MIT", + Channel: "stable", + Kind: "theme", + Trust: plugin.TrustVerified, + DownloadURL: "https://example.invalid/nord.zip", + SHA256: strings.Repeat("a", 64), + }}, + } + _ = json.NewEncoder(w).Encode(idx) + })) + defer srv.Close() + + dataRoot := t.TempDir() + layout := plugin.NewPluginsLayout(dataRoot) + mc := plugin.NewMarketClient(plugin.MarketClientOptions{ + Layout: layout, + HostVersion: "0.2.8", + URLs: []string{srv.URL + "/index.json"}, + CacheTTL: time.Minute, + AllowInsecureLocalhost: true, + }) + + // 1. Fresh remote fetch succeeds and populates disk cache. + idx, src, stale, err := mc.LoadIndex(context.Background(), false) + if err != nil || src != "remote" || stale || len(idx.Plugins) != 1 { + t.Fatalf("first LoadIndex = (src=%s stale=%v len=%d err=%v)", src, stale, len(idx.Plugins), err) + } + if _, statErr := os.Stat(layout.IndexCachePath()); statErr != nil { + t.Fatalf("expected disk cache at %s: %v", layout.IndexCachePath(), statErr) + } + + // 2. Second load within TTL hits memory cache cleanly. + _, src2, stale2, err2 := mc.LoadIndex(context.Background(), false) + if err2 != nil || src2 != "cache" || stale2 { + t.Fatalf("cached LoadIndex = (src=%s stale=%v err=%v)", src2, stale2, err2) + } + + // 3. Server goes down + forceRefresh: must retain valid disk/mem cache with stale=true. + fail.Store(true) + mcFresh := plugin.NewMarketClient(plugin.MarketClientOptions{ + Layout: layout, + HostVersion: "0.2.8", + URLs: []string{srv.URL + "/index.json"}, + AllowInsecureLocalhost: true, + }) + idx3, src3, stale3, err3 := mcFresh.LoadIndex(context.Background(), true) + if err3 == nil || src3 != "cache" || !stale3 || len(idx3.Plugins) != 1 { + t.Fatalf("stale fallback LoadIndex = (src=%s stale=%v len=%d err=%v)", src3, stale3, len(idx3.Plugins), err3) + } +} + +func TestMarketBrowseAndInstallGates(t *testing.T) { + // Prepare valid L1 theme zip and smuggled-script L1 zip. + goodManifest, _ := json.Marshal(plugin.Manifest{ + Schema: 1, + ID: "community.theme.mist", + Version: "1.1.0", + Name: plugin.LocalizedText{ZhCN: "薄雾主题", EnUS: "Mist Theme"}, + Description: plugin.LocalizedText{EnUS: "Clean L1 theme"}, + Publisher: "mist-author", + License: "MIT", + Engines: plugin.Engines{ReimsGo: ">=0.2.0", PluginAPI: "^1.0.0"}, + Contributes: plugin.Contributes{ + Themes: []plugin.ThemeContribution{{ + ID: "community.theme.mist", + Name: plugin.LocalizedText{EnUS: "Mist"}, + Stylesheet: "theme.css", + }}, + }, + }) + goodZip := makePluginZip(t, map[string][]byte{ + "plugin.json": goodManifest, + "theme.css": []byte(`.rg-p-sidebar { background: var(--surface-sidebar); }`), + }, nil, false) + goodBytes, _ := os.ReadFile(goodZip) + goodSum, _ := fetch.FileSHA256(goodZip) + + evilManifest, _ := json.Marshal(plugin.Manifest{ + Schema: 1, + ID: "community.theme.evil", + Version: "1.0.0", + Name: plugin.LocalizedText{EnUS: "Evil Theme"}, + }) + evilZip := makePluginZip(t, map[string][]byte{ + "plugin.json": evilManifest, + "steal.ps1": []byte(`Write-Host "boom"`), + }, nil, false) + evilBytes, _ := os.ReadFile(evilZip) + evilSum, _ := fetch.FileSHA256(evilZip) + + var srvURL string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/mist.zip": + w.Header().Set("Content-Type", "application/zip") + _, _ = w.Write(goodBytes) + case "/evil.zip": + w.Header().Set("Content-Type", "application/zip") + _, _ = w.Write(evilBytes) + case "/index.json": + idx := plugin.MarketIndex{ + Schema: 1, + UpdatedAt: "2026-11-30T00:00:00Z", + Plugins: []plugin.MarketEntry{ + { + ID: "community.theme.mist", + Version: "1.1.0", + Name: plugin.LocalizedText{ZhCN: "薄雾主题", EnUS: "Mist Theme"}, + Description: plugin.LocalizedText{EnUS: "Clean L1 theme"}, + Publisher: "mist-author", + License: "MIT", + Channel: "stable", + Kind: "theme", + Tier: plugin.TierL1, + Trust: plugin.TrustCommunity, + Engines: plugin.Engines{ReimsGo: ">=0.2.0", PluginAPI: "^1.0.0"}, + DownloadURL: srvURL + "/mist.zip", + SHA256: goodSum, + SizeBytes: int64(len(goodBytes)), + }, + { + ID: "community.theme.mist", + Version: "1.2.0-alpha.1", + Name: plugin.LocalizedText{EnUS: "Mist Alpha"}, + Channel: "alpha", + Kind: "theme", + Trust: plugin.TrustCommunity, + DownloadURL: srvURL + "/mist.zip", + SHA256: goodSum, + }, + { + ID: "community.theme.incompat", + Version: "2.0.0", + Name: plugin.LocalizedText{EnUS: "Future Theme"}, + Channel: "stable", + Kind: "theme", + Trust: plugin.TrustCommunity, + Engines: plugin.Engines{ReimsGo: ">=9.0.0"}, + DownloadURL: srvURL + "/never-downloaded.zip", + SHA256: strings.Repeat("b", 64), + }, + { + ID: "community.theme.badhash", + Version: "1.0.0", + Name: plugin.LocalizedText{EnUS: "Bad Hash"}, + Channel: "stable", + Kind: "theme", + Trust: plugin.TrustCommunity, + DownloadURL: srvURL + "/mist.zip", + SHA256: strings.Repeat("0", 64), + }, + { + ID: "community.theme.evil", + Version: "1.0.0", + Name: plugin.LocalizedText{EnUS: "Evil Theme"}, + Channel: "stable", + Kind: "theme", + Trust: plugin.TrustCommunity, + DownloadURL: srvURL + "/evil.zip", + SHA256: evilSum, + }, + }, + Withdrawn: []plugin.MarketWithdrawal{{ + ID: "community.old.tool", + Reason: plugin.LocalizedText{ZhCN: "已合并进新插件", EnUS: "Merged into new plugin"}, + InsteadID: "community.theme.mist", + InsteadName: "Mist Theme", + }}, + } + _ = json.NewEncoder(w).Encode(idx) + default: + w.WriteHeader(http.StatusNotFound) + } + })) + defer srv.Close() + srvURL = srv.URL + + dataRoot := t.TempDir() + mgr, err := plugin.NewManager(plugin.ManagerOptions{ + DataRoot: dataRoot, + HostVersion: "0.2.8", + }) + if err != nil { + t.Fatalf("NewManager: %v", err) + } + defer mgr.Close() + + mc := plugin.NewMarketClient(plugin.MarketClientOptions{ + Layout: mgr.Layout(), + HostVersion: "0.2.8", + URLs: []string{srvURL + "/index.json"}, + AllowInsecureLocalhost: true, + }) + + // Browse stable only: should pick 1.1.0 (not 1.2.0-alpha.1) and surface WithdrawnInstalled. + res := mc.Browse(context.Background(), []plugin.PluginInfo{ + {ID: "community.old.tool", Version: "0.9.0"}, + {ID: "community.theme.mist", Version: "1.0.0"}, + }, plugin.MarketBrowseOptions{}) + if len(res.WithdrawnInstalled) != 1 || res.WithdrawnInstalled[0].InsteadID != "community.theme.mist" { + t.Fatalf("expected withdrawn installed advisory, got %+v", res.WithdrawnInstalled) + } + var mistItem *plugin.MarketCatalogItem + for i := range res.Items { + if res.Items[i].Entry.ID == "community.theme.mist" { + mistItem = &res.Items[i] + } + } + if mistItem == nil || mistItem.Entry.Version != "1.1.0" || !mistItem.UpdateAvailable || !mistItem.Compatible { + t.Fatalf("unexpected mist catalog item: %+v", mistItem) + } + + // Withdrawn plugin install refused with replacement hint. + if _, err := mc.InstallFromMarket(context.Background(), mgr, "community.old.tool", plugin.MarketInstallOptions{}); err == nil || !strings.Contains(err.Error(), "withdrawn") { + t.Fatalf("expected withdrawn refusal, got: %v", err) + } + + // Incompatible plugin refused BEFORE download. + if _, err := mc.InstallFromMarket(context.Background(), mgr, "community.theme.incompat", plugin.MarketInstallOptions{}); err == nil || !strings.Contains(err.Error(), "incompatible") { + t.Fatalf("expected incompatible refusal, got: %v", err) + } + + // SHA-256 mismatch refused. + if _, err := mc.InstallFromMarket(context.Background(), mgr, "community.theme.badhash", plugin.MarketInstallOptions{}); err == nil || !strings.Contains(err.Error(), "SHA256 mismatch") { + t.Fatalf("expected SHA256 mismatch refusal, got: %v", err) + } + + // Smuggled .ps1 in L1 zip refused by static security gate even when archive SHA-256 matches. + if _, err := mc.InstallFromMarket(context.Background(), mgr, "community.theme.evil", plugin.MarketInstallOptions{}); err == nil || !strings.Contains(err.Error(), "static security gate") { + t.Fatalf("expected static gate refusal for smuggled .ps1, got: %v", err) + } + + // Valid market plugin installs cleanly with SourceMarket. + info, err := mc.InstallFromMarket(context.Background(), mgr, "community.theme.mist", plugin.MarketInstallOptions{}) + if err != nil { + t.Fatalf("InstallFromMarket valid plugin: %v", err) + } + if info.ID != "community.theme.mist" || info.Version != "1.1.0" || info.Source != plugin.SourceMarket { + t.Fatalf("unexpected installed info: %+v", info) + } +} diff --git a/internal/plugin/package.go b/internal/plugin/package.go index fea5a8f..96b5760 100644 --- a/internal/plugin/package.go +++ b/internal/plugin/package.go @@ -44,7 +44,7 @@ func containsForbiddenSMCKey(low string) bool { return reOSKAssignment.MatchString(low) } -// SigningKeyring maps key IDs / publishers to ed25519 public keys and trust level. +// SigningKey maps key IDs / publishers to ed25519 public keys and trust level. type SigningKey struct { KeyID string Publisher string @@ -52,36 +52,6 @@ type SigningKey struct { PublicKey ed25519.PublicKey } -// MarketEntry describes one plugin published in the remote/embedded market index (§9). -type MarketEntry struct { - ID string `json:"id"` - Version string `json:"version"` - Name LocalizedText `json:"name"` - Description LocalizedText `json:"description"` - Publisher string `json:"publisher"` - License string `json:"license"` - Channel string `json:"channel"` // "stable" | "alpha" - Trust TrustLevel `json:"trust"` - Engines Engines `json:"engines"` - DownloadURL string `json:"download_url"` - SHA256 string `json:"sha256"` - Signer string `json:"signer,omitempty"` -} - -// MarketIndex is the static index.json structure (§9). -type MarketIndex struct { - Schema int `json:"schema"` - UpdatedAt string `json:"updated_at"` - Plugins []MarketEntry `json:"plugins"` -} - -// EmbeddedFallbackMarketIndex is shipped as a zero-network fallback (§9). -var EmbeddedFallbackMarketIndex = MarketIndex{ - Schema: 1, - UpdatedAt: "2026-11-29T00:00:00Z", - Plugins: []MarketEntry{}, -} - // PackageInstallOptions controls optional expectations during transactional install. type PackageInstallOptions struct { ExpectedID string @@ -638,6 +608,23 @@ func InstallArchive(layout PluginsLayout, archivePath string, opts PackageInstal return nil, err } + // Enforce unified static security & packaging hard-gate before activation. + scanRep := ScanDirectory(stageDir, opts.HostVersion, ScanOptions{ + Keyring: opts.Keyring, + RequireChecksums: true, + }) + if scanRep.HardBlocked { + reasons := make([]string, 0, len(scanRep.HardFindings)) + for _, f := range scanRep.HardFindings { + if f.Target != "" { + reasons = append(reasons, fmt.Sprintf("[%s] %s: %s", f.Check, f.Target, f.Message)) + } else { + reasons = append(reasons, fmt.Sprintf("[%s] %s", f.Check, f.Message)) + } + } + return nil, fmt.Errorf("plugin package blocked by static security gate: %s", strings.Join(reasons, "; ")) + } + // Atomic activation into pkgs// with path-traversal guard (B3). finalDir, err := safeJoin(layout.PkgsDir(), m.ID+"/"+m.Version) if err != nil { @@ -679,97 +666,13 @@ func InstallArchive(layout PluginsLayout, archivePath string, opts PackageInstal } // DoctorDirectory validates a plugin directory (installed or local dev link), -// checking manifest, SHA256SUMS (if present), CSS safety, and UI contract compliance (§5.1, §10). +// checking manifest, SHA256SUMS (if present), static risk rules, CSS safety, +// and UI contract compliance (§5.1, §10). func DoctorDirectory(dir string, hostVersion string, contract *UIContract) []DoctorFinding { - var out []DoctorFinding - add := func(sev, check, msg string) { - out = append(out, DoctorFinding{Severity: sev, Check: check, Message: msg}) - } - raw, err := os.ReadFile(filepath.Join(dir, "plugin.json")) - if err != nil { - add("error", "manifest", "cannot read plugin.json: "+err.Error()) - return out - } - var m Manifest - if err := json.Unmarshal(raw, &m); err != nil { - add("error", "manifest", "invalid plugin.json JSON: "+err.Error()) - return out - } - if err := ValidateManifest(m, hostVersion, false); err != nil { - add("error", "manifest", err.Error()) - } else { - add("ok", "manifest", fmt.Sprintf("valid manifest %s@%s (tier=%s)", m.ID, m.Version, m.InferTier(false))) - } - - if err := checkMarketRedlines(dir); err != nil { - add("error", "redline", err.Error()) - } else { - add("ok", "redline", "no forbidden proprietary or secret files detected") - } - - if sumsRaw, err := os.ReadFile(filepath.Join(dir, "SHA256SUMS")); err == nil { - if err := verifyDirSHA256Sums(dir, sumsRaw); err != nil { - add("error", "checksum", err.Error()) - } else { - add("ok", "checksum", "SHA256SUMS verified") - } - } else { - add("warn", "checksum", "SHA256SUMS absent (acceptable in dev link mode; required for .zip distribution)") - } - - // Validate theme manifest fields and stylesheets against safety rules and UI Contract v1 (§5.1, B5). - for _, th := range m.Contributes.Themes { - if err := ValidateThemeContribution(th, dir); err != nil { - add("error", "theme-css", err.Error()) - } else if th.Stylesheet != "" { - add("ok", "theme-css", th.Stylesheet+" passed CSS safety & asset check") - } - if th.Stylesheet == "" { - continue - } - cssPath, err := safeJoin(dir, th.Stylesheet) - if err != nil { - continue - } - cssBytes, err := os.ReadFile(cssPath) - if err != nil { - continue - } - cssText := string(cssBytes) - if contract != nil { - for _, issue := range CheckCSSAgainstContract(cssText, *contract) { - add("warn", "ui-contract", issue) - } - } - } - if strings.TrimSpace(m.L10n) != "" { - if err := validatePluginL10nDir(m.L10n, dir); err != nil { - add("error", "l10n", err.Error()) - } else { - add("ok", "l10n", fmt.Sprintf("plugin l10n directory %q validated", m.L10n)) - } - } - if len(m.Contributes.Locales) > 0 { - if _, locFindings, cErr := CheckLocalePack(dir); cErr == nil && len(locFindings) > 0 { - for _, lf := range locFindings { - out = append(out, lf) - } - for _, lc := range m.Contributes.Locales { - if ValidateLocaleContribution(lc, dir) == nil { - add("ok", "locale", fmt.Sprintf("locale %s validated", lc.Locale)) - } - } - } else { - for _, lc := range m.Contributes.Locales { - if err := ValidateLocaleContribution(lc, dir); err != nil { - add("error", "locale", err.Error()) - } else { - add("ok", "locale", fmt.Sprintf("locale %s validated", lc.Locale)) - } - } - } - } - return out + return ScanDirectory(dir, hostVersion, ScanOptions{ + Contract: contract, + RequireChecksums: false, + }).ToDoctorFindings() } var ( diff --git a/internal/plugin/scanner.go b/internal/plugin/scanner.go new file mode 100644 index 0000000..67b405d --- /dev/null +++ b/internal/plugin/scanner.go @@ -0,0 +1,1006 @@ +package plugin + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "regexp" + "sort" + "strings" +) + +// ScanSeverity classifies risk findings into three actionable buckets: +// - "hard": Violates packaging/security redlines; cannot be bypassed by confirmation. +// - "capability": Legitimate declared capability or native execution boundary explained in plain language. +// - "pending": Non-blocking advisories (e.g. missing SHA256SUMS in dev mode, unsigned community build, UI contract drift). +const ( + ScanSeverityHard = "hard" + ScanSeverityCapability = "capability" + ScanSeverityPending = "pending" +) + +const ( + maxScanTextBytes = 8 << 20 // 8 MiB cap per scanned text asset + maxCapExamples = 3 // Fold evidence lists past 3 items ("…and N more") +) + +// ForbiddenBinaryExtensions enumerates native executable, dynamic library, and +// OS script extensions that are strictly forbidden in L1/L2/L4 packages and +// must be explicitly declared in L3/runtime packages. +var ForbiddenBinaryExtensions = map[string]bool{ + ".exe": true, + ".dll": true, + ".com": true, + ".scr": true, + ".pif": true, + ".cpl": true, + ".msi": true, + ".msp": true, + ".sys": true, + ".drv": true, + ".ocx": true, + ".bat": true, + ".cmd": true, + ".ps1": true, + ".psm1": true, + ".psd1": true, + ".vbs": true, + ".vbe": true, + ".jse": true, + ".wsf": true, + ".wsh": true, + ".hta": true, + ".lnk": true, + ".url": true, + ".reg": true, + ".jar": true, + ".so": true, + ".dylib": true, + ".pyd": true, + ".node": true, +} + +// ScanFinding is one concrete issue discovered by the static risk scanner. +type ScanFinding struct { + Severity string `json:"severity"` // "hard" | "capability" | "pending" + Check string `json:"check"` + Target string `json:"target,omitempty"` + Message string `json:"message"` + Localized LocalizedText `json:"localized,omitempty"` +} + +// ExecutableFile records a native binary or OS script discovered in a package. +type ExecutableFile struct { + Path string `json:"path"` + SHA256 string `json:"sha256"` + Declared bool `json:"declared"` + SizeBytes int64 `json:"size_bytes"` +} + +// CapabilityItem presents one declared permission or execution boundary in +// plain, user-readable language with capped concrete evidence examples. +type CapabilityItem struct { + ID string `json:"id"` + Level PermissionLevel `json:"level"` + Title LocalizedText `json:"title"` + Summary LocalizedText `json:"summary"` + Examples []string `json:"examples,omitempty"` + ExtraCount int `json:"extra_count,omitempty"` +} + +// ScanOptions configures ScanDirectory / ScanArchive. +type ScanOptions struct { + Contract *UIContract + Keyring []SigningKey + RequireChecksums bool +} + +// ScanReport is the unified static risk & gate report shared by `plugin doctor`, +// transactional `InstallArchive`, CLI summaries, and GUI inspection dialogs. +type ScanReport struct { + PluginID string `json:"plugin_id,omitempty"` + Version string `json:"version,omitempty"` + Name LocalizedText `json:"name,omitempty"` + Tier Tier `json:"tier,omitempty"` + Trust TrustLevel `json:"trust,omitempty"` + Publisher string `json:"publisher,omitempty"` + License string `json:"license,omitempty"` + Passed bool `json:"passed"` + HardBlocked bool `json:"hard_blocked"` + NeedsApproval bool `json:"needs_approval"` + Headline LocalizedText `json:"headline"` + NativeExecNotice LocalizedText `json:"native_exec_notice,omitempty"` + HardFindings []ScanFinding `json:"hard_findings,omitempty"` + Capabilities []CapabilityItem `json:"capabilities,omitempty"` + PendingFindings []ScanFinding `json:"pending_findings,omitempty"` + Executables []ExecutableFile `json:"executables,omitempty"` +} + +var ( + reSVGScriptTag = regexp.MustCompile(`(?i)<\s*script\b`) + reSVGEventAttr = regexp.MustCompile(`(?i)\bon[a-z]{2,32}\s*=`) + reSVGJavascriptURI = regexp.MustCompile(`(?i)javascript\s*:`) + reSVGForeignObject = regexp.MustCompile(`(?i)<\s*foreignobject\b`) + + reJSWailsGo = regexp.MustCompile(`(?i)\b(?:window|globalThis|self|parent|top)\s*(?:\.\s*go\b|\[\s*['"]go['"]\s*\])`) + reJSWailsRuntime = regexp.MustCompile(`(?i)\b(?:window|globalThis|self|parent|top)\s*(?:\.\s*runtime\b|\[\s*['"]runtime['"]\s*\])`) + reJSEval = regexp.MustCompile(`\beval\s*\(`) + reJSNewFunction = regexp.MustCompile(`\bnew\s+Function\s*\(`) + reJSFunctionCall = regexp.MustCompile(`(?:^|[^.\w$])Function\s*\(`) + reJSDocCookie = regexp.MustCompile(`\bdocument\s*\.\s*cookie\b`) + reJSDocWrite = regexp.MustCompile(`\bdocument\s*\.\s*write(?:ln)?\s*\(`) + reJSScriptTag = regexp.MustCompile(`(?i)<\s*script\b`) + reJSCreateScript = regexp.MustCompile(`(?i)\bcreateElement\s*\(\s*['"]script['"]\s*\)`) + reJSNetworkCall = regexp.MustCompile(`\b(?:fetch\s*\(|XMLHttpRequest\b|WebSocket\b|EventSource\b|navigator\s*\.\s*sendBeacon\s*\()`) +) + +// ScanArchive extracts archivePath into a temporary directory under tmpParentDir +// (e.g. `/plugins/tmp`, never system `%TEMP%` unless explicitly passed +// by caller) and runs ScanDirectory with RequireChecksums=true. +func ScanArchive(archivePath, tmpParentDir, hostVersion string, opts ScanOptions) (ScanReport, error) { + if tmpParentDir == "" { + return ScanReport{}, fmt.Errorf("tmpParentDir is required for ScanArchive") + } + if err := os.MkdirAll(tmpParentDir, 0o755); err != nil { + return ScanReport{}, err + } + stageDir, err := os.MkdirTemp(tmpParentDir, "scan-*") + if err != nil { + return ScanReport{}, err + } + defer os.RemoveAll(stageDir) + + if err := extractPluginZip(archivePath, stageDir); err != nil { + rep := ScanReport{ + Passed: false, + HardBlocked: true, + HardFindings: []ScanFinding{{ + Severity: ScanSeverityHard, + Check: "archive", + Target: filepath.Base(archivePath), + Message: err.Error(), + Localized: LocalizedText{ + ZhCN: "插件压缩包结构非法或超出安全限制:" + err.Error(), + EnUS: "Plugin archive failed safety extraction: " + err.Error(), + }, + }}, + } + finalizeScanReport(&rep) + return rep, nil + } + opts.RequireChecksums = true + return ScanDirectory(stageDir, hostVersion, opts), nil +} + +// ScanDirectory performs a comprehensive static risk and policy scan on a plugin +// directory (unpacked archive, installed package, or dev-linked directory). +func ScanDirectory(dir, hostVersion string, opts ScanOptions) ScanReport { + rep := ScanReport{ + Trust: TrustCommunity, + } + addHard := func(check, target, msg string, zh, en string) { + rep.HardFindings = append(rep.HardFindings, ScanFinding{ + Severity: ScanSeverityHard, + Check: check, + Target: target, + Message: msg, + Localized: LocalizedText{ZhCN: zh, EnUS: en}, + }) + } + addPending := func(check, target, msg string, zh, en string) { + rep.PendingFindings = append(rep.PendingFindings, ScanFinding{ + Severity: ScanSeverityPending, + Check: check, + Target: target, + Message: msg, + Localized: LocalizedText{ZhCN: zh, EnUS: en}, + }) + } + + raw, err := os.ReadFile(filepath.Join(dir, "plugin.json")) + if err != nil { + addHard("manifest", "plugin.json", "cannot read plugin.json: "+err.Error(), + "缺少或无法读取 plugin.json 清单文件", + "Cannot read plugin.json manifest") + finalizeScanReport(&rep) + return rep + } + var m Manifest + if err := json.Unmarshal(raw, &m); err != nil { + addHard("manifest", "plugin.json", "invalid plugin.json JSON: "+err.Error(), + "plugin.json 格式无效:"+err.Error(), + "Invalid plugin.json JSON: "+err.Error()) + finalizeScanReport(&rep) + return rep + } + + rep.PluginID = m.ID + rep.Version = m.Version + rep.Name = m.Name + rep.Tier = m.InferTier(false) + rep.Publisher = m.Publisher + rep.License = m.License + + if err := ValidateManifest(m, hostVersion, false); err != nil { + addHard("manifest", "plugin.json", err.Error(), + "清单校验未通过:"+err.Error(), + "Manifest validation failed: "+err.Error()) + } + + // Build normalized sets of declared entries & runtime directories. + declaredSidecar := normalizeRel(m.Entry.Sidecar) + declaredPanelDir := normalizeRel(m.Entry.PanelDir) + runtimeDirs := make([]string, 0, len(m.Contributes.Runtimes)) + for _, rtPack := range m.Contributes.Runtimes { + if d := normalizeRel(rtPack.Dir); d != "" { + runtimeDirs = append(runtimeDirs, d) + } + } + hasNetPerm := false + for _, p := range m.Permissions { + if strings.HasPrefix(strings.TrimSpace(p), "net:") { + hasNetPerm = true + break + } + } + + // Verify declared entries exist on disk. + checkEntryFile := func(label, rel string, expectDir bool) { + if strings.TrimSpace(rel) == "" { + return + } + full, jErr := safeJoin(dir, rel) + if jErr != nil { + addHard("missing-entry", rel, fmt.Sprintf("invalid %s path %q: %v", label, rel, jErr), + fmt.Sprintf("声明的入口路径 %s 非法:%v", rel, jErr), + fmt.Sprintf("Declared %s path %q is invalid: %v", label, rel, jErr)) + return + } + st, sErr := os.Stat(full) + if sErr != nil { + addHard("missing-entry", rel, fmt.Sprintf("declared %s %q is missing", label, rel), + fmt.Sprintf("清单声明的入口 %s 不存在", rel), + fmt.Sprintf("Declared %s %q is missing from package", label, rel)) + return + } + if expectDir && !st.IsDir() { + addHard("missing-entry", rel, fmt.Sprintf("declared %s %q is not a directory", label, rel), + fmt.Sprintf("清单声明的目录入口 %s 不是目录", rel), + fmt.Sprintf("Declared %s %q is not a directory", label, rel)) + } else if !expectDir && st.IsDir() { + addHard("missing-entry", rel, fmt.Sprintf("declared %s %q is a directory, expected file", label, rel), + fmt.Sprintf("清单声明的文件入口 %s 是目录而非文件", rel), + fmt.Sprintf("Declared %s %q is a directory, expected a file", label, rel)) + } + } + checkEntryFile("entry.sidecar", m.Entry.Sidecar, false) + checkEntryFile("entry.script", m.Entry.Script, false) + checkEntryFile("entry.uiScript", m.Entry.UIScript, false) + checkEntryFile("entry.panelDir", m.Entry.PanelDir, true) + for _, us := range m.Contributes.UIScripts { + checkEntryFile("contributes.uiScripts", us.Script, false) + } + for _, panel := range m.Contributes.Panels { + if declaredPanelDir != "" && panel.Entry != "" { + checkEntryFile("panel entry", declaredPanelDir+"/"+strings.TrimPrefix(panel.Entry, "/"), false) + } + } + + // Track theme stylesheets so we don't duplicate CSS checks in the directory walk. + declaredThemeCSS := map[string]bool{} + for _, th := range m.Contributes.Themes { + if th.Stylesheet != "" { + declaredThemeCSS[normalizeRel(th.Stylesheet)] = true + } + if err := ValidateThemeContribution(th, dir); err != nil { + addHard("theme-css", th.Stylesheet, err.Error(), + "主题样式或资源未通过安全校验:"+err.Error(), + "Theme stylesheet or asset failed safety validation: "+err.Error()) + } + if th.Stylesheet != "" && opts.Contract != nil { + if cssPath, jErr := safeJoin(dir, th.Stylesheet); jErr == nil { + if cssBytes, rErr := os.ReadFile(cssPath); rErr == nil { + for _, issue := range CheckCSSAgainstContract(string(cssBytes), *opts.Contract) { + addPending("ui-contract", th.Stylesheet, issue, + fmt.Sprintf("主题样式 %s 存在 UI 契约提示:%s", th.Stylesheet, issue), + fmt.Sprintf("Theme CSS %s UI contract advisory: %s", th.Stylesheet, issue)) + } + } + } + } + } + + // Walk all files in the package for redlines, executables, SVG scripts, CSS, and JS safety. + var netScriptHits []string + var walkFiles []string + _ = filepath.Walk(dir, func(p string, info os.FileInfo, wErr error) error { + if wErr != nil || info == nil || info.IsDir() { + return nil + } + rel, rErr := filepath.Rel(dir, p) + if rErr != nil { + return nil + } + walkFiles = append(walkFiles, filepath.ToSlash(rel)) + return nil + }) + sort.Strings(walkFiles) + + for _, rel := range walkFiles { + full := filepath.Join(dir, filepath.FromSlash(rel)) + info, sErr := os.Stat(full) + if sErr != nil || info.IsDir() { + continue + } + lowName := strings.ToLower(info.Name()) + ext := strings.ToLower(filepath.Ext(lowName)) + + // 1. Market redlines (Apple proprietary files & SMC OSK literals). + for _, pat := range ForbiddenMarketPatterns { + if strings.Contains(lowName, pat) { + addHard("redline", rel, fmt.Sprintf("forbidden proprietary file detected (%s)", rel), + fmt.Sprintf("检测到禁止分发的专有系统文件:%s", rel), + fmt.Sprintf("Forbidden proprietary file detected: %s", rel)) + } + } + if info.Size() <= 256*1024 && isRedlineTextExt(ext) { + if b, rErr := os.ReadFile(full); rErr == nil { + if containsForbiddenSMCKey(strings.ToLower(string(b))) { + addHard("redline", rel, fmt.Sprintf("forbidden Apple SMC OSK detected in %s", rel), + fmt.Sprintf("在 %s 中检测到禁止分发的 Apple SMC OSK 密钥", rel), + fmt.Sprintf("Forbidden Apple SMC OSK detected in %s", rel)) + } + } + } + + // 2. Executable / script extension inventory & hard-ban. + if ForbiddenBinaryExtensions[ext] { + sum, _ := fileSHA256Hex(full) + declared := false + switch rep.Tier { + case TierL3: + if declaredSidecar != "" && strings.EqualFold(rel, declaredSidecar) { + declared = true + } + case TierRuntime: + for _, rd := range runtimeDirs { + if rel == rd || strings.HasPrefix(strings.ToLower(rel), strings.ToLower(rd)+"/") { + declared = true + break + } + } + } + rep.Executables = append(rep.Executables, ExecutableFile{ + Path: rel, + SHA256: sum, + Declared: declared, + SizeBytes: info.Size(), + }) + if !declared { + if rep.Tier == TierL3 || rep.Tier == TierRuntime { + addHard("unlisted-executable", rel, + fmt.Sprintf("unlisted executable or script %q not declared in manifest", rel), + fmt.Sprintf("包含未在清单中声明的可执行文件或脚本:%s", rel), + fmt.Sprintf("Unlisted executable or script not declared in manifest: %s", rel)) + } else { + addHard("forbidden-binary", rel, + fmt.Sprintf("executable or OS script %q is forbidden in %s plugin packages", rel, rep.Tier), + fmt.Sprintf("%s 类型插件禁止夹带可执行文件或系统脚本:%s", rep.Tier, rel), + fmt.Sprintf("Executable or OS script %q is forbidden in %s packages", rel, rep.Tier)) + } + } + } + + // 3. SVG active-content scan across the entire package. + if ext == ".svg" && info.Size() <= maxScanTextBytes { + if b, rErr := os.ReadFile(full); rErr == nil { + if reason := scanSVGActiveContent(string(b)); reason != "" { + addHard("svg-script", rel, fmt.Sprintf("unsafe active content in SVG %s: %s", rel, reason), + fmt.Sprintf("SVG 文件 %s 包含被禁止的脚本或事件属性(%s)", rel, reason), + fmt.Sprintf("SVG file %s contains forbidden active content (%s)", rel, reason)) + } + } + } + + // 4. Extra CSS files outside declared theme stylesheets & sandboxed panelDir. + if ext == ".css" && !declaredThemeCSS[rel] && !inRelDir(rel, declaredPanelDir) && info.Size() <= maxScanTextBytes { + if b, rErr := os.ReadFile(full); rErr == nil { + if err := ValidateThemeCSSSafetyInDir(string(b), filepath.Dir(full)); err != nil { + addHard("theme-css", rel, fmt.Sprintf("unsafe CSS %s: %v", rel, err), + fmt.Sprintf("样式文件 %s 未通过安全校验:%v", rel, err), + fmt.Sprintf("Stylesheet %s failed safety check: %v", rel, err)) + } + } + } + + // 5. JS / MJS / HTML script static scan. + if (ext == ".js" || ext == ".mjs" || ext == ".cjs") && info.Size() <= maxScanTextBytes { + if b, rErr := os.ReadFile(full); rErr == nil { + hits, hasNet := scanScriptContent(string(b), false) + for _, hit := range hits { + addHard("ui-script", rel, fmt.Sprintf("forbidden JS pattern (%s) in %s", hit, rel), + fmt.Sprintf("脚本 %s 包含被禁止的宿主逃逸或动态执行语句(%s)", rel, hit), + fmt.Sprintf("Script %s contains forbidden host-escape or dynamic-eval pattern (%s)", rel, hit)) + } + if hasNet { + if !hasNetPerm { + addHard("ui-script-undeclared-net", rel, + fmt.Sprintf("script %s calls network APIs without declaring any net: permission", rel), + fmt.Sprintf("脚本 %s 调用了网络接口,但清单未声明 net: 权限", rel), + fmt.Sprintf("Script %s calls network APIs without declaring any net: permission", rel)) + } else { + netScriptHits = append(netScriptHits, rel) + } + } + } + } + if (ext == ".html" || ext == ".htm") && inRelDir(rel, declaredPanelDir) && info.Size() <= maxScanTextBytes { + if b, rErr := os.ReadFile(full); rErr == nil { + hits, _ := scanScriptContent(string(b), true) + for _, hit := range hits { + addHard("panel-html", rel, fmt.Sprintf("forbidden host-escape pattern (%s) in panel %s", hit, rel), + fmt.Sprintf("面板页面 %s 包含被禁止的宿主逃逸语句(%s)", rel, hit), + fmt.Sprintf("Panel HTML %s contains forbidden host-escape pattern (%s)", rel, hit)) + } + } + } + } + + // 6. Checksums & optional ed25519 signature. + sumsPath := filepath.Join(dir, "SHA256SUMS") + if sumsRaw, sErr := os.ReadFile(sumsPath); sErr == nil { + if err := verifyDirSHA256Sums(dir, sumsRaw); err != nil { + addHard("checksum", "SHA256SUMS", err.Error(), + "SHA256SUMS 完整性校验失败:"+err.Error(), + "SHA256SUMS integrity verification failed: "+err.Error()) + } + if sigRaw, sigErr := os.ReadFile(filepath.Join(dir, "SHA256SUMS.sig")); sigErr == nil { + if len(opts.Keyring) > 0 { + t, vErr := verifyEd25519Signature(sumsRaw, sigRaw, opts.Keyring) + if vErr != nil { + addHard("signature", "SHA256SUMS.sig", "invalid package signature: "+vErr.Error(), + "插件签名验证失败:"+vErr.Error(), + "Plugin signature verification failed: "+vErr.Error()) + } else { + rep.Trust = t + } + } + } + } else if opts.RequireChecksums { + addHard("checksum", "SHA256SUMS", "package missing SHA256SUMS", + "分发压缩包缺少必需的 SHA256SUMS 校验文件", + "Distribution package is missing required SHA256SUMS file") + } else { + addPending("checksum", "SHA256SUMS", "SHA256SUMS absent (acceptable in dev link mode; required for .zip distribution)", + "未包含 SHA256SUMS(本地开发链接可忽略,打包分发 .zip 时必需)", + "SHA256SUMS absent (acceptable in dev link mode; required for .zip distribution)") + } + + if rep.Trust == TrustCommunity { + addPending("trust-unsigned", "", "community package is not signed by an official or verified market key", + "社区插件未携带官方或已审核签名,请仅安装来自可信作者的插件包", + "Community package is not signed by an official or verified key; install only from authors you trust") + } + + // 7. L10n & Locale contributions. + if strings.TrimSpace(m.L10n) != "" { + if err := validatePluginL10nDir(m.L10n, dir); err != nil { + addHard("l10n", m.L10n, err.Error(), + "插件本地化目录校验失败:"+err.Error(), + "Plugin l10n directory validation failed: "+err.Error()) + } + } + if len(m.Contributes.Locales) > 0 { + if _, locFindings, cErr := CheckLocalePack(dir); cErr == nil && len(locFindings) > 0 { + for _, lf := range locFindings { + if lf.Severity == "error" { + addHard("locale", lf.Check, lf.Message, + "语言包校验错误:"+lf.Message, + "Language pack validation error: "+lf.Message) + } else if lf.Severity == "warn" { + addPending("locale", lf.Check, lf.Message, + "语言包提示:"+lf.Message, + "Language pack advisory: "+lf.Message) + } + } + } else { + for _, lc := range m.Contributes.Locales { + if err := ValidateLocaleContribution(lc, dir); err != nil { + addHard("locale", lc.Locale, err.Error(), + fmt.Sprintf("语言包 %s 校验失败:%v", lc.Locale, err), + fmt.Sprintf("Locale %s validation failed: %v", lc.Locale, err)) + } + } + } + } + + // 8. Build plain-language capability explanations & L3 native boundary notice (§7.2). + rep.Capabilities = buildCapabilityItems(m, rep.Tier, rep.Executables, netScriptHits) + if rep.Tier == TierL3 { + rep.NativeExecNotice = LocalizedText{ + ZhCN: "此插件包含原生可执行程序(L3 Sidecar),启动后将以当前 Windows 账户完整权限运行。静态扫描只能核对清单完整性与哈希,无法证明原生二进制内部行为安全,请务必核对作者来源与 SHA-256。", + EnUS: "This plugin ships a native executable (L3 Sidecar) that runs with full current Windows user privileges. Static scanning verifies manifest integrity and hashes only and cannot prove native binary safety; verify publisher provenance and SHA-256 before enabling.", + } + } + rep.NeedsApproval = computeNeedsApproval(m, rep.Trust, nil, "", firstDeclaredExecHash(rep.Executables)) + + finalizeScanReport(&rep) + return rep +} + +func finalizeScanReport(rep *ScanReport) { + rep.HardBlocked = len(rep.HardFindings) > 0 + rep.Passed = !rep.HardBlocked + if rep.HardBlocked { + rep.Headline = LocalizedText{ + ZhCN: fmt.Sprintf("拦截:发现 %d 项硬性安全/合规违规,拒绝安装", len(rep.HardFindings)), + EnUS: fmt.Sprintf("Blocked: %d hard security/policy violation(s) found; installation refused", len(rep.HardFindings)), + } + return + } + highCount := 0 + for _, c := range rep.Capabilities { + if c.Level == PermHigh { + highCount++ + } + } + if rep.Tier == TierL3 || highCount > 0 { + rep.Headline = LocalizedText{ + ZhCN: fmt.Sprintf("通过静态准入,包含 %d 项高危能力,启用前需人工确认", maxInt(highCount, 1)), + EnUS: fmt.Sprintf("Passed static gate with %d high-risk capability item(s); explicit user approval required", maxInt(highCount, 1)), + } + return + } + if len(rep.PendingFindings) > 0 { + rep.Headline = LocalizedText{ + ZhCN: fmt.Sprintf("通过静态准入(%d 项提示信息)", len(rep.PendingFindings)), + EnUS: fmt.Sprintf("Passed static gate (%d advisory note(s))", len(rep.PendingFindings)), + } + return + } + rep.Headline = LocalizedText{ + ZhCN: "通过全部静态准入检查", + EnUS: "Passed all static gate checks", + } +} + +// ToDoctorFindings converts a ScanReport into backward-compatible DoctorFinding +// entries so `DoctorDirectory` and existing callers/tests share one engine. +func (r ScanReport) ToDoctorFindings() []DoctorFinding { + var out []DoctorFinding + hasManifestErr := false + hasRedlineErr := false + hasChecksumIssue := false + for _, f := range r.HardFindings { + if f.Check == "manifest" { + hasManifestErr = true + } + if f.Check == "redline" { + hasRedlineErr = true + } + if f.Check == "checksum" { + hasChecksumIssue = true + } + out = append(out, DoctorFinding{ + Severity: "error", + Check: f.Check, + Message: f.Message, + }) + } + for _, f := range r.PendingFindings { + if f.Check == "checksum" { + hasChecksumIssue = true + } + if f.Check == "trust-unsigned" { + // Keep doctor warn signal focused on actionable package hygiene. + continue + } + out = append(out, DoctorFinding{ + Severity: "warn", + Check: f.Check, + Message: f.Message, + }) + } + if !hasManifestErr && r.PluginID != "" { + out = append([]DoctorFinding{{ + Severity: "ok", + Check: "manifest", + Message: fmt.Sprintf("valid manifest %s@%s (tier=%s)", r.PluginID, r.Version, r.Tier), + }}, out...) + } + if !hasRedlineErr && r.PluginID != "" { + out = append(out, DoctorFinding{ + Severity: "ok", + Check: "redline", + Message: "no forbidden proprietary or secret files detected", + }) + } + if !hasChecksumIssue && r.PluginID != "" { + out = append(out, DoctorFinding{ + Severity: "ok", + Check: "checksum", + Message: "SHA256SUMS verified", + }) + } + return out +} + +// SummaryText renders the three-section human-readable risk report for CLI output +// or logs: (1) Hard Blockers, (2) Capabilities & Privileges, (3) Advisories & Binaries. +func (r ScanReport) SummaryText(locale string) string { + isZh := strings.HasPrefix(strings.ToLower(locale), "zh") + var b strings.Builder + title := r.PluginID + if r.Version != "" { + title += "@" + r.Version + } + if title != "" { + fmt.Fprintf(&b, "%s [tier=%s trust=%s]\n", title, r.Tier, r.Trust) + } + fmt.Fprintf(&b, "%s\n", r.Headline.Get(locale)) + + if len(r.HardFindings) > 0 { + if isZh { + b.WriteString("\n[1] 硬性拦截项(必须修复,禁止安装):\n") + } else { + b.WriteString("\n[1] Hard Blockers (must fix; installation refused):\n") + } + for _, f := range r.HardFindings { + msg := f.Localized.Get(locale) + if msg == "" { + msg = f.Message + } + if f.Target != "" { + fmt.Fprintf(&b, " - [%s] %s: %s\n", f.Check, f.Target, msg) + } else { + fmt.Fprintf(&b, " - [%s] %s\n", f.Check, msg) + } + } + } + + if r.NativeExecNotice.HasAny() || len(r.Capabilities) > 0 { + if isZh { + b.WriteString("\n[2] 能力与权限说明:\n") + } else { + b.WriteString("\n[2] Capabilities & Privileges:\n") + } + if r.NativeExecNotice.HasAny() { + fmt.Fprintf(&b, " ! %s\n", r.NativeExecNotice.Get(locale)) + } + for _, capItem := range r.Capabilities { + fmt.Fprintf(&b, " - [%s] %s (%s): %s\n", + strings.ToUpper(string(capItem.Level)), + capItem.Title.Get(locale), + capItem.ID, + capItem.Summary.Get(locale)) + for _, ex := range capItem.Examples { + fmt.Fprintf(&b, " · %s\n", ex) + } + if capItem.ExtraCount > 0 { + if isZh { + fmt.Fprintf(&b, " · …另有 %d 项已折叠\n", capItem.ExtraCount) + } else { + fmt.Fprintf(&b, " · ...and %d more\n", capItem.ExtraCount) + } + } + } + } + + if len(r.PendingFindings) > 0 || len(r.Executables) > 0 { + if isZh { + b.WriteString("\n[3] 提示信息与可执行文件清单:\n") + } else { + b.WriteString("\n[3] Advisories & Executables:\n") + } + for _, f := range r.PendingFindings { + msg := f.Localized.Get(locale) + if msg == "" { + msg = f.Message + } + fmt.Fprintf(&b, " - [%s] %s\n", f.Check, msg) + } + for _, ex := range r.Executables { + tag := "declared" + if !ex.Declared { + tag = "UNLISTED" + } + fmt.Fprintf(&b, " - [%s] %s sha256=%s\n", tag, ex.Path, ex.SHA256) + } + } + + return strings.TrimRight(b.String(), "\n") +} + +func scanSVGActiveContent(text string) string { + switch { + case reSVGScriptTag.MatchString(text): + return "`), 0o644) + + rep := plugin.ScanDirectory(dir, "0.2.8", plugin.ScanOptions{}) + if !rep.HardBlocked { + t.Fatal("expected SVG with