Files
Reims-Go/internal/plugin/scanner.go
T

1000 lines
36 KiB
Go

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
}
// ScanDirectory performs a comprehensive static risk and policy scan on a plugin
// directory (unpacked archive, installed package, or dev-linked directory).
func ScanDirectory(dir, hostVersion string, opts ScanOptions) ScanReport {
rep := ScanReport{
Trust: TrustCommunity,
}
addHard := func(check, target, msg string, zh, en string) {
rep.HardFindings = append(rep.HardFindings, ScanFinding{
Severity: ScanSeverityHard,
Check: check,
Target: target,
Message: msg,
Localized: LocalizedText{ZhCN: zh, EnUS: en},
})
}
addPending := func(check, target, msg string, zh, en string) {
rep.PendingFindings = append(rep.PendingFindings, ScanFinding{
Severity: ScanSeverityPending,
Check: check,
Target: target,
Message: msg,
Localized: LocalizedText{ZhCN: zh, EnUS: en},
})
}
raw, err := os.ReadFile(filepath.Join(dir, "plugin.json"))
if err != nil {
addHard("manifest", "plugin.json", "cannot read plugin.json: "+err.Error(),
"缺少或无法读取 plugin.json 清单文件",
"Cannot read plugin.json manifest")
finalizeScanReport(&rep)
return rep
}
var m Manifest
if err := json.Unmarshal(raw, &m); err != nil {
addHard("manifest", "plugin.json", "invalid plugin.json JSON: "+err.Error(),
"plugin.json 格式无效:"+err.Error(),
"Invalid plugin.json JSON: "+err.Error())
finalizeScanReport(&rep)
return rep
}
rep.PluginID = m.ID
rep.Version = m.Version
rep.Name = m.Name
rep.Tier = m.InferTier(false)
rep.Publisher = m.Publisher
rep.License = m.License
if err := ValidateManifest(m, hostVersion, false); err != nil {
addHard("manifest", "plugin.json", err.Error(),
"清单校验未通过:"+err.Error(),
"Manifest validation failed: "+err.Error())
}
rep.PendingFindings = append(rep.PendingFindings, ContractFindings(m, raw)...)
// Build normalized sets of declared entries & runtime directories.
declaredSidecar := normalizeRel(m.Entry.Sidecar)
declaredPanelDir := normalizeRel(m.Entry.PanelDir)
runtimeDirs := make([]string, 0, len(m.Contributes.Runtimes))
for _, rtPack := range m.Contributes.Runtimes {
if d := normalizeRel(rtPack.Dir); d != "" {
runtimeDirs = append(runtimeDirs, d)
}
}
hasNetPerm := false
for _, p := range m.Permissions {
if strings.HasPrefix(strings.TrimSpace(p), "net:") {
hasNetPerm = true
break
}
}
// Verify declared entries exist on disk.
checkEntryFile := func(label, rel string, expectDir bool) {
if strings.TrimSpace(rel) == "" {
return
}
full, jErr := safeJoin(dir, rel)
if jErr != nil {
addHard("missing-entry", rel, fmt.Sprintf("invalid %s path %q: %v", label, rel, jErr),
fmt.Sprintf("声明的入口路径 %s 非法:%v", rel, jErr),
fmt.Sprintf("Declared %s path %q is invalid: %v", label, rel, jErr))
return
}
st, sErr := os.Stat(full)
if sErr != nil {
addHard("missing-entry", rel, fmt.Sprintf("declared %s %q is missing", label, rel),
fmt.Sprintf("清单声明的入口 %s 不存在", rel),
fmt.Sprintf("Declared %s %q is missing from package", label, rel))
return
}
if expectDir && !st.IsDir() {
addHard("missing-entry", rel, fmt.Sprintf("declared %s %q is not a directory", label, rel),
fmt.Sprintf("清单声明的目录入口 %s 不是目录", rel),
fmt.Sprintf("Declared %s %q is not a directory", label, rel))
} else if !expectDir && st.IsDir() {
addHard("missing-entry", rel, fmt.Sprintf("declared %s %q is a directory, expected file", label, rel),
fmt.Sprintf("清单声明的文件入口 %s 是目录而非文件", rel),
fmt.Sprintf("Declared %s %q is a directory, expected a file", label, rel))
}
}
checkEntryFile("entry.sidecar", m.Entry.Sidecar, false)
checkEntryFile("entry.script", m.Entry.Script, false)
checkEntryFile("entry.uiScript", m.Entry.UIScript, false)
checkEntryFile("entry.panelDir", m.Entry.PanelDir, true)
for _, us := range m.Contributes.UIScripts {
checkEntryFile("contributes.uiScripts", us.Script, false)
}
for _, panel := range m.Contributes.Panels {
if declaredPanelDir != "" && panel.Entry != "" {
checkEntryFile("panel entry", declaredPanelDir+"/"+strings.TrimPrefix(panel.Entry, "/"), false)
}
}
// Track theme stylesheets so we don't duplicate CSS checks in the directory walk.
declaredThemeCSS := map[string]bool{}
for _, th := range m.Contributes.Themes {
if th.Stylesheet != "" {
declaredThemeCSS[normalizeRel(th.Stylesheet)] = true
}
if err := ValidateThemeContribution(th, dir); err != nil {
addHard("theme-css", th.Stylesheet, err.Error(),
"主题样式或资源未通过安全校验:"+err.Error(),
"Theme stylesheet or asset failed safety validation: "+err.Error())
}
if th.Stylesheet != "" && opts.Contract != nil {
if cssPath, jErr := safeJoin(dir, th.Stylesheet); jErr == nil {
if cssBytes, rErr := os.ReadFile(cssPath); rErr == nil {
for _, issue := range CheckCSSAgainstContract(string(cssBytes), *opts.Contract) {
addPending("ui-contract", th.Stylesheet, issue,
fmt.Sprintf("主题样式 %s 存在 UI 契约提示:%s", th.Stylesheet, issue),
fmt.Sprintf("Theme CSS %s UI contract advisory: %s", th.Stylesheet, issue))
}
}
}
}
}
// Walk all files in the package for redlines, executables, SVG scripts, CSS, and JS safety.
var netScriptHits []string
var walkFiles []string
_ = filepath.Walk(dir, func(p string, info os.FileInfo, wErr error) error {
if wErr != nil || info == nil || info.IsDir() {
return nil
}
rel, rErr := filepath.Rel(dir, p)
if rErr != nil {
return nil
}
walkFiles = append(walkFiles, filepath.ToSlash(rel))
return nil
})
sort.Strings(walkFiles)
for _, rel := range walkFiles {
full := filepath.Join(dir, filepath.FromSlash(rel))
info, sErr := os.Stat(full)
if sErr != nil || info.IsDir() {
continue
}
lowName := strings.ToLower(info.Name())
ext := strings.ToLower(filepath.Ext(lowName))
for _, pat := range ForbiddenMarketPatterns {
if strings.Contains(lowName, pat) {
addHard("redline", rel, fmt.Sprintf("forbidden proprietary file detected (%s)", rel),
fmt.Sprintf("检测到禁止分发的专有系统文件:%s", rel),
fmt.Sprintf("Forbidden proprietary file detected: %s", rel))
}
}
if info.Size() <= 256*1024 && isRedlineTextExt(ext) {
if b, rErr := os.ReadFile(full); rErr == nil {
if containsForbiddenSMCKey(strings.ToLower(string(b))) {
addHard("redline", rel, fmt.Sprintf("forbidden Apple SMC OSK detected in %s", rel),
fmt.Sprintf("在 %s 中检测到禁止分发的 Apple SMC OSK 密钥", rel),
fmt.Sprintf("Forbidden Apple SMC OSK detected in %s", rel))
}
}
}
if ForbiddenBinaryExtensions[ext] {
sum, _ := fileSHA256Hex(full)
declared := false
switch rep.Tier {
case TierL3:
if declaredSidecar != "" && strings.EqualFold(rel, declaredSidecar) {
declared = true
}
case TierRuntime:
for _, rd := range runtimeDirs {
if rel == rd || strings.HasPrefix(strings.ToLower(rel), strings.ToLower(rd)+"/") {
declared = true
break
}
}
}
rep.Executables = append(rep.Executables, ExecutableFile{
Path: rel,
SHA256: sum,
Declared: declared,
SizeBytes: info.Size(),
})
if !declared {
if rep.Tier == TierL3 || rep.Tier == TierRuntime {
addHard("unlisted-executable", rel,
fmt.Sprintf("unlisted executable or script %q not declared in manifest", rel),
fmt.Sprintf("包含未在清单中声明的可执行文件或脚本:%s", rel),
fmt.Sprintf("Unlisted executable or script not declared in manifest: %s", rel))
} else {
addHard("forbidden-binary", rel,
fmt.Sprintf("executable or OS script %q is forbidden in %s plugin packages", rel, rep.Tier),
fmt.Sprintf("%s 类型插件禁止夹带可执行文件或系统脚本:%s", rep.Tier, rel),
fmt.Sprintf("Executable or OS script %q is forbidden in %s packages", rel, rep.Tier))
}
}
}
if ext == ".svg" && info.Size() <= maxScanTextBytes {
if b, rErr := os.ReadFile(full); rErr == nil {
if reason := scanSVGActiveContent(string(b)); reason != "" {
addHard("svg-script", rel, fmt.Sprintf("unsafe active content in SVG %s: %s", rel, reason),
fmt.Sprintf("SVG 文件 %s 包含被禁止的脚本或事件属性(%s)", rel, reason),
fmt.Sprintf("SVG file %s contains forbidden active content (%s)", rel, reason))
}
}
}
if ext == ".css" && !declaredThemeCSS[rel] && !inRelDir(rel, declaredPanelDir) && info.Size() <= maxScanTextBytes {
if b, rErr := os.ReadFile(full); rErr == nil {
if err := ValidateThemeCSSSafetyInDir(string(b), filepath.Dir(full)); err != nil {
addHard("theme-css", rel, fmt.Sprintf("unsafe CSS %s: %v", rel, err),
fmt.Sprintf("样式文件 %s 未通过安全校验:%v", rel, err),
fmt.Sprintf("Stylesheet %s failed safety check: %v", rel, err))
}
}
}
if (ext == ".js" || ext == ".mjs" || ext == ".cjs") && info.Size() <= maxScanTextBytes {
if b, rErr := os.ReadFile(full); rErr == nil {
hits, hasNet := scanScriptContent(string(b), false)
for _, hit := range hits {
addHard("ui-script", rel, fmt.Sprintf("forbidden JS pattern (%s) in %s", hit, rel),
fmt.Sprintf("脚本 %s 包含被禁止的宿主逃逸或动态执行语句(%s)", rel, hit),
fmt.Sprintf("Script %s contains forbidden host-escape or dynamic-eval pattern (%s)", rel, hit))
}
if hasNet {
if !hasNetPerm {
addHard("ui-script-undeclared-net", rel,
fmt.Sprintf("script %s calls network APIs without declaring any net:<host> permission", rel),
fmt.Sprintf("脚本 %s 调用了网络接口,但清单未声明 net:<host> 权限", rel),
fmt.Sprintf("Script %s calls network APIs without declaring any net:<host> permission", rel))
} else {
netScriptHits = append(netScriptHits, rel)
}
}
}
}
if (ext == ".html" || ext == ".htm") && inRelDir(rel, declaredPanelDir) && info.Size() <= maxScanTextBytes {
if b, rErr := os.ReadFile(full); rErr == nil {
hits, _ := scanScriptContent(string(b), true)
for _, hit := range hits {
addHard("panel-html", rel, fmt.Sprintf("forbidden host-escape pattern (%s) in panel %s", hit, rel),
fmt.Sprintf("面板页面 %s 包含被禁止的宿主逃逸语句(%s)", rel, hit),
fmt.Sprintf("Panel HTML %s contains forbidden host-escape pattern (%s)", rel, hit))
}
}
}
}
sumsPath := filepath.Join(dir, "SHA256SUMS")
if sumsRaw, sErr := os.ReadFile(sumsPath); sErr == nil {
if err := verifyDirSHA256Sums(dir, sumsRaw); err != nil {
addHard("checksum", "SHA256SUMS", err.Error(),
"SHA256SUMS 完整性校验失败:"+err.Error(),
"SHA256SUMS integrity verification failed: "+err.Error())
}
if sigRaw, sigErr := os.ReadFile(filepath.Join(dir, "SHA256SUMS.sig")); sigErr == nil {
if len(opts.Keyring) > 0 {
t, vErr := verifyEd25519Signature(sumsRaw, sigRaw, opts.Keyring)
if vErr != nil {
addHard("signature", "SHA256SUMS.sig", "invalid package signature: "+vErr.Error(),
"插件签名验证失败:"+vErr.Error(),
"Plugin signature verification failed: "+vErr.Error())
} else {
rep.Trust = t
}
}
}
} else if opts.RequireChecksums {
addHard("checksum", "SHA256SUMS", "package missing SHA256SUMS",
"分发压缩包缺少必需的 SHA256SUMS 校验文件",
"Distribution package is missing required SHA256SUMS file")
} else {
addPending("checksum", "SHA256SUMS", "SHA256SUMS absent (acceptable in dev link mode; required for .zip distribution)",
"未包含 SHA256SUMS(本地开发链接可忽略,打包分发 .zip 时必需)",
"SHA256SUMS absent (acceptable in dev link mode; required for .zip distribution)")
}
if rep.Trust == TrustCommunity {
addPending("trust-unsigned", "", "community package is not signed by an official or verified market key",
"社区插件未携带官方或已审核签名,请仅安装来自可信作者的插件包",
"Community package is not signed by an official or verified key; install only from authors you trust")
}
// 7. L10n & Locale contributions.
if strings.TrimSpace(m.L10n) != "" {
if err := validatePluginL10nDir(m.L10n, dir); err != nil {
addHard("l10n", m.L10n, err.Error(),
"插件本地化目录校验失败:"+err.Error(),
"Plugin l10n directory validation failed: "+err.Error())
}
}
if len(m.Contributes.Locales) > 0 {
if _, locFindings, cErr := CheckLocalePack(dir); cErr == nil && len(locFindings) > 0 {
for _, lf := range locFindings {
if lf.Severity == "error" {
addHard("locale", lf.Check, lf.Message,
"语言包校验错误:"+lf.Message,
"Language pack validation error: "+lf.Message)
} else if lf.Severity == "warn" {
addPending("locale", lf.Check, lf.Message,
"语言包提示:"+lf.Message,
"Language pack advisory: "+lf.Message)
}
}
} else {
for _, lc := range m.Contributes.Locales {
if err := ValidateLocaleContribution(lc, dir); err != nil {
addHard("locale", lc.Locale, err.Error(),
fmt.Sprintf("语言包 %s 校验失败:%v", lc.Locale, err),
fmt.Sprintf("Locale %s validation failed: %v", lc.Locale, err))
}
}
}
}
// 8. Build plain-language capability explanations & L3 native boundary notice (§7.2).
rep.Capabilities = buildCapabilityItems(m, rep.Tier, rep.Executables, netScriptHits)
if rep.Tier == TierL3 {
rep.NativeExecNotice = LocalizedText{
ZhCN: "此插件包含原生可执行程序(L3 Sidecar),启动后将以当前 Windows 账户完整权限运行。静态扫描只能核对清单完整性与哈希,无法证明原生二进制内部行为安全,请务必核对作者来源与 SHA-256。",
EnUS: "This plugin ships a native executable (L3 Sidecar) that runs with full current Windows user privileges. Static scanning verifies manifest integrity and hashes only and cannot prove native binary safety; verify publisher provenance and SHA-256 before enabling.",
}
}
_, _, entryHash, _ := resolveManifestEntry(m, dir, false)
rep.NeedsApproval = computeNeedsApproval(m, rep.Trust, nil, "", entryHash)
finalizeScanReport(&rep)
return rep
}
func finalizeScanReport(rep *ScanReport) {
rep.HardBlocked = len(rep.HardFindings) > 0
rep.Passed = !rep.HardBlocked
if rep.HardBlocked {
rep.Headline = LocalizedText{
ZhCN: fmt.Sprintf("拦截:发现 %d 项硬性安全/合规违规,拒绝安装", len(rep.HardFindings)),
EnUS: fmt.Sprintf("Blocked: %d hard security/policy violation(s) found; installation refused", len(rep.HardFindings)),
}
return
}
highCount := 0
for _, c := range rep.Capabilities {
if c.Level == PermHigh {
highCount++
}
}
if rep.Tier == TierL3 || highCount > 0 {
rep.Headline = LocalizedText{
ZhCN: fmt.Sprintf("通过静态准入,包含 %d 项高危能力,启用前需人工确认", maxInt(highCount, 1)),
EnUS: fmt.Sprintf("Passed static gate with %d high-risk capability item(s); explicit user approval required", maxInt(highCount, 1)),
}
return
}
if len(rep.PendingFindings) > 0 {
rep.Headline = LocalizedText{
ZhCN: fmt.Sprintf("通过静态准入(%d 项提示信息)", len(rep.PendingFindings)),
EnUS: fmt.Sprintf("Passed static gate (%d advisory note(s))", len(rep.PendingFindings)),
}
return
}
rep.Headline = LocalizedText{
ZhCN: "通过全部静态准入检查",
EnUS: "Passed all static gate checks",
}
}
// ToDoctorFindings converts a ScanReport into backward-compatible DoctorFinding
// entries so `DoctorDirectory` and existing callers/tests share one engine.
func (r ScanReport) ToDoctorFindings() []DoctorFinding {
var out []DoctorFinding
hasManifestErr := false
hasRedlineErr := false
hasChecksumIssue := false
for _, f := range r.HardFindings {
if f.Check == "manifest" {
hasManifestErr = true
}
if f.Check == "redline" {
hasRedlineErr = true
}
if f.Check == "checksum" {
hasChecksumIssue = true
}
out = append(out, DoctorFinding{
Severity: "error",
Check: f.Check,
Message: f.Message,
})
}
for _, f := range r.PendingFindings {
if f.Check == "checksum" {
hasChecksumIssue = true
}
if f.Check == "trust-unsigned" {
// Keep doctor warn signal focused on actionable package hygiene.
continue
}
out = append(out, DoctorFinding{
Severity: "warn",
Check: f.Check,
Message: f.Message,
})
}
if !hasManifestErr && r.PluginID != "" {
out = append([]DoctorFinding{{
Severity: "ok",
Check: "manifest",
Message: fmt.Sprintf("valid manifest %s@%s (tier=%s)", r.PluginID, r.Version, r.Tier),
}}, out...)
}
if !hasRedlineErr && r.PluginID != "" {
out = append(out, DoctorFinding{
Severity: "ok",
Check: "redline",
Message: "no forbidden proprietary or secret files detected",
})
}
if !hasChecksumIssue && r.PluginID != "" {
out = append(out, DoctorFinding{
Severity: "ok",
Check: "checksum",
Message: "SHA256SUMS verified",
})
}
return out
}
// SummaryText renders the three-section human-readable risk report for CLI output
// or logs: (1) Hard Blockers, (2) Capabilities & Privileges, (3) Advisories & Binaries.
func (r ScanReport) SummaryText(locale string) string {
isZh := strings.HasPrefix(strings.ToLower(locale), "zh")
var b strings.Builder
title := r.PluginID
if r.Version != "" {
title += "@" + r.Version
}
if title != "" {
fmt.Fprintf(&b, "%s [tier=%s trust=%s]\n", title, r.Tier, r.Trust)
}
fmt.Fprintf(&b, "%s\n", r.Headline.Get(locale))
if len(r.HardFindings) > 0 {
if isZh {
b.WriteString("\n[1] 硬性拦截项(必须修复,禁止安装):\n")
} else {
b.WriteString("\n[1] Hard Blockers (must fix; installation refused):\n")
}
for _, f := range r.HardFindings {
msg := f.Localized.Get(locale)
if msg == "" {
msg = f.Message
}
if f.Target != "" {
fmt.Fprintf(&b, " - [%s] %s: %s\n", f.Check, f.Target, msg)
} else {
fmt.Fprintf(&b, " - [%s] %s\n", f.Check, msg)
}
}
}
if r.NativeExecNotice.HasAny() || len(r.Capabilities) > 0 {
if isZh {
b.WriteString("\n[2] 能力与权限说明:\n")
} else {
b.WriteString("\n[2] Capabilities & Privileges:\n")
}
if r.NativeExecNotice.HasAny() {
fmt.Fprintf(&b, " ! %s\n", r.NativeExecNotice.Get(locale))
}
for _, capItem := range r.Capabilities {
fmt.Fprintf(&b, " - [%s] %s (%s): %s\n",
strings.ToUpper(string(capItem.Level)),
capItem.Title.Get(locale),
capItem.ID,
capItem.Summary.Get(locale))
for _, ex := range capItem.Examples {
fmt.Fprintf(&b, " · %s\n", ex)
}
if capItem.ExtraCount > 0 {
if isZh {
fmt.Fprintf(&b, " · …另有 %d 项已折叠\n", capItem.ExtraCount)
} else {
fmt.Fprintf(&b, " · ...and %d more\n", capItem.ExtraCount)
}
}
}
}
if len(r.PendingFindings) > 0 || len(r.Executables) > 0 {
if isZh {
b.WriteString("\n[3] 提示信息与可执行文件清单:\n")
} else {
b.WriteString("\n[3] Advisories & Executables:\n")
}
for _, f := range r.PendingFindings {
msg := f.Localized.Get(locale)
if msg == "" {
msg = f.Message
}
fmt.Fprintf(&b, " - [%s] %s\n", f.Check, msg)
}
for _, ex := range r.Executables {
tag := "declared"
if !ex.Declared {
tag = "UNLISTED"
}
fmt.Fprintf(&b, " - [%s] %s sha256=%s\n", tag, ex.Path, ex.SHA256)
}
}
return strings.TrimRight(b.String(), "\n")
}
func scanSVGActiveContent(text string) string {
switch {
case reSVGScriptTag.MatchString(text):
return "<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
}