Files
千川白浪 d55241cba2 feat(plugin): catalog the Host API, open secret typing and extend the SDK
Give the Sidecar Host API one authoritative catalog in pkg/pluginproto: every
host/* method's status, required permissions, handshake feature and request and
result shapes. The host, pkg/pluginsdk and plugins share those types, so a field
can no longer exist on one side only, and permissions come from the catalog
instead of from each handler. Tests gate that every served method is
catalogued, every stable catalogued method is served, and every catalogued
permission is one the host recognizes.

Open the interface up instead of adding consent gates. Typing a secret setting
is no longer reserved for reims.agent: any plugin that holds qmp:write and that
the user authorized for the VM can have the host type the plugin's own setting,
which the plugin never reads back. Restoring a snapshot works on any authorized
VM, a plugin names its own clones, a held key may carry modifiers, and a
screenshot width outside the supported range is brought into range rather than
refused. Deleting a VM stays limited to the temporary VMs a plugin created.

Record the keys and pointer buttons each plugin holds per VM and lift them when
the plugin's process exits, its scope is disposed, the VM stops or it stops
calling, so a guest never stays stuck with a modifier down. Requests from
plugins that declare pluginApi 1.3 or newer are decoded strictly and answer an
undefined field with JSON-RPC -32602, while older plugins keep tolerant
decoding.

Add typed VM and console methods to pkg/pluginsdk so a plugin no longer needs
its own JSON-RPC client. A method the contract does not catalog, or one the
host did not advertise in the handshake, is refused before it is sent, and the
host's JSON-RPC error code reaches the caller.
2026-12-05 01:43:28 -07:00

1444 lines
41 KiB
Go

package plugin
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/url"
"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
// HostHandlerFactory adds host-owned RPC handlers to each Sidecar.
type HostHandlerFactory func(pluginID string) map[string]RPCRequestHandler
// 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
HostHandlers HostHandlerFactory
OnSettingsChanged func(pluginID, vmName string)
// OnSidecarStopped runs when a plugin's Sidecar process goes away or its
// scope is disposed, so the embedder can release what that process left
// held. It may run more than once for the same plugin and must be
// idempotent.
OnSidecarStopped func(pluginID 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
viewStorageMu sync.Mutex
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) {
if len(opts.Keyring) == 0 {
opts.Keyring = DefaultKeyring()
}
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.ruleSettings = m.GetSettings
reg.OnChange(func() {
m.mu.Lock()
clear(m.l10nCache)
m.l10nGen++
m.mu.Unlock()
m.SyncActiveTheme()
})
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 }
// NotifySidecar sends a fire-and-forget notification (such as
// `download/progress`) to pluginID's running Sidecar. It never wakes an idle
// Sidecar and is a no-op when there is none.
func (m *Manager) NotifySidecar(pluginID, method string, params any) {
if m == nil {
return
}
m.mu.RLock()
supervisor := m.supervisors[pluginID]
m.mu.RUnlock()
if supervisor != nil {
supervisor.NotifyIfRunning(method, params)
}
}
// ChannelSessionClosed tells pluginID's running Sidecar that one client
// connection to channelID has ended, so it can cancel that connection's calls
// and release anything it still holds. It never wakes an idle Sidecar.
func (m *Manager) ChannelSessionClosed(pluginID, channelID, session string) {
if m == nil || session == "" || strings.TrimSpace(channelID) == "" {
return
}
m.NotifySidecar(pluginID, "channel/"+channelID+"/closed", map[string]string{"session": session})
}
// ChannelMessage forwards one JSON line to a declared, active Sidecar channel.
// session identifies the client connection, so a Sidecar can scope request ids
// and cancellation per connection. Channel payloads are never written to the
// host audit log.
func (m *Manager) ChannelMessage(ctx context.Context, pluginID, channelID, session string, message json.RawMessage) (json.RawMessage, error) {
if m == nil || m.registry == nil {
return nil, errors.New("plugin manager is unavailable")
}
if len(message) == 0 || len(message) > maxRPCFrameBytes || !json.Valid(message) {
return nil, errors.New("channel message must be valid JSON within the frame limit")
}
manifest, ok := m.registry.ManifestOf(pluginID)
if !ok {
return nil, fmt.Errorf("plugin %q is not installed", pluginID)
}
declared := false
for _, channel := range manifest.Contributes.Channels {
if channel.ID == channelID && channel.Framing == "jsonl" {
declared = true
break
}
}
if !declared {
return nil, fmt.Errorf("plugin %q does not declare JSONL channel %q", pluginID, channelID)
}
if !m.registry.IsActive(pluginID) {
return nil, fmt.Errorf("plugin %q is not enabled", pluginID)
}
if ctx == nil {
ctx = context.Background()
}
m.mu.RLock()
supervisor := m.supervisors[pluginID]
m.mu.RUnlock()
if supervisor == nil {
return nil, fmt.Errorf("plugin %q channel is unavailable", pluginID)
}
var response struct {
Message json.RawMessage `json:"message"`
}
params := map[string]any{"message": message}
if session != "" {
params["session"] = session
}
err := supervisor.Call(ctx, "channel/"+channelID+"/message", params, &response)
if err != nil {
return nil, err
}
if len(response.Message) > maxRPCFrameBytes || (len(response.Message) > 0 && string(response.Message) != "null" && !json.Valid(response.Message)) {
return nil, errors.New("Sidecar returned an invalid channel message")
}
m.broker.Audit(pluginID, "CHANNEL_MESSAGE", channelID)
return response.Message, nil
}
// 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
type extEntry struct {
id string
rec PluginRecord
}
var entries []extEntry
if st != nil {
devMode = st.DeveloperMode
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 built-in active themes immediately; external themes are restored
// by SyncActiveTheme once Registry.Reconcile activates their plugins.
m.SyncActiveTheme()
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
}
_, entryAbs, entryHash, err := resolveManifestEntry(man, dir, false)
if err != nil {
return err
}
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,
})
}
// computeNeedsApproval applies the same gate to every installed package,
// official ones included: trust labels a plugin, it does not waive review.
// Only dev links skip entry hash pinning, since their code changes on every build.
func computeNeedsApproval(m Manifest, trust TrustLevel, approvedPerms []string, approvedHash, currentHash string) bool {
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
}
}
// L3 sidecars and interactive UI scripts require explicit approval of their
// exact entry hash so upgrades modifying executable code pause for re-review (§7.2).
if trust != TrustDev && (m.InferTier(false) == TierL3 || len(collectUIScriptPaths(m)) > 0) {
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
var (
extraHandlers map[string]RPCRequestHandler
dlHub *downloaderProgressHub
)
if len(man.Contributes.Downloaders) > 0 {
dlHub = newDownloaderProgressHub()
extraHandlers = map[string]RPCRequestHandler{
"host/downloader.progress": dlHub.handleRPC,
}
}
if m.opts.HostHandlers != nil {
if extraHandlers == nil {
extraHandlers = make(map[string]RPCRequestHandler)
}
for method, handler := range m.opts.HostHandlers(pid) {
if _, exists := extraHandlers[method]; exists {
return fmt.Errorf("Sidecar Host API method %q is already registered", method)
}
extraHandlers[method] = handler
}
}
sup := NewSidecarSupervisor(SidecarOptions{
PluginID: pid,
ExePath: exePath,
DataDir: m.layout.DataDir(pid),
Broker: m.broker,
Registry: m.registry,
IdleTimeout: 5 * time.Minute,
ExtraHandlers: extraHandlers,
OnExit: func() {
if m.opts.OnSidecarStopped != nil {
m.opts.OnSidecarStopped(pid)
}
},
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()
if m.opts.OnSidecarStopped != nil {
m.opts.OnSidecarStopped(pid)
}
})
// 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)
}
}
}
// Wire Sidecar downloaders.
if dlHub != nil {
for _, dl := range man.Contributes.Downloaders {
d := dl
if d.Priority == 0 {
d.Priority = 100 // external L3 downloaders override builtin (50) by default
}
m.registry.RegisterDownloader(sc, d, newSidecarDownloader(d, sup, dlHub, func() (map[string]any, error) {
return m.DownloaderSettings(pid)
}))
}
}
// 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)
m.SyncActiveTheme()
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)
m.SyncActiveTheme()
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.SyncActiveTheme()
m.mu.Lock()
err := m.store.Save(m.state)
m.mu.Unlock()
return err
}
// SyncActiveTheme applies the persisted active theme ID in state.json to the
// Registry whenever the theme has been registered and the manager is not in
// safe mode (§5.1). Safe to call repeatedly after startup, upgrade, or re-enable.
func (m *Manager) SyncActiveTheme() {
if m.safeMode {
return
}
m.mu.RLock()
activeID := ""
if m.state != nil {
activeID = m.state.ActiveThemeID
}
m.mu.RUnlock()
if activeID == "" || activeID == "builtin.theme.default" {
return
}
if cur := m.registry.ActiveTheme(); cur != nil && cur.ID == activeID {
return
}
_ = m.registry.SetActiveTheme(activeID)
}
// Disable turns off a plugin (if not in use) and persists the state.
func (m *Manager) Disable(ctx context.Context, id string) error {
m.mu.RLock()
activeThemeID := ""
activeThemePluginID := ""
if m.state != nil {
activeThemeID = m.state.ActiveThemeID
activeThemePluginID = m.state.ActiveThemePluginID
}
m.mu.RUnlock()
ownsActiveTheme := activeThemeID != "" && ((activeThemePluginID != "" && activeThemePluginID == id) || m.registry.PluginOwnsTheme(id, activeThemeID))
if err := m.registry.SetDesired(ctx, id, false); err != nil {
return err
}
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 ownsActiveTheme && m.state.ActiveThemeID == activeThemeID {
// If disabling the active theme's plugin, fall back to builtin default theme (§5.1).
m.state.ActiveThemeID = ""
m.state.ActiveThemePluginID = ""
m.state.ActiveSchemeID = ""
}
err := m.store.Save(m.state)
m.mu.Unlock()
return err
}
// MarkBootComplete clears the plugin startup crash sentinel after Reconcile
// has activated plugins cleanly and ensures any persisted active theme is restored.
func (m *Manager) MarkBootComplete() {
m.SyncActiveTheme()
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.
func (m *Manager) Remove(ctx context.Context, id string, purgeData bool) error {
m.mu.RLock()
activeThemeID := ""
activeThemePluginID := ""
if m.state != nil {
activeThemeID = m.state.ActiveThemeID
activeThemePluginID = m.state.ActiveThemePluginID
}
m.mu.RUnlock()
ownsActiveTheme := activeThemeID != "" && ((activeThemePluginID != "" && activeThemePluginID == id) || m.registry.PluginOwnsTheme(id, activeThemeID))
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)
}
if activeThemeID != "" && activeThemePluginID == "" && m.registry.ThemeOwner(activeThemeID) == "" && (activeThemeID == id || strings.HasPrefix(activeThemeID, id+".")) {
ownsActiveTheme = true
}
}
m.mu.Lock()
if m.state == nil {
m.mu.Unlock()
return m.stateNotLoadedErr()
}
delete(m.state.Plugins, id)
delete(m.installDirs, id)
if ownsActiveTheme && m.state.ActiveThemeID == activeThemeID {
m.state.ActiveThemeID = ""
m.state.ActiveThemePluginID = ""
m.state.ActiveSchemeID = ""
}
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) {
return m.RetireRecordsInto(ids, "", nil)
}
// RetireRecordsInto drops the state.json records of ids and, in the same save,
// merges the app settings carry derives from them into target's record. One
// write means a crash cannot drop an old record without the setting that
// replaced it. carry may be nil.
func (m *Manager) RetireRecordsInto(ids []string, target string, carry func(removed map[string]*PluginRecord) map[string]any) (map[string]*PluginRecord, error) {
m.mu.Lock()
if m.state == nil {
m.mu.Unlock()
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 {
m.mu.Unlock()
return removed, nil
}
var carried map[string]any
if carry != nil && target != "" {
carried = carry(removed)
}
if len(carried) > 0 {
rec := m.state.Plugins[target]
if rec == nil {
rec = &PluginRecord{ID: target}
m.state.Plugins[target] = rec
}
if rec.AppSettings == nil {
rec.AppSettings = map[string]any{}
}
for k, v := range carried {
rec.AppSettings[k] = v
}
rec.UpdatedAt = time.Now()
}
err := m.store.Save(m.state)
cb := m.opts.OnSettingsChanged
m.mu.Unlock()
if err == nil && len(carried) > 0 && cb != nil {
cb(target, "")
}
return removed, err
}
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 inheritsAppSetting(schema *SettingsSchema, key string) bool {
if schema == nil {
return false
}
prop, exists := schema.Properties[key]
if !exists {
return false
}
if prop.Scope != "" {
return prop.Scope == "both"
}
return schema.Scope == "both"
}
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 {
for k, v := range rec.AppSettings {
if vmName == "" || inheritsAppSetting(schema, k) {
out[k] = v
}
}
if vmName != "" {
for k, v := range rec.VMSettings[vmName] {
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
}
// DownloaderSettings returns a plugin's app settings to its own downloader
// sidecar, decrypting x-secret values only for that download request.
func (m *Manager) DownloaderSettings(pluginID string) (map[string]any, error) {
info, ok := m.registry.Info(pluginID)
if !ok {
return nil, fmt.Errorf("plugin %q is unavailable", pluginID)
}
settings := m.GetSettings(pluginID, "", false)
if info.Settings == nil {
return settings, nil
}
for key, property := range info.Settings.Properties {
if !property.Secret {
continue
}
text, ok := settings[key].(string)
if !ok || !strings.HasPrefix(text, protectedSecretPrefix) {
continue
}
plain, err := unprotectSettingSecret(text)
if err != nil {
return nil, fmt.Errorf("decrypt downloader setting %q: %w", key, err)
}
settings[key] = plain
}
return settings, nil
}
// SettingConfigured reports whether a value was explicitly saved at the requested scope.
func (m *Manager) SettingConfigured(pluginID, vmName, key string) bool {
m.mu.RLock()
defer m.mu.RUnlock()
if m.state == nil {
return false
}
rec := m.state.Plugins[pluginID]
if rec == nil {
return false
}
if vmName != "" {
if _, ok := rec.VMSettings[vmName][key]; ok {
return true
}
var schema *SettingsSchema
if info, ok := m.registry.Info(pluginID); ok {
schema = info.Settings
}
if !inheritsAppSetting(schema, key) {
return false
}
}
_, ok := rec.AppSettings[key]
return ok
}
// SavedBoolSetting reads an explicitly stored boolean without applying schema
// defaults. Security decisions must not be authorized by plugin metadata.
func (m *Manager) SavedBoolSetting(pluginID, vmName, key string) bool {
m.mu.RLock()
defer m.mu.RUnlock()
if m.state == nil {
return false
}
record := m.state.Plugins[pluginID]
if record == nil {
return false
}
values := record.AppSettings
if vmName != "" {
values = record.VMSettings[vmName]
}
enabled, _ := values[key].(bool)
return enabled
}
func (m *Manager) SetSettings(pluginID, vmName string, values map[string]any) error {
info, hasInfo := m.registry.Info(pluginID)
prepared := make(map[string]any, len(values))
for key, value := range values {
if hasInfo && info.Settings != nil {
if property, ok := info.Settings.Properties[key]; ok && property.Secret {
if value == "••••••••" {
continue
}
text, ok := value.(string)
if !ok {
return fmt.Errorf("secret setting %q must be a string", key)
}
if text == "" {
prepared[key] = ""
continue
}
protected, err := protectSettingSecret(text)
if err != nil {
return fmt.Errorf("protect secret setting %q: %w", key, err)
}
prepared[key] = protected
continue
}
}
prepared[key] = value
}
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
}
if vmName == "" {
if rec.AppSettings == nil {
rec.AppSettings = map[string]any{}
}
for k, v := range prepared {
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 prepared {
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
}
// SecretSetting decrypts a DPAPI-protected setting only for host-owned use.
// The caller must never return the plaintext to a plugin or frontend.
func (m *Manager) SecretSetting(pluginID, vmName, key string) (string, error) {
info, ok := m.registry.Info(pluginID)
if !ok || info.Settings == nil {
return "", fmt.Errorf("plugin %q has no settings schema", pluginID)
}
property, ok := info.Settings.Properties[key]
if !ok || !property.Secret {
return "", fmt.Errorf("setting %q is not a secret", key)
}
m.mu.RLock()
if m.state == nil {
m.mu.RUnlock()
return "", m.stateNotLoadedErr()
}
values := map[string]any(nil)
if record := m.state.Plugins[pluginID]; record != nil {
if vmName == "" {
values = record.AppSettings
} else {
values = record.VMSettings[vmName]
}
}
text, _ := values[key].(string)
m.mu.RUnlock()
if text == "" {
return "", ErrSecretEmpty
}
if strings.HasPrefix(text, protectedSecretPrefix) {
return unprotectSettingSecret(text)
}
// Versions before DPAPI protection stored secret settings as plain text.
// Re-save the legacy value through SetSettings so the next read is protected.
if err := m.SetSettings(pluginID, vmName, map[string]any{key: text}); err != nil {
return "", fmt.Errorf("migrate legacy secret setting %q: %w", key, err)
}
return text, nil
}
// 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" || info.Settings.Scope == "both"
if !hasVMProp {
for _, p := range info.Settings.Properties {
if p.Scope == "vm" || p.Scope == "both" {
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
}
activePluginID := ""
if th := m.registry.ActiveTheme(); th != nil && th.ID == themeID {
activePluginID = th.PluginID
}
m.mu.Lock()
if m.state == nil {
m.mu.Unlock()
return m.stateNotLoadedErr()
}
m.state.ActiveThemeID = themeID
m.state.ActiveThemePluginID = activePluginID
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 ValidateThemeCSSSafety(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
}
}
// Only code shipped inside reims-go.exe is pre-approved.
approved := info.Source == SourceBuiltin || info.Source == SourceBundled
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 {
scriptURL := m.assets.AssetURL(th.PluginID, th.UIScript)
q := url.Values{}
if info.Version != "" {
q.Set("v", info.Version)
}
if info.EntryHash != "" {
h := info.EntryHash
if len(h) > 12 {
h = h[:12]
}
q.Set("h", h)
}
if enc := q.Encode(); enc != "" {
scriptURL += "?" + enc
}
payload.UIScriptURL = scriptURL
payload.UIScriptTrust = info.Trust
}
}
}
return payload
}
// 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()
}
}