package plugin import ( "encoding/json" "errors" "fmt" "os" "path/filepath" "strings" "sync" "time" ) const ( StateFileName = "state.json" StartupSentinel = ".startup-sentinel" CurrentStateSchema = 1 ) // PluginRecord persists enablement, pinned version, approved permissions, and // settings for one plugin in `/plugins/state.json` (§6.1). type PluginRecord struct { ID string `json:"id"` Version string `json:"version,omitempty"` Source SourceKind `json:"source,omitempty"` Trust TrustLevel `json:"trust,omitempty"` Enabled bool `json:"enabled"` Pinned bool `json:"pinned,omitempty"` DevPath string `json:"dev_path,omitempty"` ApprovedPermissions []string `json:"approved_permissions,omitempty"` ApprovedEntryHash string `json:"approved_entry_hash,omitempty"` BlockingGuardOK bool `json:"blocking_guard_ok,omitempty"` AppSettings map[string]any `json:"app_settings,omitempty"` VMSettings map[string]map[string]any `json:"vm_settings,omitempty"` // vmName -> key -> val InstalledVersions []string `json:"installed_versions,omitempty"` UpdatedAt time.Time `json:"updated_at,omitempty"` } // CustomThemeScheme stores a user-created or edited theme color scheme (§5.1). type CustomThemeScheme struct { ID string `json:"id"` ThemeID string `json:"theme_id"` Name string `json:"name"` Appearance string `json:"appearance,omitempty"` Seeds map[string]string `json:"seeds"` } // StateFile is the authoritative persisted plugin state at `/plugins/state.json`. type StateFile struct { Schema int `json:"schema"` DeveloperMode bool `json:"developer_mode,omitempty"` ActiveThemeID string `json:"active_theme_id,omitempty"` ActiveSchemeID string `json:"active_scheme_id,omitempty"` CustomSchemes []CustomThemeScheme `json:"custom_schemes,omitempty"` Plugins map[string]*PluginRecord `json:"plugins"` } // StateStore safely reads and atomically writes state.json with .bak fallback. // Per §6.1: read/parse errors are NEVER treated as an empty plugin list! type StateStore struct { mu sync.Mutex dir string data *StateFile } func NewStateStore(pluginsDir string) *StateStore { return &StateStore{dir: pluginsDir} } func (s *StateStore) Path() string { return filepath.Join(s.dir, StateFileName) } // Load reads state.json. Missing file initializes a fresh StateFile; any read // or JSON parse error is returned immediately (never wiped to empty, §6.1). func (s *StateStore) Load() (*StateFile, error) { s.mu.Lock() defer s.mu.Unlock() p := s.Path() raw, err := os.ReadFile(p) if err != nil { if errors.Is(err, os.ErrNotExist) { st := &StateFile{ Schema: CurrentStateSchema, Plugins: make(map[string]*PluginRecord), } s.data = st return st, nil } return nil, fmt.Errorf("read plugin state %s: %w", p, err) } var st StateFile if err := json.Unmarshal(raw, &st); err != nil { return nil, fmt.Errorf("corrupt plugin state %s (refusing to overwrite): %w", p, err) } if st.Plugins == nil { st.Plugins = make(map[string]*PluginRecord) } if st.Schema == 0 { st.Schema = CurrentStateSchema } s.data = &st return &st, nil } // Save atomically persists state.json via temp file + .bak backup + rename (§6.1). func (s *StateStore) Save(st *StateFile) error { s.mu.Lock() defer s.mu.Unlock() if st == nil { return errors.New("nil plugin state") } if st.Plugins == nil { st.Plugins = make(map[string]*PluginRecord) } st.Schema = CurrentStateSchema if err := os.MkdirAll(s.dir, 0o755); err != nil { return err } raw, err := json.MarshalIndent(st, "", " ") if err != nil { return err } raw = append(raw, '\n') target := s.Path() tmp := target + ".tmp" if err := os.WriteFile(tmp, raw, 0o644); err != nil { return err } // Preserve previous valid file as .bak before atomic swap. if prev, err := os.ReadFile(target); err == nil { _ = os.WriteFile(target+".bak", prev, 0o644) } if err := os.Rename(tmp, target); err != nil { _ = os.Remove(tmp) return err } s.data = st return nil } // ReadState reads `/plugins/state.json` without starting a Manager, // for processes such as `vm start` that only need a setting or two. It returns // nil when the file is unreadable; callers then use their defaults, as the // GUI's Manager does. func ReadState(dataRoot string) *StateFile { st, err := NewStateStore(NewPluginsLayout(dataRoot).Root).Load() if err != nil { return nil } return st } // --- Safe-mode startup sentinel (§9) --- // SentinelPath returns `/plugins/.startup-sentinel`. func SentinelPath(pluginsDir string) string { return filepath.Join(pluginsDir, StartupSentinel) } // DidLastStartupCrash reports whether a startup sentinel from an unfinished // plugin initialization is still on disk. func DidLastStartupCrash(pluginsDir string) bool { if strings.TrimSpace(pluginsDir) == "" { return false } _, err := os.Stat(SentinelPath(pluginsDir)) return err == nil } // BeginStartupInit writes the startup sentinel before loading third-party plugins. func BeginStartupInit(pluginsDir string) error { if strings.TrimSpace(pluginsDir) == "" { return nil } if err := os.MkdirAll(pluginsDir, 0o755); err != nil { return err } return os.WriteFile(SentinelPath(pluginsDir), []byte(time.Now().UTC().Format(time.RFC3339)+"\n"), 0o644) } // EndStartupInit removes the startup sentinel once plugin init succeeds. func EndStartupInit(pluginsDir string) { if strings.TrimSpace(pluginsDir) == "" { return } _ = os.Remove(SentinelPath(pluginsDir)) }