- Add unified static security scanner and install/load gate (internal/plugin/scanner.go) blocking undeclared binaries, SVG active content, theme script escapes, and undeclared network calls while reporting L3 Sidecar privileges and SHA-256 - Add lazy plugin market client (internal/plugin/market.go) with remote index fetching (REIMS_GO_PLUGIN_MARKET_URL), memory/disk caching, embedded offline fallback, withdrawn-plugin blocking, compatibility preflight, and SHA-256 verification - Extend CLI with plugin search/update/install <id> and enhanced .zip/--json security doctor output; update backend locale catalog and plugin architecture docs
2008 lines
54 KiB
Go
2008 lines
54 KiB
Go
package plugin
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"sort"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/Nwflower/reims-go/internal/i18n"
|
|
)
|
|
|
|
// SidecarDriverFactory builds a guest driver proxy from a Sidecar contribution
|
|
// and supervisor without importing internal/driver into internal/plugin.
|
|
type SidecarDriverFactory func(contrib GuestDriverContribution, sup *SidecarSupervisor) any
|
|
|
|
// ManagerOptions configures the high-level Plugin Manager.
|
|
type ManagerOptions struct {
|
|
DataRoot string
|
|
HostVersion string
|
|
SafeMode bool
|
|
Keyring []SigningKey
|
|
RedactFn func(string) string
|
|
Logger func(source, line string)
|
|
LocaleFn func() i18n.Locale
|
|
SidecarDriverFactory SidecarDriverFactory
|
|
OnSettingsChanged func(pluginID, vmName string)
|
|
}
|
|
|
|
// ActiveThemePayload is sent to the frontend to apply L1/L2/Tier-3 themes (§5.1).
|
|
type ActiveThemePayload struct {
|
|
ThemeID string `json:"theme_id"`
|
|
PluginID string `json:"plugin_id,omitempty"`
|
|
ActiveScheme string `json:"active_scheme,omitempty"`
|
|
Theme *ThemeContribution `json:"theme,omitempty"`
|
|
CustomSchemes []CustomThemeScheme `json:"custom_schemes,omitempty"`
|
|
CSS string `json:"css,omitempty"`
|
|
AssetBaseURL string `json:"asset_base_url,omitempty"`
|
|
UIScriptURL string `json:"ui_script_url,omitempty"`
|
|
UIScriptTrust TrustLevel `json:"ui_script_trust,omitempty"`
|
|
}
|
|
|
|
// Manager coordinates Registry, StateStore, package installation, safe mode,
|
|
// settings, themes, AssetServer, Broker, and L3 Sidecar supervisors.
|
|
type Manager struct {
|
|
opts ManagerOptions
|
|
layout PluginsLayout
|
|
store *StateStore
|
|
registry *Registry
|
|
broker *Broker
|
|
assets *AssetServer
|
|
|
|
mu sync.RWMutex
|
|
state *StateFile
|
|
stateLoadErr error
|
|
safeMode bool
|
|
crashDetected bool
|
|
installDirs map[string]string // pluginID -> dir (for AssetServer)
|
|
supervisors map[string]*SidecarSupervisor
|
|
l10nCache map[string]map[string]string
|
|
l10nGen uint64
|
|
}
|
|
|
|
// NewManager initializes the Plugin Manager for DataRoot. If state.json is
|
|
// corrupt, stateLoadErr is recorded and returned on load rather than wiping state (§6.1).
|
|
func NewManager(opts ManagerOptions) (*Manager, error) {
|
|
layout := NewPluginsLayout(opts.DataRoot)
|
|
reg := NewRegistry(opts.Logger)
|
|
if opts.LocaleFn != nil {
|
|
reg.SetLocaleProvider(opts.LocaleFn)
|
|
}
|
|
broker := NewBroker(layout, reg, opts.RedactFn)
|
|
|
|
m := &Manager{
|
|
opts: opts,
|
|
layout: layout,
|
|
store: NewStateStore(layout.Root),
|
|
registry: reg,
|
|
broker: broker,
|
|
safeMode: opts.SafeMode,
|
|
crashDetected: DidLastStartupCrash(layout.Root),
|
|
installDirs: make(map[string]string),
|
|
supervisors: make(map[string]*SidecarSupervisor),
|
|
l10nCache: make(map[string]map[string]string),
|
|
}
|
|
reg.OnChange(func() {
|
|
m.mu.Lock()
|
|
clear(m.l10nCache)
|
|
m.l10nGen++
|
|
m.mu.Unlock()
|
|
})
|
|
m.assets = NewAssetServer(func(pluginID string) (string, bool) {
|
|
m.mu.RLock()
|
|
dir, ok := m.installDirs[pluginID]
|
|
m.mu.RUnlock()
|
|
return dir, ok
|
|
})
|
|
|
|
st, err := m.store.Load()
|
|
if err != nil {
|
|
m.stateLoadErr = err
|
|
return m, err
|
|
}
|
|
m.state = st
|
|
return m, nil
|
|
}
|
|
|
|
func (m *Manager) Registry() *Registry { return m.registry }
|
|
func (m *Manager) Broker() *Broker { return m.broker }
|
|
func (m *Manager) Assets() *AssetServer { return m.assets }
|
|
func (m *Manager) Layout() PluginsLayout { return m.layout }
|
|
func (m *Manager) SafeMode() bool { return m.safeMode }
|
|
func (m *Manager) CrashDetected() bool { return m.crashDetected }
|
|
|
|
// DesiredFor returns whether pluginID should be enabled according to state.json,
|
|
// falling back to defaultEnabled if no saved record exists.
|
|
func (m *Manager) DesiredFor(id string, defaultEnabled bool) bool {
|
|
m.mu.RLock()
|
|
defer m.mu.RUnlock()
|
|
if m.state != nil {
|
|
if rec, ok := m.state.Plugins[id]; ok {
|
|
return rec.Enabled
|
|
}
|
|
}
|
|
return defaultEnabled
|
|
}
|
|
|
|
// LoadBundled registers official L1 plugins embedded inside reims-go.exe (§9).
|
|
func (m *Manager) LoadBundled(manifests []Manifest) error {
|
|
for _, man := range manifests {
|
|
if err := ValidateManifest(man, m.opts.HostVersion, true); err != nil {
|
|
return fmt.Errorf("invalid bundled plugin %s: %w", man.ID, err)
|
|
}
|
|
desired := m.DesiredFor(man.ID, man.DefaultEnabled)
|
|
if m.safeMode {
|
|
// Bundled official L1 plugins obey safe mode too if non-builtin?
|
|
// §9: safe mode skips all third-party plugins; bundled official defaults to off anyway.
|
|
if !man.DefaultEnabled {
|
|
desired = false
|
|
}
|
|
}
|
|
if err := m.registry.Register(PluginDef{
|
|
Manifest: man,
|
|
Source: SourceBundled,
|
|
Trust: TrustOfficial,
|
|
Removable: false,
|
|
Desired: desired,
|
|
LogPath: m.layout.LogPath(man.ID),
|
|
}); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// LoadExternal loads all installed packages and dev links from state.json.
|
|
// In SafeMode, external plugins are registered as disabled (off) so the user
|
|
// can inspect and remove/disable faulty plugins safely (§9).
|
|
func (m *Manager) LoadExternal() error {
|
|
m.mu.RLock()
|
|
st := m.state
|
|
safe := m.safeMode
|
|
var devMode bool
|
|
var activeThemeID string
|
|
type extEntry struct {
|
|
id string
|
|
rec PluginRecord
|
|
}
|
|
var entries []extEntry
|
|
if st != nil {
|
|
devMode = st.DeveloperMode
|
|
activeThemeID = st.ActiveThemeID
|
|
for id, rec := range st.Plugins {
|
|
if rec == nil || rec.Source == SourceBuiltin || rec.Source == SourceBundled {
|
|
continue
|
|
}
|
|
cp := *rec
|
|
cp.ApprovedPermissions = append([]string(nil), rec.ApprovedPermissions...)
|
|
entries = append(entries, extEntry{id: id, rec: cp})
|
|
}
|
|
}
|
|
m.mu.RUnlock()
|
|
if st == nil {
|
|
return m.stateLoadErr
|
|
}
|
|
|
|
if !safe {
|
|
_ = BeginStartupInit(m.layout.Root)
|
|
}
|
|
|
|
for _, item := range entries {
|
|
id := item.id
|
|
rec := item.rec
|
|
var dir string
|
|
switch rec.Source {
|
|
case SourceDevLink:
|
|
if !devMode {
|
|
continue
|
|
}
|
|
dir = rec.DevPath
|
|
default:
|
|
if rec.Version == "" || !reReverseDomainID.MatchString(id) {
|
|
continue
|
|
}
|
|
if _, err := ParseSemVer(rec.Version); err != nil {
|
|
continue
|
|
}
|
|
safeDir, err := safeJoin(m.layout.PkgsDir(), id+"/"+rec.Version)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
dir = safeDir
|
|
}
|
|
if dir == "" {
|
|
continue
|
|
}
|
|
if err := m.registerExternalDir(dir, &rec, safe); err != nil && m.opts.Logger != nil {
|
|
m.opts.Logger("plugin", fmt.Sprintf("skipped external plugin %s: %v", id, err))
|
|
}
|
|
}
|
|
// Restore active theme unless in safe mode (§5.1: safe mode always reverts to builtin theme).
|
|
if !safe && activeThemeID != "" {
|
|
_ = m.registry.SetActiveTheme(activeThemeID)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (m *Manager) registerExternalDir(dir string, rec *PluginRecord, safeMode bool) error {
|
|
raw, err := os.ReadFile(filepath.Join(dir, "plugin.json"))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
var man Manifest
|
|
if err := json.Unmarshal(raw, &man); err != nil {
|
|
return err
|
|
}
|
|
if err := ValidateManifest(man, m.opts.HostVersion, false); err != nil {
|
|
return err
|
|
}
|
|
if err := validateDiskContributions(man, dir); err != nil {
|
|
return err
|
|
}
|
|
if rec.ID != "" && man.ID != rec.ID {
|
|
return fmt.Errorf("manifest plugin id %q does not match state record %q", man.ID, rec.ID)
|
|
}
|
|
trust := rec.Trust
|
|
if trust == "" {
|
|
trust = TrustCommunity
|
|
}
|
|
if rec.Source == SourceDevLink {
|
|
trust = TrustDev
|
|
}
|
|
|
|
entryRel := man.Entry.Sidecar
|
|
if entryRel == "" {
|
|
entryRel = man.Entry.UIScript
|
|
}
|
|
if entryRel == "" {
|
|
entryRel = man.Entry.Script
|
|
}
|
|
entryAbs := ""
|
|
entryHash := ""
|
|
if entryRel != "" {
|
|
full, err := safeJoin(dir, entryRel)
|
|
if err != nil {
|
|
return fmt.Errorf("invalid plugin entry path %q: %w", entryRel, err)
|
|
}
|
|
entryAbs = full
|
|
entryHash, _ = fileSHA256Hex(full)
|
|
}
|
|
|
|
needsApproval := computeNeedsApproval(man, trust, rec.ApprovedPermissions, rec.ApprovedEntryHash, entryHash)
|
|
desired := rec.Enabled && !safeMode && !needsApproval
|
|
|
|
m.mu.Lock()
|
|
m.installDirs[man.ID] = dir
|
|
m.mu.Unlock()
|
|
|
|
tier := man.InferTier(false)
|
|
var activate Activator
|
|
if tier == TierL3 && entryAbs != "" {
|
|
activate = m.buildSidecarActivator(man, entryAbs, rec.BlockingGuardOK)
|
|
}
|
|
|
|
return m.registry.Register(PluginDef{
|
|
Manifest: man,
|
|
Source: rec.Source,
|
|
Trust: trust,
|
|
InstallDir: dir,
|
|
EntryPath: entryAbs,
|
|
EntryHash: entryHash,
|
|
LogPath: m.layout.LogPath(man.ID),
|
|
Removable: true,
|
|
Desired: desired,
|
|
ApprovedPermissions: append([]string(nil), rec.ApprovedPermissions...),
|
|
NeedsApproval: needsApproval,
|
|
Activate: activate,
|
|
})
|
|
}
|
|
|
|
func computeNeedsApproval(m Manifest, trust TrustLevel, approvedPerms []string, approvedHash, currentHash string) bool {
|
|
if trust == TrustOfficial {
|
|
return false
|
|
}
|
|
approvedSet := make(map[string]bool, len(approvedPerms))
|
|
for _, p := range approvedPerms {
|
|
approvedSet[p] = true
|
|
}
|
|
// Any unapproved high-risk permission requires explicit confirmation (§7.1).
|
|
for _, hp := range HighRiskPermissions(m.Permissions) {
|
|
if !approvedSet[hp] {
|
|
return true
|
|
}
|
|
}
|
|
// Community L3 sidecar requires explicit hash approval (§7.2).
|
|
if trust == TrustCommunity && m.InferTier(false) == TierL3 {
|
|
if currentHash == "" || approvedHash != currentHash {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func (m *Manager) buildSidecarActivator(man Manifest, exePath string, blockingAllowed bool) Activator {
|
|
return func(ctx context.Context, sc *Scope) error {
|
|
pid := man.ID
|
|
sup := NewSidecarSupervisor(SidecarOptions{
|
|
PluginID: pid,
|
|
ExePath: exePath,
|
|
DataDir: m.layout.DataDir(pid),
|
|
Broker: m.broker,
|
|
Registry: m.registry,
|
|
IdleTimeout: 5 * time.Minute,
|
|
LocaleProvider: func() (string, []string, map[string]string) {
|
|
loc := m.CurrentLocale()
|
|
chain := i18n.FallbackChain(loc)
|
|
strChain := make([]string, len(chain))
|
|
for i, c := range chain {
|
|
strChain[i] = string(c)
|
|
}
|
|
return string(loc), strChain, m.PluginL10nBundle(pid, loc)
|
|
},
|
|
})
|
|
m.mu.Lock()
|
|
m.supervisors[pid] = sup
|
|
m.mu.Unlock()
|
|
|
|
sc.OnDispose(func() {
|
|
sup.Stop()
|
|
m.mu.Lock()
|
|
if m.supervisors[pid] == sup {
|
|
delete(m.supervisors, pid)
|
|
}
|
|
m.mu.Unlock()
|
|
})
|
|
|
|
// Wire Sidecar hooks.
|
|
for _, hk := range man.Contributes.Hooks {
|
|
h := hk
|
|
m.registry.Hooks().Subscribe(sc, HookRegistration{
|
|
PluginID: pid,
|
|
Event: h.Event,
|
|
Priority: h.Priority,
|
|
Blocking: h.Blocking,
|
|
BlockingAllowed: blockingAllowed,
|
|
Handler: func(hctx context.Context, payload any) (any, error) {
|
|
switch h.Event {
|
|
case EventVMBeforeStart:
|
|
var intent StartIntent
|
|
if err := sup.Call(hctx, "hook/"+h.Event, payload, &intent); err != nil {
|
|
return nil, err
|
|
}
|
|
intent.PluginID = pid
|
|
return intent, nil
|
|
case EventHostPreflight:
|
|
var pr PreflightResult
|
|
if err := sup.Call(hctx, "hook/"+h.Event, payload, &pr); err != nil {
|
|
return nil, err
|
|
}
|
|
return pr, nil
|
|
case EventVMBeforeCreate:
|
|
var bcr BeforeCreateResult
|
|
if err := sup.Call(hctx, "hook/"+h.Event, payload, &bcr); err != nil {
|
|
return nil, err
|
|
}
|
|
return bcr, nil
|
|
default:
|
|
var out any
|
|
err := sup.Call(hctx, "hook/"+h.Event, payload, &out)
|
|
return out, err
|
|
}
|
|
},
|
|
})
|
|
}
|
|
|
|
// Wire Sidecar commands.
|
|
for _, cmd := range man.Contributes.Commands {
|
|
c := cmd
|
|
m.registry.RegisterCommand(sc, c, func(cctx context.Context, args map[string]any) (any, error) {
|
|
var out any
|
|
err := sup.Call(cctx, "command/invoke", map[string]any{
|
|
"command": c.ID,
|
|
"args": args,
|
|
}, &out)
|
|
return out, err
|
|
})
|
|
}
|
|
|
|
// Wire Sidecar diagnostics collectors.
|
|
for _, diag := range man.Contributes.Diagnostics {
|
|
dg := diag
|
|
m.registry.RegisterDiagnostics(sc, dg, func(dctx context.Context, vmName string) (DiagnosticsEntry, error) {
|
|
var entry DiagnosticsEntry
|
|
err := sup.Call(dctx, "diagnostics/collect", map[string]any{
|
|
"id": dg.ID,
|
|
"vm_name": vmName,
|
|
}, &entry)
|
|
return entry, err
|
|
})
|
|
}
|
|
|
|
// Wire Sidecar guest drivers.
|
|
if m.opts.SidecarDriverFactory != nil {
|
|
for _, gd := range man.Contributes.GuestDrivers {
|
|
drv := m.opts.SidecarDriverFactory(gd, sup)
|
|
if drv != nil {
|
|
m.registry.RegisterGuestDriver(sc, gd.ID, drv)
|
|
}
|
|
}
|
|
}
|
|
|
|
// Eagerly start only if activation explicitly includes "onStartup" (§8).
|
|
for _, act := range man.Activation {
|
|
if strings.EqualFold(act, "onStartup") {
|
|
if err := sup.EnsureStarted(ctx); err != nil {
|
|
return err
|
|
}
|
|
break
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
}
|
|
|
|
// InstallLocalArchive transactionally installs a local .zip plugin package and
|
|
// records it in state.json (disabled by default until user enables/approves it).
|
|
func (m *Manager) InstallLocalArchive(ctx context.Context, archivePath string, opts PackageInstallOptions) (*PluginInfo, error) {
|
|
return m.InstallArchiveWithSource(ctx, archivePath, SourceLocal, opts)
|
|
}
|
|
|
|
// InstallArchiveWithSource transactionally installs a .zip plugin package and
|
|
// records its origin source (SourceLocal or SourceMarket) in state.json.
|
|
func (m *Manager) InstallArchiveWithSource(ctx context.Context, archivePath string, source SourceKind, opts PackageInstallOptions) (*PluginInfo, error) {
|
|
if source == "" {
|
|
source = SourceLocal
|
|
}
|
|
if opts.HostVersion == "" {
|
|
opts.HostVersion = m.opts.HostVersion
|
|
}
|
|
if len(opts.Keyring) == 0 {
|
|
opts.Keyring = m.opts.Keyring
|
|
}
|
|
opts.AllowUnsigned = true
|
|
|
|
installed, err := InstallArchive(m.layout, archivePath, opts)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
m.mu.Lock()
|
|
if m.state == nil {
|
|
m.mu.Unlock()
|
|
return nil, errors.New("plugin state not loaded")
|
|
}
|
|
rec := m.state.Plugins[installed.Manifest.ID]
|
|
if rec == nil {
|
|
rec = &PluginRecord{
|
|
ID: installed.Manifest.ID,
|
|
Source: source,
|
|
Enabled: false,
|
|
}
|
|
m.state.Plugins[installed.Manifest.ID] = rec
|
|
}
|
|
// Preserve previously installed versions for rollback (§9).
|
|
foundVer := false
|
|
for _, v := range rec.InstalledVersions {
|
|
if v == installed.Manifest.Version {
|
|
foundVer = true
|
|
break
|
|
}
|
|
}
|
|
if !foundVer {
|
|
rec.InstalledVersions = append(rec.InstalledVersions, installed.Manifest.Version)
|
|
}
|
|
rec.Version = installed.Manifest.Version
|
|
rec.Source = source
|
|
rec.Trust = installed.Trust
|
|
rec.UpdatedAt = time.Now()
|
|
|
|
// If upgrade introduces unapproved high-risk permissions or changed binary hash, pause it (§7.1).
|
|
if computeNeedsApproval(installed.Manifest, installed.Trust, rec.ApprovedPermissions, rec.ApprovedEntryHash, installed.EntryHash) {
|
|
rec.Enabled = false
|
|
}
|
|
if err := m.store.Save(m.state); err != nil {
|
|
m.mu.Unlock()
|
|
return nil, err
|
|
}
|
|
recCopy := *rec
|
|
m.mu.Unlock()
|
|
|
|
if err := m.registerExternalDir(installed.InstallDir, &recCopy, m.safeMode); err != nil {
|
|
return nil, err
|
|
}
|
|
m.registry.Reconcile(ctx)
|
|
info, _ := m.registry.Info(installed.Manifest.ID)
|
|
return &info, nil
|
|
}
|
|
|
|
// LinkDev links a local plugin directory in developer mode (trust=dev, §5.1, §9).
|
|
func (m *Manager) LinkDev(ctx context.Context, dir string) (*PluginInfo, error) {
|
|
absDir, err := filepath.Abs(dir)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
raw, err := os.ReadFile(filepath.Join(absDir, "plugin.json"))
|
|
if err != nil {
|
|
return nil, fmt.Errorf("read plugin.json: %w", err)
|
|
}
|
|
var man Manifest
|
|
if err := json.Unmarshal(raw, &man); err != nil {
|
|
return nil, fmt.Errorf("parse plugin.json: %w", err)
|
|
}
|
|
if err := ValidateManifest(man, m.opts.HostVersion, false); err != nil {
|
|
return nil, err
|
|
}
|
|
if err := validateDiskContributions(man, absDir); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
m.mu.Lock()
|
|
if m.state == nil {
|
|
m.mu.Unlock()
|
|
return nil, m.stateNotLoadedErr()
|
|
}
|
|
m.state.DeveloperMode = true
|
|
rec := m.state.Plugins[man.ID]
|
|
if rec == nil {
|
|
rec = &PluginRecord{ID: man.ID}
|
|
m.state.Plugins[man.ID] = rec
|
|
}
|
|
rec.Source = SourceDevLink
|
|
rec.Trust = TrustDev
|
|
rec.Version = man.Version
|
|
rec.DevPath = absDir
|
|
rec.Enabled = false
|
|
rec.UpdatedAt = time.Now()
|
|
if err := m.store.Save(m.state); err != nil {
|
|
m.mu.Unlock()
|
|
return nil, err
|
|
}
|
|
recCopy := *rec
|
|
m.mu.Unlock()
|
|
|
|
if err := m.registerExternalDir(absDir, &recCopy, m.safeMode); err != nil {
|
|
return nil, err
|
|
}
|
|
m.registry.Reconcile(ctx)
|
|
info, _ := m.registry.Info(man.ID)
|
|
return &info, nil
|
|
}
|
|
|
|
// Enable activates a plugin, optionally recording high-risk permission approval (§7.1, §7.2).
|
|
func (m *Manager) Enable(ctx context.Context, id string, approveHighRisk bool) error {
|
|
info, ok := m.registry.Info(id)
|
|
if !ok {
|
|
return fmt.Errorf("plugin %q not found", id)
|
|
}
|
|
if m.safeMode && info.Source != SourceBuiltin {
|
|
return errors.New("cannot enable third-party plugins in safe mode")
|
|
}
|
|
if info.NeedsApproval && !approveHighRisk {
|
|
return fmt.Errorf("plugin %q requires explicit high-risk permission approval", id)
|
|
}
|
|
|
|
m.mu.Lock()
|
|
if m.state == nil {
|
|
m.mu.Unlock()
|
|
return m.stateNotLoadedErr()
|
|
}
|
|
rec := m.state.Plugins[id]
|
|
if rec == nil {
|
|
rec = &PluginRecord{ID: id, Source: info.Source, Trust: info.Trust, Version: info.Version}
|
|
m.state.Plugins[id] = rec
|
|
}
|
|
prevEnabled := rec.Enabled
|
|
prevApprovedPerms := append([]string(nil), rec.ApprovedPermissions...)
|
|
prevApprovedHash := rec.ApprovedEntryHash
|
|
rec.Enabled = true
|
|
rec.UpdatedAt = time.Now()
|
|
if approveHighRisk {
|
|
perms := make([]string, 0, len(info.Permissions))
|
|
for _, p := range info.Permissions {
|
|
perms = append(perms, p.Name)
|
|
}
|
|
rec.ApprovedPermissions = perms
|
|
rec.ApprovedEntryHash = info.EntryHash
|
|
}
|
|
dir := info.InstallDir
|
|
recCopy := *rec
|
|
recCopy.ApprovedPermissions = append([]string(nil), rec.ApprovedPermissions...)
|
|
m.mu.Unlock()
|
|
|
|
if approveHighRisk && dir != "" && info.Source != SourceBuiltin && info.Source != SourceBundled {
|
|
if err := m.registerExternalDir(dir, &recCopy, false); err != nil {
|
|
m.mu.Lock()
|
|
rec.Enabled = prevEnabled
|
|
rec.ApprovedPermissions = prevApprovedPerms
|
|
rec.ApprovedEntryHash = prevApprovedHash
|
|
m.mu.Unlock()
|
|
return err
|
|
}
|
|
}
|
|
if err := m.registry.SetDesired(ctx, id, true); err != nil {
|
|
m.mu.Lock()
|
|
rec.Enabled = prevEnabled
|
|
rec.ApprovedPermissions = prevApprovedPerms
|
|
rec.ApprovedEntryHash = prevApprovedHash
|
|
m.mu.Unlock()
|
|
return err
|
|
}
|
|
m.mu.Lock()
|
|
err := m.store.Save(m.state)
|
|
m.mu.Unlock()
|
|
return err
|
|
}
|
|
|
|
// Disable turns off a plugin (if not in use) and persists the state.
|
|
func (m *Manager) Disable(ctx context.Context, id string) error {
|
|
if err := m.registry.SetDesired(ctx, id, false); err != nil {
|
|
return err
|
|
}
|
|
activeThemeNil := m.registry.ActiveTheme() == nil
|
|
m.mu.Lock()
|
|
if m.state == nil {
|
|
m.mu.Unlock()
|
|
return m.stateNotLoadedErr()
|
|
}
|
|
rec := m.state.Plugins[id]
|
|
if rec == nil {
|
|
rec = &PluginRecord{ID: id}
|
|
m.state.Plugins[id] = rec
|
|
}
|
|
rec.Enabled = false
|
|
rec.UpdatedAt = time.Now()
|
|
if m.state.ActiveThemeID != "" && activeThemeNil {
|
|
// If disabling the active theme's plugin, fall back to builtin default theme (§5.1).
|
|
m.state.ActiveThemeID = ""
|
|
}
|
|
err := m.store.Save(m.state)
|
|
m.mu.Unlock()
|
|
return err
|
|
}
|
|
|
|
// MarkBootComplete clears the plugin startup crash sentinel AFTER Reconcile
|
|
// has activated plugins cleanly (M8, §9).
|
|
func (m *Manager) MarkBootComplete() {
|
|
EndStartupInit(m.layout.Root)
|
|
}
|
|
|
|
// Remove uninstalls a removable external plugin (refusing builtins/bundled or in-use plugins).
|
|
// Also allows removing orphaned/failed records present only in state.json (M8).
|
|
func (m *Manager) Remove(ctx context.Context, id string, purgeData bool) error {
|
|
if info, ok := m.registry.Info(id); ok {
|
|
if !info.Removable {
|
|
return fmt.Errorf("plugin %q is built-in or bundled and cannot be uninstalled (disable it instead)", id)
|
|
}
|
|
if err := m.registry.Unregister(ctx, id); err != nil {
|
|
return err
|
|
}
|
|
} else {
|
|
m.mu.RLock()
|
|
existsInState := m.state != nil && m.state.Plugins[id] != nil
|
|
m.mu.RUnlock()
|
|
if !existsInState {
|
|
return fmt.Errorf("plugin %q not found", id)
|
|
}
|
|
}
|
|
m.mu.Lock()
|
|
if m.state == nil {
|
|
m.mu.Unlock()
|
|
return m.stateNotLoadedErr()
|
|
}
|
|
delete(m.state.Plugins, id)
|
|
delete(m.installDirs, id)
|
|
err := m.store.Save(m.state)
|
|
m.mu.Unlock()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
_ = os.RemoveAll(filepath.Join(m.layout.PkgsDir(), id))
|
|
if purgeData {
|
|
_ = os.RemoveAll(m.layout.DataDir(id))
|
|
_ = os.Remove(m.layout.LogPath(id))
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// RetireRecords drops state.json records for plugin IDs that no longer exist,
|
|
// for example builtins merged into another plugin, and returns the removed
|
|
// records so the caller can carry their choices over. Nothing is saved when
|
|
// none of the IDs has a record.
|
|
func (m *Manager) RetireRecords(ids []string) (map[string]*PluginRecord, error) {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
if m.state == nil {
|
|
return nil, m.stateNotLoadedErr()
|
|
}
|
|
removed := map[string]*PluginRecord{}
|
|
for _, id := range ids {
|
|
if rec, ok := m.state.Plugins[id]; ok {
|
|
removed[id] = rec
|
|
delete(m.state.Plugins, id)
|
|
}
|
|
}
|
|
if len(removed) == 0 {
|
|
return removed, nil
|
|
}
|
|
return removed, m.store.Save(m.state)
|
|
}
|
|
|
|
func (m *Manager) stateNotLoadedErr() error {
|
|
if m.stateLoadErr != nil {
|
|
return m.stateLoadErr
|
|
}
|
|
return errors.New("plugin state not loaded")
|
|
}
|
|
|
|
// --- Settings store (app-scoped & vm-scoped, hiding x-secret on readback) ---
|
|
|
|
func (m *Manager) GetSettings(pluginID, vmName string, maskSecrets bool) map[string]any {
|
|
var schema *SettingsSchema
|
|
if info, ok := m.registry.Info(pluginID); ok {
|
|
schema = info.Settings
|
|
}
|
|
m.mu.RLock()
|
|
defer m.mu.RUnlock()
|
|
out := map[string]any{}
|
|
// Seed defaults from schema.
|
|
if schema != nil {
|
|
for k, prop := range schema.Properties {
|
|
if prop.Default != nil {
|
|
out[k] = prop.Default
|
|
}
|
|
}
|
|
}
|
|
if m.state != nil {
|
|
if rec := m.state.Plugins[pluginID]; rec != nil {
|
|
if vmName == "" {
|
|
for k, v := range rec.AppSettings {
|
|
out[k] = v
|
|
}
|
|
} else if vmMap := rec.VMSettings[vmName]; vmMap != nil {
|
|
for k, v := range vmMap {
|
|
out[k] = v
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if maskSecrets && schema != nil {
|
|
for k, prop := range schema.Properties {
|
|
if prop.Secret {
|
|
if _, exists := out[k]; exists && out[k] != "" {
|
|
out[k] = "••••••••"
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
func (m *Manager) SetSettings(pluginID, vmName string, values map[string]any) error {
|
|
info, hasInfo := m.registry.Info(pluginID)
|
|
m.mu.Lock()
|
|
if m.state == nil {
|
|
m.mu.Unlock()
|
|
return m.stateNotLoadedErr()
|
|
}
|
|
rec := m.state.Plugins[pluginID]
|
|
if rec == nil {
|
|
rec = &PluginRecord{ID: pluginID}
|
|
if hasInfo {
|
|
rec.Source = info.Source
|
|
rec.Trust = info.Trust
|
|
rec.Enabled = info.Enabled
|
|
}
|
|
m.state.Plugins[pluginID] = rec
|
|
}
|
|
isSecretMask := func(k string, v any) bool {
|
|
if info.Settings == nil {
|
|
return false
|
|
}
|
|
prop, ok := info.Settings.Properties[k]
|
|
if !ok || !prop.Secret {
|
|
return false
|
|
}
|
|
s, ok := v.(string)
|
|
return ok && s == "••••••••"
|
|
}
|
|
if vmName == "" {
|
|
if rec.AppSettings == nil {
|
|
rec.AppSettings = map[string]any{}
|
|
}
|
|
for k, v := range values {
|
|
if isSecretMask(k, v) {
|
|
continue
|
|
}
|
|
rec.AppSettings[k] = v
|
|
}
|
|
} else {
|
|
if rec.VMSettings == nil {
|
|
rec.VMSettings = map[string]map[string]any{}
|
|
}
|
|
if rec.VMSettings[vmName] == nil {
|
|
rec.VMSettings[vmName] = map[string]any{}
|
|
}
|
|
for k, v := range values {
|
|
if isSecretMask(k, v) {
|
|
continue
|
|
}
|
|
rec.VMSettings[vmName][k] = v
|
|
}
|
|
}
|
|
rec.UpdatedAt = time.Now()
|
|
err := m.store.Save(m.state)
|
|
cb := m.opts.OnSettingsChanged
|
|
m.mu.Unlock()
|
|
if err == nil && cb != nil {
|
|
cb(pluginID, vmName)
|
|
}
|
|
return err
|
|
}
|
|
|
|
// SavedVMSettingsForPlugin returns a copy of all saved per-VM setting maps for pluginID.
|
|
func (m *Manager) SavedVMSettingsForPlugin(pluginID string) map[string]map[string]any {
|
|
m.mu.RLock()
|
|
defer m.mu.RUnlock()
|
|
if m.state == nil {
|
|
return nil
|
|
}
|
|
rec := m.state.Plugins[pluginID]
|
|
if rec == nil || len(rec.VMSettings) == 0 {
|
|
return nil
|
|
}
|
|
out := make(map[string]map[string]any, len(rec.VMSettings))
|
|
for vmName, kv := range rec.VMSettings {
|
|
cp := make(map[string]any, len(kv))
|
|
for k, v := range kv {
|
|
cp[k] = v
|
|
}
|
|
out[vmName] = cp
|
|
}
|
|
return out
|
|
}
|
|
|
|
// GetAllVMSettings returns pluginID -> settings map for vmName across active plugins.
|
|
func (m *Manager) GetAllVMSettings(vmName string) map[string]map[string]any {
|
|
out := map[string]map[string]any{}
|
|
for _, info := range m.registry.List() {
|
|
if info.State != StateActive && info.State != StateDegraded {
|
|
continue
|
|
}
|
|
if info.Settings == nil {
|
|
continue
|
|
}
|
|
hasVMProp := info.Settings.Scope == "vm"
|
|
if !hasVMProp {
|
|
for _, p := range info.Settings.Properties {
|
|
if p.Scope == "vm" {
|
|
hasVMProp = true
|
|
break
|
|
}
|
|
}
|
|
}
|
|
if hasVMProp {
|
|
out[info.ID] = m.GetSettings(info.ID, vmName, true)
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
// --- Theme Management (§5.1) ---
|
|
|
|
func (m *Manager) SetActiveTheme(themeID, schemeID string) error {
|
|
if m.safeMode && themeID != "" && themeID != "builtin.theme.default" {
|
|
return errors.New("custom themes are disabled in safe mode")
|
|
}
|
|
if err := m.registry.SetActiveTheme(themeID); err != nil {
|
|
return err
|
|
}
|
|
m.mu.Lock()
|
|
if m.state == nil {
|
|
m.mu.Unlock()
|
|
return m.stateNotLoadedErr()
|
|
}
|
|
m.state.ActiveThemeID = themeID
|
|
m.state.ActiveSchemeID = schemeID
|
|
err := m.store.Save(m.state)
|
|
m.mu.Unlock()
|
|
return err
|
|
}
|
|
|
|
func (m *Manager) SaveCustomThemeScheme(scheme CustomThemeScheme) error {
|
|
if strings.TrimSpace(scheme.ID) == "" || strings.TrimSpace(scheme.Name) == "" {
|
|
return errors.New("scheme id and name required")
|
|
}
|
|
for k, v := range scheme.Seeds {
|
|
if err := ValidateCSSTokenValue(v); err != nil {
|
|
return fmt.Errorf("invalid seed %q: %w", k, err)
|
|
}
|
|
}
|
|
m.mu.Lock()
|
|
if m.state == nil {
|
|
m.mu.Unlock()
|
|
return m.stateNotLoadedErr()
|
|
}
|
|
updated := false
|
|
for i := range m.state.CustomSchemes {
|
|
if m.state.CustomSchemes[i].ID == scheme.ID {
|
|
m.state.CustomSchemes[i] = scheme
|
|
updated = true
|
|
break
|
|
}
|
|
}
|
|
if !updated {
|
|
m.state.CustomSchemes = append(m.state.CustomSchemes, scheme)
|
|
}
|
|
err := m.store.Save(m.state)
|
|
m.mu.Unlock()
|
|
return err
|
|
}
|
|
|
|
func (m *Manager) DeleteCustomThemeScheme(schemeID string) error {
|
|
m.mu.Lock()
|
|
if m.state == nil {
|
|
m.mu.Unlock()
|
|
return m.stateNotLoadedErr()
|
|
}
|
|
kept := m.state.CustomSchemes[:0]
|
|
for _, s := range m.state.CustomSchemes {
|
|
if s.ID != schemeID {
|
|
kept = append(kept, s)
|
|
}
|
|
}
|
|
m.state.CustomSchemes = kept
|
|
if m.state.ActiveSchemeID == schemeID {
|
|
m.state.ActiveSchemeID = ""
|
|
}
|
|
err := m.store.Save(m.state)
|
|
m.mu.Unlock()
|
|
return err
|
|
}
|
|
|
|
// ActiveThemePayload builds the resolved theme bundle for the frontend (§5.1).
|
|
// Returns an empty/default payload when using the builtin theme (zero extra CSS).
|
|
func (m *Manager) ActiveThemePayload() ActiveThemePayload {
|
|
m.mu.RLock()
|
|
activeScheme := ""
|
|
var customSchemes []CustomThemeScheme
|
|
if m.state != nil {
|
|
activeScheme = m.state.ActiveSchemeID
|
|
customSchemes = append([]CustomThemeScheme(nil), m.state.CustomSchemes...)
|
|
}
|
|
m.mu.RUnlock()
|
|
|
|
if m.safeMode {
|
|
return ActiveThemePayload{ThemeID: "builtin.theme.default", CustomSchemes: customSchemes}
|
|
}
|
|
th := m.registry.ActiveTheme()
|
|
if th == nil || th.ID == "builtin.theme.default" {
|
|
return ActiveThemePayload{ThemeID: "builtin.theme.default", CustomSchemes: customSchemes}
|
|
}
|
|
|
|
payload := ActiveThemePayload{
|
|
ThemeID: th.ID,
|
|
PluginID: th.PluginID,
|
|
ActiveScheme: activeScheme,
|
|
Theme: th,
|
|
CustomSchemes: customSchemes,
|
|
AssetBaseURL: "/plugin-assets/" + m.assets.Token() + "/" + th.PluginID + "/",
|
|
}
|
|
|
|
m.mu.RLock()
|
|
installDir := m.installDirs[th.PluginID]
|
|
m.mu.RUnlock()
|
|
|
|
if installDir != "" && th.Stylesheet != "" {
|
|
if full, err := safeJoin(installDir, th.Stylesheet); err == nil {
|
|
if raw, err := os.ReadFile(full); err == nil {
|
|
if ValidateThemeCSSSafetyInDir(string(raw), filepath.Dir(full)) == nil {
|
|
payload.CSS = string(raw)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if th.UIScript != "" && validateSafeManifestAsset(th.UIScript, "") == nil {
|
|
if info, ok := m.registry.Info(th.PluginID); ok {
|
|
hasPerm := false
|
|
for _, p := range info.Permissions {
|
|
if p.Name == "ui:script" {
|
|
hasPerm = true
|
|
break
|
|
}
|
|
}
|
|
approved := info.Trust == TrustOfficial || info.Source == SourceBuiltin
|
|
if !approved && !info.NeedsApproval {
|
|
for _, ap := range info.ApprovedPermissions {
|
|
if ap == "ui:script" {
|
|
approved = true
|
|
break
|
|
}
|
|
}
|
|
}
|
|
// Enforce §5.1 trust boundary: ui:script requires declared and approved permission.
|
|
if hasPerm && approved {
|
|
payload.UIScriptURL = m.assets.AssetURL(th.PluginID, th.UIScript)
|
|
payload.UIScriptTrust = info.Trust
|
|
}
|
|
}
|
|
}
|
|
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 `<l10n>/<locale>.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
|
|
}
|
|
|
|
// LocalizeMenus applies active Language Pack manifest overrides onto MenuContribution titles.
|
|
func (m *Manager) LocalizeMenus(items []MenuContribution) []MenuContribution {
|
|
ovs := m.activeManifestOverrides()
|
|
if len(ovs) == 0 || len(items) == 0 {
|
|
return items
|
|
}
|
|
out := make([]MenuContribution, len(items))
|
|
for i, it := range items {
|
|
cp := it
|
|
if list := ovs[it.PluginID]; len(list) > 0 {
|
|
cp.Title = cloneLocalizedText(it.Title)
|
|
for _, r := range list {
|
|
if v := firstNonEmptyField(r.ov.Fields, "menu."+it.ID+".title", "command."+it.Command+".title"); v != "" {
|
|
applyLocalizedOverride(&cp.Title, r.locale, v, r.privileged)
|
|
}
|
|
}
|
|
}
|
|
out[i] = cp
|
|
}
|
|
return out
|
|
}
|
|
|
|
// LocalizePanels applies active Language Pack manifest overrides onto PanelContribution titles.
|
|
func (m *Manager) LocalizePanels(items []PanelContribution) []PanelContribution {
|
|
ovs := m.activeManifestOverrides()
|
|
if len(ovs) == 0 || len(items) == 0 {
|
|
return items
|
|
}
|
|
out := make([]PanelContribution, len(items))
|
|
for i, it := range items {
|
|
cp := it
|
|
if list := ovs[it.PluginID]; len(list) > 0 {
|
|
cp.Title = cloneLocalizedText(it.Title)
|
|
for _, r := range list {
|
|
if v := firstNonEmptyField(r.ov.Fields, "panel."+it.ID+".title"); v != "" {
|
|
applyLocalizedOverride(&cp.Title, r.locale, v, r.privileged)
|
|
}
|
|
}
|
|
}
|
|
out[i] = cp
|
|
}
|
|
return out
|
|
}
|
|
|
|
// LocalizeVMCards applies active Language Pack manifest overrides onto VMCardContribution labels.
|
|
func (m *Manager) LocalizeVMCards(items []VMCardContribution) []VMCardContribution {
|
|
ovs := m.activeManifestOverrides()
|
|
if len(ovs) == 0 || len(items) == 0 {
|
|
return items
|
|
}
|
|
out := make([]VMCardContribution, len(items))
|
|
for i, it := range items {
|
|
cp := it
|
|
if list := ovs[it.PluginID]; len(list) > 0 {
|
|
cp.Title = cloneLocalizedText(it.Title)
|
|
cp.Value = cloneLocalizedText(it.Value)
|
|
for _, r := range list {
|
|
if v := firstNonEmptyField(r.ov.Fields, "vmCard."+it.ID+".title"); v != "" {
|
|
applyLocalizedOverride(&cp.Title, r.locale, v, r.privileged)
|
|
}
|
|
if v := firstNonEmptyField(r.ov.Fields, "vmCard."+it.ID+".value"); v != "" {
|
|
applyLocalizedOverride(&cp.Value, r.locale, v, r.privileged)
|
|
}
|
|
}
|
|
}
|
|
out[i] = cp
|
|
}
|
|
return out
|
|
}
|
|
|
|
// LocalizeSettingsPages applies active Language Pack manifest overrides onto SettingsPageContribution titles.
|
|
func (m *Manager) LocalizeSettingsPages(items []SettingsPageContribution) []SettingsPageContribution {
|
|
ovs := m.activeManifestOverrides()
|
|
if len(ovs) == 0 || len(items) == 0 {
|
|
return items
|
|
}
|
|
out := make([]SettingsPageContribution, len(items))
|
|
for i, it := range items {
|
|
cp := it
|
|
if list := ovs[it.PluginID]; len(list) > 0 {
|
|
cp.Title = cloneLocalizedText(it.Title)
|
|
for _, r := range list {
|
|
if v := firstNonEmptyField(r.ov.Fields, "settingsPage."+it.ID+".title"); v != "" {
|
|
applyLocalizedOverride(&cp.Title, r.locale, v, r.privileged)
|
|
}
|
|
}
|
|
}
|
|
out[i] = cp
|
|
}
|
|
return out
|
|
}
|
|
|
|
// LocalizeStatusItems applies active Language Pack manifest overrides onto StatusItemContribution labels.
|
|
func (m *Manager) LocalizeStatusItems(items []StatusItemContribution) []StatusItemContribution {
|
|
ovs := m.activeManifestOverrides()
|
|
if len(ovs) == 0 || len(items) == 0 {
|
|
return items
|
|
}
|
|
out := make([]StatusItemContribution, len(items))
|
|
for i, it := range items {
|
|
cp := it
|
|
if list := ovs[it.PluginID]; len(list) > 0 {
|
|
cp.Text = cloneLocalizedText(it.Text)
|
|
cp.Tooltip = cloneLocalizedText(it.Tooltip)
|
|
for _, r := range list {
|
|
if v := firstNonEmptyField(r.ov.Fields, "statusItem."+it.ID+".text"); v != "" {
|
|
applyLocalizedOverride(&cp.Text, r.locale, v, r.privileged)
|
|
}
|
|
if v := firstNonEmptyField(r.ov.Fields, "statusItem."+it.ID+".tooltip"); v != "" {
|
|
applyLocalizedOverride(&cp.Tooltip, r.locale, v, r.privileged)
|
|
}
|
|
}
|
|
}
|
|
out[i] = cp
|
|
}
|
|
return out
|
|
}
|
|
|
|
// 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 `<l10n>/<tag>.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
|
|
}
|
|
entryRel := man.Entry.Sidecar
|
|
if entryRel == "" {
|
|
entryRel = man.Entry.UIScript
|
|
}
|
|
if entryRel == "" {
|
|
entryRel = man.Entry.Script
|
|
}
|
|
entryHash := ""
|
|
if entryRel != "" {
|
|
full, err := safeJoin(c.dir, entryRel)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
entryHash, _ = fileSHA256Hex(full)
|
|
}
|
|
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()
|
|
defer m.mu.RUnlock()
|
|
if m.state == nil {
|
|
return nil
|
|
}
|
|
rec := m.state.Plugins[pluginID]
|
|
if rec == nil || len(rec.VMSettings) == 0 {
|
|
return nil
|
|
}
|
|
var out []string
|
|
for vmName, kv := range rec.VMSettings {
|
|
if b, ok := kv[key].(bool); ok && b {
|
|
out = append(out, vmName)
|
|
}
|
|
}
|
|
sort.Strings(out)
|
|
return out
|
|
}
|
|
|
|
// Close shuts down all active plugins and Sidecar supervisors cleanly.
|
|
func (m *Manager) Close() {
|
|
m.registry.DisposeAll()
|
|
m.mu.Lock()
|
|
sups := make([]*SidecarSupervisor, 0, len(m.supervisors))
|
|
for id, sup := range m.supervisors {
|
|
sups = append(sups, sup)
|
|
delete(m.supervisors, id)
|
|
}
|
|
m.mu.Unlock()
|
|
for _, sup := range sups {
|
|
sup.Stop()
|
|
}
|
|
}
|