diff --git a/internal/archtest/function_length_test.go b/internal/archtest/function_length_test.go new file mode 100644 index 0000000..3ccd228 --- /dev/null +++ b/internal/archtest/function_length_test.go @@ -0,0 +1,33 @@ +package archtest + +import ( + "go/ast" + "testing" +) + +// maxFunctionLines keeps one function from collecting every step of a feature, +// where two changes to unrelated steps collide. Split it into named steps. +const maxFunctionLines = 300 + +func TestFunctionLength(t *testing.T) { + for _, src := range sources(t) { + for _, decl := range src.file.Decls { + fn, ok := decl.(*ast.FuncDecl) + if !ok { + continue + } + start, end := fileSet.Position(fn.Pos()).Line, fileSet.Position(fn.End()).Line + lines := end - start + 1 + // Embedded scripts and templates are text, not steps. + ast.Inspect(fn, func(n ast.Node) bool { + if lit, ok := n.(*ast.BasicLit); ok { + lines -= fileSet.Position(lit.End()).Line - fileSet.Position(lit.Pos()).Line + } + return true + }) + if lines > maxFunctionLines { + t.Errorf("%s:%d: %s has %d lines, the limit is %d", src.rel, start, fn.Name.Name, lines, maxFunctionLines) + } + } + } +} diff --git a/internal/plugin/manager.go b/internal/plugin/manager.go index 82b6433..a4d2a01 100644 --- a/internal/plugin/manager.go +++ b/internal/plugin/manager.go @@ -8,7 +8,6 @@ import ( "net/url" "os" "path/filepath" - "slices" "sort" "strings" "sync" @@ -1377,901 +1376,6 @@ func (m *Manager) ActiveThemePayload() ActiveThemePayload { return payload } -// ResolvedLocalePacks loads and merges all active plugin locale contributions -// and per-plugin l10n bundles into frontend UI packs and backend/CLI catalogs. -// Returns nil in safe mode. -func (m *Manager) ResolvedLocalePacks() ([]ResolvedLocalePack, map[i18n.Locale]i18n.PluginCatalog) { - if m.safeMode { - return nil, nil - } - contribs := m.registry.Locales() - - m.mu.RLock() - dirs := make(map[string]string, len(m.installDirs)) - for k, v := range m.installDirs { - dirs[k] = v - } - m.mu.RUnlock() - - type mergedPack struct { - pack ResolvedLocalePack - seenPID map[string]bool - backend map[string]string - } - byLocale := make(map[string]*mergedPack) - - ensurePack := func(canon i18n.Locale) *mergedPack { - key := string(canon) - mp := byLocale[key] - if mp == nil { - mp = &mergedPack{ - pack: ResolvedLocalePack{ - Locale: key, - Fallback: string(i18n.DefaultFallback(canon)), - Messages: make(map[string]string), - }, - seenPID: make(map[string]bool), - backend: make(map[string]string), - } - byLocale[key] = mp - } - return mp - } - - setPluginMsg := func(mp *mergedPack, targetPID, k, v string, overwrite bool) { - if targetPID == "" || k == "" || v == "" { - return - } - if mp.pack.PluginMessages == nil { - mp.pack.PluginMessages = make(map[string]map[string]string) - } - pm := mp.pack.PluginMessages[targetPID] - if pm == nil { - pm = make(map[string]string) - mp.pack.PluginMessages[targetPID] = pm - } - if !overwrite { - if _, exists := pm[k]; exists { - return - } - } - pm[k] = v - } - - // 1. Collect private `/.json` bundles from active/degraded functional plugins (underlay). - // Use ActivePluginIDs() rather than List() so we never trigger inUseChecker / Sidecar wake-ups - // while Registry.Reconcile holds reconcileMu. - activeIDs := m.registry.ActivePluginIDs() - sortedActiveIDs := make([]string, 0, len(activeIDs)) - for pid := range activeIDs { - sortedActiveIDs = append(sortedActiveIDs, pid) - } - sort.Strings(sortedActiveIDs) - for _, pid := range sortedActiveIDs { - man, ok := m.registry.ManifestOf(pid) - if !ok || strings.TrimSpace(man.L10n) == "" { - continue - } - selfDir := dirs[pid] - if selfDir == "" { - continue - } - l10nClean := strings.Trim(strings.TrimSpace(man.L10n), "/") - fullL10n, err := safeJoin(selfDir, l10nClean) - if err != nil { - continue - } - entries, err := os.ReadDir(fullL10n) - if err != nil { - continue - } - for _, ent := range entries { - if ent.IsDir() || !strings.HasSuffix(strings.ToLower(ent.Name()), ".json") { - continue - } - tagRaw := strings.TrimSuffix(ent.Name(), filepath.Ext(ent.Name())) - canon, ok := i18n.ParseLocale(tagRaw) - if !ok { - continue - } - loaded, err := loadLocaleJSONFile(selfDir, l10nClean+"/"+ent.Name()) - if err != nil || len(loaded) == 0 { - continue - } - mp := ensurePack(canon) - for k, v := range loaded { - setPluginMsg(mp, pid, k, v, true) - } - } - } - - // 2. Layer active Language Pack contributions (sorted deterministically by TrustRank -> Priority -> PluginID). - uiDomains := []string{"core", "vm", "wizard", "settings", "plugins", "macosGlossary", "macos-glossary"} - backendDomains := []string{"native", "macosGlossary", "macos-glossary", "core"} - - for _, lc := range contribs { - canon, ok := i18n.ParseLocale(lc.Locale) - if !ok { - continue - } - privileged := isPrivilegedLocaleTrustRank(lc.TrustRank) - if !privileged && (canon == i18n.ZhCN || canon == i18n.EnUS) { - // Community/unprivileged language packs may not hijack built-in host catalogs. - continue - } - mp := ensurePack(canon) - if lbl := strings.TrimSpace(lc.Label); lbl != "" { - mp.pack.Label = lbl - } - if fb := strings.TrimSpace(lc.Fallback); fb != "" { - if cfb, ok := i18n.ParseLocale(fb); ok { - mp.pack.Fallback = string(cfb) - } - } - installDir := dirs[lc.PluginID] - if installDir != "" && strings.TrimSpace(lc.File) != "" { - if loaded, err := loadLocaleJSONFile(installDir, lc.File); err == nil { - for k, v := range loaded { - if k != "" && v != "" { - mp.pack.Messages[k] = v - } - } - } - } - if installDir != "" && len(lc.Files) > 0 { - for _, dom := range uiDomains { - if rel := strings.TrimSpace(lc.Files[dom]); rel != "" { - if loaded, err := loadLocaleJSONFile(installDir, rel); err == nil { - for k, v := range loaded { - if k != "" && v != "" { - mp.pack.Messages[k] = v - } - } - } - } - } - for _, dom := range backendDomains { - if rel := strings.TrimSpace(lc.Files[dom]); rel != "" { - if loaded, err := loadLocaleJSONFile(installDir, rel); err == nil { - for k, v := range loaded { - if k != "" && v != "" { - mp.backend[k] = v - } - } - } - } - } - } - for k, v := range lc.Messages { - if k != "" && v != "" { - mp.pack.Messages[k] = v - } - } - if installDir != "" && strings.TrimSpace(lc.BackendFile) != "" { - if loaded, err := loadLocaleJSONFile(installDir, lc.BackendFile); err == nil { - for k, v := range loaded { - if k != "" && v != "" { - mp.backend[k] = v - } - } - } - } - for k, v := range lc.Backend { - if k != "" && v != "" { - mp.backend[k] = v - } - } - - // Resolve bundled WOFF2 WebFonts via AssetServer. - if installDir != "" && m.assets != nil && len(lc.Fonts) > 0 { - for _, f := range lc.Fonts { - if strings.TrimSpace(f.Family) == "" || !strings.EqualFold(filepath.Ext(strings.TrimSpace(f.File)), ".woff2") { - continue - } - if full, err := safeJoin(installDir, f.File); err == nil && verifyWOFF2Header(full) == nil { - mp.pack.Fonts = append(mp.pack.Fonts, ResolvedLocaleFont{ - Family: f.Family, - URL: m.assets.AssetURL(lc.PluginID, f.File), - Weight: f.Weight, - Style: f.Style, - UnicodeRange: f.UnicodeRange, - }) - } - } - } - - // Layer cross-plugin message overrides onto PluginMessages[targetID]. - // Unprivileged community packs may only fill in missing keys, never overwrite - // a target plugin's own messages. - for targetID, ov := range lc.PluginOverrides { - if installDir != "" && strings.TrimSpace(ov.MessagesFile) != "" { - if loaded, err := loadLocaleJSONFile(installDir, ov.MessagesFile); err == nil { - for k, v := range loaded { - setPluginMsg(mp, targetID, k, v, privileged) - } - } - } - for k, v := range ov.Messages { - setPluginMsg(mp, targetID, k, v, privileged) - } - } - - if lc.PluginID != "" && !mp.seenPID[lc.PluginID] { - mp.seenPID[lc.PluginID] = true - mp.pack.PluginIDs = append(mp.pack.PluginIDs, lc.PluginID) - } - } - - if len(byLocale) == 0 { - return nil, nil - } - - uiPacks := make([]ResolvedLocalePack, 0, len(byLocale)) - backendPacks := make(map[i18n.Locale]i18n.PluginCatalog, len(byLocale)) - for key, mp := range byLocale { - if mp.pack.Label == "" { - mp.pack.Label = defaultLocaleLabel(key) - } - sort.Strings(mp.pack.PluginIDs) - if len(mp.pack.Messages) > 0 { - mp.pack.HasUIMessages = true - } else { - mp.pack.Messages = nil - } - uiPacks = append(uiPacks, mp.pack) - if len(mp.backend) > 0 { - backendPacks[i18n.Locale(key)] = i18n.PluginCatalog{ - Fallback: i18n.Locale(mp.pack.Fallback), - Messages: mp.backend, - } - } - } - sort.Slice(uiPacks, func(i, j int) bool { - return uiPacks[i].Locale < uiPacks[j].Locale - }) - if len(backendPacks) == 0 { - backendPacks = nil - } - return uiPacks, backendPacks -} - -type resolvedManifestOverride struct { - locale string - privileged bool - ov PluginManifestOverride -} - -func applyLocalizedOverride(lt *LocalizedText, locale, val string, privileged bool) { - if privileged { - lt.Set(locale, val) - } else { - lt.SetIfEmpty(locale, val) - } -} - -func (m *Manager) activeManifestOverrides() map[string][]resolvedManifestOverride { - if m == nil || m.safeMode { - return nil - } - contribs := m.registry.Locales() - if len(contribs) == 0 { - return nil - } - m.mu.RLock() - dirs := make(map[string]string, len(m.installDirs)) - for k, v := range m.installDirs { - dirs[k] = v - } - m.mu.RUnlock() - - var out map[string][]resolvedManifestOverride - for _, lc := range contribs { - if len(lc.PluginOverrides) == 0 { - continue - } - canon, ok := i18n.ParseLocale(lc.Locale) - if !ok { - continue - } - privileged := isPrivilegedLocaleTrustRank(lc.TrustRank) - if !privileged && (canon == i18n.ZhCN || canon == i18n.EnUS) { - continue - } - packDir := dirs[lc.PluginID] - for targetID, po := range lc.PluginOverrides { - var merged PluginManifestOverride - hasAny := false - if packDir != "" && strings.TrimSpace(po.ManifestFile) != "" { - if loaded, err := loadPluginManifestOverrideFile(packDir, po.ManifestFile); err == nil && loaded != nil { - merged = *loaded - hasAny = true - } - } - if po.Manifest != nil { - if po.Manifest.Name != "" { - merged.Name = po.Manifest.Name - } - if po.Manifest.Description != "" { - merged.Description = po.Manifest.Description - } - if len(po.Manifest.Fields) > 0 { - if merged.Fields == nil { - merged.Fields = make(map[string]string, len(po.Manifest.Fields)) - } - for fk, fv := range po.Manifest.Fields { - merged.Fields[fk] = fv - } - } - hasAny = true - } - if !hasAny { - continue - } - if out == nil { - out = make(map[string][]resolvedManifestOverride) - } - out[targetID] = append(out[targetID], resolvedManifestOverride{ - locale: string(canon), - privileged: privileged, - ov: merged, - }) - } - } - return out -} - -func cloneLocalizedText(lt LocalizedText) LocalizedText { - out := LocalizedText{ZhCN: lt.ZhCN, EnUS: lt.EnUS} - if len(lt.Extra) > 0 { - out.Extra = make(map[string]string, len(lt.Extra)) - for k, v := range lt.Extra { - out.Extra[k] = v - } - } - return out -} - -func cloneSettingsSchemaWithOverrides(sc *SettingsSchema, list []resolvedManifestOverride) *SettingsSchema { - if sc == nil { - return nil - } - cp := *sc - cp.Title = cloneLocalizedText(sc.Title) - if len(sc.Properties) > 0 { - cp.Properties = make(map[string]SettingProperty, len(sc.Properties)) - for pk, prop := range sc.Properties { - pcp := prop - pcp.Title = cloneLocalizedText(prop.Title) - pcp.Description = cloneLocalizedText(prop.Description) - cp.Properties[pk] = pcp - } - } - for _, r := range list { - if v := r.ov.Fields["settings.title"]; v != "" { - applyLocalizedOverride(&cp.Title, r.locale, v, r.privileged) - } - for pk, prop := range cp.Properties { - changed := false - if v := firstNonEmptyField(r.ov.Fields, "setting."+pk+".title", pk+".title"); v != "" { - applyLocalizedOverride(&prop.Title, r.locale, v, r.privileged) - changed = true - } - if v := firstNonEmptyField(r.ov.Fields, "setting."+pk+".description", pk+".description"); v != "" { - applyLocalizedOverride(&prop.Description, r.locale, v, r.privileged) - changed = true - } - if changed { - cp.Properties[pk] = prop - } - } - } - return &cp -} - -func firstNonEmptyField(fields map[string]string, keys ...string) string { - if len(fields) == 0 { - return "" - } - for _, k := range keys { - if v := strings.TrimSpace(fields[k]); v != "" { - return v - } - } - return "" -} - -// LocalizePluginInfos returns a copy of infos enriched with any active Language Pack -// `pluginOverrides` translations for plugin Name, Description, and SettingsSchema. -func (m *Manager) LocalizePluginInfos(infos []PluginInfo) []PluginInfo { - ovs := m.activeManifestOverrides() - if len(ovs) == 0 || len(infos) == 0 { - return infos - } - out := make([]PluginInfo, len(infos)) - for i, info := range infos { - cp := info - if list := ovs[info.ID]; len(list) > 0 { - cp.Name = cloneLocalizedText(info.Name) - cp.Description = cloneLocalizedText(info.Description) - for _, r := range list { - if r.ov.Name != "" { - applyLocalizedOverride(&cp.Name, r.locale, r.ov.Name, r.privileged) - } - if r.ov.Description != "" { - applyLocalizedOverride(&cp.Description, r.locale, r.ov.Description, r.privileged) - } - } - cp.Settings = cloneSettingsSchemaWithOverrides(info.Settings, list) - } - out[i] = cp - } - return out -} - -// overridableText is a contribution text that a Language Pack may replace, and -// the override fields that do so, in order of preference. -type overridableText struct { - text *LocalizedText - keys []string -} - -// localizeContributions returns a copy of items with the active Language Pack -// overrides applied to the texts that texts lists for each item. -func localizeContributions[T any](m *Manager, items []T, texts func(*T) (pluginID string, list []overridableText)) []T { - ovs := m.activeManifestOverrides() - if len(ovs) == 0 || len(items) == 0 { - return items - } - out := slices.Clone(items) - for i := range out { - pluginID, list := texts(&out[i]) - for _, t := range list { - if len(ovs[pluginID]) > 0 { - *t.text = cloneLocalizedText(*t.text) - } - for _, r := range ovs[pluginID] { - if v := firstNonEmptyField(r.ov.Fields, t.keys...); v != "" { - applyLocalizedOverride(t.text, r.locale, v, r.privileged) - } - } - } - } - return out -} - -// LocalizeMenus applies Language Pack overrides to menu titles. -func (m *Manager) LocalizeMenus(items []MenuContribution) []MenuContribution { - return localizeContributions(m, items, func(c *MenuContribution) (string, []overridableText) { - return c.PluginID, []overridableText{{&c.Title, []string{"menu." + c.ID + ".title", "command." + c.Command + ".title"}}} - }) -} - -// LocalizePanels applies Language Pack overrides to panel titles. -func (m *Manager) LocalizePanels(items []PanelContribution) []PanelContribution { - return localizeContributions(m, items, func(c *PanelContribution) (string, []overridableText) { - return c.PluginID, []overridableText{{&c.Title, []string{"panel." + c.ID + ".title"}}} - }) -} - -// LocalizeViews applies Language Pack overrides to view titles. -func (m *Manager) LocalizeViews(items []ViewContribution) []ViewContribution { - return localizeContributions(m, items, func(c *ViewContribution) (string, []overridableText) { - return c.PluginID, []overridableText{{&c.Title, []string{"view." + c.ID + ".title"}}} - }) -} - -// LocalizeImageSources applies Language Pack overrides to image source titles and descriptions. -func (m *Manager) LocalizeImageSources(items []ImageSourceContribution) []ImageSourceContribution { - return localizeContributions(m, items, func(c *ImageSourceContribution) (string, []overridableText) { - return c.PluginID, []overridableText{ - {&c.Title, []string{"imageSource." + c.ID + ".title"}}, - {&c.Description, []string{"imageSource." + c.ID + ".description"}}, - } - }) -} - -// LocalizeVMCards applies Language Pack overrides to VM card titles and values. -func (m *Manager) LocalizeVMCards(items []VMCardContribution) []VMCardContribution { - return localizeContributions(m, items, func(c *VMCardContribution) (string, []overridableText) { - return c.PluginID, []overridableText{ - {&c.Title, []string{"vmCard." + c.ID + ".title"}}, - {&c.Value, []string{"vmCard." + c.ID + ".value"}}, - } - }) -} - -// LocalizeSettingsPages applies Language Pack overrides to settings page titles. -func (m *Manager) LocalizeSettingsPages(items []SettingsPageContribution) []SettingsPageContribution { - return localizeContributions(m, items, func(c *SettingsPageContribution) (string, []overridableText) { - return c.PluginID, []overridableText{{&c.Title, []string{"settingsPage." + c.ID + ".title"}}} - }) -} - -// LocalizeStatusItems applies Language Pack overrides to status item texts and tooltips. -func (m *Manager) LocalizeStatusItems(items []StatusItemContribution) []StatusItemContribution { - return localizeContributions(m, items, func(c *StatusItemContribution) (string, []overridableText) { - return c.PluginID, []overridableText{ - {&c.Text, []string{"statusItem." + c.ID + ".text"}}, - {&c.Tooltip, []string{"statusItem." + c.ID + ".tooltip"}}, - } - }) -} - -// CurrentLocale returns the active effective host locale for plugin operations. -func (m *Manager) CurrentLocale() i18n.Locale { - if m != nil && m.opts.LocaleFn != nil { - return i18n.EffectiveLocale(m.opts.LocaleFn()) - } - return i18n.Detect() -} - -// PluginL10nBundle builds the merged private localization dictionary for pluginID -// in loc, layering the plugin's own `/.json` files underneath any -// active Language Pack `pluginOverrides[pluginID]` entries along FallbackChain(loc). -func (m *Manager) PluginL10nBundle(pluginID string, loc i18n.Locale) map[string]string { - if m == nil || pluginID == "" || m.safeMode { - return nil - } - cacheKey := pluginID + "\x00" + string(loc) - m.mu.RLock() - gen := m.l10nGen - if cached, ok := m.l10nCache[cacheKey]; ok { - m.mu.RUnlock() - if len(cached) == 0 { - return nil - } - cp := make(map[string]string, len(cached)) - for k, v := range cached { - cp[k] = v - } - return cp - } - selfDir := m.installDirs[pluginID] - dirs := make(map[string]string, len(m.installDirs)) - for k, v := range m.installDirs { - dirs[k] = v - } - m.mu.RUnlock() - - chain := i18n.FallbackChain(loc) - out := make(map[string]string) - - var l10nRel string - selfLocaleFiles := make(map[string]string) - if man, ok := m.registry.ManifestOf(pluginID); ok && strings.TrimSpace(man.L10n) != "" { - l10nRel = strings.Trim(strings.TrimSpace(man.L10n), "/") - if selfDir != "" && l10nRel != "" { - if fullL10n, err := safeJoin(selfDir, l10nRel); err == nil { - if entries, err := os.ReadDir(fullL10n); err == nil { - for _, ent := range entries { - if ent.IsDir() || !strings.HasSuffix(strings.ToLower(ent.Name()), ".json") { - continue - } - tagRaw := strings.TrimSuffix(ent.Name(), filepath.Ext(ent.Name())) - if canon, ok := i18n.ParseLocale(tagRaw); ok { - if _, exists := selfLocaleFiles[string(canon)]; !exists { - selfLocaleFiles[string(canon)] = l10nRel + "/" + ent.Name() - } - } - } - } - } - } - } - - contribs := m.registry.Locales() - // Walk fallback chain from least specific to most specific so higher-priority hops win. - for idx := len(chain) - 1; idx >= 0; idx-- { - step := string(chain[idx]) - selfKeysThisStep := make(map[string]bool) - if rel, ok := selfLocaleFiles[step]; ok { - if loaded, err := loadLocaleJSONFile(selfDir, rel); err == nil { - for k, v := range loaded { - if k != "" && v != "" { - out[k] = v - selfKeysThisStep[k] = true - } - } - } - } - for _, lc := range contribs { - if lc.Locale != step { - continue - } - privileged := isPrivilegedLocaleTrustRank(lc.TrustRank) - if !privileged && (step == string(i18n.ZhCN) || step == string(i18n.EnUS)) { - continue - } - ov, ok := lc.PluginOverrides[pluginID] - if !ok { - continue - } - applyMsg := func(k, v string) { - if k == "" || v == "" { - return - } - if !privileged && selfKeysThisStep[k] { - return - } - out[k] = v - } - packDir := dirs[lc.PluginID] - if packDir != "" && strings.TrimSpace(ov.MessagesFile) != "" { - if loaded, err := loadLocaleJSONFile(packDir, ov.MessagesFile); err == nil { - for k, v := range loaded { - applyMsg(k, v) - } - } - } - for k, v := range ov.Messages { - applyMsg(k, v) - } - } - } - m.mu.Lock() - if m.l10nGen == gen { - if len(m.l10nCache) >= 512 { - clear(m.l10nCache) - } - if len(out) == 0 { - m.l10nCache[cacheKey] = nil - } else { - stored := make(map[string]string, len(out)) - for k, v := range out { - stored[k] = v - } - m.l10nCache[cacheKey] = stored - } - } - m.mu.Unlock() - if len(out) == 0 { - return nil - } - return out -} - -// NotifyLocaleChanged broadcasts `plugin/localeChanged` to all currently running -// L3 Sidecar processes without waking sleeping Sidecars. -func (m *Manager) NotifyLocaleChanged(eff i18n.Locale) { - if m == nil { - return - } - m.mu.RLock() - sups := make(map[string]*SidecarSupervisor, len(m.supervisors)) - for pid, s := range m.supervisors { - sups[pid] = s - } - m.mu.RUnlock() - if len(sups) == 0 { - return - } - chain := i18n.FallbackChain(eff) - strChain := make([]string, len(chain)) - for i, c := range chain { - strChain[i] = string(c) - } - for pid, sup := range sups { - if sup.PID() == 0 { - continue - } - sup.NotifyIfRunning("plugin/localeChanged", map[string]any{ - "locale": string(eff), - "fallbackChain": strChain, - "l10nBundle": m.PluginL10nBundle(pid, eff), - }) - } -} - -func defaultLocaleLabel(code string) string { - switch code { - case string(i18n.ZhCN): - return "简体中文" - case string(i18n.EnUS): - return "English" - default: - return code - } -} - -func isPrivilegedLocaleTrustRank(rank int) bool { - return rank == 10 || rank == 20 || rank >= 50 -} - -func localeTrustRank(source SourceKind, trust TrustLevel) int { - switch { - case source == SourceBuiltin: - return 10 - case source == SourceBundled: - return 20 - case trust == TrustCommunity: - return 30 - case trust == TrustVerified: - return 40 - case trust == TrustOfficial: - return 50 - case source == SourceDevLink || trust == TrustDev: - return 60 - default: - return 30 - } -} - -// LoadStaticLocalePacks performs an ultra-fast (< 2ms), side-effect-free scan of -// enabled plugins under dataRoot to populate backend/CLI language packs without -// starting any L3 Sidecars, AssetServer, or service dependency reconciliation. -func LoadStaticLocalePacks(dataRoot string) map[i18n.Locale]i18n.PluginCatalog { - if strings.TrimSpace(dataRoot) == "" { - i18n.SetPluginCatalogs(nil) - return nil - } - layout := NewPluginsLayout(dataRoot) - if DidLastStartupCrash(layout.Root) { - i18n.SetPluginCatalogs(nil) - return nil - } - st, err := NewStateStore(layout.Root).Load() - if err != nil || st == nil || len(st.Plugins) == 0 { - i18n.SetPluginCatalogs(nil) - return nil - } - - type staticCandidate struct { - id string - dir string - rec *PluginRecord - rank int - } - var candidates []staticCandidate - for id, rec := range st.Plugins { - if rec == nil || !rec.Enabled || rec.Source == SourceBuiltin || rec.Source == SourceBundled { - continue - } - var dir string - if rec.Source == SourceDevLink { - if !st.DeveloperMode || strings.TrimSpace(rec.DevPath) == "" { - continue - } - dir = rec.DevPath - } else { - if rec.Version == "" || !reReverseDomainID.MatchString(id) { - continue - } - if _, err := ParseSemVer(rec.Version); err != nil { - continue - } - safeDir, err := safeJoin(layout.PkgsDir(), id+"/"+rec.Version) - if err != nil { - continue - } - dir = safeDir - } - candidates = append(candidates, staticCandidate{ - id: id, - dir: dir, - rec: rec, - rank: localeTrustRank(rec.Source, rec.Trust), - }) - } - sort.Slice(candidates, func(i, j int) bool { - if candidates[i].rank != candidates[j].rank { - return candidates[i].rank < candidates[j].rank - } - return candidates[i].id < candidates[j].id - }) - - type staticLocaleItem struct { - canon i18n.Locale - rank int - id string - dir string - lc LocaleContribution - } - var items []staticLocaleItem - for _, c := range candidates { - raw, err := os.ReadFile(filepath.Join(c.dir, "plugin.json")) - if err != nil { - continue - } - var man Manifest - if json.Unmarshal(raw, &man) != nil || len(man.Contributes.Locales) == 0 { - continue - } - if c.id != "" && man.ID != c.id { - continue - } - trust := c.rec.Trust - if trust == "" { - trust = TrustCommunity - } - if c.rec.Source == SourceDevLink { - trust = TrustDev - } - _, _, entryHash, err := resolveManifestEntry(man, c.dir, false) - if err != nil { - continue - } - if computeNeedsApproval(man, trust, c.rec.ApprovedPermissions, c.rec.ApprovedEntryHash, entryHash) { - continue - } - for _, lc := range man.Contributes.Locales { - canon, ok := i18n.ParseLocale(lc.Locale) - if !ok { - continue - } - items = append(items, staticLocaleItem{ - canon: canon, - rank: c.rank, - id: c.id, - dir: c.dir, - lc: lc, - }) - } - } - - sort.Slice(items, func(i, j int) bool { - if items[i].canon != items[j].canon { - return items[i].canon < items[j].canon - } - if items[i].rank != items[j].rank { - return items[i].rank < items[j].rank - } - if items[i].lc.Priority != items[j].lc.Priority { - return items[i].lc.Priority < items[j].lc.Priority - } - return items[i].id < items[j].id - }) - - packs := make(map[i18n.Locale]i18n.PluginCatalog) - for _, it := range items { - canon := it.canon - if !isPrivilegedLocaleTrustRank(it.rank) && (canon == i18n.ZhCN || canon == i18n.EnUS) { - continue - } - lc := it.lc - cur, exists := packs[canon] - if !exists { - cur = i18n.PluginCatalog{ - Fallback: i18n.DefaultFallback(canon), - Messages: make(map[string]string), - } - } - if fb, ok := i18n.ParseLocale(lc.Fallback); ok { - cur.Fallback = fb - } - // Match ResolvedLocalePacks precedence: Files first, then BackendFile, then inline Backend. - for _, domKey := range []string{"native", "macosGlossary", "macos-glossary", "core"} { - if rel := strings.TrimSpace(lc.Files[domKey]); rel != "" { - if loaded, err := loadLocaleJSONFile(it.dir, rel); err == nil { - for k, v := range loaded { - if k != "" && v != "" { - cur.Messages[k] = v - } - } - } - } - } - if strings.TrimSpace(lc.BackendFile) != "" { - if loaded, err := loadLocaleJSONFile(it.dir, lc.BackendFile); err == nil { - for k, v := range loaded { - if k != "" && v != "" { - cur.Messages[k] = v - } - } - } - } - for k, v := range lc.Backend { - if k != "" && v != "" { - cur.Messages[k] = v - } - } - if len(cur.Messages) > 0 { - packs[canon] = cur - } - } - i18n.SetPluginCatalogs(packs) - return packs -} - // ActiveVMNamesWithSetting scans saved VM settings for pluginID where key==true. func (m *Manager) ActiveVMNamesWithSetting(pluginID, key string) []string { m.mu.RLock() diff --git a/internal/plugin/manager_locale.go b/internal/plugin/manager_locale.go new file mode 100644 index 0000000..eaee9df --- /dev/null +++ b/internal/plugin/manager_locale.go @@ -0,0 +1,844 @@ +package plugin + +import ( + "encoding/json" + "maps" + "os" + "path/filepath" + "slices" + "sort" + "strings" + + "github.com/Nwflower/reims-go/internal/i18n" +) + +// ResolvedLocalePacks loads and merges all active plugin locale contributions +// and per-plugin l10n bundles into frontend UI packs and backend/CLI catalogs. +// Returns nil in safe mode. +func (m *Manager) ResolvedLocalePacks() ([]ResolvedLocalePack, map[i18n.Locale]i18n.PluginCatalog) { + if m.safeMode { + return nil, nil + } + contribs := m.registry.Locales() + + m.mu.RLock() + dirs := maps.Clone(m.installDirs) + m.mu.RUnlock() + + type mergedPack struct { + pack ResolvedLocalePack + seenPID map[string]bool + backend map[string]string + } + byLocale := make(map[string]*mergedPack) + + ensurePack := func(canon i18n.Locale) *mergedPack { + key := string(canon) + mp := byLocale[key] + if mp == nil { + mp = &mergedPack{ + pack: ResolvedLocalePack{ + Locale: key, + Fallback: string(i18n.DefaultFallback(canon)), + Messages: make(map[string]string), + }, + seenPID: make(map[string]bool), + backend: make(map[string]string), + } + byLocale[key] = mp + } + return mp + } + + setPluginMsg := func(mp *mergedPack, targetPID, k, v string, overwrite bool) { + if targetPID == "" || k == "" || v == "" { + return + } + if mp.pack.PluginMessages == nil { + mp.pack.PluginMessages = make(map[string]map[string]string) + } + pm := mp.pack.PluginMessages[targetPID] + if pm == nil { + pm = make(map[string]string) + mp.pack.PluginMessages[targetPID] = pm + } + if !overwrite { + if _, exists := pm[k]; exists { + return + } + } + pm[k] = v + } + + // 1. Collect private `/.json` bundles from active/degraded functional plugins (underlay). + // Use ActivePluginIDs() rather than List() so we never trigger inUseChecker / Sidecar wake-ups + // while Registry.Reconcile holds reconcileMu. + activeIDs := m.registry.ActivePluginIDs() + sortedActiveIDs := make([]string, 0, len(activeIDs)) + for pid := range activeIDs { + sortedActiveIDs = append(sortedActiveIDs, pid) + } + sort.Strings(sortedActiveIDs) + for _, pid := range sortedActiveIDs { + man, ok := m.registry.ManifestOf(pid) + if !ok { + continue + } + for _, file := range l10nFiles(dirs[pid], man.L10n) { + loaded, err := loadLocaleJSONFile(dirs[pid], file.rel) + if err != nil || len(loaded) == 0 { + continue + } + mp := ensurePack(file.locale) + for k, v := range loaded { + setPluginMsg(mp, pid, k, v, true) + } + } + } + + // 2. Layer active Language Pack contributions (sorted deterministically by TrustRank -> Priority -> PluginID). + uiDomains := []string{"core", "vm", "wizard", "settings", "plugins", "macosGlossary", "macos-glossary"} + + for _, lc := range contribs { + canon, ok := i18n.ParseLocale(lc.Locale) + if !ok { + continue + } + privileged := isPrivilegedLocaleTrustRank(lc.TrustRank) + if !privileged && (canon == i18n.ZhCN || canon == i18n.EnUS) { + // Community/unprivileged language packs may not hijack built-in host catalogs. + continue + } + mp := ensurePack(canon) + if lbl := strings.TrimSpace(lc.Label); lbl != "" { + mp.pack.Label = lbl + } + if fb := strings.TrimSpace(lc.Fallback); fb != "" { + if cfb, ok := i18n.ParseLocale(fb); ok { + mp.pack.Fallback = string(cfb) + } + } + installDir := dirs[lc.PluginID] + mergeLocaleFile(mp.pack.Messages, installDir, lc.File) + for _, dom := range uiDomains { + mergeLocaleFile(mp.pack.Messages, installDir, lc.Files[dom]) + } + mergeMessages(mp.pack.Messages, lc.Messages) + mergeBackendMessages(mp.backend, installDir, lc) + + // Resolve bundled WOFF2 WebFonts via AssetServer. + if installDir != "" && m.assets != nil && len(lc.Fonts) > 0 { + for _, f := range lc.Fonts { + if strings.TrimSpace(f.Family) == "" || !strings.EqualFold(filepath.Ext(strings.TrimSpace(f.File)), ".woff2") { + continue + } + if full, err := safeJoin(installDir, f.File); err == nil && verifyWOFF2Header(full) == nil { + mp.pack.Fonts = append(mp.pack.Fonts, ResolvedLocaleFont{ + Family: f.Family, + URL: m.assets.AssetURL(lc.PluginID, f.File), + Weight: f.Weight, + Style: f.Style, + UnicodeRange: f.UnicodeRange, + }) + } + } + } + + // Layer cross-plugin message overrides onto PluginMessages[targetID]. + // Unprivileged community packs may only fill in missing keys, never overwrite + // a target plugin's own messages. + for targetID, ov := range lc.PluginOverrides { + if installDir != "" && strings.TrimSpace(ov.MessagesFile) != "" { + if loaded, err := loadLocaleJSONFile(installDir, ov.MessagesFile); err == nil { + for k, v := range loaded { + setPluginMsg(mp, targetID, k, v, privileged) + } + } + } + for k, v := range ov.Messages { + setPluginMsg(mp, targetID, k, v, privileged) + } + } + + if lc.PluginID != "" && !mp.seenPID[lc.PluginID] { + mp.seenPID[lc.PluginID] = true + mp.pack.PluginIDs = append(mp.pack.PluginIDs, lc.PluginID) + } + } + + if len(byLocale) == 0 { + return nil, nil + } + + uiPacks := make([]ResolvedLocalePack, 0, len(byLocale)) + backendPacks := make(map[i18n.Locale]i18n.PluginCatalog, len(byLocale)) + for key, mp := range byLocale { + if mp.pack.Label == "" { + mp.pack.Label = defaultLocaleLabel(key) + } + sort.Strings(mp.pack.PluginIDs) + if len(mp.pack.Messages) > 0 { + mp.pack.HasUIMessages = true + } else { + mp.pack.Messages = nil + } + uiPacks = append(uiPacks, mp.pack) + if len(mp.backend) > 0 { + backendPacks[i18n.Locale(key)] = i18n.PluginCatalog{ + Fallback: i18n.Locale(mp.pack.Fallback), + Messages: mp.backend, + } + } + } + sort.Slice(uiPacks, func(i, j int) bool { + return uiPacks[i].Locale < uiPacks[j].Locale + }) + if len(backendPacks) == 0 { + backendPacks = nil + } + return uiPacks, backendPacks +} + +type resolvedManifestOverride struct { + locale string + privileged bool + ov PluginManifestOverride +} + +func applyLocalizedOverride(lt *LocalizedText, locale, val string, privileged bool) { + if privileged { + lt.Set(locale, val) + } else { + lt.SetIfEmpty(locale, val) + } +} + +func (m *Manager) activeManifestOverrides() map[string][]resolvedManifestOverride { + if m == nil || m.safeMode { + return nil + } + contribs := m.registry.Locales() + if len(contribs) == 0 { + return nil + } + m.mu.RLock() + dirs := maps.Clone(m.installDirs) + m.mu.RUnlock() + + var out map[string][]resolvedManifestOverride + for _, lc := range contribs { + if len(lc.PluginOverrides) == 0 { + continue + } + canon, ok := i18n.ParseLocale(lc.Locale) + if !ok { + continue + } + privileged := isPrivilegedLocaleTrustRank(lc.TrustRank) + if !privileged && (canon == i18n.ZhCN || canon == i18n.EnUS) { + continue + } + packDir := dirs[lc.PluginID] + for targetID, po := range lc.PluginOverrides { + var merged PluginManifestOverride + hasAny := false + if packDir != "" && strings.TrimSpace(po.ManifestFile) != "" { + if loaded, err := loadPluginManifestOverrideFile(packDir, po.ManifestFile); err == nil && loaded != nil { + merged = *loaded + hasAny = true + } + } + if po.Manifest != nil { + if po.Manifest.Name != "" { + merged.Name = po.Manifest.Name + } + if po.Manifest.Description != "" { + merged.Description = po.Manifest.Description + } + if len(po.Manifest.Fields) > 0 { + if merged.Fields == nil { + merged.Fields = make(map[string]string, len(po.Manifest.Fields)) + } + for fk, fv := range po.Manifest.Fields { + merged.Fields[fk] = fv + } + } + hasAny = true + } + if !hasAny { + continue + } + if out == nil { + out = make(map[string][]resolvedManifestOverride) + } + out[targetID] = append(out[targetID], resolvedManifestOverride{ + locale: string(canon), + privileged: privileged, + ov: merged, + }) + } + } + return out +} + +func cloneLocalizedText(lt LocalizedText) LocalizedText { + out := LocalizedText{ZhCN: lt.ZhCN, EnUS: lt.EnUS} + if len(lt.Extra) > 0 { + out.Extra = make(map[string]string, len(lt.Extra)) + for k, v := range lt.Extra { + out.Extra[k] = v + } + } + return out +} + +func cloneSettingsSchemaWithOverrides(sc *SettingsSchema, list []resolvedManifestOverride) *SettingsSchema { + if sc == nil { + return nil + } + cp := *sc + cp.Title = cloneLocalizedText(sc.Title) + if len(sc.Properties) > 0 { + cp.Properties = make(map[string]SettingProperty, len(sc.Properties)) + for pk, prop := range sc.Properties { + pcp := prop + pcp.Title = cloneLocalizedText(prop.Title) + pcp.Description = cloneLocalizedText(prop.Description) + cp.Properties[pk] = pcp + } + } + for _, r := range list { + if v := r.ov.Fields["settings.title"]; v != "" { + applyLocalizedOverride(&cp.Title, r.locale, v, r.privileged) + } + for pk, prop := range cp.Properties { + changed := false + if v := firstNonEmptyField(r.ov.Fields, "setting."+pk+".title", pk+".title"); v != "" { + applyLocalizedOverride(&prop.Title, r.locale, v, r.privileged) + changed = true + } + if v := firstNonEmptyField(r.ov.Fields, "setting."+pk+".description", pk+".description"); v != "" { + applyLocalizedOverride(&prop.Description, r.locale, v, r.privileged) + changed = true + } + if changed { + cp.Properties[pk] = prop + } + } + } + return &cp +} + +func firstNonEmptyField(fields map[string]string, keys ...string) string { + if len(fields) == 0 { + return "" + } + for _, k := range keys { + if v := strings.TrimSpace(fields[k]); v != "" { + return v + } + } + return "" +} + +// LocalizePluginInfos returns a copy of infos enriched with any active Language Pack +// `pluginOverrides` translations for plugin Name, Description, and SettingsSchema. +func (m *Manager) LocalizePluginInfos(infos []PluginInfo) []PluginInfo { + ovs := m.activeManifestOverrides() + if len(ovs) == 0 || len(infos) == 0 { + return infos + } + out := make([]PluginInfo, len(infos)) + for i, info := range infos { + cp := info + if list := ovs[info.ID]; len(list) > 0 { + cp.Name = cloneLocalizedText(info.Name) + cp.Description = cloneLocalizedText(info.Description) + for _, r := range list { + if r.ov.Name != "" { + applyLocalizedOverride(&cp.Name, r.locale, r.ov.Name, r.privileged) + } + if r.ov.Description != "" { + applyLocalizedOverride(&cp.Description, r.locale, r.ov.Description, r.privileged) + } + } + cp.Settings = cloneSettingsSchemaWithOverrides(info.Settings, list) + } + out[i] = cp + } + return out +} + +// overridableText is a contribution text that a Language Pack may replace, and +// the override fields that do so, in order of preference. +type overridableText struct { + text *LocalizedText + keys []string +} + +// localizeContributions returns a copy of items with the active Language Pack +// overrides applied to the texts that texts lists for each item. +func localizeContributions[T any](m *Manager, items []T, texts func(*T) (pluginID string, list []overridableText)) []T { + ovs := m.activeManifestOverrides() + if len(ovs) == 0 || len(items) == 0 { + return items + } + out := slices.Clone(items) + for i := range out { + pluginID, list := texts(&out[i]) + for _, t := range list { + if len(ovs[pluginID]) > 0 { + *t.text = cloneLocalizedText(*t.text) + } + for _, r := range ovs[pluginID] { + if v := firstNonEmptyField(r.ov.Fields, t.keys...); v != "" { + applyLocalizedOverride(t.text, r.locale, v, r.privileged) + } + } + } + } + return out +} + +// LocalizeMenus applies Language Pack overrides to menu titles. +func (m *Manager) LocalizeMenus(items []MenuContribution) []MenuContribution { + return localizeContributions(m, items, func(c *MenuContribution) (string, []overridableText) { + return c.PluginID, []overridableText{{&c.Title, []string{"menu." + c.ID + ".title", "command." + c.Command + ".title"}}} + }) +} + +// LocalizePanels applies Language Pack overrides to panel titles. +func (m *Manager) LocalizePanels(items []PanelContribution) []PanelContribution { + return localizeContributions(m, items, func(c *PanelContribution) (string, []overridableText) { + return c.PluginID, []overridableText{{&c.Title, []string{"panel." + c.ID + ".title"}}} + }) +} + +// LocalizeViews applies Language Pack overrides to view titles. +func (m *Manager) LocalizeViews(items []ViewContribution) []ViewContribution { + return localizeContributions(m, items, func(c *ViewContribution) (string, []overridableText) { + return c.PluginID, []overridableText{{&c.Title, []string{"view." + c.ID + ".title"}}} + }) +} + +// LocalizeImageSources applies Language Pack overrides to image source titles and descriptions. +func (m *Manager) LocalizeImageSources(items []ImageSourceContribution) []ImageSourceContribution { + return localizeContributions(m, items, func(c *ImageSourceContribution) (string, []overridableText) { + return c.PluginID, []overridableText{ + {&c.Title, []string{"imageSource." + c.ID + ".title"}}, + {&c.Description, []string{"imageSource." + c.ID + ".description"}}, + } + }) +} + +// LocalizeVMCards applies Language Pack overrides to VM card titles and values. +func (m *Manager) LocalizeVMCards(items []VMCardContribution) []VMCardContribution { + return localizeContributions(m, items, func(c *VMCardContribution) (string, []overridableText) { + return c.PluginID, []overridableText{ + {&c.Title, []string{"vmCard." + c.ID + ".title"}}, + {&c.Value, []string{"vmCard." + c.ID + ".value"}}, + } + }) +} + +// LocalizeSettingsPages applies Language Pack overrides to settings page titles. +func (m *Manager) LocalizeSettingsPages(items []SettingsPageContribution) []SettingsPageContribution { + return localizeContributions(m, items, func(c *SettingsPageContribution) (string, []overridableText) { + return c.PluginID, []overridableText{{&c.Title, []string{"settingsPage." + c.ID + ".title"}}} + }) +} + +// LocalizeStatusItems applies Language Pack overrides to status item texts and tooltips. +func (m *Manager) LocalizeStatusItems(items []StatusItemContribution) []StatusItemContribution { + return localizeContributions(m, items, func(c *StatusItemContribution) (string, []overridableText) { + return c.PluginID, []overridableText{ + {&c.Text, []string{"statusItem." + c.ID + ".text"}}, + {&c.Tooltip, []string{"statusItem." + c.ID + ".tooltip"}}, + } + }) +} + +// CurrentLocale returns the active effective host locale for plugin operations. +func (m *Manager) CurrentLocale() i18n.Locale { + if m != nil && m.opts.LocaleFn != nil { + return i18n.EffectiveLocale(m.opts.LocaleFn()) + } + return i18n.Detect() +} + +// PluginL10nBundle builds the merged private localization dictionary for pluginID +// in loc, layering the plugin's own `/.json` files underneath any +// active Language Pack `pluginOverrides[pluginID]` entries along FallbackChain(loc). +func (m *Manager) PluginL10nBundle(pluginID string, loc i18n.Locale) map[string]string { + if m == nil || pluginID == "" || m.safeMode { + return nil + } + cacheKey := pluginID + "\x00" + string(loc) + m.mu.RLock() + gen := m.l10nGen + if cached, ok := m.l10nCache[cacheKey]; ok { + m.mu.RUnlock() + if len(cached) == 0 { + return nil + } + return maps.Clone(cached) + } + selfDir := m.installDirs[pluginID] + dirs := maps.Clone(m.installDirs) + m.mu.RUnlock() + + chain := i18n.FallbackChain(loc) + out := make(map[string]string) + + selfLocaleFiles := make(map[string]string) + if man, ok := m.registry.ManifestOf(pluginID); ok { + for _, file := range l10nFiles(selfDir, man.L10n) { + if _, exists := selfLocaleFiles[string(file.locale)]; !exists { + selfLocaleFiles[string(file.locale)] = file.rel + } + } + } + + contribs := m.registry.Locales() + // Walk fallback chain from least specific to most specific so higher-priority hops win. + for idx := len(chain) - 1; idx >= 0; idx-- { + step := string(chain[idx]) + selfKeysThisStep := make(map[string]bool) + if rel, ok := selfLocaleFiles[step]; ok { + if loaded, err := loadLocaleJSONFile(selfDir, rel); err == nil { + for k, v := range loaded { + if k != "" && v != "" { + out[k] = v + selfKeysThisStep[k] = true + } + } + } + } + for _, lc := range contribs { + if lc.Locale != step { + continue + } + privileged := isPrivilegedLocaleTrustRank(lc.TrustRank) + if !privileged && (step == string(i18n.ZhCN) || step == string(i18n.EnUS)) { + continue + } + ov, ok := lc.PluginOverrides[pluginID] + if !ok { + continue + } + applyMsg := func(k, v string) { + if k == "" || v == "" { + return + } + if !privileged && selfKeysThisStep[k] { + return + } + out[k] = v + } + packDir := dirs[lc.PluginID] + if packDir != "" && strings.TrimSpace(ov.MessagesFile) != "" { + if loaded, err := loadLocaleJSONFile(packDir, ov.MessagesFile); err == nil { + for k, v := range loaded { + applyMsg(k, v) + } + } + } + for k, v := range ov.Messages { + applyMsg(k, v) + } + } + } + m.mu.Lock() + if m.l10nGen == gen { + if len(m.l10nCache) >= 512 { + clear(m.l10nCache) + } + if len(out) == 0 { + m.l10nCache[cacheKey] = nil + } else { + m.l10nCache[cacheKey] = maps.Clone(out) + } + } + m.mu.Unlock() + if len(out) == 0 { + return nil + } + return out +} + +// NotifyLocaleChanged broadcasts `plugin/localeChanged` to all currently running +// L3 Sidecar processes without waking sleeping Sidecars. +func (m *Manager) NotifyLocaleChanged(eff i18n.Locale) { + if m == nil { + return + } + m.mu.RLock() + sups := maps.Clone(m.supervisors) + m.mu.RUnlock() + if len(sups) == 0 { + return + } + chain := i18n.FallbackChain(eff) + strChain := make([]string, len(chain)) + for i, c := range chain { + strChain[i] = string(c) + } + for pid, sup := range sups { + if sup.PID() == 0 { + continue + } + sup.NotifyIfRunning("plugin/localeChanged", map[string]any{ + "locale": string(eff), + "fallbackChain": strChain, + "l10nBundle": m.PluginL10nBundle(pid, eff), + }) + } +} + +func defaultLocaleLabel(code string) string { + switch code { + case string(i18n.ZhCN): + return "简体中文" + case string(i18n.EnUS): + return "English" + default: + return code + } +} + +func isPrivilegedLocaleTrustRank(rank int) bool { + return rank == 10 || rank == 20 || rank >= 50 +} + +func localeTrustRank(source SourceKind, trust TrustLevel) int { + switch { + case source == SourceBuiltin: + return 10 + case source == SourceBundled: + return 20 + case trust == TrustCommunity: + return 30 + case trust == TrustVerified: + return 40 + case trust == TrustOfficial: + return 50 + case source == SourceDevLink || trust == TrustDev: + return 60 + default: + return 30 + } +} + +func mergeMessages(dst, src map[string]string) { + for k, v := range src { + if k != "" && v != "" { + dst[k] = v + } + } +} + +// mergeLocaleFile merges the messages in dir/rel into dst. A missing or +// invalid file adds nothing; the plugin scanner reports those. +func mergeLocaleFile(dst map[string]string, dir, rel string) { + rel = strings.TrimSpace(rel) + if dir == "" || rel == "" { + return + } + if loaded, err := loadLocaleJSONFile(dir, rel); err == nil { + mergeMessages(dst, loaded) + } +} + +// mergeBackendMessages merges the Go-side messages of one language pack. +// Later sources win: domain files, the backend file, then inline messages. +func mergeBackendMessages(dst map[string]string, dir string, lc LocaleContribution) { + for _, dom := range []string{"native", "macosGlossary", "macos-glossary", "core"} { + mergeLocaleFile(dst, dir, lc.Files[dom]) + } + mergeLocaleFile(dst, dir, lc.BackendFile) + mergeMessages(dst, lc.Backend) +} + +// l10nFile is one `/.json` message file of a plugin. +type l10nFile struct { + locale i18n.Locale + rel string +} + +// l10nFiles lists the private message files a plugin ships in its l10n folder. +func l10nFiles(pluginDir, l10n string) []l10nFile { + l10n = strings.Trim(strings.TrimSpace(l10n), "/") + if pluginDir == "" || l10n == "" { + return nil + } + full, err := safeJoin(pluginDir, l10n) + if err != nil { + return nil + } + entries, err := os.ReadDir(full) + if err != nil { + return nil + } + var files []l10nFile + for _, ent := range entries { + if ent.IsDir() || !strings.HasSuffix(strings.ToLower(ent.Name()), ".json") { + continue + } + tag := strings.TrimSuffix(ent.Name(), filepath.Ext(ent.Name())) + if canon, ok := i18n.ParseLocale(tag); ok { + files = append(files, l10nFile{locale: canon, rel: l10n + "/" + ent.Name()}) + } + } + return files +} + +// LoadStaticLocalePacks performs an ultra-fast (< 2ms), side-effect-free scan of +// enabled plugins under dataRoot to populate backend/CLI language packs without +// starting any L3 Sidecars, AssetServer, or service dependency reconciliation. +func LoadStaticLocalePacks(dataRoot string) map[i18n.Locale]i18n.PluginCatalog { + if strings.TrimSpace(dataRoot) == "" { + i18n.SetPluginCatalogs(nil) + return nil + } + layout := NewPluginsLayout(dataRoot) + if DidLastStartupCrash(layout.Root) { + i18n.SetPluginCatalogs(nil) + return nil + } + st, err := NewStateStore(layout.Root).Load() + if err != nil || st == nil || len(st.Plugins) == 0 { + i18n.SetPluginCatalogs(nil) + return nil + } + + type staticCandidate struct { + id string + dir string + rec *PluginRecord + rank int + } + var candidates []staticCandidate + for id, rec := range st.Plugins { + if rec == nil || !rec.Enabled || rec.Source == SourceBuiltin || rec.Source == SourceBundled { + continue + } + var dir string + if rec.Source == SourceDevLink { + if !st.DeveloperMode || strings.TrimSpace(rec.DevPath) == "" { + continue + } + dir = rec.DevPath + } else { + if rec.Version == "" || !reReverseDomainID.MatchString(id) { + continue + } + if _, err := ParseSemVer(rec.Version); err != nil { + continue + } + safeDir, err := safeJoin(layout.PkgsDir(), id+"/"+rec.Version) + if err != nil { + continue + } + dir = safeDir + } + candidates = append(candidates, staticCandidate{ + id: id, + dir: dir, + rec: rec, + rank: localeTrustRank(rec.Source, rec.Trust), + }) + } + sort.Slice(candidates, func(i, j int) bool { + if candidates[i].rank != candidates[j].rank { + return candidates[i].rank < candidates[j].rank + } + return candidates[i].id < candidates[j].id + }) + + type staticLocaleItem struct { + canon i18n.Locale + rank int + id string + dir string + lc LocaleContribution + } + var items []staticLocaleItem + for _, c := range candidates { + raw, err := os.ReadFile(filepath.Join(c.dir, "plugin.json")) + if err != nil { + continue + } + var man Manifest + if json.Unmarshal(raw, &man) != nil || len(man.Contributes.Locales) == 0 { + continue + } + if c.id != "" && man.ID != c.id { + continue + } + trust := c.rec.Trust + if trust == "" { + trust = TrustCommunity + } + if c.rec.Source == SourceDevLink { + trust = TrustDev + } + _, _, entryHash, err := resolveManifestEntry(man, c.dir, false) + if err != nil { + continue + } + if computeNeedsApproval(man, trust, c.rec.ApprovedPermissions, c.rec.ApprovedEntryHash, entryHash) { + continue + } + for _, lc := range man.Contributes.Locales { + canon, ok := i18n.ParseLocale(lc.Locale) + if !ok { + continue + } + items = append(items, staticLocaleItem{ + canon: canon, + rank: c.rank, + id: c.id, + dir: c.dir, + lc: lc, + }) + } + } + + sort.Slice(items, func(i, j int) bool { + if items[i].canon != items[j].canon { + return items[i].canon < items[j].canon + } + if items[i].rank != items[j].rank { + return items[i].rank < items[j].rank + } + if items[i].lc.Priority != items[j].lc.Priority { + return items[i].lc.Priority < items[j].lc.Priority + } + return items[i].id < items[j].id + }) + + packs := make(map[i18n.Locale]i18n.PluginCatalog) + for _, it := range items { + canon := it.canon + if !isPrivilegedLocaleTrustRank(it.rank) && (canon == i18n.ZhCN || canon == i18n.EnUS) { + continue + } + lc := it.lc + cur, exists := packs[canon] + if !exists { + cur = i18n.PluginCatalog{ + Fallback: i18n.DefaultFallback(canon), + Messages: make(map[string]string), + } + } + if fb, ok := i18n.ParseLocale(lc.Fallback); ok { + cur.Fallback = fb + } + mergeBackendMessages(cur.Messages, it.dir, lc) + if len(cur.Messages) > 0 { + packs[canon] = cur + } + } + i18n.SetPluginCatalogs(packs) + return packs +} diff --git a/internal/plugin/scanner.go b/internal/plugin/scanner.go index ff07e89..81cc375 100644 --- a/internal/plugin/scanner.go +++ b/internal/plugin/scanner.go @@ -173,137 +173,170 @@ func ScanArchive(archivePath, tmpParentDir, hostVersion string, opts ScanOptions 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 { - 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")) + 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 { - addHard("manifest", "plugin.json", "cannot read plugin.json: "+err.Error(), + s.hard("manifest", "plugin.json", "cannot read plugin.json: "+err.Error(), "缺少或无法读取 plugin.json 清单文件", "Cannot read plugin.json manifest") - finalizeScanReport(&rep) - return rep + finalizeScanReport(&s.rep) + return s.rep } - var m Manifest - if err := json.Unmarshal(raw, &m); err != nil { - addHard("manifest", "plugin.json", "invalid plugin.json JSON: "+err.Error(), + 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(&rep) - return rep + finalizeScanReport(&s.rep) + return s.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 + 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(m, hostVersion, false); err != nil { - addHard("manifest", "plugin.json", err.Error(), + if err := ValidateManifest(s.m, hostVersion, false); err != nil { + s.hard("manifest", "plugin.json", err.Error(), "清单校验未通过:"+err.Error(), "Manifest validation failed: "+err.Error()) } - rep.PendingFindings = append(rep.PendingFindings, ContractFindings(m, raw)...) + s.rep.PendingFindings = append(s.rep.PendingFindings, ContractFindings(s.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 { + 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 != "" { - runtimeDirs = append(runtimeDirs, d) + s.runtimeDirs = append(s.runtimeDirs, d) } } - hasNetPerm := false - for _, p := range m.Permissions { + for _, p := range s.m.Permissions { if strings.HasPrefix(strings.TrimSpace(p), "net:") { - hasNetPerm = true + s.hasNetPerm = true break } } - // Verify declared entries exist on disk. + 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(dir, rel) + full, jErr := safeJoin(s.dir, rel) if jErr != nil { - addHard("missing-entry", rel, fmt.Sprintf("invalid %s path %q: %v", label, rel, jErr), + 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 { - addHard("missing-entry", rel, fmt.Sprintf("declared %s %q is missing", label, rel), + 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() { - addHard("missing-entry", rel, fmt.Sprintf("declared %s %q is not a directory", label, rel), + 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() { - addHard("missing-entry", rel, fmt.Sprintf("declared %s %q is a directory, expected file", label, rel), + 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)) } } - 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("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 m.Contributes.Panels { - if declaredPanelDir != "" && panel.Entry != "" { - checkEntryFile("panel entry", declaredPanelDir+"/"+strings.TrimPrefix(panel.Entry, "/"), false) + for _, panel := range s.m.Contributes.Panels { + if s.panelDir != "" && panel.Entry != "" { + checkEntryFile("panel entry", s.panelDir+"/"+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 { +func (s *packageScan) checkThemes() { + for _, th := range s.m.Contributes.Themes { if th.Stylesheet != "" { - declaredThemeCSS[normalizeRel(th.Stylesheet)] = true + s.themeCSS[normalizeRel(th.Stylesheet)] = true } - if err := ValidateThemeContribution(th, dir); err != nil { - addHard("theme-css", th.Stylesheet, err.Error(), + 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 != "" && opts.Contract != nil { - if cssPath, jErr := safeJoin(dir, th.Stylesheet); jErr == nil { + 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), *opts.Contract) { - addPending("ui-contract", th.Stylesheet, issue, + 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)) } @@ -311,15 +344,15 @@ func ScanDirectory(dir, hostVersion string, opts ScanOptions) ScanReport { } } } +} - // Walk all files in the package for redlines, executables, SVG scripts, CSS, and JS safety. - var netScriptHits []string +func (s *packageScan) checkFiles() { var walkFiles []string - _ = filepath.Walk(dir, func(p string, info os.FileInfo, wErr error) error { + _ = 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(dir, p) + rel, rErr := filepath.Rel(s.dir, p) if rErr != nil { return nil } @@ -327,202 +360,195 @@ func ScanDirectory(dir, hostVersion string, opts ScanOptions) ScanReport { 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)) + s.checkFile(rel) + } +} - 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)) - } - } - } +// 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)) - 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)) - } - } + 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 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 := ValidateThemeCSSSafety(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: 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)) - } + } + 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)) } } } - 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 + 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 } } } - } else if opts.RequireChecksums { - addHard("checksum", "SHA256SUMS", "package missing SHA256SUMS", + 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: permission", rel), + fmt.Sprintf("脚本 %s 调用了网络接口,但清单未声明 net: 权限", rel), + fmt.Sprintf("Script %s calls network APIs without declaring any net: 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 { - addPending("checksum", "SHA256SUMS", "SHA256SUMS absent (acceptable in dev link mode; required for .zip distribution)", + 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 rep.Trust == TrustCommunity { - addPending("trust-unsigned", "", "community package is not signed by an official or verified market key", + 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") } +} - // 7. L10n & Locale contributions. - if strings.TrimSpace(m.L10n) != "" { - if err := validatePluginL10nDir(m.L10n, dir); err != nil { - addHard("l10n", m.L10n, err.Error(), +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(m.Contributes.Locales) > 0 { - if _, locFindings, cErr := CheckLocalePack(dir); cErr == nil && len(locFindings) > 0 { + 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" { - addHard("locale", lf.Check, lf.Message, + s.hard("locale", lf.Check, lf.Message, "语言包校验错误:"+lf.Message, "Language pack validation error: "+lf.Message) } else if lf.Severity == "warn" { - addPending("locale", lf.Check, lf.Message, + s.pending("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(), + 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)) } } } } - - // 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) {