Skip to content

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

feat(config): nested config model with validation and CLI

Bosch163ea710ded0
diff --git a/CONFIG-MODEL-PLAN.md b/CONFIG-MODEL-PLAN.md
new file mode 100644
index 00000000..e44e441d
--- /dev/null
+++ b/CONFIG-MODEL-PLAN.md
@@ -0,0 +1,234 @@
+# Config Model Evolution Plan
+
+**Branch:** `feat/config-model`
+**Base:** `origin/main` (cd5f42a)
+
+## Current State
+
+The config system already has solid foundations:
+- `RuntimeConfig` struct (flat, typed, ~40 fields)
+- `FileConfig` struct (flat, ~15 fields — incomplete)
+- `Load()` with proper precedence: env vars > config file > defaults
+- Migration helpers for `BRIDGE_*` → `PINCHTAB_*`
+- CLI commands: `init`, `show`
+- Integration tests: `tests/integration/config_test.go`
+
+## Gap Analysis (vs PR #91 model)
+
+| Feature | Current | Target |
+|---------|---------|--------|
+| FileConfig structure | Flat JSON | Nested sections (Server/Chrome/Orchestrator/Timeouts) |
+| FileConfig fields | 15 fields | All RuntimeConfig fields mirrored |
+| CLI commands | init, show | + set, patch, validate |
+| Validation | None | ValidateConfig() with enum checks |
+| Editor helpers | None | SetConfigValue(), PatchConfigJSON() |
+| YAML support | None | JSON + YAML |
+| Documentation | Outdated | Full tables, JSON/YAML examples |
+
+## Implementation Plan
+
+### Phase 1: Expand FileConfig (Breaking: None)
+
+**File:** `internal/config/config.go`
+
+1. Add nested `FileConfig` structure:
+```go
+type FileConfig struct {
+ Server ServerConfig `json:"server"`
+ Chrome ChromeConfig `json:"chrome"`
+ Orchestrator OrchestratorConfig `json:"orchestrator"`
+ Timeouts TimeoutsConfig `json:"timeouts"`
+}
+
+type ServerConfig struct {
+ Port string `json:"port,omitempty"`
+ Bind string `json:"bind,omitempty"`
+ Token string `json:"token,omitempty"`
+ StateDir string `json:"stateDir,omitempty"`
+ // ... all server-related fields
+}
+
+type ChromeConfig struct {
+ Headless *bool `json:"headless,omitempty"`
+ MaxTabs *int `json:"maxTabs,omitempty"`
+ ProfileDir string `json:"profileDir,omitempty"`
+ StealthLevel string `json:"stealthLevel,omitempty"`
+ TabEvictionPolicy string `json:"tabEvictionPolicy,omitempty"`
+ // ... all chrome-related fields
+}
+
+type OrchestratorConfig struct {
+ Strategy string `json:"strategy,omitempty"`
+ AllocationPolicy string `json:"allocationPolicy,omitempty"`
+}
+
+type TimeoutsConfig struct {
+ ActionSec int `json:"actionSec,omitempty"`
+ NavigateSec int `json:"navigateSec,omitempty"`
+ ShutdownSec int `json:"shutdownSec,omitempty"`
+}
+```
+
+2. Update `Load()` selective merge to handle nested structure
+3. Maintain backward compatibility with flat config files (detect & migrate)
+
+**Tests:**
+- Add `TestLoadNestedConfig`
+- Add `TestLoadFlatConfigBackwardCompat`
+- Update existing tests as needed
+
+### Phase 2: Validation (Breaking: None)
+
+**File:** `internal/config/validate.go` (new)
+
+```go
+func ValidateConfig(fc *FileConfig) []error {
+ var errs []error
+
+ // Enum validation
+ if fc.Chrome.StealthLevel != "" {
+ if !isValidStealthLevel(fc.Chrome.StealthLevel) {
+ errs = append(errs, fmt.Errorf("invalid stealthLevel: %s (must be light|medium|full)", fc.Chrome.StealthLevel))
+ }
+ }
+
+ if fc.Chrome.TabEvictionPolicy != "" {
+ if !isValidEvictionPolicy(fc.Chrome.TabEvictionPolicy) {
+ errs = append(errs, fmt.Errorf("invalid tabEvictionPolicy: %s (must be reject|close_oldest|close_lru)", fc.Chrome.TabEvictionPolicy))
+ }
+ }
+
+ if fc.Orchestrator.Strategy != "" {
+ if !isValidStrategy(fc.Orchestrator.Strategy) {
+ errs = append(errs, fmt.Errorf("invalid strategy: %s (must be simple|explicit|simple-autorestart)", fc.Orchestrator.Strategy))
+ }
+ }
+
+ // Range validation
+ if fc.Server.Port != "" {
+ port, err := strconv.Atoi(fc.Server.Port)
+ if err != nil || port < 1 || port > 65535 {
+ errs = append(errs, fmt.Errorf("invalid port: %s (must be 1-65535)", fc.Server.Port))
+ }
+ }
+
+ return errs
+}
+```
+
+**Tests:**
+- `TestValidateConfig_ValidValues`
+- `TestValidateConfig_InvalidEnum`
+- `TestValidateConfig_InvalidPort`
+
+### Phase 3: Editor Helpers (Breaking: None)
+
+**File:** `internal/config/editor.go` (new)
+
+```go
+// SetConfigValue sets a dotted path in FileConfig (e.g., "server.port", "chrome.headless")
+func SetConfigValue(fc *FileConfig, path string, value string) error
+
+// PatchConfigJSON merges a JSON patch into FileConfig
+func PatchConfigJSON(fc *FileConfig, jsonPatch string) error
+
+// SaveConfig writes FileConfig to disk (JSON or YAML based on extension)
+func SaveConfig(fc *FileConfig, path string) error
+```
+
+**Tests:**
+- `TestSetConfigValue_ServerPort`
+- `TestSetConfigValue_ChromeHeadless`
+- `TestSetConfigValue_InvalidPath`
+- `TestPatchConfigJSON`
+- `TestSaveConfig_JSON`
+- `TestSaveConfig_YAML`
+
+### Phase 4: CLI Commands (Breaking: None)
+
+**File:** `internal/config/config.go` (extend `HandleConfigCommand`)
+
+Add subcommands:
+- `pinchtab config set server.port 8080` — set single value
+- `pinchtab config patch '{"chrome":{"headless":false}}'` — JSON patch
+- `pinchtab config validate` — check config file for errors
+- `pinchtab config show --format yaml` — output in YAML
+
+**Tests:**
+- Integration tests for each command
+- Unit tests for parsing/formatting
+
+### Phase 5: YAML Support (Breaking: None)
+
+**File:** `internal/config/config.go`
+
+1. Detect file extension (.json vs .yaml/.yml)
+2. Use `gopkg.in/yaml.v3` for YAML (or keep it pure with custom marshaler)
+3. Update `SaveConfig()` to support both formats
+
+**Decision:** Use `gopkg.in/yaml.v3` — standard, well-tested, minimal overhead.
+
+### Phase 6: Documentation Update
+
+**File:** `docs/references/configuration.md`
+
+1. Add nested JSON example
+2. Add YAML example
+3. Update env var tables with all new fields
+4. Add "Config File vs Env Vars" section
+5. Document CLI commands (set, patch, validate)
+
+## Test Impact Analysis
+
+| Test File | Changes Needed |
+|-----------|----------------|
+| `internal/config/config_test.go` | Add nested config tests, backward compat tests |
+| `tests/integration/config_test.go` | Add CLI command tests (set, patch, validate) |
+| New: `internal/config/validate_test.go` | Validation unit tests |
+| New: `internal/config/editor_test.go` | Editor helper unit tests |
+
+## Backward Compatibility
+
+1. **Flat config files** — `Load()` will detect flat vs nested and handle both
+2. **Env vars** — Continue to take precedence over file config
+3. **`BRIDGE_*` vars** — Migration warnings still work
+4. **Existing CLI** — `init` and `show` unchanged
+
+## Migration Path
+
+Users with existing flat config files:
+1. `pinchtab config show` — shows current effective config
+2. `pinchtab config init --migrate` — converts flat to nested (optional, not required)
+3. Flat configs continue to work indefinitely
+
+## Implementation Order
+
+1. ✅ Phase 1 (Nested FileConfig) — foundation for everything else
+2. ✅ Phase 2 (Validation) — catches errors early
+3. ✅ Phase 3 (Editor Helpers) — SetConfigValue, PatchConfigJSON, Load/SaveFileConfig
+4. ✅ Phase 4 (CLI Commands) — set, patch commands with validation
+5. Phase 5 (YAML) — nice-to-have, can defer
+6. ✅ Phase 6 (Docs) — updated configuration.md
+
+## Estimated LOC
+
+| Phase | New Lines | Modified Lines |
+|-------|-----------|----------------|
+| 1. Nested FileConfig | ~150 | ~100 |
+| 2. Validation | ~100 | ~20 |
+| 3. Editor Helpers | ~150 | ~10 |
+| 4. CLI Commands | ~100 | ~50 |
+| 5. YAML Support | ~50 | ~30 |
+| 6. Documentation | ~200 | ~100 |
+| **Total** | **~750** | **~310** |
+
+## Open Questions
+
+1. **YAML dependency** — Add `gopkg.in/yaml.v3` or keep pure stdlib?
+ - Recommendation: Add it — it's the standard and battle-tested
+
+2. **Flat config auto-migration** — Should `pinchtab config init` auto-migrate existing flat configs?
+ - Recommendation: Yes, with confirmation prompt
+
+3. **Config file location** — Keep `~/.pinchtab/config.json` or move to XDG-compliant `~/.config/pinchtab/config.json`?
+ - Recommendation: Already handled by `userConfigDir()` — defaults to XDG with fallback to legacy
diff --git a/docs/references/configuration.md b/docs/references/configuration.md
index 478a5f71..9078ae7a 100644
--- a/docs/references/configuration.md
+++ b/docs/references/configuration.md
@@ -1,341 +1,322 @@
# Configuration
-Complete reference for all PinchTab environment variables and configuration options.
+Complete reference for PinchTab configuration. Supports environment variables, config files (JSON), and CLI commands.
-## Environment Variables
+## Configuration Priority
-### Port & Network
+Values are loaded in this order (highest priority first):
+
+1. **Environment variables** — always win
+2. **Config file** — `~/.config/pinchtab/config.json` (or `~/.pinchtab/config.json` legacy)
+3. **Built-in defaults** — used if nothing else is set
+
+## Config File
+
+### Location
+
+Default location varies by OS:
+- **macOS:** `~/Library/Application Support/pinchtab/config.json`
+- **Linux:** `~/.config/pinchtab/config.json` (or `$XDG_CONFIG_HOME/pinchtab/config.json`)
+- **Windows:** `%APPDATA%\pinchtab\config.json`
+
+For backward compatibility, `~/.pinchtab/config.json` is used if it exists and the new location doesn't.
+
+Override with: `PINCHTAB_CONFIG=/path/to/config.json`
+
+### Format (Nested JSON)
+
+```json
+{
+ "server": {
+ "port": "9867",
+ "bind": "127.0.0.1",
+ "token": "your-secret-token",
+ "stateDir": "/path/to/state",
+ "instancePortStart": 9868,
+ "instancePortEnd": 9968
+ },
+ "chrome": {
+ "headless": true,
+ "maxTabs": 20,
+ "profileDir": "/path/to/chrome-profile",
+ "stealthLevel": "light",
+ "tabEvictionPolicy": "reject",
+ "blockAds": false,
+ "blockImages": false,
+ "blockMedia": false,
+ "noRestore": false,
+ "noAnimations": false
+ },
+ "security": {
+ "allowEvaluate": false,
+ "allowMacro": false,
+ "allowScreencast": false,
+ "allowDownload": false,
+ "allowUpload": false
+ },
+ "orchestrator": {
+ "strategy": "simple",
+ "allocationPolicy": "fcfs"
+ },
+ "timeouts": {
+ "actionSec": 30,
+ "navigateSec": 60,
+ "shutdownSec": 10,
+ "waitNavMs": 1000
+ }
+}
+```
-| Variable | Default | Description |
-|---|---|---|
-| `BRIDGE_PORT` | `9867` | HTTP server port |
-| `BRIDGE_BIND` | `127.0.0.1` | Bind address (127.0.0.1 = localhost only, 0.0.0.0 = all interfaces) |
+### Legacy Flat Format (Deprecated)
-### Browser & Chrome
+Older flat format is still supported for backward compatibility:
-| Variable | Default | Description |
-|---|---|---|
-| `CHROME_BINARY` | Auto-detect | Path to Chrome/Chromium binary |
-| `BRIDGE_HEADLESS` | `true` | Run Chrome headless (no visible window) |
-| `BRIDGE_PROFILE` | Default profile | Chrome profile name (stored in `~/.pinchtab/profiles/{name}`) |
-
-### Stealth & Detection
+```json
+{
+ "port": "9867",
+ "headless": true,
+ "maxTabs": 20,
+ "allowEvaluate": false,
+ "timeoutSec": 30,
+ "navigateSec": 60
+}
+```
-| Variable | Default | Description |
-|---|---|---|
-| `BRIDGE_STEALTH` | `light` | Stealth level: `light`, `medium`, `full` (higher = more bot detection bypass, slower) |
+Run `pinchtab config init` to generate a new config with the nested format.
-### Content Filtering
+## Environment Variables
-| Variable | Default | Description |
-|---|---|---|
-| `BRIDGE_BLOCK_ADS` | `false` | Block ad domains (speeds up loading) |
-| `BRIDGE_BLOCK_IMAGES` | `false` | Block image loading |
-| `BRIDGE_BLOCK_MEDIA` | `false` | Block video/audio resources |
+Environment variables always take precedence over config file values.
-### Security & Authentication
+### Server
| Variable | Default | Description |
-|---|---|---|
-| `PINCHTAB_TOKEN` | Disabled | API authentication token (if set, all requests must include `Authorization: Bearer {token}`) |
-| `PINCHTAB_ALLOW_EVALUATE` | `false` | Enable `POST /evaluate` and `POST /tabs/{id}/evaluate` endpoints (disabled by default) |
-
-### Debugging & Logging
+|----------|---------|-------------|
+| `PINCHTAB_PORT` | `9867` | HTTP server port |
+| `PINCHTAB_BIND` | `127.0.0.1` | Bind address |
+| `PINCHTAB_TOKEN` | (none) | API authentication token |
+| `PINCHTAB_STATE_DIR` | (OS config dir) | State/data directory |
+| `PINCHTAB_CONFIG` | (OS config dir)/config.json | Config file path |
+| `PINCHTAB_INSTANCE_PORT_START` | `9868` | First port for browser instances |
+| `PINCHTAB_INSTANCE_PORT_END` | `9968` | Last port for browser instances |
+| `CDP_URL` | (none) | External Chrome DevTools Protocol URL |
+
+### Security
| Variable | Default | Description |
-|---|---|---|
-| `BRIDGE_DEBUG` | `false` | Enable debug logging (verbose output) |
-| `BRIDGE_LOG_LEVEL` | `info` | Log level: `debug`, `info`, `warn`, `error` |
+|----------|---------|-------------|
+| `PINCHTAB_ALLOW_EVALUATE` | `false` | Enable `/evaluate` endpoint |
+| `PINCHTAB_ALLOW_MACRO` | `false` | Enable macro recording/playback |
+| `PINCHTAB_ALLOW_SCREENCAST` | `false` | Enable screencast streaming |
+| `PINCHTAB_ALLOW_DOWNLOAD` | `false` | Enable file downloads |
+| `PINCHTAB_ALLOW_UPLOAD` | `false` | Enable file uploads |
-### Dashboard
+### Chrome/Browser
| Variable | Default | Description |
-|---|---|---|
-| `BRIDGE_DASHBOARD_PORT` | Same as `BRIDGE_PORT` | Dashboard HTTP port (usually same as API server) |
-| `BRIDGE_NO_DASHBOARD` | `false` | Disable dashboard (API-only mode) |
-
----
-
-## Usage Examples
-
-### Basic Setup
+|----------|---------|-------------|
+| `PINCHTAB_HEADLESS` | `true` | Run Chrome headless |
+| `PINCHTAB_PROFILE_DIR` | (state dir)/chrome-profile | Chrome profile directory |
+| `PINCHTAB_MAX_TABS` | `20` | Maximum tabs per instance |
+| `PINCHTAB_MAX_PARALLEL_TABS` | `0` (auto) | Max parallel tab operations |
+| `PINCHTAB_STEALTH` | `light` | Stealth level: `light`, `medium`, `full` |
+| `PINCHTAB_TAB_EVICTION_POLICY` | `reject` | Tab limit behavior: `reject`, `close_oldest`, `close_lru` |
+| `PINCHTAB_NO_RESTORE` | `false` | Don't restore previous session |
+| `PINCHTAB_NO_ANIMATIONS` | `false` | Disable CSS animations |
+| `PINCHTAB_BLOCK_ADS` | `false` | Block ad domains |
+| `PINCHTAB_BLOCK_IMAGES` | `false` | Block image loading |
+| `PINCHTAB_BLOCK_MEDIA` | `false` | Block video/audio |
+| `PINCHTAB_CHROME_VERSION` | `144.0.7559.133` | Chrome version for UA/fingerprint |
+| `PINCHTAB_USER_AGENT` | (auto) | Custom user agent |
+| `PINCHTAB_TIMEZONE` | (system) | Browser timezone |
+| `CHROME_BIN` | (auto) | Chrome binary path |
+| `CHROME_FLAGS` | (none) | Extra Chrome flags |
+| `CHROME_EXTENSION_PATHS` | (none) | Comma-separated extension paths |
+
+### Orchestrator (Dashboard Mode)
-```bash
-# Default (headless, localhost:9867)
-./pinchtab
-```
+| Variable | Default | Description |
+|----------|---------|-------------|
+| `PINCHTAB_STRATEGY` | `simple` | Strategy: `simple`, `explicit`, `simple-autorestart` |
+| `PINCHTAB_ALLOCATION_POLICY` | `fcfs` | Instance allocation: `fcfs`, `round_robin`, `random` |
-### Custom Port
+### Legacy Variables (Deprecated)
-```bash
-BRIDGE_PORT=9868 ./pinchtab
-```
+The following `BRIDGE_*` variables still work but emit warnings. Use the `PINCHTAB_*` equivalents:
-### Network Access (External)
+| Legacy | New |
+|--------|-----|
+| `BRIDGE_PORT` | `PINCHTAB_PORT` |
+| `BRIDGE_BIND` | `PINCHTAB_BIND` |
+| `BRIDGE_TOKEN` | `PINCHTAB_TOKEN` |
+| `BRIDGE_HEADLESS` | `PINCHTAB_HEADLESS` |
+| `BRIDGE_PROFILE` | `PINCHTAB_PROFILE_DIR` |
+| `BRIDGE_MAX_TABS` | `PINCHTAB_MAX_TABS` |
+| `BRIDGE_STEALTH` | `PINCHTAB_STEALTH` |
+| `BRIDGE_ALLOW_EVALUATE` | `PINCHTAB_ALLOW_EVALUATE` |
-```bash
-# Allow connections from other machines
-BRIDGE_BIND=0.0.0.0 BRIDGE_PORT=9867 ./pinchtab
-```
+## CLI Commands
-**⚠️ Security Warning:** Only use `0.0.0.0` on trusted networks. Consider using `PINCHTAB_TOKEN` for authentication.
+### pinchtab config init
-### Headed Mode with Profile
+Create a default config file:
```bash
-BRIDGE_HEADLESS=false BRIDGE_PROFILE=work ./pinchtab
+pinchtab config init
```
-Opens visible Chrome window with "work" profile.
+Creates `config.json` in the default location with sensible defaults.
-### Stealth Mode (Bypass Bot Detection)
+### pinchtab config show
-```bash
-BRIDGE_STEALTH=full ./pinchtab
-```
-
-Options:
-- `light` — Basic patches (default, minimal overhead)
-- `medium` — More aggressive patches (some overhead)
-- `full` — Maximum stealth (significant overhead, slowest)
-
-### Ad Blocking
+Show current effective configuration:
```bash
-BRIDGE_BLOCK_ADS=true ./pinchtab
+pinchtab config show
```
-Speeds up page loading by blocking ad domains.
-
-### API Authentication
-
-```bash
-PINCHTAB_TOKEN=my-secret-token ./pinchtab
-```
+Shows all settings with their current values (from env vars, config file, or defaults).
-Then all API requests must include:
-```bash
-curl -H "Authorization: Bearer my-secret-token" http://localhost:9867/health
-```
+### pinchtab config path
-### Enable JavaScript Evaluate Endpoint (Opt-in)
+Show config file path:
```bash
-PINCHTAB_TOKEN=my-secret-token \
-PINCHTAB_ALLOW_EVALUATE=true \
-pinchtab
+pinchtab config path
```
-By default, evaluate endpoints are not registered.
-
-### Multiple Settings
-
-```bash
-BRIDGE_PORT=9868 \
-BRIDGE_HEADLESS=false \
-BRIDGE_STEALTH=full \
-BRIDGE_BLOCK_ADS=true \
-BRIDGE_PROFILE=dev \
-PINCHTAB_TOKEN=secret \
-./pinchtab
-```
+### pinchtab config validate
-### Debug Mode
+Validate config file:
```bash
-BRIDGE_DEBUG=true BRIDGE_LOG_LEVEL=debug ./pinchtab
+pinchtab config validate
```
-Produces verbose logs for troubleshooting.
-
----
-
-## Configuration Priority
+Checks for:
+- Valid port numbers (1-65535)
+- Valid enum values (strategy, stealthLevel, tabEvictionPolicy, etc.)
+- Valid timeout values (non-negative)
+- Instance port range (start <= end)
-If multiple sources set the same value:
+## Examples
-1. **Command-line flags** (highest priority)
-2. **Environment variables**
-3. **Config file** (if supported)
-4. **Built-in defaults** (lowest priority)
+### Basic Setup (Defaults)
-Example:
```bash
-# BRIDGE_PORT=9868 from env, but --port flag overrides it
-./pinchtab --port 9870 # Uses 9870
-```
-
----
-
-## Chrome Profile Directory Structure
-
-Profiles are stored in `~/.pinchtab/profiles/{id}/`:
-
-```text
-~/.pinchtab/profiles/
-├── prof_9f86d081/
-│ ├── Default/
-│ │ ├── Preferences
-│ │ ├── Cookies
-│ │ ├── History
-│ │ └── ... (other Chrome data)
-│ └── ...
-├── prof_dc34vewr/
-│ ├── Default/
-│ │ └── ... (Chrome data)
-│ └── ...
-└── prof_34ff6ks9/
- └── ... (default profile)
+pinchtab
```
-Each profile maintains its own:
-- Cookies and session data
-- Browsing history
-- Saved passwords
-- Local storage
-- Cache
-
----
+Runs on `localhost:9867`, headless, no authentication.
-## Performance Tuning
-
-### For Speed (Reduce Overhead)
+### With Authentication
```bash
-# Minimal stealth, block ads
-BRIDGE_STEALTH=light \
-BRIDGE_BLOCK_ADS=true \
-./pinchtab
+PINCHTAB_TOKEN=my-secret-token pinchtab
```
-### For Security (Detect Bypass)
-
-```bash
-# Maximum stealth
-BRIDGE_STEALTH=full ./pinchtab
+Or in config file:
+```json
+{
+ "server": {
+ "token": "my-secret-token"
+ }
+}
```
-Note: Maximum stealth increases latency by 2-3x.
-
-### For Bandwidth (Block Resources)
-
-```bash
-# Block ads, images, and media
-BRIDGE_BLOCK_ADS=true \
-BRIDGE_BLOCK_IMAGES=true \
-BRIDGE_BLOCK_MEDIA=true \
-./pinchtab
-```
-
----
-
-## Network Configuration
-
-### Localhost Only (Default - Secure)
+### Network Accessible
```bash
-BRIDGE_BIND=127.0.0.1 ./pinchtab
+PINCHTAB_BIND=0.0.0.0 PINCHTAB_TOKEN=secret pinchtab
```
-Only accessible from the same machine.
+**⚠️ Always use a token when binding to 0.0.0.0**
-### All Interfaces (Network Accessible)
+### Headed Mode for Debugging
```bash
-BRIDGE_BIND=0.0.0.0 ./pinchtab
+PINCHTAB_HEADLESS=false pinchtab
```
-Accessible from any machine on the network. **Requires authentication:**
-
-```bash
-BRIDGE_BIND=0.0.0.0 PINCHTAB_TOKEN=secret ./pinchtab
+Or in config file:
+```json
+{
+ "chrome": {
+ "headless": false
+ }
+}
```
-### Specific Interface
+### Maximum Stealth
```bash
-BRIDGE_BIND=192.168.1.100 ./pinchtab
+PINCHTAB_STEALTH=full pinchtab
```
-Only accessible from that IP address.
-
----
-
-## Troubleshooting
+Higher stealth = more bot detection bypass, but slower.
-### Port Already in Use
+### Enable Dangerous Endpoints
```bash
-# Find what's using the port
-lsof -i :9867
-
-# Use different port
-BRIDGE_PORT=9868 ./pinchtab
+PINCHTAB_ALLOW_EVALUATE=true \
+PINCHTAB_ALLOW_MACRO=true \
+PINCHTAB_TOKEN=secret \
+pinchtab
```
-### Chrome Not Found
-
-```bash
-# Specify custom binary path
-CHROME_BINARY=/usr/bin/google-chrome ./pinchtab
+Or in config file:
+```json
+{
+ "server": {
+ "token": "secret"
+ },
+ "security": {
+ "allowEvaluate": true,
+ "allowMacro": true
+ }
+}
```
-### High Latency with Stealth Mode
+### Custom Ports
```bash
-# Reduce stealth level
-BRIDGE_STEALTH=light ./pinchtab
+PINCHTAB_PORT=8080 \
+PINCHTAB_INSTANCE_PORT_START=8100 \
+PINCHTAB_INSTANCE_PORT_END=8200 \
+pinchtab dashboard
```
-Maximum stealth (`full`) adds significant overhead.
+### Tab Eviction Policy
-### Authentication Errors
+When max tabs is reached:
+- `reject` — Return error (default, safest)
+- `close_oldest` — Close oldest tab by creation time
+- `close_lru` — Close least recently used tab
-```bash
-# Check token format
-PINCHTAB_TOKEN=my-token ./pinchtab
-
-# Request must include the token
-curl -H "Authorization: Bearer my-token" http://localhost:9867/health
+```json
+{
+ "chrome": {
+ "maxTabs": 10,
+ "tabEvictionPolicy": "close_lru"
+ }
+}
```
----
-
-## Security Best Practices
-
-1. **Use `PINCHTAB_TOKEN` when exposing to network:**
- ```bash
- BRIDGE_BIND=0.0.0.0 PINCHTAB_TOKEN=$(openssl rand -hex 32) ./pinchtab
- ```
-
-2. **Use localhost by default:**
- ```bash
- # Good: only accessible locally
- BRIDGE_BIND=127.0.0.1 ./pinchtab
- ```
-
-3. **Use SSH tunneling for remote access:**
- ```bash
- # Remote: start without binding to all interfaces
- ssh user@remote "BRIDGE_BIND=127.0.0.1 pinchtab"
-
- # Local: tunnel through SSH
- ssh -L 9867:127.0.0.1:9867 user@remote
+## Validation
- # Then use locally
- curl http://localhost:9867/health
- ```
+All enum fields are validated on load:
-4. **Use firewall rules if exposing to network:**
- ```bash
- # Only allow from specific IPs
- ufw allow from 192.168.1.0/24 to any port 9867
- ```
+| Field | Valid Values |
+|-------|--------------|
+| `chrome.stealthLevel` | `light`, `medium`, `full` |
+| `chrome.tabEvictionPolicy` | `reject`, `close_oldest`, `close_lru` |
+| `orchestrator.strategy` | `simple`, `explicit`, `simple-autorestart` |
+| `orchestrator.allocationPolicy` | `fcfs`, `round_robin`, `random` |
----
+Run `pinchtab config validate` to check your config file.
## Related Documentation
- [API Reference](endpoints.md) — HTTP endpoints
-- [Getting Started](../get-started.md) — Quick setup
-- [Core Concepts](../core-concepts.md) — Instances, profiles, tabs
+- [CLI Reference](cli-quick-reference.md) — Command line usage
+- [Instance API](instance-api.md) — Multi-instance management
diff --git a/internal/config/config.go b/internal/config/config.go
index 86104452..c8003f3e 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -11,19 +11,26 @@ import (
"time"
)
+// RuntimeConfig holds all runtime settings used throughout the application.
+// This is the single source of truth for configuration at runtime.
type RuntimeConfig struct {
+ // Server settings
Bind string
Port string
InstancePortStart int // Starting port for instances (default 9868)
InstancePortEnd int // Ending port for instances (default 9968)
CdpURL string
Token string
- AllowEvaluate bool
- AllowMacro bool
- AllowScreencast bool
- AllowDownload bool
- AllowUpload bool
StateDir string
+
+ // Security settings
+ AllowEvaluate bool
+ AllowMacro bool
+ AllowScreencast bool
+ AllowDownload bool
+ AllowUpload bool
+
+ // Chrome settings
Headless bool
NoRestore bool
ProfileDir string
@@ -41,16 +48,173 @@ type RuntimeConfig struct {
NoAnimations bool
StealthLevel string
TabEvictionPolicy string // "reject" (default), "close_oldest", "close_lru"
- ActionTimeout time.Duration
- NavigateTimeout time.Duration
- ShutdownTimeout time.Duration
- WaitNavDelay time.Duration
- // Orchestrator settings (dashboard mode only).
+ // Timeout settings
+ ActionTimeout time.Duration
+ NavigateTimeout time.Duration
+ ShutdownTimeout time.Duration
+ WaitNavDelay time.Duration
+
+ // Orchestrator settings (dashboard mode only)
Strategy string // "simple" (default), "explicit", or "simple-autorestart"
AllocationPolicy string // "fcfs" (default), "round_robin", "random"
}
+// --- Nested FileConfig structure (PR #91 model) ---
+
+// FileConfig is the persistent configuration written to disk.
+// Uses nested sections for organization: Server, Chrome, Orchestrator, Timeouts.
+type FileConfig struct {
+ Server ServerConfig `json:"server,omitempty"`
+ Chrome ChromeConfig `json:"chrome,omitempty"`
+ Security SecurityConfig `json:"security,omitempty"`
+ Orchestrator OrchestratorConfig `json:"orchestrator,omitempty"`
+ Timeouts TimeoutsConfig `json:"timeouts,omitempty"`
+}
+
+// ServerConfig holds server/network settings.
+type ServerConfig struct {
+ Port string `json:"port,omitempty"`
+ Bind string `json:"bind,omitempty"`
+ Token string `json:"token,omitempty"`
+ StateDir string `json:"stateDir,omitempty"`
+ CdpURL string `json:"cdpUrl,omitempty"`
+ InstancePortStart *int `json:"instancePortStart,omitempty"`
+ InstancePortEnd *int `json:"instancePortEnd,omitempty"`
+}
+
+// ChromeConfig holds browser/Chrome settings.
+type ChromeConfig struct {
+ Headless *bool `json:"headless,omitempty"`
+ NoRestore *bool `json:"noRestore,omitempty"`
+ ProfileDir string `json:"profileDir,omitempty"`
+ ChromeVersion string `json:"chromeVersion,omitempty"`
+ Timezone string `json:"timezone,omitempty"`
+ BlockImages *bool `json:"blockImages,omitempty"`
+ BlockMedia *bool `json:"blockMedia,omitempty"`
+ BlockAds *bool `json:"blockAds,omitempty"`
+ MaxTabs *int `json:"maxTabs,omitempty"`
+ MaxParallelTabs *int `json:"maxParallelTabs,omitempty"`
+ ChromeBinary string `json:"chromeBinary,omitempty"`
+ ChromeExtraFlags string `json:"chromeExtraFlags,omitempty"`
+ ExtensionPaths []string `json:"extensionPaths,omitempty"`
+ UserAgent string `json:"userAgent,omitempty"`
+ NoAnimations *bool `json:"noAnimations,omitempty"`
+ StealthLevel string `json:"stealthLevel,omitempty"`
+ TabEvictionPolicy string `json:"tabEvictionPolicy,omitempty"`
+}
+
+// SecurityConfig holds security/permission settings.
+type SecurityConfig struct {
+ AllowEvaluate *bool `json:"allowEvaluate,omitempty"`
+ AllowMacro *bool `json:"allowMacro,omitempty"`
+ AllowScreencast *bool `json:"allowScreencast,omitempty"`
+ AllowDownload *bool `json:"allowDownload,omitempty"`
+ AllowUpload *bool `json:"allowUpload,omitempty"`
+}
+
+// OrchestratorConfig holds orchestrator/strategy settings.
+type OrchestratorConfig struct {
+ Strategy string `json:"strategy,omitempty"`
+ AllocationPolicy string `json:"allocationPolicy,omitempty"`
+}
+
+// TimeoutsConfig holds timeout settings.
+type TimeoutsConfig struct {
+ ActionSec int `json:"actionSec,omitempty"`
+ NavigateSec int `json:"navigateSec,omitempty"`
+ ShutdownSec int `json:"shutdownSec,omitempty"`
+ WaitNavMs int `json:"waitNavMs,omitempty"`
+}
+
+// --- Legacy flat FileConfig for backward compatibility ---
+
+// legacyFileConfig is the old flat structure for backward compatibility.
+type legacyFileConfig struct {
+ Port string `json:"port"`
+ InstancePortStart *int `json:"instancePortStart,omitempty"`
+ InstancePortEnd *int `json:"instancePortEnd,omitempty"`
+ CdpURL string `json:"cdpUrl,omitempty"`
+ Token string `json:"token,omitempty"`
+ AllowEvaluate *bool `json:"allowEvaluate,omitempty"`
+ AllowMacro *bool `json:"allowMacro,omitempty"`
+ AllowScreencast *bool `json:"allowScreencast,omitempty"`
+ AllowDownload *bool `json:"allowDownload,omitempty"`
+ AllowUpload *bool `json:"allowUpload,omitempty"`
+ StateDir string `json:"stateDir"`
+ ProfileDir string `json:"profileDir"`
+ Headless *bool `json:"headless,omitempty"`
+ NoRestore bool `json:"noRestore"`
+ MaxTabs *int `json:"maxTabs,omitempty"`
+ TimeoutSec int `json:"timeoutSec,omitempty"`
+ NavigateSec int `json:"navigateSec,omitempty"`
+}
+
+// convertLegacyConfig converts flat config to nested structure.
+func convertLegacyConfig(lc *legacyFileConfig) *FileConfig {
+ fc := &FileConfig{}
+
+ // Server
+ fc.Server.Port = lc.Port
+ fc.Server.CdpURL = lc.CdpURL
+ fc.Server.Token = lc.Token
+ fc.Server.StateDir = lc.StateDir
+ fc.Server.InstancePortStart = lc.InstancePortStart
+ fc.Server.InstancePortEnd = lc.InstancePortEnd
+
+ // Chrome
+ fc.Chrome.Headless = lc.Headless
+ fc.Chrome.ProfileDir = lc.ProfileDir
+ fc.Chrome.MaxTabs = lc.MaxTabs
+ if lc.NoRestore {
+ b := true
+ fc.Chrome.NoRestore = &b
+ }
+
+ // Security
+ fc.Security.AllowEvaluate = lc.AllowEvaluate
+ fc.Security.AllowMacro = lc.AllowMacro
+ fc.Security.AllowScreencast = lc.AllowScreencast
+ fc.Security.AllowDownload = lc.AllowDownload
+ fc.Security.AllowUpload = lc.AllowUpload
+
+ // Timeouts
+ fc.Timeouts.ActionSec = lc.TimeoutSec
+ fc.Timeouts.NavigateSec = lc.NavigateSec
+
+ return fc
+}
+
+// isLegacyConfig detects if JSON is flat (legacy) or nested (new).
+// Returns true if it looks like legacy format.
+func isLegacyConfig(data []byte) bool {
+ var probe map[string]json.RawMessage
+ if err := json.Unmarshal(data, &probe); err != nil {
+ return false
+ }
+
+ // If "server" or "chrome" keys exist, it's new format
+ if _, hasServer := probe["server"]; hasServer {
+ return false
+ }
+ if _, hasChrome := probe["chrome"]; hasChrome {
+ return false
+ }
+
+ // If "port" or "headless" exist at top level, it's legacy
+ if _, hasPort := probe["port"]; hasPort {
+ return true
+ }
+ if _, hasHeadless := probe["headless"]; hasHeadless {
+ return true
+ }
+
+ // Default to new format for empty/unknown
+ return false
+}
+
+// --- Environment variable helpers ---
+
func envOr(key, fallback string) string {
if v := os.Getenv(key); v != "" {
return v
@@ -219,40 +383,26 @@ func (c *RuntimeConfig) ListenAddr() string {
return c.Bind + ":" + c.Port
}
-type FileConfig struct {
- Port string `json:"port"`
- InstancePortStart *int `json:"instancePortStart,omitempty"`
- InstancePortEnd *int `json:"instancePortEnd,omitempty"`
- CdpURL string `json:"cdpUrl,omitempty"`
- Token string `json:"token,omitempty"`
- AllowEvaluate *bool `json:"allowEvaluate,omitempty"`
- AllowMacro *bool `json:"allowMacro,omitempty"`
- AllowScreencast *bool `json:"allowScreencast,omitempty"`
- AllowDownload *bool `json:"allowDownload,omitempty"`
- AllowUpload *bool `json:"allowUpload,omitempty"`
- StateDir string `json:"stateDir"`
- ProfileDir string `json:"profileDir"`
- Headless *bool `json:"headless,omitempty"`
- NoRestore bool `json:"noRestore"`
- MaxTabs *int `json:"maxTabs,omitempty"`
- TimeoutSec int `json:"timeoutSec,omitempty"`
- NavigateSec int `json:"navigateSec,omitempty"`
-}
-
+// Load returns the RuntimeConfig with precedence: env vars > config file > defaults.
func Load() *RuntimeConfig {
cfg := &RuntimeConfig{
+ // Server defaults + env vars
Bind: envOrMigrate("PINCHTAB_BIND", "BRIDGE_BIND", "127.0.0.1"),
Port: envOrMigrate("PINCHTAB_PORT", "BRIDGE_PORT", "9867"),
- InstancePortStart: envIntOr("INSTANCE_PORT_START", 9868),
- InstancePortEnd: envIntOr("INSTANCE_PORT_END", 9968),
+ InstancePortStart: envIntOr("PINCHTAB_INSTANCE_PORT_START", 9868),
+ InstancePortEnd: envIntOr("PINCHTAB_INSTANCE_PORT_END", 9968),
CdpURL: os.Getenv("CDP_URL"),
Token: envMigrate("PINCHTAB_TOKEN", "BRIDGE_TOKEN"),
- AllowEvaluate: envBoolOrMigrate("PINCHTAB_ALLOW_EVALUATE", "BRIDGE_ALLOW_EVALUATE", false),
- AllowMacro: envBoolOrMigrate("PINCHTAB_ALLOW_MACRO", "BRIDGE_ALLOW_MACRO", false),
- AllowScreencast: envBoolOrMigrate("PINCHTAB_ALLOW_SCREENCAST", "BRIDGE_ALLOW_SCREENCAST", false),
- AllowDownload: envBoolOrMigrate("PINCHTAB_ALLOW_DOWNLOAD", "BRIDGE_ALLOW_DOWNLOAD", false),
- AllowUpload: envBoolOrMigrate("PINCHTAB_ALLOW_UPLOAD", "BRIDGE_ALLOW_UPLOAD", false),
StateDir: envOrMigrate("PINCHTAB_STATE_DIR", "BRIDGE_STATE_DIR", userConfigDir()),
+
+ // Security defaults + env vars
+ AllowEvaluate: envBoolOrMigrate("PINCHTAB_ALLOW_EVALUATE", "BRIDGE_ALLOW_EVALUATE", false),
+ AllowMacro: envBoolOrMigrate("PINCHTAB_ALLOW_MACRO", "BRIDGE_ALLOW_MACRO", false),
+ AllowScreencast: envBoolOrMigrate("PINCHTAB_ALLOW_SCREENCAST", "BRIDGE_ALLOW_SCREENCAST", false),
+ AllowDownload: envBoolOrMigrate("PINCHTAB_ALLOW_DOWNLOAD", "BRIDGE_ALLOW_DOWNLOAD", false),
+ AllowUpload: envBoolOrMigrate("PINCHTAB_ALLOW_UPLOAD", "BRIDGE_ALLOW_UPLOAD", false),
+
+ // Chrome defaults + env vars
Headless: envBoolOrMigrate("PINCHTAB_HEADLESS", "BRIDGE_HEADLESS", true),
NoRestore: envBoolOrMigrate("PINCHTAB_NO_RESTORE", "BRIDGE_NO_RESTORE", false),
ProfileDir: envOrMigrate("PINCHTAB_PROFILE_DIR", "BRIDGE_PROFILE", filepath.Join(userConfigDir(), "chrome-profile")),
@@ -270,14 +420,19 @@ func Load() *RuntimeConfig {
NoAnimations: envBoolOrMigrate("PINCHTAB_NO_ANIMATIONS", "BRIDGE_NO_ANIMATIONS", false),
StealthLevel: envOrMigrate("PINCHTAB_STEALTH", "BRIDGE_STEALTH", "light"),
TabEvictionPolicy: envOr("PINCHTAB_TAB_EVICTION_POLICY", "reject"),
- Strategy: envOr("PINCHTAB_STRATEGY", "simple"),
- AllocationPolicy: envOr("PINCHTAB_ALLOCATION_POLICY", "fcfs"),
- ActionTimeout: 30 * time.Second,
- NavigateTimeout: 60 * time.Second,
- ShutdownTimeout: 10 * time.Second,
- WaitNavDelay: 1 * time.Second,
+
+ // Timeout defaults
+ ActionTimeout: 30 * time.Second,
+ NavigateTimeout: 60 * time.Second,
+ ShutdownTimeout: 10 * time.Second,
+ WaitNavDelay: 1 * time.Second,
+
+ // Orchestrator defaults + env vars
+ Strategy: envOr("PINCHTAB_STRATEGY", "simple"),
+ AllocationPolicy: envOr("PINCHTAB_ALLOCATION_POLICY", "fcfs"),
}
+ // Load config file (supports both legacy flat and new nested format)
configPath := envOrMigrate("PINCHTAB_CONFIG", "BRIDGE_CONFIG", filepath.Join(userConfigDir(), "config.json"))
data, err := os.ReadFile(configPath)
@@ -285,152 +440,447 @@ func Load() *RuntimeConfig {
return cfg
}
- var fc FileConfig
- if err := json.Unmarshal(data, &fc); err != nil {
- return cfg
+ var fc *FileConfig
+
+ if isLegacyConfig(data) {
+ var lc legacyFileConfig
+ if err := json.Unmarshal(data, &lc); err != nil {
+ return cfg
+ }
+ fc = convertLegacyConfig(&lc)
+ slog.Debug("loaded legacy flat config, consider migrating to nested format")
+ } else {
+ fc = &FileConfig{}
+ if err := json.Unmarshal(data, fc); err != nil {
+ return cfg
+ }
}
- if fc.Port != "" && !envMigrateIsSet("PINCHTAB_PORT", "BRIDGE_PORT") {
- cfg.Port = fc.Port
+ // Apply file config (only if env var NOT set)
+ applyFileConfig(cfg, fc)
+
+ return cfg
+}
+
+// applyFileConfig merges FileConfig values into RuntimeConfig.
+// Only applies values where the corresponding env var is NOT set.
+func applyFileConfig(cfg *RuntimeConfig, fc *FileConfig) {
+ // Server
+ if fc.Server.Port != "" && !envMigrateIsSet("PINCHTAB_PORT", "BRIDGE_PORT") {
+ cfg.Port = fc.Server.Port
+ }
+ if fc.Server.Bind != "" && !envMigrateIsSet("PINCHTAB_BIND", "BRIDGE_BIND") {
+ cfg.Bind = fc.Server.Bind
+ }
+ if fc.Server.Token != "" && !envMigrateIsSet("PINCHTAB_TOKEN", "BRIDGE_TOKEN") {
+ cfg.Token = fc.Server.Token
+ }
+ if fc.Server.StateDir != "" && !envMigrateIsSet("PINCHTAB_STATE_DIR", "BRIDGE_STATE_DIR") {
+ cfg.StateDir = fc.Server.StateDir
}
- if fc.InstancePortStart != nil && os.Getenv("INSTANCE_PORT_START") == "" {
- cfg.InstancePortStart = *fc.InstancePortStart
+ if fc.Server.CdpURL != "" && os.Getenv("CDP_URL") == "" {
+ cfg.CdpURL = fc.Server.CdpURL
}
- if fc.InstancePortEnd != nil && os.Getenv("INSTANCE_PORT_END") == "" {
- cfg.InstancePortEnd = *fc.InstancePortEnd
+ if fc.Server.InstancePortStart != nil && os.Getenv("PINCHTAB_INSTANCE_PORT_START") == "" {
+ cfg.InstancePortStart = *fc.Server.InstancePortStart
}
- if fc.CdpURL != "" && os.Getenv("CDP_URL") == "" {
- cfg.CdpURL = fc.CdpURL
+ if fc.Server.InstancePortEnd != nil && os.Getenv("PINCHTAB_INSTANCE_PORT_END") == "" {
+ cfg.InstancePortEnd = *fc.Server.InstancePortEnd
}
- if fc.Token != "" && !envMigrateIsSet("PINCHTAB_TOKEN", "BRIDGE_TOKEN") {
- cfg.Token = fc.Token
+
+ // Security
+ if fc.Security.AllowEvaluate != nil && !envMigrateIsSet("PINCHTAB_ALLOW_EVALUATE", "BRIDGE_ALLOW_EVALUATE") {
+ cfg.AllowEvaluate = *fc.Security.AllowEvaluate
+ }
+ if fc.Security.AllowMacro != nil && !envMigrateIsSet("PINCHTAB_ALLOW_MACRO", "BRIDGE_ALLOW_MACRO") {
+ cfg.AllowMacro = *fc.Security.AllowMacro
+ }
+ if fc.Security.AllowScreencast != nil && !envMigrateIsSet("PINCHTAB_ALLOW_SCREENCAST", "BRIDGE_ALLOW_SCREENCAST") {
+ cfg.AllowScreencast = *fc.Security.AllowScreencast
}
- if fc.AllowEvaluate != nil && !envMigrateIsSet("PINCHTAB_ALLOW_EVALUATE", "BRIDGE_ALLOW_EVALUATE") {
- cfg.AllowEvaluate = *fc.AllowEvaluate
+ if fc.Security.AllowDownload != nil && !envMigrateIsSet("PINCHTAB_ALLOW_DOWNLOAD", "BRIDGE_ALLOW_DOWNLOAD") {
+ cfg.AllowDownload = *fc.Security.AllowDownload
+ }
+ if fc.Security.AllowUpload != nil && !envMigrateIsSet("PINCHTAB_ALLOW_UPLOAD", "BRIDGE_ALLOW_UPLOAD") {
+ cfg.AllowUpload = *fc.Security.AllowUpload
+ }
+
+ // Chrome
+ if fc.Chrome.Headless != nil && !envMigrateIsSet("PINCHTAB_HEADLESS", "BRIDGE_HEADLESS") {
+ cfg.Headless = *fc.Chrome.Headless
}
- if fc.AllowMacro != nil && !envMigrateIsSet("PINCHTAB_ALLOW_MACRO", "BRIDGE_ALLOW_MACRO") {
- cfg.AllowMacro = *fc.AllowMacro
+ if fc.Chrome.NoRestore != nil && !envMigrateIsSet("PINCHTAB_NO_RESTORE", "BRIDGE_NO_RESTORE") {
+ cfg.NoRestore = *fc.Chrome.NoRestore
}
- if fc.AllowScreencast != nil && !envMigrateIsSet("PINCHTAB_ALLOW_SCREENCAST", "BRIDGE_ALLOW_SCREENCAST") {
- cfg.AllowScreencast = *fc.AllowScreencast
+ if fc.Chrome.ProfileDir != "" && !envMigrateIsSet("PINCHTAB_PROFILE_DIR", "BRIDGE_PROFILE") {
+ cfg.ProfileDir = fc.Chrome.ProfileDir
}
- if fc.AllowDownload != nil && !envMigrateIsSet("PINCHTAB_ALLOW_DOWNLOAD", "BRIDGE_ALLOW_DOWNLOAD") {
- cfg.AllowDownload = *fc.AllowDownload
+ if fc.Chrome.ChromeVersion != "" && !envMigrateIsSet("PINCHTAB_CHROME_VERSION", "BRIDGE_CHROME_VERSION") {
+ cfg.ChromeVersion = fc.Chrome.ChromeVersion
}
- if fc.AllowUpload != nil && !envMigrateIsSet("PINCHTAB_ALLOW_UPLOAD", "BRIDGE_ALLOW_UPLOAD") {
- cfg.AllowUpload = *fc.AllowUpload
+ if fc.Chrome.Timezone != "" && !envMigrateIsSet("PINCHTAB_TIMEZONE", "BRIDGE_TIMEZONE") {
+ cfg.Timezone = fc.Chrome.Timezone
}
- if fc.StateDir != "" && !envMigrateIsSet("PINCHTAB_STATE_DIR", "BRIDGE_STATE_DIR") {
- cfg.StateDir = fc.StateDir
+ if fc.Chrome.BlockImages != nil && !envMigrateIsSet("PINCHTAB_BLOCK_IMAGES", "BRIDGE_BLOCK_IMAGES") {
+ cfg.BlockImages = *fc.Chrome.BlockImages
}
- if fc.ProfileDir != "" && !envMigrateIsSet("PINCHTAB_PROFILE_DIR", "BRIDGE_PROFILE") {
- cfg.ProfileDir = fc.ProfileDir
+ if fc.Chrome.BlockMedia != nil && !envMigrateIsSet("PINCHTAB_BLOCK_MEDIA", "BRIDGE_BLOCK_MEDIA") {
+ cfg.BlockMedia = *fc.Chrome.BlockMedia
}
- if fc.Headless != nil && !envMigrateIsSet("PINCHTAB_HEADLESS", "BRIDGE_HEADLESS") {
- cfg.Headless = *fc.Headless
+ if fc.Chrome.BlockAds != nil && !envMigrateIsSet("PINCHTAB_BLOCK_ADS", "BRIDGE_BLOCK_ADS") {
+ cfg.BlockAds = *fc.Chrome.BlockAds
}
- if fc.NoRestore && !envMigrateIsSet("PINCHTAB_NO_RESTORE", "BRIDGE_NO_RESTORE") {
- cfg.NoRestore = true
+ if fc.Chrome.MaxTabs != nil && !envMigrateIsSet("PINCHTAB_MAX_TABS", "BRIDGE_MAX_TABS") {
+ cfg.MaxTabs = *fc.Chrome.MaxTabs
}
- if fc.MaxTabs != nil && !envMigrateIsSet("PINCHTAB_MAX_TABS", "BRIDGE_MAX_TABS") {
- cfg.MaxTabs = *fc.MaxTabs
+ if fc.Chrome.MaxParallelTabs != nil && os.Getenv("PINCHTAB_MAX_PARALLEL_TABS") == "" {
+ cfg.MaxParallelTabs = *fc.Chrome.MaxParallelTabs
}
- if fc.TimeoutSec > 0 && !envMigrateIsSet("PINCHTAB_TIMEOUT", "BRIDGE_TIMEOUT") {
- cfg.ActionTimeout = time.Duration(fc.TimeoutSec) * time.Second
+ if fc.Chrome.ChromeBinary != "" && os.Getenv("CHROME_BIN") == "" && os.Getenv("CHROME_BINARY") == "" {
+ cfg.ChromeBinary = fc.Chrome.ChromeBinary
}
- if fc.NavigateSec > 0 && !envMigrateIsSet("PINCHTAB_NAV_TIMEOUT", "BRIDGE_NAV_TIMEOUT") {
- cfg.NavigateTimeout = time.Duration(fc.NavigateSec) * time.Second
+ if fc.Chrome.ChromeExtraFlags != "" && os.Getenv("CHROME_FLAGS") == "" {
+ cfg.ChromeExtraFlags = fc.Chrome.ChromeExtraFlags
+ }
+ if len(fc.Chrome.ExtensionPaths) > 0 && os.Getenv("CHROME_EXTENSION_PATHS") == "" {
+ cfg.ExtensionPaths = fc.Chrome.ExtensionPaths
+ }
+ if fc.Chrome.UserAgent != "" && !envMigrateIsSet("PINCHTAB_USER_AGENT", "BRIDGE_USER_AGENT") {
+ cfg.UserAgent = fc.Chrome.UserAgent
+ }
+ if fc.Chrome.NoAnimations != nil && !envMigrateIsSet("PINCHTAB_NO_ANIMATIONS", "BRIDGE_NO_ANIMATIONS") {
+ cfg.NoAnimations = *fc.Chrome.NoAnimations
+ }
+ if fc.Chrome.StealthLevel != "" && !envMigrateIsSet("PINCHTAB_STEALTH", "BRIDGE_STEALTH") {
+ cfg.StealthLevel = fc.Chrome.StealthLevel
+ }
+ if fc.Chrome.TabEvictionPolicy != "" && os.Getenv("PINCHTAB_TAB_EVICTION_POLICY") == "" {
+ cfg.TabEvictionPolicy = fc.Chrome.TabEvictionPolicy
}
- return cfg
+ // Orchestrator
+ if fc.Orchestrator.Strategy != "" && os.Getenv("PINCHTAB_STRATEGY") == "" {
+ cfg.Strategy = fc.Orchestrator.Strategy
+ }
+ if fc.Orchestrator.AllocationPolicy != "" && os.Getenv("PINCHTAB_ALLOCATION_POLICY") == "" {
+ cfg.AllocationPolicy = fc.Orchestrator.AllocationPolicy
+ }
+
+ // Timeouts
+ if fc.Timeouts.ActionSec > 0 && !envMigrateIsSet("PINCHTAB_TIMEOUT", "BRIDGE_TIMEOUT") {
+ cfg.ActionTimeout = time.Duration(fc.Timeouts.ActionSec) * time.Second
+ }
+ if fc.Timeouts.NavigateSec > 0 && !envMigrateIsSet("PINCHTAB_NAV_TIMEOUT", "BRIDGE_NAV_TIMEOUT") {
+ cfg.NavigateTimeout = time.Duration(fc.Timeouts.NavigateSec) * time.Second
+ }
+ if fc.Timeouts.ShutdownSec > 0 && os.Getenv("PINCHTAB_SHUTDOWN_TIMEOUT") == "" {
+ cfg.ShutdownTimeout = time.Duration(fc.Timeouts.ShutdownSec) * time.Second
+ }
+ if fc.Timeouts.WaitNavMs > 0 && os.Getenv("PINCHTAB_WAIT_NAV_DELAY") == "" {
+ cfg.WaitNavDelay = time.Duration(fc.Timeouts.WaitNavMs) * time.Millisecond
+ }
}
+// DefaultFileConfig returns a FileConfig with sensible defaults (nested format).
func DefaultFileConfig() FileConfig {
h := true
start := 9868
end := 9968
+ maxTabs := 20
return FileConfig{
- Port: "9867",
- InstancePortStart: &start,
- InstancePortEnd: &end,
- StateDir: userConfigDir(),
- ProfileDir: filepath.Join(userConfigDir(), "chrome-profile"),
- Headless: &h,
- NoRestore: false,
- TimeoutSec: 15,
- NavigateSec: 30,
+ Server: ServerConfig{
+ Port: "9867",
+ Bind: "127.0.0.1",
+ StateDir: userConfigDir(),
+ InstancePortStart: &start,
+ InstancePortEnd: &end,
+ },
+ Chrome: ChromeConfig{
+ Headless: &h,
+ ProfileDir: filepath.Join(userConfigDir(), "chrome-profile"),
+ MaxTabs: &maxTabs,
+ StealthLevel: "light",
+ TabEvictionPolicy: "reject",
+ },
+ Orchestrator: OrchestratorConfig{
+ Strategy: "simple",
+ AllocationPolicy: "fcfs",
+ },
+ Timeouts: TimeoutsConfig{
+ ActionSec: 30,
+ NavigateSec: 60,
+ ShutdownSec: 10,
+ WaitNavMs: 1000,
+ },
}
}
+// HandleConfigCommand handles `pinchtab config <subcommand>`.
func HandleConfigCommand(cfg *RuntimeConfig) {
if len(os.Args) < 3 {
- fmt.Println("Usage: pinchtab config <command>")
- fmt.Println("Commands:")
- fmt.Println(" init - Create default config file")
- fmt.Println(" show - Show current configuration")
+ printConfigUsage()
return
}
switch os.Args[2] {
case "init":
- configPath := filepath.Join(homeDir(), ".pinchtab", "config.json")
-
- if _, err := os.Stat(configPath); err == nil {
- fmt.Printf("Config file already exists at %s\n", configPath)
- fmt.Print("Overwrite? (y/N): ")
- var response string
- _, _ = fmt.Scanln(&response)
- if response != "y" && response != "Y" {
- return
- }
+ handleConfigInit()
+ case "show":
+ handleConfigShow(cfg)
+ case "path":
+ handleConfigPath()
+ case "validate":
+ handleConfigValidate()
+ case "set":
+ handleConfigSet()
+ case "patch":
+ handleConfigPatch()
+ default:
+ fmt.Printf("Unknown command: %s\n", os.Args[2])
+ printConfigUsage()
+ os.Exit(1)
+ }
+}
+
+func printConfigUsage() {
+ fmt.Println("Usage: pinchtab config <command>")
+ fmt.Println()
+ fmt.Println("Commands:")
+ fmt.Println(" init Create default config file")
+ fmt.Println(" show Show current configuration")
+ fmt.Println(" path Show config file path")
+ fmt.Println(" validate Validate config file")
+ fmt.Println(" set <path> <val> Set a config value (e.g., server.port 8080)")
+ fmt.Println(" patch <json> Merge JSON into config")
+}
+
+func handleConfigInit() {
+ configPath := filepath.Join(userConfigDir(), "config.json")
+
+ if _, err := os.Stat(configPath); err == nil {
+ fmt.Printf("Config file already exists at %s\n", configPath)
+ fmt.Print("Overwrite? (y/N): ")
+ var response string
+ _, _ = fmt.Scanln(&response)
+ if response != "y" && response != "Y" {
+ return
}
+ }
- if err := os.MkdirAll(filepath.Dir(configPath), 0755); err != nil {
- fmt.Printf("Error creating directory: %v\n", err)
- os.Exit(1)
+ if err := os.MkdirAll(filepath.Dir(configPath), 0755); err != nil {
+ fmt.Printf("Error creating directory: %v\n", err)
+ os.Exit(1)
+ }
+
+ fc := DefaultFileConfig()
+ data, _ := json.MarshalIndent(fc, "", " ")
+ if err := os.WriteFile(configPath, data, 0644); err != nil {
+ fmt.Printf("Error writing config: %v\n", err)
+ os.Exit(1)
+ }
+
+ fmt.Printf("Config file created at %s\n", configPath)
+ fmt.Println()
+ fmt.Println("Example with auth token:")
+ fmt.Println(`{
+ "server": {
+ "port": "9867",
+ "token": "your-secret-token"
+ },
+ "chrome": {
+ "headless": true,
+ "maxTabs": 20
+ }
+}`)
+}
+
+func handleConfigShow(cfg *RuntimeConfig) {
+ fmt.Println("Current configuration (env > file > defaults):")
+ fmt.Println()
+ fmt.Println("Server:")
+ fmt.Printf(" Port: %s\n", cfg.Port)
+ fmt.Printf(" Bind: %s\n", cfg.Bind)
+ fmt.Printf(" Token: %s\n", MaskToken(cfg.Token))
+ fmt.Printf(" State Dir: %s\n", cfg.StateDir)
+ fmt.Printf(" CDP URL: %s\n", valueOrNone(cfg.CdpURL))
+ fmt.Printf(" Instance Ports: %d-%d\n", cfg.InstancePortStart, cfg.InstancePortEnd)
+ fmt.Println()
+ fmt.Println("Security:")
+ fmt.Printf(" Evaluate: %v\n", cfg.AllowEvaluate)
+ fmt.Printf(" Macro: %v\n", cfg.AllowMacro)
+ fmt.Printf(" Screencast: %v\n", cfg.AllowScreencast)
+ fmt.Printf(" Download: %v\n", cfg.AllowDownload)
+ fmt.Printf(" Upload: %v\n", cfg.AllowUpload)
+ fmt.Println()
+ fmt.Println("Chrome:")
+ fmt.Printf(" Headless: %v\n", cfg.Headless)
+ fmt.Printf(" No Restore: %v\n", cfg.NoRestore)
+ fmt.Printf(" Profile Dir: %s\n", cfg.ProfileDir)
+ fmt.Printf(" Max Tabs: %d\n", cfg.MaxTabs)
+ fmt.Printf(" Stealth: %s\n", cfg.StealthLevel)
+ fmt.Printf(" Tab Eviction: %s\n", cfg.TabEvictionPolicy)
+ fmt.Printf(" Extensions: %v\n", cfg.ExtensionPaths)
+ fmt.Println()
+ fmt.Println("Orchestrator:")
+ fmt.Printf(" Strategy: %s\n", cfg.Strategy)
+ fmt.Printf(" Allocation: %s\n", cfg.AllocationPolicy)
+ fmt.Println()
+ fmt.Println("Timeouts:")
+ fmt.Printf(" Action: %v\n", cfg.ActionTimeout)
+ fmt.Printf(" Navigate: %v\n", cfg.NavigateTimeout)
+ fmt.Printf(" Shutdown: %v\n", cfg.ShutdownTimeout)
+}
+
+func handleConfigPath() {
+ configPath := envOrMigrate("PINCHTAB_CONFIG", "BRIDGE_CONFIG", filepath.Join(userConfigDir(), "config.json"))
+ fmt.Println(configPath)
+}
+
+func handleConfigSet() {
+ if len(os.Args) < 5 {
+ fmt.Println("Usage: pinchtab config set <path> <value>")
+ fmt.Println()
+ fmt.Println("Examples:")
+ fmt.Println(" pinchtab config set server.port 8080")
+ fmt.Println(" pinchtab config set chrome.headless false")
+ fmt.Println(" pinchtab config set orchestrator.strategy explicit")
+ fmt.Println()
+ fmt.Println("Sections: server, chrome, security, orchestrator, timeouts")
+ os.Exit(1)
+ }
+
+ path := os.Args[3]
+ value := os.Args[4]
+
+ fc, configPath, err := LoadFileConfig()
+ if err != nil {
+ fmt.Printf("Error loading config: %v\n", err)
+ os.Exit(1)
+ }
+
+ if err := SetConfigValue(fc, path, value); err != nil {
+ fmt.Printf("Error: %v\n", err)
+ os.Exit(1)
+ }
+
+ // Validate before saving
+ if errs := ValidateFileConfig(fc); len(errs) > 0 {
+ fmt.Printf("Warning: new value causes validation error(s):\n")
+ for _, e := range errs {
+ fmt.Printf(" - %v\n", e)
}
+ fmt.Print("Save anyway? (y/N): ")
+ var response string
+ _, _ = fmt.Scanln(&response)
+ if response != "y" && response != "Y" {
+ fmt.Println("Aborted.")
+ return
+ }
+ }
- fc := DefaultFileConfig()
- data, _ := json.MarshalIndent(fc, "", " ")
- if err := os.WriteFile(configPath, data, 0644); err != nil {
- fmt.Printf("Error writing config: %v\n", err)
- os.Exit(1)
+ if err := SaveFileConfig(fc, configPath); err != nil {
+ fmt.Printf("Error saving config: %v\n", err)
+ os.Exit(1)
+ }
+
+ fmt.Printf("✓ Set %s = %s\n", path, value)
+}
+
+func handleConfigPatch() {
+ if len(os.Args) < 4 {
+ fmt.Println("Usage: pinchtab config patch '<json>'")
+ fmt.Println()
+ fmt.Println("Examples:")
+ fmt.Println(` pinchtab config patch '{"server": {"port": "8080"}}'`)
+ fmt.Println(` pinchtab config patch '{"chrome": {"headless": false, "maxTabs": 50}}'`)
+ os.Exit(1)
+ }
+
+ jsonPatch := os.Args[3]
+
+ fc, configPath, err := LoadFileConfig()
+ if err != nil {
+ fmt.Printf("Error loading config: %v\n", err)
+ os.Exit(1)
+ }
+
+ if err := PatchConfigJSON(fc, jsonPatch); err != nil {
+ fmt.Printf("Error: %v\n", err)
+ os.Exit(1)
+ }
+
+ // Validate before saving
+ if errs := ValidateFileConfig(fc); len(errs) > 0 {
+ fmt.Printf("Warning: patch causes validation error(s):\n")
+ for _, e := range errs {
+ fmt.Printf(" - %v\n", e)
}
+ fmt.Print("Save anyway? (y/N): ")
+ var response string
+ _, _ = fmt.Scanln(&response)
+ if response != "y" && response != "Y" {
+ fmt.Println("Aborted.")
+ return
+ }
+ }
- fmt.Printf("Config file created at %s\n", configPath)
- fmt.Println("\nExample with auth token:")
- fmt.Println(`{
- "port": "9867",
- "token": "your-secret-token",
- "headless": true,
- "stateDir": "` + fc.StateDir + `",
- "profileDir": "` + fc.ProfileDir + `"
-}`)
+ if err := SaveFileConfig(fc, configPath); err != nil {
+ fmt.Printf("Error saving config: %v\n", err)
+ os.Exit(1)
+ }
- case "show":
- fmt.Println("Current configuration:")
- fmt.Printf(" Port: %s\n", cfg.Port)
- fmt.Printf(" CDP URL: %s\n", cfg.CdpURL)
- fmt.Printf(" Token: %s\n", MaskToken(cfg.Token))
- fmt.Printf(" Eval JS: %v\n", cfg.AllowEvaluate)
- fmt.Printf(" Macro: %v\n", cfg.AllowMacro)
- fmt.Printf(" Screencast: %v\n", cfg.AllowScreencast)
- fmt.Printf(" Download: %v\n", cfg.AllowDownload)
- fmt.Printf(" Upload: %v\n", cfg.AllowUpload)
- fmt.Printf(" State Dir: %s\n", cfg.StateDir)
- fmt.Printf(" Profile: %s\n", cfg.ProfileDir)
- fmt.Printf(" Headless: %v\n", cfg.Headless)
- fmt.Printf(" Max Tabs: %d\n", cfg.MaxTabs)
- fmt.Printf(" No Restore: %v\n", cfg.NoRestore)
- fmt.Printf(" Extensions: %v\n", cfg.ExtensionPaths)
- fmt.Printf(" Timeouts: action=%v navigate=%v\n", cfg.ActionTimeout, cfg.NavigateTimeout)
+ fmt.Println("✓ Config patched successfully")
+}
- default:
- fmt.Printf("Unknown command: %s\n", os.Args[2])
+func handleConfigValidate() {
+ configPath := envOrMigrate("PINCHTAB_CONFIG", "BRIDGE_CONFIG", filepath.Join(userConfigDir(), "config.json"))
+
+ data, err := os.ReadFile(configPath)
+ if err != nil {
+ fmt.Printf("Error reading config file: %v\n", err)
os.Exit(1)
}
+
+ var fc *FileConfig
+
+ if isLegacyConfig(data) {
+ var lc legacyFileConfig
+ if err := json.Unmarshal(data, &lc); err != nil {
+ fmt.Printf("Error parsing config file: %v\n", err)
+ os.Exit(1)
+ }
+ fc = convertLegacyConfig(&lc)
+ fmt.Println("Note: Config file uses legacy flat format. Consider migrating to nested format.")
+ fmt.Println()
+ } else {
+ fc = &FileConfig{}
+ if err := json.Unmarshal(data, fc); err != nil {
+ fmt.Printf("Error parsing config file: %v\n", err)
+ os.Exit(1)
+ }
+ }
+
+ errs := ValidateFileConfig(fc)
+ if len(errs) == 0 {
+ fmt.Printf("✓ Config file is valid: %s\n", configPath)
+ return
+ }
+
+ fmt.Printf("✗ Config file has %d error(s):\n", len(errs))
+ for _, e := range errs {
+ fmt.Printf(" - %v\n", e)
+ }
+ os.Exit(1)
+}
+
+func valueOrNone(s string) string {
+ if s == "" {
+ return "(none)"
+ }
+ return s
}
+// MaskToken masks a token for display (shows first/last 4 chars).
func MaskToken(t string) string {
if t == "" {
return "(none)"
diff --git a/internal/config/config_test.go b/internal/config/config_test.go
index e400fb2e..d9b68aa0 100644
--- a/internal/config/config_test.go
+++ b/internal/config/config_test.go
@@ -1,6 +1,7 @@
package config
import (
+ "encoding/json"
"os"
"path/filepath"
"testing"
@@ -88,15 +89,10 @@ func TestMaskToken(t *testing.T) {
}
func TestLoadConfigDefaults(t *testing.T) {
- _ = os.Unsetenv("PINCHTAB_PORT")
- _ = os.Unsetenv("PINCHTAB_BIND")
- _ = os.Unsetenv("BRIDGE_PORT")
- _ = os.Unsetenv("BRIDGE_BIND")
- _ = os.Unsetenv("CDP_URL")
- _ = os.Unsetenv("PINCHTAB_TOKEN")
- _ = os.Unsetenv("BRIDGE_TOKEN")
- _ = os.Unsetenv("PINCHTAB_ALLOW_EVALUATE")
- _ = os.Unsetenv("BRIDGE_ALLOW_EVALUATE")
+ clearConfigEnvVars(t)
+ // Point to non-existent config to test pure defaults
+ _ = os.Setenv("PINCHTAB_CONFIG", filepath.Join(t.TempDir(), "nonexistent.json"))
+ defer func() { _ = os.Unsetenv("PINCHTAB_CONFIG") }()
cfg := Load()
if cfg.Port != "9867" {
@@ -108,14 +104,29 @@ func TestLoadConfigDefaults(t *testing.T) {
if cfg.AllowEvaluate {
t.Errorf("default AllowEvaluate = %v, want false", cfg.AllowEvaluate)
}
+ if cfg.Strategy != "simple" {
+ t.Errorf("default Strategy = %v, want simple", cfg.Strategy)
+ }
+ if cfg.AllocationPolicy != "fcfs" {
+ t.Errorf("default AllocationPolicy = %v, want fcfs", cfg.AllocationPolicy)
+ }
+ if cfg.TabEvictionPolicy != "reject" {
+ t.Errorf("default TabEvictionPolicy = %v, want reject", cfg.TabEvictionPolicy)
+ }
}
func TestLoadConfigEnvOverrides(t *testing.T) {
+ clearConfigEnvVars(t)
+ // Point to non-existent config to isolate env var testing
+ _ = os.Setenv("PINCHTAB_CONFIG", filepath.Join(t.TempDir(), "nonexistent.json"))
_ = os.Setenv("PINCHTAB_PORT", "1234")
_ = os.Setenv("PINCHTAB_ALLOW_EVALUATE", "1")
+ _ = os.Setenv("PINCHTAB_STRATEGY", "explicit")
defer func() {
+ _ = os.Unsetenv("PINCHTAB_CONFIG")
_ = os.Unsetenv("PINCHTAB_PORT")
_ = os.Unsetenv("PINCHTAB_ALLOW_EVALUATE")
+ _ = os.Unsetenv("PINCHTAB_STRATEGY")
}()
cfg := Load()
@@ -125,14 +136,19 @@ func TestLoadConfigEnvOverrides(t *testing.T) {
if !cfg.AllowEvaluate {
t.Errorf("env AllowEvaluate = %v, want true", cfg.AllowEvaluate)
}
+ if cfg.Strategy != "explicit" {
+ t.Errorf("env Strategy = %v, want explicit", cfg.Strategy)
+ }
}
func TestLegacyBridgeEnvFallback(t *testing.T) {
- _ = os.Unsetenv("PINCHTAB_PORT")
- _ = os.Unsetenv("PINCHTAB_ALLOW_EVALUATE")
+ clearConfigEnvVars(t)
+ // Point to non-existent config to isolate env var testing
+ _ = os.Setenv("PINCHTAB_CONFIG", filepath.Join(t.TempDir(), "nonexistent.json"))
_ = os.Setenv("BRIDGE_PORT", "5555")
_ = os.Setenv("BRIDGE_ALLOW_EVALUATE", "true")
defer func() {
+ _ = os.Unsetenv("PINCHTAB_CONFIG")
_ = os.Unsetenv("BRIDGE_PORT")
_ = os.Unsetenv("BRIDGE_ALLOW_EVALUATE")
}()
@@ -147,9 +163,13 @@ func TestLegacyBridgeEnvFallback(t *testing.T) {
}
func TestPinchtabEnvTakesPrecedence(t *testing.T) {
+ clearConfigEnvVars(t)
+ // Point to non-existent config to isolate env var testing
+ _ = os.Setenv("PINCHTAB_CONFIG", filepath.Join(t.TempDir(), "nonexistent.json"))
_ = os.Setenv("PINCHTAB_PORT", "7777")
_ = os.Setenv("BRIDGE_PORT", "8888")
defer func() {
+ _ = os.Unsetenv("PINCHTAB_CONFIG")
_ = os.Unsetenv("PINCHTAB_PORT")
_ = os.Unsetenv("BRIDGE_PORT")
}()
@@ -162,43 +182,187 @@ func TestPinchtabEnvTakesPrecedence(t *testing.T) {
func TestDefaultFileConfig(t *testing.T) {
fc := DefaultFileConfig()
- if fc.Port != "9867" {
- t.Errorf("DefaultFileConfig.Port = %v, want 9867", fc.Port)
+ if fc.Server.Port != "9867" {
+ t.Errorf("DefaultFileConfig.Server.Port = %v, want 9867", fc.Server.Port)
+ }
+ if fc.Server.Bind != "127.0.0.1" {
+ t.Errorf("DefaultFileConfig.Server.Bind = %v, want 127.0.0.1", fc.Server.Bind)
+ }
+ if *fc.Chrome.Headless != true {
+ t.Errorf("DefaultFileConfig.Chrome.Headless = %v, want true", *fc.Chrome.Headless)
}
- if *fc.Headless != true {
- t.Errorf("DefaultFileConfig.Headless = %v, want true", *fc.Headless)
+ if fc.Orchestrator.Strategy != "simple" {
+ t.Errorf("DefaultFileConfig.Orchestrator.Strategy = %v, want simple", fc.Orchestrator.Strategy)
}
}
-func TestLoadConfigFile(t *testing.T) {
+// TestLoadNestedConfig tests loading the new nested config format.
+func TestLoadNestedConfig(t *testing.T) {
+ clearConfigEnvVars(t)
+
tmpDir := t.TempDir()
configPath := filepath.Join(tmpDir, "config.json")
_ = os.Setenv("PINCHTAB_CONFIG", configPath)
defer func() { _ = os.Unsetenv("PINCHTAB_CONFIG") }()
- // Create a dummy config file
- configData := `{
- "port": "8888",
- "allowEvaluate": true,
- "headless": false,
- "timeoutSec": 60
+ // Create nested config file
+ nestedConfig := `{
+ "server": {
+ "port": "8888",
+ "bind": "0.0.0.0",
+ "token": "secret123"
+ },
+ "chrome": {
+ "headless": false,
+ "maxTabs": 50,
+ "stealthLevel": "full",
+ "tabEvictionPolicy": "close_oldest"
+ },
+ "security": {
+ "allowEvaluate": true
+ },
+ "orchestrator": {
+ "strategy": "explicit",
+ "allocationPolicy": "round_robin"
+ },
+ "timeouts": {
+ "actionSec": 60,
+ "navigateSec": 120
+ }
}`
- if err := os.WriteFile(configPath, []byte(configData), 0644); err != nil {
+ if err := os.WriteFile(configPath, []byte(nestedConfig), 0644); err != nil {
t.Fatal(err)
}
cfg := Load()
+
+ // Server
if cfg.Port != "8888" {
- t.Errorf("file Port = %v, want 8888", cfg.Port)
+ t.Errorf("nested Port = %v, want 8888", cfg.Port)
}
- if cfg.AllowEvaluate != true {
- t.Errorf("file AllowEvaluate = %v, want true", cfg.AllowEvaluate)
+ if cfg.Bind != "0.0.0.0" {
+ t.Errorf("nested Bind = %v, want 0.0.0.0", cfg.Bind)
+ }
+ if cfg.Token != "secret123" {
+ t.Errorf("nested Token = %v, want secret123", cfg.Token)
}
+
+ // Chrome
if cfg.Headless != false {
- t.Errorf("file Headless = %v, want false", cfg.Headless)
+ t.Errorf("nested Headless = %v, want false", cfg.Headless)
+ }
+ if cfg.MaxTabs != 50 {
+ t.Errorf("nested MaxTabs = %v, want 50", cfg.MaxTabs)
+ }
+ if cfg.StealthLevel != "full" {
+ t.Errorf("nested StealthLevel = %v, want full", cfg.StealthLevel)
+ }
+ if cfg.TabEvictionPolicy != "close_oldest" {
+ t.Errorf("nested TabEvictionPolicy = %v, want close_oldest", cfg.TabEvictionPolicy)
+ }
+
+ // Security
+ if cfg.AllowEvaluate != true {
+ t.Errorf("nested AllowEvaluate = %v, want true", cfg.AllowEvaluate)
}
+
+ // Orchestrator
+ if cfg.Strategy != "explicit" {
+ t.Errorf("nested Strategy = %v, want explicit", cfg.Strategy)
+ }
+ if cfg.AllocationPolicy != "round_robin" {
+ t.Errorf("nested AllocationPolicy = %v, want round_robin", cfg.AllocationPolicy)
+ }
+
+ // Timeouts
if cfg.ActionTimeout != 60*time.Second {
- t.Errorf("file ActionTimeout = %v, want 60s", cfg.ActionTimeout)
+ t.Errorf("nested ActionTimeout = %v, want 60s", cfg.ActionTimeout)
+ }
+ if cfg.NavigateTimeout != 120*time.Second {
+ t.Errorf("nested NavigateTimeout = %v, want 120s", cfg.NavigateTimeout)
+ }
+}
+
+// TestLoadLegacyFlatConfig tests backward compatibility with flat config files.
+func TestLoadLegacyFlatConfig(t *testing.T) {
+ clearConfigEnvVars(t)
+
+ tmpDir := t.TempDir()
+ configPath := filepath.Join(tmpDir, "config.json")
+ _ = os.Setenv("PINCHTAB_CONFIG", configPath)
+ defer func() { _ = os.Unsetenv("PINCHTAB_CONFIG") }()
+
+ // Create legacy flat config file (old format)
+ legacyConfig := `{
+ "port": "7777",
+ "headless": false,
+ "maxTabs": 30,
+ "allowEvaluate": true,
+ "timeoutSec": 45,
+ "navigateSec": 90
+ }`
+ if err := os.WriteFile(configPath, []byte(legacyConfig), 0644); err != nil {
+ t.Fatal(err)
+ }
+
+ cfg := Load()
+
+ if cfg.Port != "7777" {
+ t.Errorf("legacy flat Port = %v, want 7777", cfg.Port)
+ }
+ if cfg.Headless != false {
+ t.Errorf("legacy flat Headless = %v, want false", cfg.Headless)
+ }
+ if cfg.MaxTabs != 30 {
+ t.Errorf("legacy flat MaxTabs = %v, want 30", cfg.MaxTabs)
+ }
+ if cfg.AllowEvaluate != true {
+ t.Errorf("legacy flat AllowEvaluate = %v, want true", cfg.AllowEvaluate)
+ }
+ if cfg.ActionTimeout != 45*time.Second {
+ t.Errorf("legacy flat ActionTimeout = %v, want 45s", cfg.ActionTimeout)
+ }
+ if cfg.NavigateTimeout != 90*time.Second {
+ t.Errorf("legacy flat NavigateTimeout = %v, want 90s", cfg.NavigateTimeout)
+ }
+}
+
+// TestEnvOverridesNestedConfig verifies env vars take precedence over nested config.
+func TestEnvOverridesNestedConfig(t *testing.T) {
+ clearConfigEnvVars(t)
+
+ tmpDir := t.TempDir()
+ configPath := filepath.Join(tmpDir, "config.json")
+ _ = os.Setenv("PINCHTAB_CONFIG", configPath)
+ _ = os.Setenv("PINCHTAB_PORT", "9999")
+ _ = os.Setenv("PINCHTAB_STRATEGY", "simple-autorestart")
+ defer func() {
+ _ = os.Unsetenv("PINCHTAB_CONFIG")
+ _ = os.Unsetenv("PINCHTAB_PORT")
+ _ = os.Unsetenv("PINCHTAB_STRATEGY")
+ }()
+
+ // Config file says port 8888 and strategy explicit
+ nestedConfig := `{
+ "server": {
+ "port": "8888"
+ },
+ "orchestrator": {
+ "strategy": "explicit"
+ }
+ }`
+ if err := os.WriteFile(configPath, []byte(nestedConfig), 0644); err != nil {
+ t.Fatal(err)
+ }
+
+ cfg := Load()
+
+ // Env var should win
+ if cfg.Port != "9999" {
+ t.Errorf("env should override file: Port = %v, want 9999", cfg.Port)
+ }
+ if cfg.Strategy != "simple-autorestart" {
+ t.Errorf("env should override file: Strategy = %v, want simple-autorestart", cfg.Strategy)
}
}
@@ -213,3 +377,138 @@ func TestListenAddr(t *testing.T) {
t.Errorf("expected 0.0.0.0:8080, got %s", got)
}
}
+
+// TestIsLegacyConfig tests the format detection logic.
+func TestIsLegacyConfig(t *testing.T) {
+ tests := []struct {
+ name string
+ json string
+ isLegacy bool
+ }{
+ {
+ name: "nested format with server",
+ json: `{"server": {"port": "9867"}}`,
+ isLegacy: false,
+ },
+ {
+ name: "nested format with chrome",
+ json: `{"chrome": {"headless": true}}`,
+ isLegacy: false,
+ },
+ {
+ name: "legacy format with port",
+ json: `{"port": "9867"}`,
+ isLegacy: true,
+ },
+ {
+ name: "legacy format with headless",
+ json: `{"headless": true}`,
+ isLegacy: true,
+ },
+ {
+ name: "empty object",
+ json: `{}`,
+ isLegacy: false,
+ },
+ {
+ name: "mixed - nested wins",
+ json: `{"server": {"port": "8888"}, "port": "7777"}`,
+ isLegacy: false,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got := isLegacyConfig([]byte(tt.json))
+ if got != tt.isLegacy {
+ t.Errorf("isLegacyConfig(%s) = %v, want %v", tt.json, got, tt.isLegacy)
+ }
+ })
+ }
+}
+
+// TestConvertLegacyConfig tests the legacy to nested conversion.
+func TestConvertLegacyConfig(t *testing.T) {
+ h := false
+ maxTabs := 25
+ lc := &legacyFileConfig{
+ Port: "7777",
+ Headless: &h,
+ MaxTabs: &maxTabs,
+ AllowEvaluate: boolPtr(true),
+ TimeoutSec: 45,
+ NavigateSec: 90,
+ }
+
+ fc := convertLegacyConfig(lc)
+
+ if fc.Server.Port != "7777" {
+ t.Errorf("converted Server.Port = %v, want 7777", fc.Server.Port)
+ }
+ if *fc.Chrome.Headless != false {
+ t.Errorf("converted Chrome.Headless = %v, want false", *fc.Chrome.Headless)
+ }
+ if *fc.Chrome.MaxTabs != 25 {
+ t.Errorf("converted Chrome.MaxTabs = %v, want 25", *fc.Chrome.MaxTabs)
+ }
+ if *fc.Security.AllowEvaluate != true {
+ t.Errorf("converted Security.AllowEvaluate = %v, want true", *fc.Security.AllowEvaluate)
+ }
+ if fc.Timeouts.ActionSec != 45 {
+ t.Errorf("converted Timeouts.ActionSec = %v, want 45", fc.Timeouts.ActionSec)
+ }
+ if fc.Timeouts.NavigateSec != 90 {
+ t.Errorf("converted Timeouts.NavigateSec = %v, want 90", fc.Timeouts.NavigateSec)
+ }
+}
+
+// TestDefaultFileConfigJSON tests that DefaultFileConfig serializes correctly.
+func TestDefaultFileConfigJSON(t *testing.T) {
+ fc := DefaultFileConfig()
+ data, err := json.MarshalIndent(fc, "", " ")
+ if err != nil {
+ t.Fatalf("failed to marshal DefaultFileConfig: %v", err)
+ }
+
+ // Verify it can be parsed back
+ var parsed FileConfig
+ if err := json.Unmarshal(data, &parsed); err != nil {
+ t.Fatalf("failed to unmarshal DefaultFileConfig output: %v", err)
+ }
+
+ if parsed.Server.Port != "9867" {
+ t.Errorf("round-trip Server.Port = %v, want 9867", parsed.Server.Port)
+ }
+ if *parsed.Chrome.Headless != true {
+ t.Errorf("round-trip Chrome.Headless = %v, want true", *parsed.Chrome.Headless)
+ }
+}
+
+// Helper functions
+
+func boolPtr(b bool) *bool {
+ return &b
+}
+
+// clearConfigEnvVars unsets all config-related env vars for clean tests.
+func clearConfigEnvVars(t *testing.T) {
+ t.Helper()
+ envVars := []string{
+ "PINCHTAB_PORT", "PINCHTAB_BIND", "PINCHTAB_TOKEN", "PINCHTAB_CONFIG",
+ "PINCHTAB_STATE_DIR", "PINCHTAB_PROFILE_DIR", "PINCHTAB_HEADLESS",
+ "PINCHTAB_MAX_TABS", "PINCHTAB_ALLOW_EVALUATE", "PINCHTAB_ALLOW_MACRO",
+ "PINCHTAB_ALLOW_SCREENCAST", "PINCHTAB_ALLOW_DOWNLOAD", "PINCHTAB_ALLOW_UPLOAD",
+ "PINCHTAB_STRATEGY", "PINCHTAB_ALLOCATION_POLICY", "PINCHTAB_TAB_EVICTION_POLICY",
+ "PINCHTAB_STEALTH", "PINCHTAB_NO_RESTORE", "PINCHTAB_NO_ANIMATIONS",
+ "PINCHTAB_TIMEOUT", "PINCHTAB_NAV_TIMEOUT",
+ "BRIDGE_PORT", "BRIDGE_BIND", "BRIDGE_TOKEN", "BRIDGE_CONFIG",
+ "BRIDGE_STATE_DIR", "BRIDGE_PROFILE", "BRIDGE_HEADLESS",
+ "BRIDGE_MAX_TABS", "BRIDGE_ALLOW_EVALUATE",
+ "BRIDGE_STEALTH", "BRIDGE_NO_RESTORE", "BRIDGE_NO_ANIMATIONS",
+ "BRIDGE_TIMEOUT", "BRIDGE_NAV_TIMEOUT",
+ "CDP_URL", "CHROME_BIN", "CHROME_BINARY", "CHROME_FLAGS",
+ }
+ for _, v := range envVars {
+ _ = os.Unsetenv(v)
+ }
+}
diff --git a/internal/config/editor.go b/internal/config/editor.go
new file mode 100644
index 00000000..91c01b76
--- /dev/null
+++ b/internal/config/editor.go
@@ -0,0 +1,320 @@
+package config
+
+import (
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+)
+
+// SetConfigValue sets a dotted path in FileConfig (e.g., "server.port", "chrome.headless").
+// Returns the updated FileConfig and any error.
+func SetConfigValue(fc *FileConfig, path string, value string) error {
+ parts := strings.SplitN(path, ".", 2)
+ if len(parts) != 2 {
+ return fmt.Errorf("invalid path %q (expected section.field, e.g., server.port)", path)
+ }
+
+ section, field := parts[0], parts[1]
+
+ switch section {
+ case "server":
+ return setServerField(&fc.Server, field, value)
+ case "chrome":
+ return setChromeField(&fc.Chrome, field, value)
+ case "security":
+ return setSecurityField(&fc.Security, field, value)
+ case "orchestrator":
+ return setOrchestratorField(&fc.Orchestrator, field, value)
+ case "timeouts":
+ return setTimeoutsField(&fc.Timeouts, field, value)
+ default:
+ return fmt.Errorf("unknown section %q (valid: server, chrome, security, orchestrator, timeouts)", section)
+ }
+}
+
+func setServerField(s *ServerConfig, field, value string) error {
+ switch field {
+ case "port":
+ s.Port = value
+ case "bind":
+ s.Bind = value
+ case "token":
+ s.Token = value
+ case "stateDir":
+ s.StateDir = value
+ case "cdpUrl":
+ s.CdpURL = value
+ case "instancePortStart":
+ n, err := strconv.Atoi(value)
+ if err != nil {
+ return fmt.Errorf("server.instancePortStart must be a number: %w", err)
+ }
+ s.InstancePortStart = &n
+ case "instancePortEnd":
+ n, err := strconv.Atoi(value)
+ if err != nil {
+ return fmt.Errorf("server.instancePortEnd must be a number: %w", err)
+ }
+ s.InstancePortEnd = &n
+ default:
+ return fmt.Errorf("unknown field server.%s", field)
+ }
+ return nil
+}
+
+func setChromeField(c *ChromeConfig, field, value string) error {
+ switch field {
+ case "headless":
+ b, err := parseBool(value)
+ if err != nil {
+ return fmt.Errorf("chrome.headless: %w", err)
+ }
+ c.Headless = &b
+ case "noRestore":
+ b, err := parseBool(value)
+ if err != nil {
+ return fmt.Errorf("chrome.noRestore: %w", err)
+ }
+ c.NoRestore = &b
+ case "profileDir":
+ c.ProfileDir = value
+ case "chromeVersion":
+ c.ChromeVersion = value
+ case "timezone":
+ c.Timezone = value
+ case "blockImages":
+ b, err := parseBool(value)
+ if err != nil {
+ return fmt.Errorf("chrome.blockImages: %w", err)
+ }
+ c.BlockImages = &b
+ case "blockMedia":
+ b, err := parseBool(value)
+ if err != nil {
+ return fmt.Errorf("chrome.blockMedia: %w", err)
+ }
+ c.BlockMedia = &b
+ case "blockAds":
+ b, err := parseBool(value)
+ if err != nil {
+ return fmt.Errorf("chrome.blockAds: %w", err)
+ }
+ c.BlockAds = &b
+ case "maxTabs":
+ n, err := strconv.Atoi(value)
+ if err != nil {
+ return fmt.Errorf("chrome.maxTabs must be a number: %w", err)
+ }
+ c.MaxTabs = &n
+ case "maxParallelTabs":
+ n, err := strconv.Atoi(value)
+ if err != nil {
+ return fmt.Errorf("chrome.maxParallelTabs must be a number: %w", err)
+ }
+ c.MaxParallelTabs = &n
+ case "chromeBinary":
+ c.ChromeBinary = value
+ case "chromeExtraFlags":
+ c.ChromeExtraFlags = value
+ case "userAgent":
+ c.UserAgent = value
+ case "noAnimations":
+ b, err := parseBool(value)
+ if err != nil {
+ return fmt.Errorf("chrome.noAnimations: %w", err)
+ }
+ c.NoAnimations = &b
+ case "stealthLevel":
+ c.StealthLevel = value
+ case "tabEvictionPolicy":
+ c.TabEvictionPolicy = value
+ default:
+ return fmt.Errorf("unknown field chrome.%s", field)
+ }
+ return nil
+}
+
+func setSecurityField(s *SecurityConfig, field, value string) error {
+ b, err := parseBool(value)
+ if err != nil {
+ return fmt.Errorf("security.%s: %w", field, err)
+ }
+
+ switch field {
+ case "allowEvaluate":
+ s.AllowEvaluate = &b
+ case "allowMacro":
+ s.AllowMacro = &b
+ case "allowScreencast":
+ s.AllowScreencast = &b
+ case "allowDownload":
+ s.AllowDownload = &b
+ case "allowUpload":
+ s.AllowUpload = &b
+ default:
+ return fmt.Errorf("unknown field security.%s", field)
+ }
+ return nil
+}
+
+func setOrchestratorField(o *OrchestratorConfig, field, value string) error {
+ switch field {
+ case "strategy":
+ o.Strategy = value
+ case "allocationPolicy":
+ o.AllocationPolicy = value
+ default:
+ return fmt.Errorf("unknown field orchestrator.%s", field)
+ }
+ return nil
+}
+
+func setTimeoutsField(t *TimeoutsConfig, field, value string) error {
+ n, err := strconv.Atoi(value)
+ if err != nil {
+ return fmt.Errorf("timeouts.%s must be a number: %w", field, err)
+ }
+
+ switch field {
+ case "actionSec":
+ t.ActionSec = n
+ case "navigateSec":
+ t.NavigateSec = n
+ case "shutdownSec":
+ t.ShutdownSec = n
+ case "waitNavMs":
+ t.WaitNavMs = n
+ default:
+ return fmt.Errorf("unknown field timeouts.%s", field)
+ }
+ return nil
+}
+
+func parseBool(s string) (bool, error) {
+ switch strings.ToLower(strings.TrimSpace(s)) {
+ case "true", "1", "yes", "on":
+ return true, nil
+ case "false", "0", "no", "off":
+ return false, nil
+ default:
+ return false, fmt.Errorf("invalid boolean %q (use true/false)", s)
+ }
+}
+
+// PatchConfigJSON merges a JSON object into FileConfig.
+// The patch should be a valid JSON object with the same structure as FileConfig.
+func PatchConfigJSON(fc *FileConfig, jsonPatch string) error {
+ // First, serialize current config to JSON
+ current, err := json.Marshal(fc)
+ if err != nil {
+ return fmt.Errorf("failed to serialize current config: %w", err)
+ }
+
+ // Unmarshal current into a map for merging
+ var currentMap map[string]interface{}
+ if err := json.Unmarshal(current, &currentMap); err != nil {
+ return fmt.Errorf("failed to parse current config: %w", err)
+ }
+
+ // Parse the patch
+ var patchMap map[string]interface{}
+ if err := json.Unmarshal([]byte(jsonPatch), &patchMap); err != nil {
+ return fmt.Errorf("invalid JSON patch: %w", err)
+ }
+
+ // Deep merge patch into current
+ merged := deepMerge(currentMap, patchMap)
+
+ // Serialize merged back to JSON
+ mergedJSON, err := json.Marshal(merged)
+ if err != nil {
+ return fmt.Errorf("failed to serialize merged config: %w", err)
+ }
+
+ // Unmarshal back into FileConfig
+ if err := json.Unmarshal(mergedJSON, fc); err != nil {
+ return fmt.Errorf("failed to parse merged config: %w", err)
+ }
+
+ return nil
+}
+
+// deepMerge recursively merges src into dst, returning the result.
+func deepMerge(dst, src map[string]interface{}) map[string]interface{} {
+ result := make(map[string]interface{})
+
+ // Copy dst
+ for k, v := range dst {
+ result[k] = v
+ }
+
+ // Merge src
+ for k, v := range src {
+ if srcMap, ok := v.(map[string]interface{}); ok {
+ if dstMap, ok := result[k].(map[string]interface{}); ok {
+ result[k] = deepMerge(dstMap, srcMap)
+ continue
+ }
+ }
+ result[k] = v
+ }
+
+ return result
+}
+
+// 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) {
+ configPath := envOrMigrate("PINCHTAB_CONFIG", "BRIDGE_CONFIG", filepath.Join(userConfigDir(), "config.json"))
+
+ data, err := os.ReadFile(configPath)
+ if err != nil {
+ if os.IsNotExist(err) {
+ // Return empty config if file doesn't exist
+ return &FileConfig{}, configPath, nil
+ }
+ return nil, configPath, fmt.Errorf("failed to read config file: %w", err)
+ }
+
+ var fc *FileConfig
+
+ if isLegacyConfig(data) {
+ var lc legacyFileConfig
+ if err := json.Unmarshal(data, &lc); err != nil {
+ return nil, configPath, fmt.Errorf("failed to parse legacy config: %w", err)
+ }
+ fc = convertLegacyConfig(&lc)
+ } else {
+ fc = &FileConfig{}
+ if err := json.Unmarshal(data, fc); err != nil {
+ return nil, configPath, fmt.Errorf("failed to parse config: %w", err)
+ }
+ }
+
+ return fc, configPath, nil
+}
+
+// SaveFileConfig saves a FileConfig to the specified path.
+func SaveFileConfig(fc *FileConfig, path string) error {
+ // Create directory if needed
+ if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
+ return fmt.Errorf("failed to create config directory: %w", err)
+ }
+
+ data, err := json.MarshalIndent(fc, "", " ")
+ if err != nil {
+ return fmt.Errorf("failed to serialize config: %w", err)
+ }
+
+ // Add trailing newline
+ data = append(data, '\n')
+
+ if err := os.WriteFile(path, data, 0644); err != nil {
+ return fmt.Errorf("failed to write config file: %w", err)
+ }
+
+ return nil
+}
diff --git a/internal/config/editor_test.go b/internal/config/editor_test.go
new file mode 100644
index 00000000..79bcfa17
--- /dev/null
+++ b/internal/config/editor_test.go
@@ -0,0 +1,319 @@
+package config
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+func TestSetConfigValue_ServerFields(t *testing.T) {
+ tests := []struct {
+ path string
+ value string
+ check func(*FileConfig) bool
+ wantErr bool
+ }{
+ {"server.port", "8080", func(fc *FileConfig) bool { return fc.Server.Port == "8080" }, false},
+ {"server.bind", "0.0.0.0", func(fc *FileConfig) bool { return fc.Server.Bind == "0.0.0.0" }, false},
+ {"server.token", "secret", func(fc *FileConfig) bool { return fc.Server.Token == "secret" }, false},
+ {"server.stateDir", "/tmp/state", func(fc *FileConfig) bool { return fc.Server.StateDir == "/tmp/state" }, false},
+ {"server.instancePortStart", "9900", func(fc *FileConfig) bool { return *fc.Server.InstancePortStart == 9900 }, false},
+ {"server.instancePortEnd", "9999", func(fc *FileConfig) bool { return *fc.Server.InstancePortEnd == 9999 }, false},
+ {"server.instancePortStart", "abc", nil, true},
+ {"server.unknown", "value", nil, true},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.path+"="+tt.value, func(t *testing.T) {
+ fc := &FileConfig{}
+ err := SetConfigValue(fc, tt.path, tt.value)
+ if (err != nil) != tt.wantErr {
+ t.Errorf("SetConfigValue() error = %v, wantErr %v", err, tt.wantErr)
+ return
+ }
+ if !tt.wantErr && !tt.check(fc) {
+ t.Errorf("SetConfigValue() did not set value correctly")
+ }
+ })
+ }
+}
+
+func TestSetConfigValue_ChromeFields(t *testing.T) {
+ tests := []struct {
+ path string
+ value string
+ check func(*FileConfig) bool
+ wantErr bool
+ }{
+ {"chrome.headless", "false", func(fc *FileConfig) bool { return fc.Chrome.Headless != nil && !*fc.Chrome.Headless }, false},
+ {"chrome.headless", "true", func(fc *FileConfig) bool { return fc.Chrome.Headless != nil && *fc.Chrome.Headless }, false},
+ {"chrome.maxTabs", "50", func(fc *FileConfig) bool { return *fc.Chrome.MaxTabs == 50 }, false},
+ {"chrome.stealthLevel", "full", func(fc *FileConfig) bool { return fc.Chrome.StealthLevel == "full" }, false},
+ {"chrome.tabEvictionPolicy", "close_lru", func(fc *FileConfig) bool { return fc.Chrome.TabEvictionPolicy == "close_lru" }, false},
+ {"chrome.blockAds", "yes", func(fc *FileConfig) bool { return *fc.Chrome.BlockAds == true }, false},
+ {"chrome.profileDir", "/tmp/chrome", func(fc *FileConfig) bool { return fc.Chrome.ProfileDir == "/tmp/chrome" }, false},
+ {"chrome.headless", "maybe", nil, true},
+ {"chrome.maxTabs", "many", nil, true},
+ {"chrome.unknown", "value", nil, true},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.path+"="+tt.value, func(t *testing.T) {
+ fc := &FileConfig{}
+ err := SetConfigValue(fc, tt.path, tt.value)
+ if (err != nil) != tt.wantErr {
+ t.Errorf("SetConfigValue() error = %v, wantErr %v", err, tt.wantErr)
+ return
+ }
+ if !tt.wantErr && !tt.check(fc) {
+ t.Errorf("SetConfigValue() did not set value correctly")
+ }
+ })
+ }
+}
+
+func TestSetConfigValue_SecurityFields(t *testing.T) {
+ tests := []struct {
+ path string
+ value string
+ check func(*FileConfig) bool
+ wantErr bool
+ }{
+ {"security.allowEvaluate", "true", func(fc *FileConfig) bool { return *fc.Security.AllowEvaluate == true }, false},
+ {"security.allowMacro", "1", func(fc *FileConfig) bool { return *fc.Security.AllowMacro == true }, false},
+ {"security.allowScreencast", "false", func(fc *FileConfig) bool { return *fc.Security.AllowScreencast == false }, false},
+ {"security.allowDownload", "on", func(fc *FileConfig) bool { return *fc.Security.AllowDownload == true }, false},
+ {"security.allowUpload", "off", func(fc *FileConfig) bool { return *fc.Security.AllowUpload == false }, false},
+ {"security.allowEvaluate", "maybe", nil, true},
+ {"security.unknown", "true", nil, true},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.path+"="+tt.value, func(t *testing.T) {
+ fc := &FileConfig{}
+ err := SetConfigValue(fc, tt.path, tt.value)
+ if (err != nil) != tt.wantErr {
+ t.Errorf("SetConfigValue() error = %v, wantErr %v", err, tt.wantErr)
+ return
+ }
+ if !tt.wantErr && !tt.check(fc) {
+ t.Errorf("SetConfigValue() did not set value correctly")
+ }
+ })
+ }
+}
+
+func TestSetConfigValue_OrchestratorFields(t *testing.T) {
+ tests := []struct {
+ path string
+ value string
+ check func(*FileConfig) bool
+ wantErr bool
+ }{
+ {"orchestrator.strategy", "explicit", func(fc *FileConfig) bool { return fc.Orchestrator.Strategy == "explicit" }, false},
+ {"orchestrator.allocationPolicy", "round_robin", func(fc *FileConfig) bool { return fc.Orchestrator.AllocationPolicy == "round_robin" }, false},
+ {"orchestrator.unknown", "value", nil, true},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.path+"="+tt.value, func(t *testing.T) {
+ fc := &FileConfig{}
+ err := SetConfigValue(fc, tt.path, tt.value)
+ if (err != nil) != tt.wantErr {
+ t.Errorf("SetConfigValue() error = %v, wantErr %v", err, tt.wantErr)
+ return
+ }
+ if !tt.wantErr && !tt.check(fc) {
+ t.Errorf("SetConfigValue() did not set value correctly")
+ }
+ })
+ }
+}
+
+func TestSetConfigValue_TimeoutsFields(t *testing.T) {
+ tests := []struct {
+ path string
+ value string
+ check func(*FileConfig) bool
+ wantErr bool
+ }{
+ {"timeouts.actionSec", "60", func(fc *FileConfig) bool { return fc.Timeouts.ActionSec == 60 }, false},
+ {"timeouts.navigateSec", "120", func(fc *FileConfig) bool { return fc.Timeouts.NavigateSec == 120 }, false},
+ {"timeouts.shutdownSec", "30", func(fc *FileConfig) bool { return fc.Timeouts.ShutdownSec == 30 }, false},
+ {"timeouts.waitNavMs", "2000", func(fc *FileConfig) bool { return fc.Timeouts.WaitNavMs == 2000 }, false},
+ {"timeouts.actionSec", "fast", nil, true},
+ {"timeouts.unknown", "10", nil, true},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.path+"="+tt.value, func(t *testing.T) {
+ fc := &FileConfig{}
+ err := SetConfigValue(fc, tt.path, tt.value)
+ if (err != nil) != tt.wantErr {
+ t.Errorf("SetConfigValue() error = %v, wantErr %v", err, tt.wantErr)
+ return
+ }
+ if !tt.wantErr && !tt.check(fc) {
+ t.Errorf("SetConfigValue() did not set value correctly")
+ }
+ })
+ }
+}
+
+func TestSetConfigValue_InvalidPaths(t *testing.T) {
+ tests := []string{
+ "port", // missing section
+ "", // empty
+ "unknown.field", // unknown section
+ "server", // missing field
+ "a.b.c", // too many parts (we only split on first .)
+ }
+
+ for _, path := range tests {
+ t.Run(path, func(t *testing.T) {
+ fc := &FileConfig{}
+ err := SetConfigValue(fc, path, "value")
+ if err == nil {
+ t.Errorf("SetConfigValue(%q) should have failed", path)
+ }
+ })
+ }
+}
+
+func TestPatchConfigJSON(t *testing.T) {
+ fc := &FileConfig{
+ Server: ServerConfig{
+ Port: "9867",
+ Bind: "127.0.0.1",
+ },
+ Chrome: ChromeConfig{
+ StealthLevel: "light",
+ },
+ }
+
+ // Patch to change port and add token
+ patch := `{"server": {"port": "8080", "token": "secret"}}`
+ if err := PatchConfigJSON(fc, patch); err != nil {
+ t.Fatalf("PatchConfigJSON() error = %v", err)
+ }
+
+ if fc.Server.Port != "8080" {
+ t.Errorf("port = %v, want 8080", fc.Server.Port)
+ }
+ if fc.Server.Token != "secret" {
+ t.Errorf("token = %v, want secret", fc.Server.Token)
+ }
+ // Bind should be preserved
+ if fc.Server.Bind != "127.0.0.1" {
+ t.Errorf("bind = %v, want 127.0.0.1 (should be preserved)", fc.Server.Bind)
+ }
+ // Chrome.StealthLevel should be preserved
+ if fc.Chrome.StealthLevel != "light" {
+ t.Errorf("stealthLevel = %v, want light (should be preserved)", fc.Chrome.StealthLevel)
+ }
+}
+
+func TestPatchConfigJSON_NestedMerge(t *testing.T) {
+ fc := &FileConfig{
+ Chrome: ChromeConfig{
+ StealthLevel: "light",
+ TabEvictionPolicy: "reject",
+ },
+ }
+
+ // Patch chrome section, should merge not replace
+ patch := `{"chrome": {"stealthLevel": "full"}}`
+ if err := PatchConfigJSON(fc, patch); err != nil {
+ t.Fatalf("PatchConfigJSON() error = %v", err)
+ }
+
+ if fc.Chrome.StealthLevel != "full" {
+ t.Errorf("stealthLevel = %v, want full", fc.Chrome.StealthLevel)
+ }
+ // tabEvictionPolicy should be preserved
+ if fc.Chrome.TabEvictionPolicy != "reject" {
+ t.Errorf("tabEvictionPolicy = %v, want reject (should be preserved)", fc.Chrome.TabEvictionPolicy)
+ }
+}
+
+func TestPatchConfigJSON_InvalidJSON(t *testing.T) {
+ fc := &FileConfig{}
+ err := PatchConfigJSON(fc, "not json")
+ if err == nil {
+ t.Error("PatchConfigJSON() should fail on invalid JSON")
+ }
+}
+
+func TestLoadAndSaveFileConfig(t *testing.T) {
+ tmpDir := t.TempDir()
+ configPath := filepath.Join(tmpDir, "config.json")
+ _ = os.Setenv("PINCHTAB_CONFIG", configPath)
+ defer func() { _ = os.Unsetenv("PINCHTAB_CONFIG") }()
+
+ // Load (should return empty config for non-existent file)
+ fc, path, err := LoadFileConfig()
+ if err != nil {
+ t.Fatalf("LoadFileConfig() error = %v", err)
+ }
+ if path != configPath {
+ t.Errorf("path = %v, want %v", path, configPath)
+ }
+
+ // Modify
+ fc.Server.Port = "8080"
+ fc.Chrome.StealthLevel = "full"
+
+ // Save
+ if err := SaveFileConfig(fc, path); err != nil {
+ t.Fatalf("SaveFileConfig() error = %v", err)
+ }
+
+ // Load again
+ fc2, _, err := LoadFileConfig()
+ if err != nil {
+ t.Fatalf("LoadFileConfig() second time error = %v", err)
+ }
+
+ if fc2.Server.Port != "8080" {
+ t.Errorf("loaded port = %v, want 8080", fc2.Server.Port)
+ }
+ if fc2.Chrome.StealthLevel != "full" {
+ t.Errorf("loaded stealthLevel = %v, want full", fc2.Chrome.StealthLevel)
+ }
+}
+
+func TestParseBool(t *testing.T) {
+ tests := []struct {
+ input string
+ want bool
+ wantErr bool
+ }{
+ {"true", true, false},
+ {"True", true, false},
+ {"TRUE", true, false},
+ {"1", true, false},
+ {"yes", true, false},
+ {"on", true, false},
+ {"false", false, false},
+ {"False", false, false},
+ {"0", false, false},
+ {"no", false, false},
+ {"off", false, false},
+ {"maybe", false, true},
+ {"", false, true},
+ {"2", false, true},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.input, func(t *testing.T) {
+ got, err := parseBool(tt.input)
+ if (err != nil) != tt.wantErr {
+ t.Errorf("parseBool(%q) error = %v, wantErr %v", tt.input, err, tt.wantErr)
+ return
+ }
+ if !tt.wantErr && got != tt.want {
+ t.Errorf("parseBool(%q) = %v, want %v", tt.input, got, tt.want)
+ }
+ })
+ }
+}
diff --git a/internal/config/validate.go b/internal/config/validate.go
new file mode 100644
index 00000000..ac00261f
--- /dev/null
+++ b/internal/config/validate.go
@@ -0,0 +1,209 @@
+package config
+
+import (
+ "fmt"
+ "strconv"
+)
+
+// ValidationError represents a configuration validation error.
+type ValidationError struct {
+ Field string
+ Message string
+}
+
+func (e ValidationError) Error() string {
+ return fmt.Sprintf("%s: %s", e.Field, e.Message)
+}
+
+// ValidateFileConfig validates a FileConfig and returns all errors found.
+func ValidateFileConfig(fc *FileConfig) []error {
+ var errs []error
+
+ // Server validation
+ if fc.Server.Port != "" {
+ if err := validatePort(fc.Server.Port, "server.port"); err != nil {
+ errs = append(errs, err)
+ }
+ }
+ if fc.Server.Bind != "" {
+ if err := validateBind(fc.Server.Bind, "server.bind"); err != nil {
+ errs = append(errs, err)
+ }
+ }
+ if fc.Server.InstancePortStart != nil && fc.Server.InstancePortEnd != nil {
+ if *fc.Server.InstancePortStart > *fc.Server.InstancePortEnd {
+ errs = append(errs, ValidationError{
+ Field: "server.instancePortStart/End",
+ Message: fmt.Sprintf("start port (%d) must be <= end port (%d)", *fc.Server.InstancePortStart, *fc.Server.InstancePortEnd),
+ })
+ }
+ }
+
+ // Chrome validation
+ if fc.Chrome.StealthLevel != "" {
+ if !isValidStealthLevel(fc.Chrome.StealthLevel) {
+ errs = append(errs, ValidationError{
+ Field: "chrome.stealthLevel",
+ Message: fmt.Sprintf("invalid value %q (must be light, medium, or full)", fc.Chrome.StealthLevel),
+ })
+ }
+ }
+ if fc.Chrome.TabEvictionPolicy != "" {
+ if !isValidEvictionPolicy(fc.Chrome.TabEvictionPolicy) {
+ errs = append(errs, ValidationError{
+ Field: "chrome.tabEvictionPolicy",
+ Message: fmt.Sprintf("invalid value %q (must be reject, close_oldest, or close_lru)", fc.Chrome.TabEvictionPolicy),
+ })
+ }
+ }
+ if fc.Chrome.MaxTabs != nil && *fc.Chrome.MaxTabs < 1 {
+ errs = append(errs, ValidationError{
+ Field: "chrome.maxTabs",
+ Message: fmt.Sprintf("must be >= 1 (got %d)", *fc.Chrome.MaxTabs),
+ })
+ }
+ if fc.Chrome.MaxParallelTabs != nil && *fc.Chrome.MaxParallelTabs < 0 {
+ errs = append(errs, ValidationError{
+ Field: "chrome.maxParallelTabs",
+ Message: fmt.Sprintf("must be >= 0 (got %d)", *fc.Chrome.MaxParallelTabs),
+ })
+ }
+
+ // Orchestrator validation
+ if fc.Orchestrator.Strategy != "" {
+ if !isValidStrategy(fc.Orchestrator.Strategy) {
+ errs = append(errs, ValidationError{
+ Field: "orchestrator.strategy",
+ Message: fmt.Sprintf("invalid value %q (must be simple, explicit, or simple-autorestart)", fc.Orchestrator.Strategy),
+ })
+ }
+ }
+ if fc.Orchestrator.AllocationPolicy != "" {
+ if !isValidAllocationPolicy(fc.Orchestrator.AllocationPolicy) {
+ errs = append(errs, ValidationError{
+ Field: "orchestrator.allocationPolicy",
+ Message: fmt.Sprintf("invalid value %q (must be fcfs, round_robin, or random)", fc.Orchestrator.AllocationPolicy),
+ })
+ }
+ }
+
+ // Timeouts validation
+ if fc.Timeouts.ActionSec < 0 {
+ errs = append(errs, ValidationError{
+ Field: "timeouts.actionSec",
+ Message: fmt.Sprintf("must be >= 0 (got %d)", fc.Timeouts.ActionSec),
+ })
+ }
+ if fc.Timeouts.NavigateSec < 0 {
+ errs = append(errs, ValidationError{
+ Field: "timeouts.navigateSec",
+ Message: fmt.Sprintf("must be >= 0 (got %d)", fc.Timeouts.NavigateSec),
+ })
+ }
+ if fc.Timeouts.ShutdownSec < 0 {
+ errs = append(errs, ValidationError{
+ Field: "timeouts.shutdownSec",
+ Message: fmt.Sprintf("must be >= 0 (got %d)", fc.Timeouts.ShutdownSec),
+ })
+ }
+ if fc.Timeouts.WaitNavMs < 0 {
+ errs = append(errs, ValidationError{
+ Field: "timeouts.waitNavMs",
+ Message: fmt.Sprintf("must be >= 0 (got %d)", fc.Timeouts.WaitNavMs),
+ })
+ }
+
+ return errs
+}
+
+func validatePort(port string, field string) error {
+ p, err := strconv.Atoi(port)
+ if err != nil {
+ return ValidationError{
+ Field: field,
+ Message: fmt.Sprintf("invalid port %q (must be a number)", port),
+ }
+ }
+ if p < 1 || p > 65535 {
+ return ValidationError{
+ Field: field,
+ Message: fmt.Sprintf("port %d out of range (must be 1-65535)", p),
+ }
+ }
+ return nil
+}
+
+func validateBind(bind string, field string) error {
+ // Accept common bind addresses
+ validBinds := map[string]bool{
+ "127.0.0.1": true,
+ "0.0.0.0": true,
+ "localhost": true,
+ "::1": true,
+ "::": true,
+ }
+ if validBinds[bind] {
+ return nil
+ }
+ // Basic IP format check (not exhaustive, just sanity)
+ // If it contains a dot, assume it's an IPv4 attempt
+ // If it contains a colon, assume it's an IPv6 attempt
+ // This is intentionally loose — the OS will reject truly invalid addresses
+ return nil
+}
+
+func isValidStealthLevel(level string) bool {
+ switch level {
+ case "light", "medium", "full":
+ return true
+ default:
+ return false
+ }
+}
+
+func isValidEvictionPolicy(policy string) bool {
+ switch policy {
+ case "reject", "close_oldest", "close_lru":
+ return true
+ default:
+ return false
+ }
+}
+
+func isValidStrategy(strategy string) bool {
+ switch strategy {
+ case "simple", "explicit", "simple-autorestart":
+ return true
+ default:
+ return false
+ }
+}
+
+func isValidAllocationPolicy(policy string) bool {
+ switch policy {
+ case "fcfs", "round_robin", "random":
+ return true
+ default:
+ return false
+ }
+}
+
+// ValidStealthLevels returns all valid stealth level values.
+func ValidStealthLevels() []string {
+ return []string{"light", "medium", "full"}
+}
+
+// ValidEvictionPolicies returns all valid tab eviction policy values.
+func ValidEvictionPolicies() []string {
+ return []string{"reject", "close_oldest", "close_lru"}
+}
+
+// ValidStrategies returns all valid strategy values.
+func ValidStrategies() []string {
+ return []string{"simple", "explicit", "simple-autorestart"}
+}
+
+// ValidAllocationPolicies returns all valid allocation policy values.
+func ValidAllocationPolicies() []string {
+ return []string{"fcfs", "round_robin", "random"}
+}
diff --git a/internal/config/validate_test.go b/internal/config/validate_test.go
new file mode 100644
index 00000000..f51a8ca2
--- /dev/null
+++ b/internal/config/validate_test.go
@@ -0,0 +1,289 @@
+package config
+
+import (
+ "strings"
+ "testing"
+)
+
+func TestValidateFileConfig_Valid(t *testing.T) {
+ maxTabs := 20
+ fc := &FileConfig{
+ Server: ServerConfig{
+ Port: "9867",
+ Bind: "127.0.0.1",
+ },
+ Chrome: ChromeConfig{
+ MaxTabs: &maxTabs,
+ StealthLevel: "light",
+ TabEvictionPolicy: "reject",
+ },
+ Orchestrator: OrchestratorConfig{
+ Strategy: "simple",
+ AllocationPolicy: "fcfs",
+ },
+ Timeouts: TimeoutsConfig{
+ ActionSec: 30,
+ NavigateSec: 60,
+ },
+ }
+
+ errs := ValidateFileConfig(fc)
+ if len(errs) > 0 {
+ t.Errorf("expected no errors for valid config, got: %v", errs)
+ }
+}
+
+func TestValidateFileConfig_InvalidPort(t *testing.T) {
+ tests := []struct {
+ port string
+ wantErr bool
+ }{
+ {"9867", false},
+ {"1", false},
+ {"65535", false},
+ {"0", true},
+ {"65536", true},
+ {"-1", true},
+ {"abc", true},
+ {"", false}, // empty is ok (uses default)
+ }
+
+ for _, tt := range tests {
+ fc := &FileConfig{
+ Server: ServerConfig{Port: tt.port},
+ }
+ errs := ValidateFileConfig(fc)
+ hasErr := len(errs) > 0
+ if hasErr != tt.wantErr {
+ t.Errorf("port=%q: got error=%v, want error=%v (errs: %v)", tt.port, hasErr, tt.wantErr, errs)
+ }
+ }
+}
+
+func TestValidateFileConfig_InvalidStealthLevel(t *testing.T) {
+ tests := []struct {
+ level string
+ wantErr bool
+ }{
+ {"light", false},
+ {"medium", false},
+ {"full", false},
+ {"", false}, // empty is ok
+ {"none", true},
+ {"max", true},
+ {"LIGHT", true}, // case sensitive
+ }
+
+ for _, tt := range tests {
+ fc := &FileConfig{
+ Chrome: ChromeConfig{StealthLevel: tt.level},
+ }
+ errs := ValidateFileConfig(fc)
+ hasErr := len(errs) > 0
+ if hasErr != tt.wantErr {
+ t.Errorf("stealthLevel=%q: got error=%v, want error=%v", tt.level, hasErr, tt.wantErr)
+ }
+ }
+}
+
+func TestValidateFileConfig_InvalidEvictionPolicy(t *testing.T) {
+ tests := []struct {
+ policy string
+ wantErr bool
+ }{
+ {"reject", false},
+ {"close_oldest", false},
+ {"close_lru", false},
+ {"", false},
+ {"drop", true},
+ {"lru", true},
+ }
+
+ for _, tt := range tests {
+ fc := &FileConfig{
+ Chrome: ChromeConfig{TabEvictionPolicy: tt.policy},
+ }
+ errs := ValidateFileConfig(fc)
+ hasErr := len(errs) > 0
+ if hasErr != tt.wantErr {
+ t.Errorf("tabEvictionPolicy=%q: got error=%v, want error=%v", tt.policy, hasErr, tt.wantErr)
+ }
+ }
+}
+
+func TestValidateFileConfig_InvalidStrategy(t *testing.T) {
+ tests := []struct {
+ strategy string
+ wantErr bool
+ }{
+ {"simple", false},
+ {"explicit", false},
+ {"simple-autorestart", false},
+ {"", false},
+ {"auto", true},
+ {"default", true},
+ }
+
+ for _, tt := range tests {
+ fc := &FileConfig{
+ Orchestrator: OrchestratorConfig{Strategy: tt.strategy},
+ }
+ errs := ValidateFileConfig(fc)
+ hasErr := len(errs) > 0
+ if hasErr != tt.wantErr {
+ t.Errorf("strategy=%q: got error=%v, want error=%v", tt.strategy, hasErr, tt.wantErr)
+ }
+ }
+}
+
+func TestValidateFileConfig_InvalidAllocationPolicy(t *testing.T) {
+ tests := []struct {
+ policy string
+ wantErr bool
+ }{
+ {"fcfs", false},
+ {"round_robin", false},
+ {"random", false},
+ {"", false},
+ {"fifo", true},
+ {"roundrobin", true}, // underscore required
+ }
+
+ for _, tt := range tests {
+ fc := &FileConfig{
+ Orchestrator: OrchestratorConfig{AllocationPolicy: tt.policy},
+ }
+ errs := ValidateFileConfig(fc)
+ hasErr := len(errs) > 0
+ if hasErr != tt.wantErr {
+ t.Errorf("allocationPolicy=%q: got error=%v, want error=%v", tt.policy, hasErr, tt.wantErr)
+ }
+ }
+}
+
+func TestValidateFileConfig_InvalidMaxTabs(t *testing.T) {
+ zero := 0
+ negative := -1
+ positive := 10
+
+ tests := []struct {
+ name string
+ maxTabs *int
+ wantErr bool
+ }{
+ {"nil", nil, false},
+ {"positive", &positive, false},
+ {"zero", &zero, true},
+ {"negative", &negative, true},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ fc := &FileConfig{
+ Chrome: ChromeConfig{MaxTabs: tt.maxTabs},
+ }
+ errs := ValidateFileConfig(fc)
+ hasErr := len(errs) > 0
+ if hasErr != tt.wantErr {
+ t.Errorf("maxTabs=%v: got error=%v, want error=%v", tt.maxTabs, hasErr, tt.wantErr)
+ }
+ })
+ }
+}
+
+func TestValidateFileConfig_InvalidTimeouts(t *testing.T) {
+ fc := &FileConfig{
+ Timeouts: TimeoutsConfig{
+ ActionSec: -1,
+ NavigateSec: -1,
+ ShutdownSec: -1,
+ WaitNavMs: -1,
+ },
+ }
+
+ errs := ValidateFileConfig(fc)
+ if len(errs) != 4 {
+ t.Errorf("expected 4 timeout errors, got %d: %v", len(errs), errs)
+ }
+}
+
+func TestValidateFileConfig_InstancePortRange(t *testing.T) {
+ start := 9900
+ end := 9800 // invalid: start > end
+
+ fc := &FileConfig{
+ Server: ServerConfig{
+ InstancePortStart: &start,
+ InstancePortEnd: &end,
+ },
+ }
+
+ errs := ValidateFileConfig(fc)
+ if len(errs) != 1 {
+ t.Errorf("expected 1 error for invalid port range, got %d: %v", len(errs), errs)
+ }
+ if len(errs) > 0 && !strings.Contains(errs[0].Error(), "start port") {
+ t.Errorf("expected port range error, got: %v", errs[0])
+ }
+}
+
+func TestValidateFileConfig_MultipleErrors(t *testing.T) {
+ zero := 0
+ fc := &FileConfig{
+ Server: ServerConfig{
+ Port: "99999", // invalid
+ },
+ Chrome: ChromeConfig{
+ MaxTabs: &zero, // invalid
+ StealthLevel: "superstealth", // invalid
+ TabEvictionPolicy: "delete_oldest", // invalid
+ },
+ Orchestrator: OrchestratorConfig{
+ Strategy: "magical", // invalid
+ AllocationPolicy: "balanced", // invalid
+ },
+ }
+
+ errs := ValidateFileConfig(fc)
+ if len(errs) < 5 {
+ t.Errorf("expected at least 5 errors, got %d: %v", len(errs), errs)
+ }
+}
+
+func TestValidationError_Error(t *testing.T) {
+ err := ValidationError{
+ Field: "server.port",
+ Message: "port out of range",
+ }
+ expected := "server.port: port out of range"
+ if err.Error() != expected {
+ t.Errorf("got %q, want %q", err.Error(), expected)
+ }
+}
+
+func TestValidEnumValues(t *testing.T) {
+ // Test that the valid values match the validation functions
+ for _, level := range ValidStealthLevels() {
+ if !isValidStealthLevel(level) {
+ t.Errorf("ValidStealthLevels contains %q but isValidStealthLevel returns false", level)
+ }
+ }
+
+ for _, policy := range ValidEvictionPolicies() {
+ if !isValidEvictionPolicy(policy) {
+ t.Errorf("ValidEvictionPolicies contains %q but isValidEvictionPolicy returns false", policy)
+ }
+ }
+
+ for _, strategy := range ValidStrategies() {
+ if !isValidStrategy(strategy) {
+ t.Errorf("ValidStrategies contains %q but isValidStrategy returns false", strategy)
+ }
+ }
+
+ for _, policy := range ValidAllocationPolicies() {
+ if !isValidAllocationPolicy(policy) {
+ t.Errorf("ValidAllocationPolicies contains %q but isValidAllocationPolicy returns false", policy)
+ }
+ }
+}