Files
Reims-Go/internal/plugin/scanner.go
T
千川白浪 781f129fc1 feat(plugin): custom SVG icons, market stats, submit link, and native locale scaffold (#170)
* feat(plugin): custom SVG icons, market stats, submit link, and native locale scaffold

* chore(ci): allow spaces in PR model names and rename agent declaration to tool

* fix(plugin): validate icon.svg size and markup during static scan
2026-12-04 22:34:12 +08:00

1046 lines
37 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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. `<DataRoot>/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
}
// packageScan is one ScanDirectory run.
type packageScan struct {
dir string
opts ScanOptions
m Manifest
rep ScanReport
sidecar string // declared entries, normalized
panelDir string
runtimeDirs []string
hasNetPerm bool
themeCSS map[string]bool // stylesheets checked with their theme
netScripts []string // scripts that use a declared net permission
}
func (s *packageScan) hard(check, target, msg string, zh, en string) {
s.rep.HardFindings = append(s.rep.HardFindings, ScanFinding{
Severity: ScanSeverityHard,
Check: check,
Target: target,
Message: msg,
Localized: LocalizedText{ZhCN: zh, EnUS: en},
})
}
func (s *packageScan) pending(check, target, msg string, zh, en string) {
s.rep.PendingFindings = append(s.rep.PendingFindings, ScanFinding{
Severity: ScanSeverityPending,
Check: check,
Target: target,
Message: msg,
Localized: LocalizedText{ZhCN: zh, EnUS: en},
})
}
// 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 {
s := &packageScan{dir: dir, opts: opts, rep: ScanReport{Trust: TrustCommunity}, themeCSS: map[string]bool{}}
raw, err := os.ReadFile(filepath.Join(s.dir, "plugin.json"))
if err != nil {
s.hard("manifest", "plugin.json", "cannot read plugin.json: "+err.Error(),
"缺少或无法读取 plugin.json 清单文件",
"Cannot read plugin.json manifest")
finalizeScanReport(&s.rep)
return s.rep
}
if err := json.Unmarshal(raw, &s.m); err != nil {
s.hard("manifest", "plugin.json", "invalid plugin.json JSON: "+err.Error(),
"plugin.json 格式无效:"+err.Error(),
"Invalid plugin.json JSON: "+err.Error())
finalizeScanReport(&s.rep)
return s.rep
}
s.rep.PluginID = s.m.ID
s.rep.Version = s.m.Version
s.rep.Name = s.m.Name
s.rep.Tier = s.m.InferTier(false)
s.rep.Publisher = s.m.Publisher
s.rep.License = s.m.License
if err := ValidateManifest(s.m, hostVersion, false); err != nil {
s.hard("manifest", "plugin.json", err.Error(),
"清单校验未通过:"+err.Error(),
"Manifest validation failed: "+err.Error())
}
s.rep.PendingFindings = append(s.rep.PendingFindings, ContractFindings(s.m, raw)...)
// Build normalized sets of declared entries & runtime directories.
s.sidecar = normalizeRel(s.m.Entry.Sidecar)
s.panelDir = normalizeRel(s.m.Entry.PanelDir)
for _, rtPack := range s.m.Contributes.Runtimes {
if d := normalizeRel(rtPack.Dir); d != "" {
s.runtimeDirs = append(s.runtimeDirs, d)
}
}
for _, p := range s.m.Permissions {
if strings.HasPrefix(strings.TrimSpace(p), "net:") {
s.hasNetPerm = true
break
}
}
s.checkEntries()
s.checkThemes()
s.checkFiles()
s.checkChecksums()
s.checkLocales()
// Build plain-language capability explanations & L3 native boundary notice (§7.2).
s.rep.Capabilities = buildCapabilityItems(s.m, s.rep.Tier, s.rep.Executables, s.netScripts)
if s.rep.Tier == TierL3 {
s.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.",
}
}
_, _, entryHash, _ := resolveManifestEntry(s.m, s.dir, false)
s.rep.NeedsApproval = computeNeedsApproval(s.m, s.rep.Trust, nil, "", entryHash)
finalizeScanReport(&s.rep)
return s.rep
}
// checkEntries verifies that the declared entries exist on disk.
func (s *packageScan) checkEntries() {
checkEntryFile := func(label, rel string, expectDir bool) {
if strings.TrimSpace(rel) == "" {
return
}
full, jErr := safeJoin(s.dir, rel)
if jErr != nil {
s.hard("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 {
s.hard("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() {
s.hard("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() {
s.hard("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))
}
}
if s.m.Icon != nil && strings.TrimSpace(s.m.Icon.SVG) != "" && !IsInlineSVG(s.m.Icon.SVG) {
rel := s.m.Icon.SVG
checkEntryFile("icon.svg", rel, false)
if full, jErr := safeJoin(s.dir, rel); jErr == nil {
if st, sErr := os.Stat(full); sErr == nil && !st.IsDir() {
if st.Size() > maxPluginIconSVGBytes {
s.hard("invalid-icon", rel, fmt.Sprintf("icon.svg exceeds %d bytes (%d bytes)", maxPluginIconSVGBytes, st.Size()),
fmt.Sprintf("插件图标 %s 超过 %d 字节上限", rel, maxPluginIconSVGBytes),
fmt.Sprintf("Plugin icon %q exceeds the %d-byte limit", rel, maxPluginIconSVGBytes))
} else if data, rErr := os.ReadFile(full); rErr != nil {
s.hard("invalid-icon", rel, fmt.Sprintf("failed to read icon.svg: %v", rErr),
fmt.Sprintf("无法读取插件图标 %s:%v", rel, rErr),
fmt.Sprintf("Failed to read plugin icon %q: %v", rel, rErr))
} else if _, vErr := SanitizePluginIconSVG(data); vErr != nil {
s.hard("invalid-icon", rel, fmt.Sprintf("invalid icon.svg: %v", vErr),
fmt.Sprintf("插件图标 %s 格式无效:%v", rel, vErr),
fmt.Sprintf("Plugin icon %q is invalid: %v", rel, vErr))
}
}
}
}
checkEntryFile("entry.sidecar", s.m.Entry.Sidecar, false)
checkEntryFile("entry.script", s.m.Entry.Script, false)
checkEntryFile("entry.uiScript", s.m.Entry.UIScript, false)
checkEntryFile("entry.panelDir", s.m.Entry.PanelDir, true)
for _, us := range s.m.Contributes.UIScripts {
checkEntryFile("contributes.uiScripts", us.Script, false)
}
for _, panel := range s.m.Contributes.Panels {
if s.panelDir != "" && panel.Entry != "" {
checkEntryFile("panel entry", s.panelDir+"/"+strings.TrimPrefix(panel.Entry, "/"), false)
}
}
}
func (s *packageScan) checkThemes() {
for _, th := range s.m.Contributes.Themes {
if th.Stylesheet != "" {
s.themeCSS[normalizeRel(th.Stylesheet)] = true
}
if err := ValidateThemeContribution(th, s.dir); err != nil {
s.hard("theme-css", th.Stylesheet, err.Error(),
"主题样式或资源未通过安全校验:"+err.Error(),
"Theme stylesheet or asset failed safety validation: "+err.Error())
}
if th.Stylesheet != "" && s.opts.Contract != nil {
if cssPath, jErr := safeJoin(s.dir, th.Stylesheet); jErr == nil {
if cssBytes, rErr := os.ReadFile(cssPath); rErr == nil {
for _, issue := range CheckCSSAgainstContract(string(cssBytes), *s.opts.Contract) {
s.pending("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))
}
}
}
}
}
}
func (s *packageScan) checkFiles() {
var walkFiles []string
_ = filepath.Walk(s.dir, func(p string, info os.FileInfo, wErr error) error {
if wErr != nil || info == nil || info.IsDir() {
return nil
}
rel, rErr := filepath.Rel(s.dir, p)
if rErr != nil {
return nil
}
walkFiles = append(walkFiles, filepath.ToSlash(rel))
return nil
})
sort.Strings(walkFiles)
for _, rel := range walkFiles {
s.checkFile(rel)
}
}
// checkFile looks for redlines, executables, SVG scripts, and unsafe CSS and JS.
func (s *packageScan) checkFile(rel string) {
full := filepath.Join(s.dir, filepath.FromSlash(rel))
info, sErr := os.Stat(full)
if sErr != nil || info.IsDir() {
return
}
lowName := strings.ToLower(info.Name())
ext := strings.ToLower(filepath.Ext(lowName))
for _, pat := range ForbiddenMarketPatterns {
if strings.Contains(lowName, pat) {
s.hard("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))) {
s.hard("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))
}
}
}
if ForbiddenBinaryExtensions[ext] {
sum, _ := fileSHA256Hex(full)
declared := false
switch s.rep.Tier {
case TierL3:
if s.sidecar != "" && strings.EqualFold(rel, s.sidecar) {
declared = true
}
case TierRuntime:
for _, rd := range s.runtimeDirs {
if rel == rd || strings.HasPrefix(strings.ToLower(rel), strings.ToLower(rd)+"/") {
declared = true
break
}
}
}
s.rep.Executables = append(s.rep.Executables, ExecutableFile{
Path: rel,
SHA256: sum,
Declared: declared,
SizeBytes: info.Size(),
})
if !declared {
if s.rep.Tier == TierL3 || s.rep.Tier == TierRuntime {
s.hard("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 {
s.hard("forbidden-binary", rel,
fmt.Sprintf("executable or OS script %q is forbidden in %s plugin packages", rel, s.rep.Tier),
fmt.Sprintf("%s 类型插件禁止夹带可执行文件或系统脚本:%s", s.rep.Tier, rel),
fmt.Sprintf("Executable or OS script %q is forbidden in %s packages", rel, s.rep.Tier))
}
}
}
if ext == ".svg" && info.Size() <= maxScanTextBytes {
if b, rErr := os.ReadFile(full); rErr == nil {
if reason := scanSVGActiveContent(string(b)); reason != "" {
s.hard("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))
}
}
}
if ext == ".css" && !s.themeCSS[rel] && !inRelDir(rel, s.panelDir) && info.Size() <= maxScanTextBytes {
if b, rErr := os.ReadFile(full); rErr == nil {
if err := ValidateThemeCSSSafety(string(b), filepath.Dir(full)); err != nil {
s.hard("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))
}
}
}
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 {
s.hard("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 !s.hasNetPerm {
s.hard("ui-script-undeclared-net", rel,
fmt.Sprintf("script %s calls network APIs without declaring any net:<host> permission", rel),
fmt.Sprintf("脚本 %s 调用了网络接口,但清单未声明 net:<host> 权限", rel),
fmt.Sprintf("Script %s calls network APIs without declaring any net:<host> permission", rel))
} else {
s.netScripts = append(s.netScripts, rel)
}
}
}
}
if (ext == ".html" || ext == ".htm") && inRelDir(rel, s.panelDir) && info.Size() <= maxScanTextBytes {
if b, rErr := os.ReadFile(full); rErr == nil {
hits, _ := scanScriptContent(string(b), true)
for _, hit := range hits {
s.hard("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))
}
}
}
}
func (s *packageScan) checkChecksums() {
sumsPath := filepath.Join(s.dir, "SHA256SUMS")
if sumsRaw, sErr := os.ReadFile(sumsPath); sErr == nil {
if err := verifyDirSHA256Sums(s.dir, sumsRaw); err != nil {
s.hard("checksum", "SHA256SUMS", err.Error(),
"SHA256SUMS 完整性校验失败:"+err.Error(),
"SHA256SUMS integrity verification failed: "+err.Error())
}
if sigRaw, sigErr := os.ReadFile(filepath.Join(s.dir, "SHA256SUMS.sig")); sigErr == nil {
if len(s.opts.Keyring) > 0 {
t, vErr := verifyEd25519Signature(sumsRaw, sigRaw, s.opts.Keyring)
if vErr != nil {
s.hard("signature", "SHA256SUMS.sig", "invalid package signature: "+vErr.Error(),
"插件签名验证失败:"+vErr.Error(),
"Plugin signature verification failed: "+vErr.Error())
} else {
s.rep.Trust = t
}
}
}
} else if s.opts.RequireChecksums {
s.hard("checksum", "SHA256SUMS", "package missing SHA256SUMS",
"分发压缩包缺少必需的 SHA256SUMS 校验文件",
"Distribution package is missing required SHA256SUMS file")
} else {
s.pending("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 s.rep.Trust == TrustCommunity {
s.pending("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")
}
}
func (s *packageScan) checkLocales() {
if strings.TrimSpace(s.m.L10n) != "" {
if err := validatePluginL10nDir(s.m.L10n, s.dir); err != nil {
s.hard("l10n", s.m.L10n, err.Error(),
"插件本地化目录校验失败:"+err.Error(),
"Plugin l10n directory validation failed: "+err.Error())
}
}
if len(s.m.Contributes.Locales) > 0 {
if _, locFindings, cErr := CheckLocalePack(s.dir); cErr == nil && len(locFindings) > 0 {
for _, lf := range locFindings {
if lf.Severity == "error" {
s.hard("locale", lf.Check, lf.Message,
"语言包校验错误:"+lf.Message,
"Language pack validation error: "+lf.Message)
} else if lf.Severity == "warn" {
s.pending("locale", lf.Check, lf.Message,
"语言包提示:"+lf.Message,
"Language pack advisory: "+lf.Message)
}
}
} else {
for _, lc := range s.m.Contributes.Locales {
if err := ValidateLocaleContribution(lc, s.dir); err != nil {
s.hard("locale", lc.Locale, err.Error(),
fmt.Sprintf("语言包 %s 校验失败:%v", lc.Locale, err),
fmt.Sprintf("Locale %s validation failed: %v", lc.Locale, err))
}
}
}
}
}
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 lists a ScanReport's results the way `plugin doctor` prints them.
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 "<script> tag"
case reSVGEventAttr.MatchString(text):
return "inline on* event handler"
case reSVGJavascriptURI.MatchString(text):
return "javascript: URI"
case reSVGForeignObject.MatchString(text):
return "<foreignObject> element"
default:
return ""
}
}
func scanScriptContent(text string, htmlMode bool) (hardHits []string, hasNetwork bool) {
seen := map[string]bool{}
add := func(label string) {
if !seen[label] {
seen[label] = true
hardHits = append(hardHits, label)
}
}
if reJSWailsGo.MatchString(text) {
add("window.go host bridge access")
}
if reJSWailsRuntime.MatchString(text) {
add("window.runtime host bridge access")
}
if !htmlMode {
if reJSEval.MatchString(text) {
add("eval()")
}
if reJSNewFunction.MatchString(text) || reJSFunctionCall.MatchString(text) {
add("Function() dynamic code execution")
}
if reJSDocCookie.MatchString(text) {
add("document.cookie access")
}
if reJSDocWrite.MatchString(text) {
add("document.write()")
}
if reJSScriptTag.MatchString(text) || reJSCreateScript.MatchString(text) {
add("dynamic <script> injection")
}
if reJSNetworkCall.MatchString(text) {
hasNetwork = true
}
}
return hardHits, hasNetwork
}
func buildCapabilityItems(m Manifest, tier Tier, execs []ExecutableFile, netHits []string) []CapabilityItem {
var items []CapabilityItem
if tier == TierL3 {
var exList []string
for _, e := range execs {
if e.Declared {
short := e.SHA256
if len(short) > 16 {
short = short[:16] + "…"
}
exList = append(exList, fmt.Sprintf("%s (sha256: %s)", e.Path, short))
}
}
capped, extra := capExamples(exList, maxCapExamples)
items = append(items, CapabilityItem{
ID: "native:sidecar",
Level: PermHigh,
Title: LocalizedText{
ZhCN: "原生可执行程序(完整系统账户权限)",
EnUS: "Native executable (full Windows user privileges)",
},
Summary: LocalizedText{
ZhCN: "以独立子进程直接运行原生二进制,拥有当前 Windows 账户的全部本地文件与网络权限。",
EnUS: "Runs a native binary process with all local file and network privileges of your Windows user account.",
},
Examples: capped,
ExtraCount: extra,
})
}
uiScriptPaths := collectUIScriptPaths(m)
for _, rawPerm := range m.Permissions {
perm := strings.TrimSpace(rawPerm)
if perm == "" {
continue
}
lvl := ClassifyPermission(perm)
if lvl == PermForbidden {
continue
}
title, summary := describePermission(perm)
var examples []string
switch {
case perm == "ui:script":
examples = uiScriptPaths
case strings.HasPrefix(perm, "net:"):
examples = append(examples, strings.TrimPrefix(perm, "net:"))
examples = append(examples, netHits...)
case perm == "driver:vm":
for _, d := range m.Contributes.GuestDrivers {
examples = append(examples, d.ID)
}
case perm == "runtime:provider":
for _, rk := range m.Contributes.RuntimeKinds {
examples = append(examples, rk.Kind)
}
case perm == "runtime:source":
for _, rs := range m.Contributes.RuntimeSources {
examples = append(examples, rs.IndexURL)
}
}
capped, extra := capExamples(examples, maxCapExamples)
items = append(items, CapabilityItem{
ID: perm,
Level: lvl,
Title: title,
Summary: summary,
Examples: capped,
ExtraCount: extra,
})
}
sort.SliceStable(items, func(i, j int) bool {
return permRank(items[i].Level) > permRank(items[j].Level)
})
return items
}
func describePermission(perm string) (LocalizedText, LocalizedText) {
if strings.HasPrefix(perm, "net:") {
host := strings.TrimPrefix(perm, "net:")
return LocalizedText{
ZhCN: "访问指定网络主机",
EnUS: "Access declared network host",
}, LocalizedText{
ZhCN: fmt.Sprintf("允许向 %s 发起网络请求。", host),
EnUS: fmt.Sprintf("Allows outbound network requests to %s.", host),
}
}
switch perm {
case "ui:script":
return LocalizedText{ZhCN: "运行交互主题脚本", EnUS: "Run interactive theme script"},
LocalizedText{
ZhCN: "在主窗口前端环境中运行交互脚本并访问界面 DOM(非隔离沙盒),启用前务必核对来源与脚本哈希。",
EnUS: "Runs frontend JavaScript in the main window with DOM access (not an isolated sandbox); verify publisher and script hash before enabling.",
}
case "driver:vm":
return LocalizedText{ZhCN: "提供虚拟机客体驱动", EnUS: "Provide VM guest driver"},
LocalizedText{ZhCN: "创建、配置并驱动新的虚拟机客体类型。", EnUS: "Creates, configures, and drives guest virtual machine lifecycles."}
case "runtime:provider":
return LocalizedText{ZhCN: "提供运行时类型", EnUS: "Provide runtime engine"},
LocalizedText{ZhCN: "向宿主注册新的虚拟化运行时后端。", EnUS: "Registers an additional virtualization runtime backend."}
case "process:spawn":
return LocalizedText{ZhCN: "请求启动宿主进程", EnUS: "Spawn managed host processes"},
LocalizedText{ZhCN: "通过宿主代理启动外部虚拟化进程。", EnUS: "Requests the host broker to launch external VM processes."}
case "vm:control":
return LocalizedText{ZhCN: "控制虚拟机启停", EnUS: "Control VM power state"},
LocalizedText{ZhCN: "可以启动、停止或重启你的虚拟机。", EnUS: "Can start, stop, or reboot your virtual machines."}
case "vm:screen":
return LocalizedText{ZhCN: "读取虚拟机屏幕", EnUS: "Read VM screen"},
LocalizedText{ZhCN: "可截取运行中虚拟机的屏幕内容。", EnUS: "Can capture the screen of a running virtual machine."}
case "qmp:write":
return LocalizedText{ZhCN: "向 QEMU 发送写命令", EnUS: "Send QEMU QMP write commands"},
LocalizedText{ZhCN: "可向运行中的 QEMU 虚拟机发送控制指令。", EnUS: "Can send mutating control commands to running QEMU VMs."}
case "fs:vm_dir":
return LocalizedText{ZhCN: "读写虚拟机目录", EnUS: "Read/write VM directory"},
LocalizedText{ZhCN: "可访问虚拟机配置与磁盘所在目录。", EnUS: "Can access VM configuration and disk directories."}
case "fs:shared":
return LocalizedText{ZhCN: "访问共享目录", EnUS: "Access shared folder"},
LocalizedText{ZhCN: "可访问宿主机与虚拟机之间的共享文件夹。", EnUS: "Can access host-guest shared directories."}
case "host:clipboard":
return LocalizedText{ZhCN: "读取或写入系统剪贴板", EnUS: "Read/write host clipboard"},
LocalizedText{ZhCN: "可读取或修改你的 Windows 系统剪贴板内容。", EnUS: "Can read or modify your Windows clipboard contents."}
case "vm:intent":
return LocalizedText{ZhCN: "参与虚拟机启动参数", EnUS: "Participate in VM launch intent"},
LocalizedText{ZhCN: "在虚拟机启动前声明受控的设备或启动参数建议。", EnUS: "Contributes governed launch arguments before VM startup."}
case "runtime:source":
return LocalizedText{ZhCN: "添加运行时下载源", EnUS: "Add runtime download source"},
LocalizedText{ZhCN: "为便携运行时提供额外镜像或索引地址。", EnUS: "Adds an extra mirror or index source for portable runtimes."}
case "ui:slot":
return LocalizedText{ZhCN: "扩展界面插槽", EnUS: "Extend UI slots"},
LocalizedText{ZhCN: "在宿主声明的工具栏、卡片或设置槽位添加入口。", EnUS: "Adds controls to host-declared toolbar, card, or settings slots."}
case "input:filter":
return LocalizedText{ZhCN: "过滤虚拟机输入事件", EnUS: "Filter VM input events"},
LocalizedText{ZhCN: "在虚拟机窗口前台时拦截或变换键鼠输入(如滚轮方向)。", EnUS: "Transforms mouse/keyboard input while a VM window is focused."}
case "vm:read":
return LocalizedText{ZhCN: "读取虚拟机状态", EnUS: "Read VM status"},
LocalizedText{ZhCN: "仅读取虚拟机列表与运行状态,不修改配置。", EnUS: "Reads VM list and runtime status without making changes."}
case "ui:notify":
return LocalizedText{ZhCN: "发送界面通知", EnUS: "Show UI notifications"},
LocalizedText{ZhCN: "向用户展示状态提示或通知消息。", EnUS: "Displays informational notifications to the user."}
case "task:progress":
return LocalizedText{ZhCN: "回报后台任务进度", EnUS: "Report task progress"},
LocalizedText{ZhCN: "在任务栏展示当前插件操作的进度。", EnUS: "Reports long-running operation progress in the host UI."}
case "fs:plugin_data":
return LocalizedText{ZhCN: "读写插件私有数据", EnUS: "Read/write private plugin data"},
LocalizedText{ZhCN: "仅在插件独立数据目录内保存配置与缓存。", EnUS: "Stores settings and cache strictly inside the plugin's own data folder."}
case "log:read":
return LocalizedText{ZhCN: "读取脱敏日志", EnUS: "Read redacted logs"},
LocalizedText{ZhCN: "读取经过敏感信息脱敏的虚拟机运行日志。", EnUS: "Reads VM runtime logs after sensitive field redaction."}
default:
return LocalizedText{ZhCN: perm, EnUS: perm},
LocalizedText{ZhCN: "声明权限:" + perm, EnUS: "Declared permission: " + perm}
}
}
func collectUIScriptPaths(m Manifest) []string {
seen := map[string]bool{}
var out []string
add := func(p string) {
p = normalizeRel(p)
if p != "" && !seen[p] {
seen[p] = true
out = append(out, p)
}
}
add(m.Entry.UIScript)
for _, u := range m.Contributes.UIScripts {
add(u.Script)
}
for _, th := range m.Contributes.Themes {
add(th.UIScript)
}
return out
}
func capExamples(items []string, limit int) ([]string, int) {
if len(items) == 0 {
return nil, 0
}
if len(items) <= limit {
return append([]string(nil), items...), 0
}
return append([]string(nil), items[:limit]...), len(items) - limit
}
func permRank(lvl PermissionLevel) int {
switch lvl {
case PermHigh:
return 3
case PermMedium:
return 2
case PermLow:
return 1
default:
return 0
}
}
func normalizeRel(p string) string {
p = strings.TrimSpace(p)
if p == "" {
return ""
}
p = filepath.ToSlash(filepath.Clean(p))
p = strings.TrimPrefix(p, "./")
if p == "." {
return ""
}
return p
}
func inRelDir(rel, dir string) bool {
if dir == "" {
return false
}
lr := strings.ToLower(rel)
ld := strings.ToLower(dir)
return lr == ld || strings.HasPrefix(lr, ld+"/")
}
func isRedlineTextExt(ext string) bool {
switch ext {
case ".json", ".toml", ".txt", ".md", ".yaml", ".yml", ".js", ".mjs", ".cjs", ".svg", ".html", ".htm", ".css":
return true
default:
return false
}
}
func maxInt(a, b int) int {
if a > b {
return a
}
return b
}