package plugin import ( "encoding/json" "fmt" "os" "path/filepath" "regexp" "sort" "strings" ) // ScanSeverity classifies risk findings into three actionable buckets: // - "hard": Violates packaging/security redlines; cannot be bypassed by confirmation. // - "capability": Legitimate declared capability or native execution boundary explained in plain language. // - "pending": Non-blocking advisories (e.g. missing SHA256SUMS in dev mode, unsigned community build, UI contract drift). const ( ScanSeverityHard = "hard" ScanSeverityCapability = "capability" ScanSeverityPending = "pending" ) const ( maxScanTextBytes = 8 << 20 // 8 MiB cap per scanned text asset maxCapExamples = 3 // Fold evidence lists past 3 items ("…and N more") ) // ForbiddenBinaryExtensions enumerates native executable, dynamic library, and // OS script extensions that are strictly forbidden in L1/L2/L4 packages and // must be explicitly declared in L3/runtime packages. var ForbiddenBinaryExtensions = map[string]bool{ ".exe": true, ".dll": true, ".com": true, ".scr": true, ".pif": true, ".cpl": true, ".msi": true, ".msp": true, ".sys": true, ".drv": true, ".ocx": true, ".bat": true, ".cmd": true, ".ps1": true, ".psm1": true, ".psd1": true, ".vbs": true, ".vbe": true, ".jse": true, ".wsf": true, ".wsh": true, ".hta": true, ".lnk": true, ".url": true, ".reg": true, ".jar": true, ".so": true, ".dylib": true, ".pyd": true, ".node": true, } // ScanFinding is one concrete issue discovered by the static risk scanner. type ScanFinding struct { Severity string `json:"severity"` // "hard" | "capability" | "pending" Check string `json:"check"` Target string `json:"target,omitempty"` Message string `json:"message"` Localized LocalizedText `json:"localized,omitempty"` } // ExecutableFile records a native binary or OS script discovered in a package. type ExecutableFile struct { Path string `json:"path"` SHA256 string `json:"sha256"` Declared bool `json:"declared"` SizeBytes int64 `json:"size_bytes"` } // CapabilityItem presents one declared permission or execution boundary in // plain, user-readable language with capped concrete evidence examples. type CapabilityItem struct { ID string `json:"id"` Level PermissionLevel `json:"level"` Title LocalizedText `json:"title"` Summary LocalizedText `json:"summary"` Examples []string `json:"examples,omitempty"` ExtraCount int `json:"extra_count,omitempty"` } // ScanOptions configures ScanDirectory / ScanArchive. type ScanOptions struct { Contract *UIContract Keyring []SigningKey RequireChecksums bool } // ScanReport is the unified static risk & gate report shared by `plugin doctor`, // transactional `InstallArchive`, CLI summaries, and GUI inspection dialogs. type ScanReport struct { PluginID string `json:"plugin_id,omitempty"` Version string `json:"version,omitempty"` Name LocalizedText `json:"name,omitempty"` Tier Tier `json:"tier,omitempty"` Trust TrustLevel `json:"trust,omitempty"` Publisher string `json:"publisher,omitempty"` License string `json:"license,omitempty"` Passed bool `json:"passed"` HardBlocked bool `json:"hard_blocked"` NeedsApproval bool `json:"needs_approval"` Headline LocalizedText `json:"headline"` NativeExecNotice LocalizedText `json:"native_exec_notice,omitempty"` HardFindings []ScanFinding `json:"hard_findings,omitempty"` Capabilities []CapabilityItem `json:"capabilities,omitempty"` PendingFindings []ScanFinding `json:"pending_findings,omitempty"` Executables []ExecutableFile `json:"executables,omitempty"` } var ( reSVGScriptTag = regexp.MustCompile(`(?i)<\s*script\b`) reSVGEventAttr = regexp.MustCompile(`(?i)\bon[a-z]{2,32}\s*=`) reSVGJavascriptURI = regexp.MustCompile(`(?i)javascript\s*:`) reSVGForeignObject = regexp.MustCompile(`(?i)<\s*foreignobject\b`) reJSWailsGo = regexp.MustCompile(`(?i)\b(?:window|globalThis|self|parent|top)\s*(?:\.\s*go\b|\[\s*['"]go['"]\s*\])`) reJSWailsRuntime = regexp.MustCompile(`(?i)\b(?:window|globalThis|self|parent|top)\s*(?:\.\s*runtime\b|\[\s*['"]runtime['"]\s*\])`) reJSEval = regexp.MustCompile(`\beval\s*\(`) reJSNewFunction = regexp.MustCompile(`\bnew\s+Function\s*\(`) reJSFunctionCall = regexp.MustCompile(`(?:^|[^.\w$])Function\s*\(`) reJSDocCookie = regexp.MustCompile(`\bdocument\s*\.\s*cookie\b`) reJSDocWrite = regexp.MustCompile(`\bdocument\s*\.\s*write(?:ln)?\s*\(`) reJSScriptTag = regexp.MustCompile(`(?i)<\s*script\b`) reJSCreateScript = regexp.MustCompile(`(?i)\bcreateElement\s*\(\s*['"]script['"]\s*\)`) reJSNetworkCall = regexp.MustCompile(`\b(?:fetch\s*\(|XMLHttpRequest\b|WebSocket\b|EventSource\b|navigator\s*\.\s*sendBeacon\s*\()`) ) // ScanArchive extracts archivePath into a temporary directory under tmpParentDir // (e.g. `/plugins/tmp`, never system `%TEMP%` unless explicitly passed // by caller) and runs ScanDirectory with RequireChecksums=true. func ScanArchive(archivePath, tmpParentDir, hostVersion string, opts ScanOptions) (ScanReport, error) { if tmpParentDir == "" { return ScanReport{}, fmt.Errorf("tmpParentDir is required for ScanArchive") } if err := os.MkdirAll(tmpParentDir, 0o755); err != nil { return ScanReport{}, err } stageDir, err := os.MkdirTemp(tmpParentDir, "scan-*") if err != nil { return ScanReport{}, err } defer os.RemoveAll(stageDir) if err := extractPluginZip(archivePath, stageDir); err != nil { rep := ScanReport{ Passed: false, HardBlocked: true, HardFindings: []ScanFinding{{ Severity: ScanSeverityHard, Check: "archive", Target: filepath.Base(archivePath), Message: err.Error(), Localized: LocalizedText{ ZhCN: "插件压缩包结构非法或超出安全限制:" + err.Error(), EnUS: "Plugin archive failed safety extraction: " + err.Error(), }, }}, } finalizeScanReport(&rep) return rep, nil } opts.RequireChecksums = true return ScanDirectory(stageDir, hostVersion, opts), nil } // ScanDirectory performs a comprehensive static risk and policy scan on a plugin // directory (unpacked archive, installed package, or dev-linked directory). func ScanDirectory(dir, hostVersion string, opts ScanOptions) ScanReport { rep := ScanReport{ Trust: TrustCommunity, } addHard := func(check, target, msg string, zh, en string) { rep.HardFindings = append(rep.HardFindings, ScanFinding{ Severity: ScanSeverityHard, Check: check, Target: target, Message: msg, Localized: LocalizedText{ZhCN: zh, EnUS: en}, }) } addPending := func(check, target, msg string, zh, en string) { rep.PendingFindings = append(rep.PendingFindings, ScanFinding{ Severity: ScanSeverityPending, Check: check, Target: target, Message: msg, Localized: LocalizedText{ZhCN: zh, EnUS: en}, }) } raw, err := os.ReadFile(filepath.Join(dir, "plugin.json")) if err != nil { addHard("manifest", "plugin.json", "cannot read plugin.json: "+err.Error(), "缺少或无法读取 plugin.json 清单文件", "Cannot read plugin.json manifest") finalizeScanReport(&rep) return rep } var m Manifest if err := json.Unmarshal(raw, &m); err != nil { addHard("manifest", "plugin.json", "invalid plugin.json JSON: "+err.Error(), "plugin.json 格式无效:"+err.Error(), "Invalid plugin.json JSON: "+err.Error()) finalizeScanReport(&rep) return rep } rep.PluginID = m.ID rep.Version = m.Version rep.Name = m.Name rep.Tier = m.InferTier(false) rep.Publisher = m.Publisher rep.License = m.License if err := ValidateManifest(m, hostVersion, false); err != nil { addHard("manifest", "plugin.json", err.Error(), "清单校验未通过:"+err.Error(), "Manifest validation failed: "+err.Error()) } 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)) // 1. Market redlines (Apple proprietary files & SMC OSK literals). for _, pat := range ForbiddenMarketPatterns { if strings.Contains(lowName, pat) { addHard("redline", rel, fmt.Sprintf("forbidden proprietary file detected (%s)", rel), fmt.Sprintf("检测到禁止分发的专有系统文件:%s", rel), fmt.Sprintf("Forbidden proprietary file detected: %s", rel)) } } if info.Size() <= 256*1024 && isRedlineTextExt(ext) { if b, rErr := os.ReadFile(full); rErr == nil { if containsForbiddenSMCKey(strings.ToLower(string(b))) { addHard("redline", rel, fmt.Sprintf("forbidden Apple SMC OSK detected in %s", rel), fmt.Sprintf("在 %s 中检测到禁止分发的 Apple SMC OSK 密钥", rel), fmt.Sprintf("Forbidden Apple SMC OSK detected in %s", rel)) } } } // 2. Executable / script extension inventory & hard-ban. if ForbiddenBinaryExtensions[ext] { sum, _ := fileSHA256Hex(full) declared := false switch rep.Tier { case TierL3: if declaredSidecar != "" && strings.EqualFold(rel, declaredSidecar) { declared = true } case TierRuntime: for _, rd := range runtimeDirs { if rel == rd || strings.HasPrefix(strings.ToLower(rel), strings.ToLower(rd)+"/") { declared = true break } } } rep.Executables = append(rep.Executables, ExecutableFile{ Path: rel, SHA256: sum, Declared: declared, SizeBytes: info.Size(), }) if !declared { if rep.Tier == TierL3 || rep.Tier == TierRuntime { addHard("unlisted-executable", rel, fmt.Sprintf("unlisted executable or script %q not declared in manifest", rel), fmt.Sprintf("包含未在清单中声明的可执行文件或脚本:%s", rel), fmt.Sprintf("Unlisted executable or script not declared in manifest: %s", rel)) } else { addHard("forbidden-binary", rel, fmt.Sprintf("executable or OS script %q is forbidden in %s plugin packages", rel, rep.Tier), fmt.Sprintf("%s 类型插件禁止夹带可执行文件或系统脚本:%s", rep.Tier, rel), fmt.Sprintf("Executable or OS script %q is forbidden in %s packages", rel, rep.Tier)) } } } // 3. SVG active-content scan across the entire package. if ext == ".svg" && info.Size() <= maxScanTextBytes { if b, rErr := os.ReadFile(full); rErr == nil { if reason := scanSVGActiveContent(string(b)); reason != "" { addHard("svg-script", rel, fmt.Sprintf("unsafe active content in SVG %s: %s", rel, reason), fmt.Sprintf("SVG 文件 %s 包含被禁止的脚本或事件属性(%s)", rel, reason), fmt.Sprintf("SVG file %s contains forbidden active content (%s)", rel, reason)) } } } // 4. Extra CSS files outside declared theme stylesheets & sandboxed panelDir. if ext == ".css" && !declaredThemeCSS[rel] && !inRelDir(rel, declaredPanelDir) && info.Size() <= maxScanTextBytes { if b, rErr := os.ReadFile(full); rErr == nil { if err := ValidateThemeCSSSafetyInDir(string(b), filepath.Dir(full)); err != nil { addHard("theme-css", rel, fmt.Sprintf("unsafe CSS %s: %v", rel, err), fmt.Sprintf("样式文件 %s 未通过安全校验:%v", rel, err), fmt.Sprintf("Stylesheet %s failed safety check: %v", rel, err)) } } } // 5. JS / MJS / HTML script static scan. if (ext == ".js" || ext == ".mjs" || ext == ".cjs") && info.Size() <= maxScanTextBytes { if b, rErr := os.ReadFile(full); rErr == nil { hits, hasNet := scanScriptContent(string(b), false) for _, hit := range hits { addHard("ui-script", rel, fmt.Sprintf("forbidden JS pattern (%s) in %s", hit, rel), fmt.Sprintf("脚本 %s 包含被禁止的宿主逃逸或动态执行语句(%s)", rel, hit), fmt.Sprintf("Script %s contains forbidden host-escape or dynamic-eval pattern (%s)", rel, hit)) } if hasNet { if !hasNetPerm { addHard("ui-script-undeclared-net", rel, fmt.Sprintf("script %s calls network APIs without declaring any net: permission", rel), fmt.Sprintf("脚本 %s 调用了网络接口,但清单未声明 net: 权限", rel), fmt.Sprintf("Script %s calls network APIs without declaring any net: permission", rel)) } else { netScriptHits = append(netScriptHits, rel) } } } } if (ext == ".html" || ext == ".htm") && inRelDir(rel, declaredPanelDir) && info.Size() <= maxScanTextBytes { if b, rErr := os.ReadFile(full); rErr == nil { hits, _ := scanScriptContent(string(b), true) for _, hit := range hits { addHard("panel-html", rel, fmt.Sprintf("forbidden host-escape pattern (%s) in panel %s", hit, rel), fmt.Sprintf("面板页面 %s 包含被禁止的宿主逃逸语句(%s)", rel, hit), fmt.Sprintf("Panel HTML %s contains forbidden host-escape pattern (%s)", rel, hit)) } } } } // 6. Checksums & optional ed25519 signature. sumsPath := filepath.Join(dir, "SHA256SUMS") if sumsRaw, sErr := os.ReadFile(sumsPath); sErr == nil { if err := verifyDirSHA256Sums(dir, sumsRaw); err != nil { addHard("checksum", "SHA256SUMS", err.Error(), "SHA256SUMS 完整性校验失败:"+err.Error(), "SHA256SUMS integrity verification failed: "+err.Error()) } if sigRaw, sigErr := os.ReadFile(filepath.Join(dir, "SHA256SUMS.sig")); sigErr == nil { if len(opts.Keyring) > 0 { t, vErr := verifyEd25519Signature(sumsRaw, sigRaw, opts.Keyring) if vErr != nil { addHard("signature", "SHA256SUMS.sig", "invalid package signature: "+vErr.Error(), "插件签名验证失败:"+vErr.Error(), "Plugin signature verification failed: "+vErr.Error()) } else { rep.Trust = t } } } } else if opts.RequireChecksums { addHard("checksum", "SHA256SUMS", "package missing SHA256SUMS", "分发压缩包缺少必需的 SHA256SUMS 校验文件", "Distribution package is missing required SHA256SUMS file") } else { addPending("checksum", "SHA256SUMS", "SHA256SUMS absent (acceptable in dev link mode; required for .zip distribution)", "未包含 SHA256SUMS(本地开发链接可忽略,打包分发 .zip 时必需)", "SHA256SUMS absent (acceptable in dev link mode; required for .zip distribution)") } if rep.Trust == TrustCommunity { addPending("trust-unsigned", "", "community package is not signed by an official or verified market key", "社区插件未携带官方或已审核签名,请仅安装来自可信作者的插件包", "Community package is not signed by an official or verified key; install only from authors you trust") } // 7. L10n & Locale contributions. if strings.TrimSpace(m.L10n) != "" { if err := validatePluginL10nDir(m.L10n, dir); err != nil { addHard("l10n", m.L10n, err.Error(), "插件本地化目录校验失败:"+err.Error(), "Plugin l10n directory validation failed: "+err.Error()) } } if len(m.Contributes.Locales) > 0 { if _, locFindings, cErr := CheckLocalePack(dir); cErr == nil && len(locFindings) > 0 { for _, lf := range locFindings { if lf.Severity == "error" { addHard("locale", lf.Check, lf.Message, "语言包校验错误:"+lf.Message, "Language pack validation error: "+lf.Message) } else if lf.Severity == "warn" { addPending("locale", lf.Check, lf.Message, "语言包提示:"+lf.Message, "Language pack advisory: "+lf.Message) } } } else { for _, lc := range m.Contributes.Locales { if err := ValidateLocaleContribution(lc, dir); err != nil { addHard("locale", lc.Locale, err.Error(), fmt.Sprintf("语言包 %s 校验失败:%v", lc.Locale, err), fmt.Sprintf("Locale %s validation failed: %v", lc.Locale, err)) } } } } // 8. Build plain-language capability explanations & L3 native boundary notice (§7.2). rep.Capabilities = buildCapabilityItems(m, rep.Tier, rep.Executables, netScriptHits) if rep.Tier == TierL3 { rep.NativeExecNotice = LocalizedText{ ZhCN: "此插件包含原生可执行程序(L3 Sidecar),启动后将以当前 Windows 账户完整权限运行。静态扫描只能核对清单完整性与哈希,无法证明原生二进制内部行为安全,请务必核对作者来源与 SHA-256。", EnUS: "This plugin ships a native executable (L3 Sidecar) that runs with full current Windows user privileges. Static scanning verifies manifest integrity and hashes only and cannot prove native binary safety; verify publisher provenance and SHA-256 before enabling.", } } rep.NeedsApproval = computeNeedsApproval(m, rep.Trust, nil, "", firstDeclaredExecHash(rep.Executables)) finalizeScanReport(&rep) return rep } func finalizeScanReport(rep *ScanReport) { rep.HardBlocked = len(rep.HardFindings) > 0 rep.Passed = !rep.HardBlocked if rep.HardBlocked { rep.Headline = LocalizedText{ ZhCN: fmt.Sprintf("拦截:发现 %d 项硬性安全/合规违规,拒绝安装", len(rep.HardFindings)), EnUS: fmt.Sprintf("Blocked: %d hard security/policy violation(s) found; installation refused", len(rep.HardFindings)), } return } highCount := 0 for _, c := range rep.Capabilities { if c.Level == PermHigh { highCount++ } } if rep.Tier == TierL3 || highCount > 0 { rep.Headline = LocalizedText{ ZhCN: fmt.Sprintf("通过静态准入,包含 %d 项高危能力,启用前需人工确认", maxInt(highCount, 1)), EnUS: fmt.Sprintf("Passed static gate with %d high-risk capability item(s); explicit user approval required", maxInt(highCount, 1)), } return } if len(rep.PendingFindings) > 0 { rep.Headline = LocalizedText{ ZhCN: fmt.Sprintf("通过静态准入(%d 项提示信息)", len(rep.PendingFindings)), EnUS: fmt.Sprintf("Passed static gate (%d advisory note(s))", len(rep.PendingFindings)), } return } rep.Headline = LocalizedText{ ZhCN: "通过全部静态准入检查", EnUS: "Passed all static gate checks", } } // ToDoctorFindings converts a ScanReport into backward-compatible DoctorFinding // entries so `DoctorDirectory` and existing callers/tests share one engine. func (r ScanReport) ToDoctorFindings() []DoctorFinding { var out []DoctorFinding hasManifestErr := false hasRedlineErr := false hasChecksumIssue := false for _, f := range r.HardFindings { if f.Check == "manifest" { hasManifestErr = true } if f.Check == "redline" { hasRedlineErr = true } if f.Check == "checksum" { hasChecksumIssue = true } out = append(out, DoctorFinding{ Severity: "error", Check: f.Check, Message: f.Message, }) } for _, f := range r.PendingFindings { if f.Check == "checksum" { hasChecksumIssue = true } if f.Check == "trust-unsigned" { // Keep doctor warn signal focused on actionable package hygiene. continue } out = append(out, DoctorFinding{ Severity: "warn", Check: f.Check, Message: f.Message, }) } if !hasManifestErr && r.PluginID != "" { out = append([]DoctorFinding{{ Severity: "ok", Check: "manifest", Message: fmt.Sprintf("valid manifest %s@%s (tier=%s)", r.PluginID, r.Version, r.Tier), }}, out...) } if !hasRedlineErr && r.PluginID != "" { out = append(out, DoctorFinding{ Severity: "ok", Check: "redline", Message: "no forbidden proprietary or secret files detected", }) } if !hasChecksumIssue && r.PluginID != "" { out = append(out, DoctorFinding{ Severity: "ok", Check: "checksum", Message: "SHA256SUMS verified", }) } return out } // SummaryText renders the three-section human-readable risk report for CLI output // or logs: (1) Hard Blockers, (2) Capabilities & Privileges, (3) Advisories & Binaries. func (r ScanReport) SummaryText(locale string) string { isZh := strings.HasPrefix(strings.ToLower(locale), "zh") var b strings.Builder title := r.PluginID if r.Version != "" { title += "@" + r.Version } if title != "" { fmt.Fprintf(&b, "%s [tier=%s trust=%s]\n", title, r.Tier, r.Trust) } fmt.Fprintf(&b, "%s\n", r.Headline.Get(locale)) if len(r.HardFindings) > 0 { if isZh { b.WriteString("\n[1] 硬性拦截项(必须修复,禁止安装):\n") } else { b.WriteString("\n[1] Hard Blockers (must fix; installation refused):\n") } for _, f := range r.HardFindings { msg := f.Localized.Get(locale) if msg == "" { msg = f.Message } if f.Target != "" { fmt.Fprintf(&b, " - [%s] %s: %s\n", f.Check, f.Target, msg) } else { fmt.Fprintf(&b, " - [%s] %s\n", f.Check, msg) } } } if r.NativeExecNotice.HasAny() || len(r.Capabilities) > 0 { if isZh { b.WriteString("\n[2] 能力与权限说明:\n") } else { b.WriteString("\n[2] Capabilities & Privileges:\n") } if r.NativeExecNotice.HasAny() { fmt.Fprintf(&b, " ! %s\n", r.NativeExecNotice.Get(locale)) } for _, capItem := range r.Capabilities { fmt.Fprintf(&b, " - [%s] %s (%s): %s\n", strings.ToUpper(string(capItem.Level)), capItem.Title.Get(locale), capItem.ID, capItem.Summary.Get(locale)) for _, ex := range capItem.Examples { fmt.Fprintf(&b, " · %s\n", ex) } if capItem.ExtraCount > 0 { if isZh { fmt.Fprintf(&b, " · …另有 %d 项已折叠\n", capItem.ExtraCount) } else { fmt.Fprintf(&b, " · ...and %d more\n", capItem.ExtraCount) } } } } if len(r.PendingFindings) > 0 || len(r.Executables) > 0 { if isZh { b.WriteString("\n[3] 提示信息与可执行文件清单:\n") } else { b.WriteString("\n[3] Advisories & Executables:\n") } for _, f := range r.PendingFindings { msg := f.Localized.Get(locale) if msg == "" { msg = f.Message } fmt.Fprintf(&b, " - [%s] %s\n", f.Check, msg) } for _, ex := range r.Executables { tag := "declared" if !ex.Declared { tag = "UNLISTED" } fmt.Fprintf(&b, " - [%s] %s sha256=%s\n", tag, ex.Path, ex.SHA256) } } return strings.TrimRight(b.String(), "\n") } func scanSVGActiveContent(text string) string { switch { case reSVGScriptTag.MatchString(text): return "