Skip to content

High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.

fix: starting the server silently rewrites the user config, freezing every default (PIN-071)

Luigi Agosti2a1ed96486bf
diff --git a/cmd/pinchtab/cmd_wizard.go b/cmd/pinchtab/cmd_wizard.go
index 9f1f3cb2..a380b62c 100644
--- a/cmd/pinchtab/cmd_wizard.go
+++ b/cmd/pinchtab/cmd_wizard.go
@@ -14,13 +14,14 @@ import (
// Returns true if the user completed setup, false if they cancelled.
func runSecurityWizard(cfg *config.FileConfig, configPath string, isNew bool) bool {
interactive := isInteractiveTerminal()
- if _, err := config.EnsureFileToken(cfg); err != nil {
+ tokenGenerated, err := config.EnsureFileToken(cfg)
+ if err != nil {
fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.ErrorStyle, fmt.Sprintf("failed to generate auth token: %v", err)))
return false
}
if !interactive {
- return runNonInteractiveSetup(cfg, configPath, isNew)
+ return runNonInteractiveSetup(cfg, configPath, isNew, tokenGenerated)
}
if isNew {
@@ -29,7 +30,17 @@ func runSecurityWizard(cfg *config.FileConfig, configPath string, isNew bool) bo
return runUpgradeNotice(cfg, configPath)
}
-func runNonInteractiveSetup(cfg *config.FileConfig, configPath string, isNew bool) bool {
+// A non-interactive start writes the config ONLY when a token had to be generated.
+// Nothing else here is genuinely required: a config that loads, validates and already
+// authenticates needs no rewrite, and stamping configVersion was never worth touching
+// the user's file for — that stamp is what turned a plain `pinchtab server` into a
+// silent whole-file rewrite. So an existing valid config is now left byte-identical and
+// the banner stays quiet, since there is nothing to report and nothing was recorded.
+func runNonInteractiveSetup(cfg *config.FileConfig, configPath string, isNew, tokenGenerated bool) bool {
+ if !tokenGenerated {
+ return true
+ }
+
if isNew {
fmt.Println()
fmt.Println(cli.StyleStdout(cli.HeadingStyle, "🛡️ Know your config"))
@@ -46,9 +57,7 @@ func runNonInteractiveSetup(cfg *config.FileConfig, configPath string, isNew boo
fmt.Println()
}
- cfg.ConfigVersion = config.CurrentConfigVersion
- _ = config.SaveFileConfig(cfg, configPath)
- return true
+ return recordConfigVersion(cfg, configPath, true)
}
func runFullWizard(cfg *config.FileConfig, configPath string) bool {
@@ -128,9 +137,7 @@ func runUpgradeNotice(cfg *config.FileConfig, configPath string) bool {
fmt.Println(" Run " + cli.StyleStdout(cli.CommandStyle, "pinchtab security") + " to review all settings.")
fmt.Println()
- cfg.ConfigVersion = config.CurrentConfigVersion
- _ = config.SaveFileConfig(cfg, configPath)
- return true
+ return recordConfigVersion(cfg, configPath, false)
}
// securityPosture is the single source of truth for a wizard security choice:
@@ -243,3 +250,24 @@ func orDefault(val, fallback string) string {
}
return val
}
+
+// recordConfigVersion is the only write a plain `pinchtab server` start performs. It
+// exists to stamp configVersion (plus any token EnsureFileToken generated), and it used
+// to be silent and to marshal the whole defaults-populated struct — which is how a
+// 50-byte config became a 3.8kB frozen snapshot of one build's defaults. SaveFileConfig
+// now writes only changed keys; announce says it out loud on the startup path, where
+// nothing else tells the user their file was touched.
+//
+// The error is reported rather than discarded either way: a config the user marked
+// read-only must not be replaced, and swallowing EACCES here is what made that silent.
+func recordConfigVersion(cfg *config.FileConfig, configPath string, announce bool) bool {
+ cfg.ConfigVersion = config.CurrentConfigVersion
+ if announce {
+ fmt.Fprintf(os.Stderr, "pinchtab: recording configVersion %s in %s\n", config.CurrentConfigVersion, configPath)
+ }
+ if err := config.SaveFileConfig(cfg, configPath); err != nil {
+ fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.ErrorStyle, fmt.Sprintf("pinchtab: could not record configVersion in %s: %v", configPath, err)))
+ return false
+ }
+ return true
+}
diff --git a/cmd/pinchtab/cmd_wizard_test.go b/cmd/pinchtab/cmd_wizard_test.go
index cf906a3a..8027e8f2 100644
--- a/cmd/pinchtab/cmd_wizard_test.go
+++ b/cmd/pinchtab/cmd_wizard_test.go
@@ -15,7 +15,9 @@ func TestRunNonInteractiveSetupDoesNotPrintToken(t *testing.T) {
cfg.Security.AllowedDomains = []string{"localhost"}
output := captureStdout(t, func() {
- if !runNonInteractiveSetup(&cfg, configPath, true) {
+ // tokenGenerated=true: the only case that still writes, and the case whose
+ // output this test is about.
+ if !runNonInteractiveSetup(&cfg, configPath, true, true) {
t.Fatal("runNonInteractiveSetup() = false")
}
})
diff --git a/internal/config/config_file.go b/internal/config/config_file.go
index e4a427d0..e87c6d04 100644
--- a/internal/config/config_file.go
+++ b/internal/config/config_file.go
@@ -1,7 +1,6 @@
package config
import (
- "path/filepath"
"strconv"
"strings"
)
@@ -212,8 +211,14 @@ func DefaultFileConfig() FileConfig {
ScanTimeoutSec: 5,
},
},
+ // BaseDir is deliberately empty. Pre-filling it with an absolute
+ // userConfigDir() path did two things: it baked a host home directory into any
+ // config that got written, and it made finalizeProfileConfig's
+ // filepath.Join(StateDir, "profiles") fallback unreachable, so server.stateDir
+ // could never relocate profiles. Left empty, the fallback is the live path and
+ // resolves to the same place for a default install, because StateDir itself
+ // defaults to userConfigDir().
Profiles: ProfilesConfig{
- BaseDir: filepath.Join(userConfigDir(), "profiles"),
DefaultProfile: "default",
},
MultiInstance: MultiInstanceConfig{
diff --git a/internal/config/fileio.go b/internal/config/fileio.go
index 26c2ca8c..3cf6ed00 100644
--- a/internal/config/fileio.go
+++ b/internal/config/fileio.go
@@ -36,6 +36,45 @@ func applyConfigPerms(path string) error {
return nil
}
+// tightenConfigPermsOnRead narrows a leaky config on the read path but never touches a
+// file the user made read-only.
+//
+// Tightening 0644 to 0600 is worth doing: the file holds an auth token. Doing it
+// unconditionally was not, because it also restored the owner-write bit on a 0444 file —
+// which is precisely why a later write against a config the user had protected
+// SUCCEEDED instead of failing, replacing it silently and handing it back writable. The
+// absence of owner-write is a deliberate signal, so it is the one mode this leaves
+// alone; a genuinely leaky file is still narrowed, and the write paths tighten on their
+// own after they write.
+func tightenConfigPermsOnRead(path string) error {
+ if runtime.GOOS == "windows" {
+ return nil
+ }
+ fi, err := os.Stat(path)
+ if err != nil {
+ return err
+ }
+ if fi.Mode().Perm()&0200 == 0 {
+ return nil
+ }
+ return applyConfigPerms(path)
+}
+
+// savedConfigBaseline is what a file's ABSENT keys mean: the shipped defaults, with
+// ConfigVersion zeroed because an absent configVersion is a first-install signal that
+// NeedsWizard reads — not the current version.
+//
+// One owner on purpose, shared by the load path and by the minimal-diff save. Using
+// DefaultFileConfig() directly as the save baseline suppressed exactly the key the
+// startup write exists to add: configVersion equals the shipped value, so the stamp was
+// treated as "same as default, not on disk, skip" and never landed, leaving the wizard
+// to re-run on every single start.
+func savedConfigBaseline() *FileConfig {
+ defaults := DefaultFileConfig()
+ defaults.ConfigVersion = ""
+ return &defaults
+}
+
// LoadFileConfig loads a FileConfig from the default or specified path.
// Returns the config and the path it was loaded from.
func LoadFileConfig() (*FileConfig, string, error) {
@@ -51,23 +90,19 @@ func LoadFileConfig() (*FileConfig, string, error) {
// previously caused IDPI and other defaults to be silently disabled
// on first-run auto-config. ConfigVersion is reset so NeedsWizard()
// still treats this as a first-install state.
- defaults := DefaultFileConfig()
- defaults.ConfigVersion = ""
- return &defaults, configPath, nil
+ return savedConfigBaseline(), configPath, nil
}
return nil, configPath, fmt.Errorf("failed to read config file: %w", err)
}
- _ = applyConfigPerms(configPath)
+ _ = tightenConfigPermsOnRead(configPath)
if isLegacyConfig(data) {
fc, err := loadLegacyFileConfig(data)
return fc, configPath, err
}
- defaults := DefaultFileConfig()
- defaults.ConfigVersion = ""
- fc := &defaults
+ fc := savedConfigBaseline()
if err := json.Unmarshal(data, fc); err != nil {
return nil, configPath, fmt.Errorf("failed to parse config: %w", err)
}
@@ -76,18 +111,33 @@ func LoadFileConfig() (*FileConfig, string, error) {
return fc, configPath, nil
}
-// SaveFileConfig saves a FileConfig to the specified path.
+// SaveFileConfig saves a FileConfig to the specified path, writing only the keys the
+// file already had plus the ones that actually changed.
+//
+// Marshalling the struct wholesale was the amplifier behind a whole class of damage:
+// LoadFileConfig unmarshals the user's file ON TOP OF DefaultFileConfig(), so the
+// in-memory FileConfig is always fully populated, and any writer then materialised
+// every default into the user's file. A 50-byte config became 3.8kB, host-absolute
+// paths were baked in, and — worst — every untouched setting became explicitly set, so
+// a shipped default change could never reach that install again.
+//
+// So the shape of the file on disk is authoritative for which keys exist, and this
+// function only ever adds a key when its value differs from the shipped default.
func SaveFileConfig(fc *FileConfig, path string) error {
dir := filepath.Dir(path)
if err := os.MkdirAll(dir, 0700); err != nil {
return fmt.Errorf("failed to create config directory: %w", err)
}
- data, err := json.MarshalIndent(fc, "", " ")
+ existing, err := os.ReadFile(path)
+ if err != nil && !os.IsNotExist(err) {
+ return fmt.Errorf("failed to read config file before writing: %w", err)
+ }
+
+ data, err := renderMinimalConfig(fc, existing)
if err != nil {
- return fmt.Errorf("failed to serialize config: %w", err)
+ return err
}
- data = append(data, '\n')
if err := os.WriteFile(path, data, 0600); err != nil {
return fmt.Errorf("failed to write config file: %w", err)
@@ -96,6 +146,27 @@ func SaveFileConfig(fc *FileConfig, path string) error {
return applyConfigPerms(path)
}
+func configAsMap(fc *FileConfig) (map[string]any, error) {
+ raw, err := json.Marshal(fc)
+ if err != nil {
+ return nil, fmt.Errorf("failed to serialize config: %w", err)
+ }
+ out := map[string]any{}
+ if err := json.Unmarshal(raw, &out); err != nil {
+ return nil, fmt.Errorf("failed to serialize config: %w", err)
+ }
+ return out, nil
+}
+
+func sameJSONValue(a, b any) bool {
+ left, errLeft := json.Marshal(a)
+ right, errRight := json.Marshal(b)
+ if errLeft != nil || errRight != nil {
+ return false
+ }
+ return string(left) == string(right)
+}
+
func loadLegacyFileConfig(data []byte) (*FileConfig, error) {
var lc legacyFileConfig
if err := json.Unmarshal(data, &lc); err != nil {
diff --git a/internal/config/fileio_minimal.go b/internal/config/fileio_minimal.go
new file mode 100644
index 00000000..b67d56b0
--- /dev/null
+++ b/internal/config/fileio_minimal.go
@@ -0,0 +1,173 @@
+package config
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "sort"
+ "strings"
+)
+
+// This file renders a config write as a PATCH over the bytes already on disk rather
+// than as a fresh marshal of the struct.
+//
+// Marshalling a map[string]any would satisfy "write only changed keys" but sorts every
+// key alphabetically, so a user's hand-ordered file comes back shuffled — the same
+// unexplained diff this whole card exists to remove, in a different form. Preserving
+// order means keeping the original member sequence, which encoding/json cannot do, so
+// the document is held as an ordered member list.
+
+type jsonMember struct {
+ key string
+ value json.RawMessage
+}
+
+// parseJSONObject reads an object into its members, in file order. A non-object or
+// unparseable input yields nil, which callers treat as "no shape to preserve".
+func parseJSONObject(data []byte) []jsonMember {
+ dec := json.NewDecoder(bytes.NewReader(data))
+ tok, err := dec.Token()
+ if err != nil {
+ return nil
+ }
+ delim, ok := tok.(json.Delim)
+ if !ok || delim != '{' {
+ return nil
+ }
+
+ var members []jsonMember
+ for dec.More() {
+ keyTok, err := dec.Token()
+ if err != nil {
+ return nil
+ }
+ key, ok := keyTok.(string)
+ if !ok {
+ return nil
+ }
+ var raw json.RawMessage
+ if err := dec.Decode(&raw); err != nil {
+ return nil
+ }
+ members = append(members, jsonMember{key: key, value: raw})
+ }
+ return members
+}
+
+// patchConfigObject produces the members to write for one object level: every member
+// the file already had, in its original position and carrying fc's current value, then
+// the keys fc holds that the file lacked and that differ from the shipped baseline.
+//
+// Existing members are rewritten unconditionally so an edit back to the default value
+// still lands; a pure difference-from-baseline render would omit that key and leave the
+// stale value in place, which is the one way writing less can lose data.
+func patchConfigObject(onDisk []jsonMember, full, shipped map[string]any) []jsonMember {
+ seen := make(map[string]bool, len(onDisk))
+ out := make([]jsonMember, 0, len(onDisk)+len(full))
+
+ for _, member := range onDisk {
+ seen[member.key] = true
+ value, known := full[member.key]
+ if !known {
+ // A key the struct does not model: preserved verbatim rather than
+ // dropped. A save must not delete what it merely failed to parse.
+ out = append(out, member)
+ continue
+ }
+ out = append(out, jsonMember{key: member.key, value: patchedValue(member.value, value, shipped[member.key])})
+ }
+
+ // Deterministic order for additions, since map iteration is not.
+ added := make([]string, 0, len(full))
+ for key := range full {
+ if !seen[key] {
+ added = append(added, key)
+ }
+ }
+ sort.Strings(added)
+
+ for _, key := range added {
+ value := full[key]
+ if nested, isObj := value.(map[string]any); isObj {
+ shippedObj, _ := shipped[key].(map[string]any)
+ members := patchConfigObject(nil, nested, shippedObj)
+ if len(members) == 0 {
+ continue
+ }
+ out = append(out, jsonMember{key: key, value: encodeJSONObject(members, 0)})
+ continue
+ }
+ if sameJSONValue(value, shipped[key]) {
+ continue
+ }
+ raw, err := json.Marshal(value)
+ if err != nil {
+ continue
+ }
+ out = append(out, jsonMember{key: key, value: raw})
+ }
+ return out
+}
+
+// patchedValue recurses into objects so a nested section keeps its own member order,
+// and replaces anything else with fc's value.
+func patchedValue(onDisk json.RawMessage, full, shipped any) json.RawMessage {
+ fullObj, isObj := full.(map[string]any)
+ if !isObj {
+ raw, err := json.Marshal(full)
+ if err != nil {
+ return onDisk
+ }
+ return raw
+ }
+ shippedObj, _ := shipped.(map[string]any)
+ return encodeJSONObject(patchConfigObject(parseJSONObject(onDisk), fullObj, shippedObj), 0)
+}
+
+// encodeJSONObject serialises members in order. Nested values are re-indented by
+// indentJSONValue at write time, so depth is handled once at the top rather than
+// threaded through every recursion.
+func encodeJSONObject(members []jsonMember, depth int) json.RawMessage {
+ if len(members) == 0 {
+ return json.RawMessage("{}")
+ }
+ var buf bytes.Buffer
+ buf.WriteString("{")
+ for i, member := range members {
+ if i > 0 {
+ buf.WriteString(",")
+ }
+ key, err := json.Marshal(member.key)
+ if err != nil {
+ continue
+ }
+ buf.Write(key)
+ buf.WriteString(":")
+ buf.Write(member.value)
+ }
+ buf.WriteString("}")
+ return buf.Bytes()
+}
+
+// renderMinimalConfig patches fc over the file's existing bytes and returns indented
+// JSON with the original member order intact.
+func renderMinimalConfig(fc *FileConfig, existing []byte) ([]byte, error) {
+ full, err := configAsMap(fc)
+ if err != nil {
+ return nil, err
+ }
+ shipped, err := configAsMap(savedConfigBaseline())
+ if err != nil {
+ return nil, err
+ }
+
+ members := patchConfigObject(parseJSONObject(existing), full, shipped)
+ compact := encodeJSONObject(members, 0)
+
+ var out bytes.Buffer
+ if err := json.Indent(&out, compact, "", " "); err != nil {
+ return nil, fmt.Errorf("failed to serialize config: %w", err)
+ }
+ body := strings.TrimRight(out.String(), "\n")
+ return []byte(body + "\n"), nil
+}