Skip to content

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

refactor config-driven instance launch and remove legacy env behavior

Luigi Agosti3df44e79e880
diff --git a/.gitignore b/.gitignore
index 515d6bc0..5e36bf16 100644
--- a/.gitignore
+++ b/.gitignore
@@ -32,7 +32,6 @@ USER.md
BOOTSTRAP.md
TOOLS.md
MEMORY.md
-.openclaw/
AGENTS.md
*.test
memory/
@@ -42,3 +41,5 @@ pinchtab-small
MY_PROJECT_NOTES.md
debug.log
pinchtab.exe
+
+.gocache
diff --git a/cmd/pinchtab/cmd_dashboard.go b/cmd/pinchtab/cmd_dashboard.go
index 1080a923..f2b472cc 100644
--- a/cmd/pinchtab/cmd_dashboard.go
+++ b/cmd/pinchtab/cmd_dashboard.go
@@ -38,7 +38,7 @@ func runDashboard(cfg *config.RuntimeConfig) {
slog.Info("πŸ¦€ PinchTab", "port", dashPort)
- profilesDir := filepath.Join(cfg.StateDir, "profiles")
+ profilesDir := cfg.ProfilesBaseDir
if err := os.MkdirAll(profilesDir, 0755); err != nil {
slog.Error("cannot create profiles dir", "err", err)
os.Exit(1)
@@ -47,8 +47,8 @@ func runDashboard(cfg *config.RuntimeConfig) {
profMgr := profiles.NewProfileManager(profilesDir)
dash := dashboard.NewDashboard(nil)
orch := orchestrator.NewOrchestrator(profilesDir)
+ orch.ApplyRuntimeConfig(cfg)
orch.SetProfileManager(profMgr)
- orch.SetPortRange(cfg.InstancePortStart, cfg.InstancePortEnd)
dash.SetInstanceLister(orch)
// Wire up instance events to SSE broadcast
diff --git a/docs/guides/data-storage.md b/docs/guides/data-storage.md
index dd35db95..426c2a01 100644
--- a/docs/guides/data-storage.md
+++ b/docs/guides/data-storage.md
@@ -6,10 +6,10 @@ Pinchtab stores configuration, state, and browser profiles on your local filesys
| File/Directory | Purpose | Configurable Via |
|----------------|---------|------------------|
-| `chrome-profile/` | Chrome browser profile (cookies, cache, localStorage, etc.) | `BRIDGE_PROFILE` env var or `profileDir` in config |
-| `config.json` | Runtime configuration (port, token, headless mode, etc.) | `BRIDGE_CONFIG` env var |
+| `profiles/<name>/` | Chrome browser profile (cookies, cache, localStorage, etc.) | `profiles.baseDir` + `profiles.defaultProfile` in config |
+| `config.json` | Runtime configuration (port, token, headless mode, etc.) | `PINCHTAB_CONFIG` env var |
| `action_logs.json` | Profile action history and analytics | *(not currently configurable)* |
-| `*.state.json` | Bridge state files (orchestrator state, etc.) | `BRIDGE_STATE_DIR` env var or `stateDir` in config |
+| `*.state.json` | Bridge state files (orchestrator state, etc.) | `server.stateDir` in config |
### Chrome Profile Directory
@@ -28,11 +28,18 @@ The largest and most important directory. Contains:
`config.json` stores runtime settings:
```json
{
- "port": "9867",
- "token": "your-secret-token",
- "headless": true,
- "stateDir": "/custom/path/state",
- "profileDir": "/custom/path/chrome-profile"
+ "server": {
+ "port": "9867",
+ "token": "your-secret-token",
+ "stateDir": "/custom/path/state"
+ },
+ "instanceDefaults": {
+ "mode": "headless"
+ },
+ "profiles": {
+ "baseDir": "/custom/path/profiles",
+ "defaultProfile": "default"
+ }
}
```
@@ -68,7 +75,8 @@ Pinchtab now uses **OS-native application data directories**:
Inside that directory:
```
pinchtab/
-β”œβ”€β”€ chrome-profile/ # Browser profile
+β”œβ”€β”€ profiles/ # Browser profiles
+β”‚ └── default/
β”œβ”€β”€ config.json # Configuration
β”œβ”€β”€ action_logs.json # Action history
└── *.state.json # Bridge state files
@@ -96,19 +104,11 @@ Previously, everything lived in `~/.pinchtab/`:
### Via Environment Variables
-Override defaults before starting pinchtab:
+Only `PINCHTAB_CONFIG` remains for storage-related path selection:
```bash
-# Custom profile directory
-export BRIDGE_PROFILE=/mnt/data/my-chrome-profile
-pinchtab
-
-# Custom state directory
-export BRIDGE_STATE_DIR=/var/lib/pinchtab/state
-pinchtab
-
# Custom config file location
-export BRIDGE_CONFIG=/etc/pinchtab/config.json
+export PINCHTAB_CONFIG=/etc/pinchtab/config.json
pinchtab
```
@@ -117,12 +117,17 @@ pinchtab
Set custom paths in `config.json`:
```json
{
- "profileDir": "/mnt/data/my-chrome-profile",
- "stateDir": "/var/lib/pinchtab/state"
+ "server": {
+ "stateDir": "/var/lib/pinchtab/state"
+ },
+ "profiles": {
+ "baseDir": "/mnt/data/profiles",
+ "defaultProfile": "default"
+ }
}
```
-**Priority order:** Environment variables take precedence over config file values.
+**Priority order:** `PINCHTAB_CONFIG` chooses which config file to load. Storage paths inside that file control the actual directories.
## Migration from Legacy Location
@@ -161,14 +166,19 @@ rmdir ~/.pinchtab
### Option 3: Stay on Legacy Location
-Set `BRIDGE_PROFILE` and `BRIDGE_STATE_DIR` to point to `~/.pinchtab/`:
-```bash
-export BRIDGE_STATE_DIR=~/.pinchtab
-export BRIDGE_PROFILE=~/.pinchtab/chrome-profile
+Set your config file to point to the legacy location:
+```json
+{
+ "server": {
+ "stateDir": "~/.pinchtab"
+ },
+ "profiles": {
+ "baseDir": "~/.pinchtab/profiles",
+ "defaultProfile": "default"
+ }
+}
```
-Add these to your shell profile (`.bashrc`, `.zshrc`, etc.) to make them permanent.
-
## Container Deployments
In Docker/containerized environments:
@@ -176,8 +186,7 @@ In Docker/containerized environments:
1. **Mount a volume** for persistence:
```bash
docker run -v /host/pinchtab-data:/data \
- -e BRIDGE_STATE_DIR=/data \
- -e BRIDGE_PROFILE=/data/chrome-profile \
+ -e PINCHTAB_CONFIG=/data/config.json \
pinchtab/pinchtab
```
@@ -186,7 +195,7 @@ In Docker/containerized environments:
ENV HOME=/app
```
-3. **Or use explicit paths** via environment variables (recommended for containers).
+3. **Store explicit paths in the mounted config file**.
## Security Considerations
@@ -197,7 +206,7 @@ In Docker/containerized environments:
- **History & Cache** β€” Reveals browsing activity
**Recommendations:**
-- Set restrictive permissions: `chmod 700 ~/.config/pinchtab/chrome-profile`
+- Set restrictive permissions on profile directories, for example `chmod 700 ~/.config/pinchtab/profiles/default`
- Don't commit profile directories to version control
- Use separate profiles for different security contexts
- Consider encrypting the filesystem or using encrypted volumes
@@ -246,10 +255,7 @@ Failed to create SingletonLock: Permission denied (13)
**Cause:** Using an old pinchtab version that stores profiles in `~/.pinchtab` (blocked by Snap AppArmor).
-**Solution:** Upgrade to the latest version (uses `~/.config/pinchtab` by default) or set:
-```bash
-export BRIDGE_PROFILE=~/.local/share/pinchtab/chrome-profile
-```
+**Solution:** Upgrade to the latest version (uses `~/.config/pinchtab` by default) or move profile storage under your configured `profiles.baseDir`.
See [Issue #98](https://github.com/pinchtab/pinchtab/issues/98) for details.
@@ -262,9 +268,9 @@ See [Issue #98](https://github.com/pinchtab/pinchtab/issues/98) for details.
cp ~/.pinchtab/config.json ~/.config/pinchtab/config.json # Linux
```
-Or use `BRIDGE_CONFIG`:
+Or use `PINCHTAB_CONFIG`:
```bash
-export BRIDGE_CONFIG=~/.pinchtab/config.json
+export PINCHTAB_CONFIG=~/.pinchtab/config.json
```
### Profile directory size is huge
@@ -273,14 +279,11 @@ export BRIDGE_CONFIG=~/.pinchtab/config.json
**Solution:** Clear the cache periodically:
```bash
-rm -rf ~/.config/pinchtab/chrome-profile/Default/Cache
-rm -rf ~/.config/pinchtab/chrome-profile/Default/Code\ Cache
+rm -rf ~/.config/pinchtab/profiles/default/Default/Cache
+rm -rf ~/.config/pinchtab/profiles/default/Default/Code\ Cache
```
-Or start pinchtab with a fresh profile for temporary sessions:
-```bash
-BRIDGE_PROFILE=/tmp/pinchtab-temp-profile pinchtab
-```
+Or point `profiles.baseDir` at a temporary directory for short-lived sessions.
## Further Reading
diff --git a/docs/references/configuration.md b/docs/references/configuration.md
index 9078ae7a..86ac84be 100644
--- a/docs/references/configuration.md
+++ b/docs/references/configuration.md
@@ -2,13 +2,28 @@
Complete reference for PinchTab configuration. Supports environment variables, config files (JSON), and CLI commands.
+PinchTab has two instance ownership models:
+- `launch`: PinchTab starts and manages Chrome
+- `attach`: PinchTab connects to an externally managed Chrome instance
+
+The config file defines defaults and policy for those models. It does not define a global instance-specific CDP target.
+
## Configuration Priority
Values are loaded in this order (highest priority first):
-1. **Environment variables** β€” always win
+1. **Environment variables**
2. **Config file** β€” `~/.config/pinchtab/config.json` (or `~/.pinchtab/config.json` legacy)
-3. **Built-in defaults** β€” used if nothing else is set
+3. **Built-in defaults**
+
+Only a small operational env surface remains:
+- `PINCHTAB_CONFIG`
+- `PINCHTAB_BIND`
+- `PINCHTAB_PORT`
+- `PINCHTAB_TOKEN`
+- `CHROME_BIN`
+
+Everything else should be configured in `config.json`.
## Config File
@@ -21,9 +36,9 @@ Default location varies by OS:
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`
+Override with `PINCHTAB_CONFIG=/path/to/config.json`.
-### Format (Nested JSON)
+### Format
```json
{
@@ -31,14 +46,17 @@ Override with: `PINCHTAB_CONFIG=/path/to/config.json`
"port": "9867",
"bind": "127.0.0.1",
"token": "your-secret-token",
- "stateDir": "/path/to/state",
- "instancePortStart": 9868,
- "instancePortEnd": 9968
+ "stateDir": "/path/to/state"
+ },
+ "browser": {
+ "version": "144.0.7559.133",
+ "binary": "/path/to/chrome",
+ "extraFlags": "",
+ "extensionPaths": []
},
- "chrome": {
- "headless": true,
+ "instanceDefaults": {
+ "mode": "headless",
"maxTabs": 20,
- "profileDir": "/path/to/chrome-profile",
"stealthLevel": "light",
"tabEvictionPolicy": "reject",
"blockAds": false,
@@ -54,9 +72,20 @@ Override with: `PINCHTAB_CONFIG=/path/to/config.json`
"allowDownload": false,
"allowUpload": false
},
- "orchestrator": {
+ "profiles": {
+ "baseDir": "/path/to/profiles",
+ "defaultProfile": "default"
+ },
+ "multiInstance": {
"strategy": "simple",
- "allocationPolicy": "fcfs"
+ "allocationPolicy": "fcfs",
+ "instancePortStart": 9868,
+ "instancePortEnd": 9968
+ },
+ "attach": {
+ "enabled": false,
+ "allowHosts": ["127.0.0.1", "localhost", "::1"],
+ "allowSchemes": ["ws", "wss"]
},
"timeouts": {
"actionSec": 30,
@@ -67,7 +96,18 @@ Override with: `PINCHTAB_CONFIG=/path/to/config.json`
}
```
-### Legacy Flat Format (Deprecated)
+### Section Semantics
+
+- `server`: PinchTab HTTP server settings.
+- `browser`: Chrome executable/runtime wiring used when PinchTab launches Chrome.
+- `instanceDefaults`: Default launch-time behavior for managed instances.
+- `security`: Feature gates for sensitive endpoints.
+- `profiles`: Shared profile storage model for both single-instance and multi-instance flows.
+- `multiInstance`: Orchestration strategy and instance port allocation.
+- `attach`: Policy for whether attach is allowed and which remote CDP targets are acceptable.
+- `timeouts`: PinchTab runtime timeouts.
+
+### Legacy Flat Format
Older flat format is still supported for backward compatibility:
@@ -88,76 +128,21 @@ Run `pinchtab config init` to generate a new config with the nested format.
Environment variables always take precedence over config file values.
-### Server
+### Operational Env Vars
| Variable | Default | Description |
|----------|---------|-------------|
| `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 |
-|----------|---------|-------------|
-| `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 |
-
-### Chrome/Browser
-
-| Variable | Default | Description |
-|----------|---------|-------------|
-| `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)
-
-| Variable | Default | Description |
-|----------|---------|-------------|
-| `PINCHTAB_STRATEGY` | `simple` | Strategy: `simple`, `explicit`, `simple-autorestart` |
-| `PINCHTAB_ALLOCATION_POLICY` | `fcfs` | Instance allocation: `fcfs`, `round_robin`, `random` |
-### Legacy Variables (Deprecated)
-
-The following `BRIDGE_*` variables still work but emit warnings. Use the `PINCHTAB_*` equivalents:
-
-| 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` |
+All behavior settings such as display mode, feature gates, profile defaults, attach policy, timeouts, and multi-instance strategy live in `config.json`.
## CLI Commands
-### pinchtab config init
+### `pinchtab config init`
Create a default config file:
@@ -165,9 +150,7 @@ Create a default config file:
pinchtab config init
```
-Creates `config.json` in the default location with sensible defaults.
-
-### pinchtab config show
+### `pinchtab config show`
Show current effective configuration:
@@ -175,9 +158,7 @@ Show current effective configuration:
pinchtab config show
```
-Shows all settings with their current values (from env vars, config file, or defaults).
-
-### pinchtab config path
+### `pinchtab config path`
Show config file path:
@@ -185,7 +166,7 @@ Show config file path:
pinchtab config path
```
-### pinchtab config validate
+### `pinchtab config validate`
Validate config file:
@@ -196,12 +177,13 @@ pinchtab config validate
Checks for:
- Valid port numbers (1-65535)
- Valid enum values (strategy, stealthLevel, tabEvictionPolicy, etc.)
+- Valid attach schemes (`ws`, `wss`)
- Valid timeout values (non-negative)
-- Instance port range (start <= end)
+- Valid instance port range (`start <= end`)
## Examples
-### Basic Setup (Defaults)
+### Basic Setup
```bash
pinchtab
@@ -216,6 +198,7 @@ PINCHTAB_TOKEN=my-secret-token pinchtab
```
Or in config file:
+
```json
{
"server": {
@@ -230,72 +213,64 @@ Or in config file:
PINCHTAB_BIND=0.0.0.0 PINCHTAB_TOKEN=secret pinchtab
```
-**⚠️ Always use a token when binding to 0.0.0.0**
+Always use a token when binding to `0.0.0.0`.
### Headed Mode for Debugging
-```bash
-PINCHTAB_HEADLESS=false pinchtab
-```
-
-Or in config file:
```json
{
- "chrome": {
- "headless": false
+ "instanceDefaults": {
+ "mode": "headed"
}
}
```
-### Maximum Stealth
+### Attach Policy
-```bash
-PINCHTAB_STEALTH=full pinchtab
+Enable attach mode only if you want PinchTab to accept attach requests to externally managed Chrome instances.
+
+```json
+{
+ "attach": {
+ "enabled": true,
+ "allowHosts": ["127.0.0.1", "localhost", "chrome.internal"],
+ "allowSchemes": ["ws", "wss"]
+ }
+}
```
-Higher stealth = more bot detection bypass, but slower.
+This is policy only. The actual `cdpUrl` belongs to the attach request, not global config.
-### Enable Dangerous Endpoints
+### Custom Ports
```bash
-PINCHTAB_ALLOW_EVALUATE=true \
-PINCHTAB_ALLOW_MACRO=true \
-PINCHTAB_TOKEN=secret \
-pinchtab
+PINCHTAB_PORT=8080 pinchtab dashboard
```
Or in config file:
+
```json
{
"server": {
- "token": "secret"
+ "port": "8080"
},
- "security": {
- "allowEvaluate": true,
- "allowMacro": true
+ "multiInstance": {
+ "instancePortStart": 8100,
+ "instancePortEnd": 8200
}
}
```
-### Custom Ports
-
-```bash
-PINCHTAB_PORT=8080 \
-PINCHTAB_INSTANCE_PORT_START=8100 \
-PINCHTAB_INSTANCE_PORT_END=8200 \
-pinchtab dashboard
-```
-
### Tab Eviction Policy
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
+- `reject` β€” return error
+- `close_oldest` β€” close oldest tab by creation time
+- `close_lru` β€” close least recently used tab
```json
{
- "chrome": {
+ "instanceDefaults": {
"maxTabs": 10,
"tabEvictionPolicy": "close_lru"
}
@@ -308,15 +283,17 @@ All enum fields are validated on load:
| 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` |
+| `instanceDefaults.mode` | `headless`, `headed` |
+| `instanceDefaults.stealthLevel` | `light`, `medium`, `full` |
+| `instanceDefaults.tabEvictionPolicy` | `reject`, `close_oldest`, `close_lru` |
+| `multiInstance.strategy` | `simple`, `explicit`, `simple-autorestart` |
+| `multiInstance.allocationPolicy` | `fcfs`, `round_robin`, `random` |
+| `attach.allowSchemes` | `ws`, `wss` |
Run `pinchtab config validate` to check your config file.
## Related Documentation
-- [API Reference](endpoints.md) β€” HTTP endpoints
-- [CLI Reference](cli-quick-reference.md) β€” Command line usage
-- [Instance API](instance-api.md) β€” Multi-instance management
+- [API Reference](endpoints.md)
+- [CLI Reference](cli-quick-reference.md)
+- [Instance API](instance-api.md)
diff --git a/internal/bridge/bridge_test.go b/internal/bridge/bridge_test.go
index 98af11ed..1420a11f 100644
--- a/internal/bridge/bridge_test.go
+++ b/internal/bridge/bridge_test.go
@@ -71,11 +71,9 @@ func TestRefCacheLookup(t *testing.T) {
func TestTabManagerRemoteAllocatorInitialization(t *testing.T) {
// Test that TabManager can be initialized without a valid browser context.
- // This is the case for remote allocators (CDP_URL mode) where the browser
- // context is established lazily.
- cfg := &config.RuntimeConfig{
- CdpURL: "ws://localhost:9222/devtools/browser/test",
- }
+ // This is the case for remote allocators where the browser context is
+ // established lazily.
+ cfg := &config.RuntimeConfig{}
// Use context.TODO() instead of nil to avoid lint warnings
ctx := context.TODO()
diff --git a/internal/config/config.go b/internal/config/config.go
index 29d662a1..6286e313 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -19,7 +19,6 @@ type RuntimeConfig struct {
Port string
InstancePortStart int // Starting port for instances (default 9868)
InstancePortEnd int // Ending port for instances (default 9968)
- CdpURL string
Token string
StateDir string
@@ -30,10 +29,12 @@ type RuntimeConfig struct {
AllowDownload bool
AllowUpload bool
- // Chrome settings
+ // Browser/instance settings
Headless bool
NoRestore bool
ProfileDir string
+ ProfilesBaseDir string
+ DefaultProfile string
ChromeVersion string
Timezone string
BlockImages bool
@@ -58,50 +59,64 @@ type RuntimeConfig struct {
// Orchestrator settings (dashboard mode only)
Strategy string // "simple" (default), "explicit", or "simple-autorestart"
AllocationPolicy string // "fcfs" (default), "round_robin", "random"
+
+ // Attach settings
+ AttachEnabled bool
+ AttachAllowHosts []string
+ AttachAllowSchemes []string
}
// --- Nested FileConfig structure (PR #91 model) ---
// FileConfig is the persistent configuration written to disk.
-// Uses nested sections for organization: Server, Chrome, Orchestrator, Timeouts.
+// Uses nested sections that match actual runtime ownership.
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"`
+ Server ServerConfig `json:"server,omitempty"`
+ Browser BrowserConfig `json:"browser,omitempty"`
+ InstanceDefaults InstanceDefaultsConfig `json:"instanceDefaults,omitempty"`
+ Security SecurityConfig `json:"security,omitempty"`
+ Profiles ProfilesConfig `json:"profiles,omitempty"`
+ MultiInstance MultiInstanceConfig `json:"multiInstance,omitempty"`
+ Attach AttachConfig `json:"attach,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"`
+ Port string `json:"port,omitempty"`
+ Bind string `json:"bind,omitempty"`
+ Token string `json:"token,omitempty"`
+ StateDir string `json:"stateDir,omitempty"`
+}
+
+// BrowserConfig holds Chrome executable/runtime wiring.
+type BrowserConfig struct {
+ ChromeVersion string `json:"version,omitempty"`
+ ChromeBinary string `json:"binary,omitempty"`
+ ChromeExtraFlags string `json:"extraFlags,omitempty"`
+ ExtensionPaths []string `json:"extensionPaths,omitempty"`
+}
+
+// InstanceDefaultsConfig holds the default behavior for a launched browser instance.
+type InstanceDefaultsConfig struct {
+ Mode string `json:"mode,omitempty"`
+ NoRestore *bool `json:"noRestore,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"`
+ UserAgent string `json:"userAgent,omitempty"`
+ NoAnimations *bool `json:"noAnimations,omitempty"`
+ StealthLevel string `json:"stealthLevel,omitempty"`
+ TabEvictionPolicy string `json:"tabEvictionPolicy,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"`
+// ProfilesConfig holds profile storage defaults.
+type ProfilesConfig struct {
+ BaseDir string `json:"baseDir,omitempty"`
+ DefaultProfile string `json:"defaultProfile,omitempty"`
}
// SecurityConfig holds security/permission settings.
@@ -113,10 +128,19 @@ type SecurityConfig struct {
AllowUpload *bool `json:"allowUpload,omitempty"`
}
-// OrchestratorConfig holds orchestrator/strategy settings.
-type OrchestratorConfig struct {
- Strategy string `json:"strategy,omitempty"`
- AllocationPolicy string `json:"allocationPolicy,omitempty"`
+// MultiInstanceConfig holds multi-instance orchestration settings.
+type MultiInstanceConfig struct {
+ Strategy string `json:"strategy,omitempty"`
+ AllocationPolicy string `json:"allocationPolicy,omitempty"`
+ InstancePortStart *int `json:"instancePortStart,omitempty"`
+ InstancePortEnd *int `json:"instancePortEnd,omitempty"`
+}
+
+// AttachConfig holds policy for attaching to externally managed Chrome instances.
+type AttachConfig struct {
+ Enabled *bool `json:"enabled,omitempty"`
+ AllowHosts []string `json:"allowHosts,omitempty"`
+ AllowSchemes []string `json:"allowSchemes,omitempty"`
}
// TimeoutsConfig holds timeout settings.
@@ -134,7 +158,6 @@ 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"`
@@ -156,19 +179,27 @@ func convertLegacyConfig(lc *legacyFileConfig) *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
+ // Browser / instance defaults
+ if lc.Headless != nil {
+ if *lc.Headless {
+ fc.InstanceDefaults.Mode = "headless"
+ } else {
+ fc.InstanceDefaults.Mode = "headed"
+ }
+ }
+ fc.InstanceDefaults.MaxTabs = lc.MaxTabs
if lc.NoRestore {
b := true
- fc.Chrome.NoRestore = &b
+ fc.InstanceDefaults.NoRestore = &b
+ }
+
+ // Profiles
+ if lc.ProfileDir != "" {
+ fc.Profiles.BaseDir = filepath.Dir(lc.ProfileDir)
+ fc.Profiles.DefaultProfile = filepath.Base(lc.ProfileDir)
}
// Security
@@ -182,6 +213,10 @@ func convertLegacyConfig(lc *legacyFileConfig) *FileConfig {
fc.Timeouts.ActionSec = lc.TimeoutSec
fc.Timeouts.NavigateSec = lc.NavigateSec
+ // Multi-instance
+ fc.MultiInstance.InstancePortStart = lc.InstancePortStart
+ fc.MultiInstance.InstancePortEnd = lc.InstancePortEnd
+
return fc
}
@@ -193,11 +228,29 @@ func isLegacyConfig(data []byte) bool {
return false
}
- // If "server" or "chrome" keys exist, it's new format
+ // If any new nested keys exist, it's new format
if _, hasServer := probe["server"]; hasServer {
return false
}
- if _, hasChrome := probe["chrome"]; hasChrome {
+ if _, hasBrowser := probe["browser"]; hasBrowser {
+ return false
+ }
+ if _, hasInstanceDefaults := probe["instanceDefaults"]; hasInstanceDefaults {
+ return false
+ }
+ if _, hasProfiles := probe["profiles"]; hasProfiles {
+ return false
+ }
+ if _, hasMultiInstance := probe["multiInstance"]; hasMultiInstance {
+ return false
+ }
+ if _, hasSecurity := probe["security"]; hasSecurity {
+ return false
+ }
+ if _, hasAttach := probe["attach"]; hasAttach {
+ return false
+ }
+ if _, hasTimeouts := probe["timeouts"]; hasTimeouts {
return false
}
@@ -234,102 +287,6 @@ func envIntOr(key string, fallback int) int {
return n
}
-// splitCommaPaths splits a comma-separated string into non-empty trimmed paths.
-func splitCommaPaths(s string) []string {
- if s == "" {
- return nil
- }
- parts := strings.Split(s, ",")
- out := make([]string, 0, len(parts))
- for _, p := range parts {
- p = strings.TrimSpace(p)
- if p != "" {
- out = append(out, p)
- }
- }
- if len(out) == 0 {
- return nil
- }
- return out
-}
-
-func envBoolOr(key string, fallback bool) bool {
- v, ok := os.LookupEnv(key)
- if !ok {
- return fallback
- }
- switch strings.ToLower(strings.TrimSpace(v)) {
- case "1", "true", "yes", "on":
- return true
- case "0", "false", "no", "off":
- return false
- default:
- return fallback
- }
-}
-
-func envMigrate(newKey, oldKey string) string {
- if v := os.Getenv(newKey); v != "" {
- return v
- }
- if v := os.Getenv(oldKey); v != "" {
- slog.Warn("deprecated env var, use "+newKey+" instead", "var", oldKey)
- return v
- }
- return ""
-}
-
-func envOrMigrate(newKey, oldKey, fallback string) string {
- if v := envMigrate(newKey, oldKey); v != "" {
- return v
- }
- return fallback
-}
-
-func envIntOrMigrate(newKey, oldKey string, fallback int) int {
- v := envMigrate(newKey, oldKey)
- if v == "" {
- return fallback
- }
- n, err := strconv.Atoi(v)
- if err != nil || n < 0 {
- return fallback
- }
- return n
-}
-
-func envBoolOrMigrate(newKey, oldKey string, fallback bool) bool {
- if v, ok := os.LookupEnv(newKey); ok {
- switch strings.ToLower(strings.TrimSpace(v)) {
- case "1", "true", "yes", "on":
- return true
- case "0", "false", "no", "off":
- return false
- default:
- return fallback
- }
- }
- if v, ok := os.LookupEnv(oldKey); ok {
- slog.Warn("deprecated env var, use "+newKey+" instead", "var", oldKey)
- switch strings.ToLower(strings.TrimSpace(v)) {
- case "1", "true", "yes", "on":
- return true
- case "0", "false", "no", "off":
- return false
- default:
- return fallback
- }
- }
- return fallback
-}
-
-func envMigrateIsSet(newKey, oldKey string) bool {
- if os.Getenv(newKey) != "" {
- return true
- }
- return os.Getenv(oldKey) != ""
-}
-
// homeDir returns the user's home directory, checking $HOME first for container compatibility
func homeDir() string {
if home := os.Getenv("HOME"); home != "" {
@@ -383,43 +340,69 @@ func (c *RuntimeConfig) ListenAddr() string {
return c.Bind + ":" + c.Port
}
+func modeToHeadless(mode string, fallback bool) bool {
+ switch strings.ToLower(strings.TrimSpace(mode)) {
+ case "":
+ return fallback
+ case "headless":
+ return true
+ case "headed":
+ return false
+ default:
+ return fallback
+ }
+}
+
+func finalizeProfileConfig(cfg *RuntimeConfig) {
+ if cfg.DefaultProfile == "" {
+ cfg.DefaultProfile = "default"
+ }
+ if cfg.ProfilesBaseDir == "" {
+ cfg.ProfilesBaseDir = filepath.Join(cfg.StateDir, "profiles")
+ }
+ if cfg.ProfileDir == "" {
+ cfg.ProfileDir = filepath.Join(cfg.ProfilesBaseDir, cfg.DefaultProfile)
+ }
+}
+
// 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: envIntOrMigrate("PINCHTAB_INSTANCE_PORT_START", "INSTANCE_PORT_START", 9868),
- InstancePortEnd: envIntOrMigrate("PINCHTAB_INSTANCE_PORT_END", "INSTANCE_PORT_END", 9968),
- CdpURL: os.Getenv("CDP_URL"),
- Token: envMigrate("PINCHTAB_TOKEN", "BRIDGE_TOKEN"),
- 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")),
- ChromeVersion: envOrMigrate("PINCHTAB_CHROME_VERSION", "BRIDGE_CHROME_VERSION", "144.0.7559.133"),
- Timezone: envMigrate("PINCHTAB_TIMEZONE", "BRIDGE_TIMEZONE"),
- BlockImages: envBoolOrMigrate("PINCHTAB_BLOCK_IMAGES", "BRIDGE_BLOCK_IMAGES", false),
- BlockMedia: envBoolOrMigrate("PINCHTAB_BLOCK_MEDIA", "BRIDGE_BLOCK_MEDIA", false),
- BlockAds: envBoolOrMigrate("PINCHTAB_BLOCK_ADS", "BRIDGE_BLOCK_ADS", false),
- MaxTabs: envIntOrMigrate("PINCHTAB_MAX_TABS", "BRIDGE_MAX_TABS", 20),
- MaxParallelTabs: envIntOr("PINCHTAB_MAX_PARALLEL_TABS", 0),
- ChromeBinary: envOr("CHROME_BIN", os.Getenv("CHROME_BINARY")),
- ChromeExtraFlags: os.Getenv("CHROME_FLAGS"),
- ExtensionPaths: splitCommaPaths(os.Getenv("CHROME_EXTENSION_PATHS")),
- UserAgent: envMigrate("PINCHTAB_USER_AGENT", "BRIDGE_USER_AGENT"),
- NoAnimations: envBoolOrMigrate("PINCHTAB_NO_ANIMATIONS", "BRIDGE_NO_ANIMATIONS", false),
- StealthLevel: envOrMigrate("PINCHTAB_STEALTH", "BRIDGE_STEALTH", "light"),
- TabEvictionPolicy: envOr("PINCHTAB_TAB_EVICTION_POLICY", "reject"),
+ // Server defaults + selected env vars
+ Bind: envOr("PINCHTAB_BIND", "127.0.0.1"),
+ Port: envOr("PINCHTAB_PORT", "9867"),
+ InstancePortStart: 9868,
+ InstancePortEnd: 9968,
+ Token: os.Getenv("PINCHTAB_TOKEN"),
+ StateDir: userConfigDir(),
+
+ // Security defaults
+ AllowEvaluate: false,
+ AllowMacro: false,
+ AllowScreencast: false,
+ AllowDownload: false,
+ AllowUpload: false,
+
+ // Browser / instance defaults
+ Headless: true,
+ NoRestore: false,
+ ProfileDir: "",
+ ProfilesBaseDir: "",
+ DefaultProfile: "default",
+ ChromeVersion: "144.0.7559.133",
+ Timezone: "",
+ BlockImages: false,
+ BlockMedia: false,
+ BlockAds: false,
+ MaxTabs: 20,
+ MaxParallelTabs: 0,
+ ChromeBinary: os.Getenv("CHROME_BIN"),
+ ChromeExtraFlags: "",
+ ExtensionPaths: nil,
+ UserAgent: "",
+ NoAnimations: false,
+ StealthLevel: "light",
+ TabEvictionPolicy: "reject",
// Timeout defaults
ActionTimeout: 30 * time.Second,
@@ -427,13 +410,19 @@ func Load() *RuntimeConfig {
ShutdownTimeout: 10 * time.Second,
WaitNavDelay: 1 * time.Second,
- // Orchestrator defaults + env vars
- Strategy: envOr("PINCHTAB_STRATEGY", "simple"),
- AllocationPolicy: envOr("PINCHTAB_ALLOCATION_POLICY", "fcfs"),
+ // Orchestrator defaults
+ Strategy: "simple",
+ AllocationPolicy: "fcfs",
+
+ // Attach defaults
+ AttachEnabled: false,
+ AttachAllowHosts: []string{"127.0.0.1", "localhost", "::1"},
+ AttachAllowSchemes: []string{"ws", "wss"},
}
+ finalizeProfileConfig(cfg)
// Load config file (supports both legacy flat and new nested format)
- configPath := envOrMigrate("PINCHTAB_CONFIG", "BRIDGE_CONFIG", filepath.Join(userConfigDir(), "config.json"))
+ configPath := envOr("PINCHTAB_CONFIG", filepath.Join(userConfigDir(), "config.json"))
data, err := os.ReadFile(configPath)
if err != nil {
@@ -472,6 +461,7 @@ func Load() *RuntimeConfig {
// Apply file config (only if env var NOT set)
applyFileConfig(cfg, fc)
+ finalizeProfileConfig(cfg)
return cfg
}
@@ -480,145 +470,169 @@ func Load() *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") {
+ if fc.Server.Port != "" && os.Getenv("PINCHTAB_PORT") == "" {
cfg.Port = fc.Server.Port
}
- if fc.Server.Bind != "" && !envMigrateIsSet("PINCHTAB_BIND", "BRIDGE_BIND") {
+ if fc.Server.Bind != "" && os.Getenv("PINCHTAB_BIND") == "" {
cfg.Bind = fc.Server.Bind
}
- if fc.Server.Token != "" && !envMigrateIsSet("PINCHTAB_TOKEN", "BRIDGE_TOKEN") {
+ if fc.Server.Token != "" && os.Getenv("PINCHTAB_TOKEN") == "" {
cfg.Token = fc.Server.Token
}
- if fc.Server.StateDir != "" && !envMigrateIsSet("PINCHTAB_STATE_DIR", "BRIDGE_STATE_DIR") {
+ if fc.Server.StateDir != "" {
cfg.StateDir = fc.Server.StateDir
}
- if fc.Server.CdpURL != "" && os.Getenv("CDP_URL") == "" {
- cfg.CdpURL = fc.Server.CdpURL
- }
- if fc.Server.InstancePortStart != nil && !envMigrateIsSet("PINCHTAB_INSTANCE_PORT_START", "INSTANCE_PORT_START") {
- cfg.InstancePortStart = *fc.Server.InstancePortStart
- }
- if fc.Server.InstancePortEnd != nil && !envMigrateIsSet("PINCHTAB_INSTANCE_PORT_END", "INSTANCE_PORT_END") {
- cfg.InstancePortEnd = *fc.Server.InstancePortEnd
- }
-
// Security
- if fc.Security.AllowEvaluate != nil && !envMigrateIsSet("PINCHTAB_ALLOW_EVALUATE", "BRIDGE_ALLOW_EVALUATE") {
+ if fc.Security.AllowEvaluate != nil {
cfg.AllowEvaluate = *fc.Security.AllowEvaluate
}
- if fc.Security.AllowMacro != nil && !envMigrateIsSet("PINCHTAB_ALLOW_MACRO", "BRIDGE_ALLOW_MACRO") {
+ if fc.Security.AllowMacro != nil {
cfg.AllowMacro = *fc.Security.AllowMacro
}
- if fc.Security.AllowScreencast != nil && !envMigrateIsSet("PINCHTAB_ALLOW_SCREENCAST", "BRIDGE_ALLOW_SCREENCAST") {
+ if fc.Security.AllowScreencast != nil {
cfg.AllowScreencast = *fc.Security.AllowScreencast
}
- if fc.Security.AllowDownload != nil && !envMigrateIsSet("PINCHTAB_ALLOW_DOWNLOAD", "BRIDGE_ALLOW_DOWNLOAD") {
+ if fc.Security.AllowDownload != nil {
cfg.AllowDownload = *fc.Security.AllowDownload
}
- if fc.Security.AllowUpload != nil && !envMigrateIsSet("PINCHTAB_ALLOW_UPLOAD", "BRIDGE_ALLOW_UPLOAD") {
+ if fc.Security.AllowUpload != nil {
cfg.AllowUpload = *fc.Security.AllowUpload
}
- // Chrome
- if fc.Chrome.Headless != nil && !envMigrateIsSet("PINCHTAB_HEADLESS", "BRIDGE_HEADLESS") {
- cfg.Headless = *fc.Chrome.Headless
+ // Browser
+ if fc.Browser.ChromeVersion != "" {
+ cfg.ChromeVersion = fc.Browser.ChromeVersion
+ }
+ if fc.Browser.ChromeBinary != "" && os.Getenv("CHROME_BIN") == "" {
+ cfg.ChromeBinary = fc.Browser.ChromeBinary
}
- if fc.Chrome.NoRestore != nil && !envMigrateIsSet("PINCHTAB_NO_RESTORE", "BRIDGE_NO_RESTORE") {
- cfg.NoRestore = *fc.Chrome.NoRestore
+ if fc.Browser.ChromeExtraFlags != "" {
+ cfg.ChromeExtraFlags = fc.Browser.ChromeExtraFlags
}
- if fc.Chrome.ProfileDir != "" && !envMigrateIsSet("PINCHTAB_PROFILE_DIR", "BRIDGE_PROFILE") {
- cfg.ProfileDir = fc.Chrome.ProfileDir
+ if len(fc.Browser.ExtensionPaths) > 0 {
+ cfg.ExtensionPaths = fc.Browser.ExtensionPaths
}
- if fc.Chrome.ChromeVersion != "" && !envMigrateIsSet("PINCHTAB_CHROME_VERSION", "BRIDGE_CHROME_VERSION") {
- cfg.ChromeVersion = fc.Chrome.ChromeVersion
+
+ // Instance defaults
+ if fc.InstanceDefaults.Mode != "" {
+ cfg.Headless = modeToHeadless(fc.InstanceDefaults.Mode, cfg.Headless)
}
- if fc.Chrome.Timezone != "" && !envMigrateIsSet("PINCHTAB_TIMEZONE", "BRIDGE_TIMEZONE") {
- cfg.Timezone = fc.Chrome.Timezone
+ if fc.InstanceDefaults.NoRestore != nil {
+ cfg.NoRestore = *fc.InstanceDefaults.NoRestore
}
- if fc.Chrome.BlockImages != nil && !envMigrateIsSet("PINCHTAB_BLOCK_IMAGES", "BRIDGE_BLOCK_IMAGES") {
- cfg.BlockImages = *fc.Chrome.BlockImages
+ if fc.InstanceDefaults.Timezone != "" {
+ cfg.Timezone = fc.InstanceDefaults.Timezone
}
- if fc.Chrome.BlockMedia != nil && !envMigrateIsSet("PINCHTAB_BLOCK_MEDIA", "BRIDGE_BLOCK_MEDIA") {
- cfg.BlockMedia = *fc.Chrome.BlockMedia
+ if fc.InstanceDefaults.BlockImages != nil {
+ cfg.BlockImages = *fc.InstanceDefaults.BlockImages
}
- if fc.Chrome.BlockAds != nil && !envMigrateIsSet("PINCHTAB_BLOCK_ADS", "BRIDGE_BLOCK_ADS") {
- cfg.BlockAds = *fc.Chrome.BlockAds
+ if fc.InstanceDefaults.BlockMedia != nil {
+ cfg.BlockMedia = *fc.InstanceDefaults.BlockMedia
}
- if fc.Chrome.MaxTabs != nil && !envMigrateIsSet("PINCHTAB_MAX_TABS", "BRIDGE_MAX_TABS") {
- cfg.MaxTabs = *fc.Chrome.MaxTabs
+ if fc.InstanceDefaults.BlockAds != nil {
+ cfg.BlockAds = *fc.InstanceDefaults.BlockAds
}
- if fc.Chrome.MaxParallelTabs != nil && os.Getenv("PINCHTAB_MAX_PARALLEL_TABS") == "" {
- cfg.MaxParallelTabs = *fc.Chrome.MaxParallelTabs
+ if fc.InstanceDefaults.MaxTabs != nil {
+ cfg.MaxTabs = *fc.InstanceDefaults.MaxTabs
}
- if fc.Chrome.ChromeBinary != "" && os.Getenv("CHROME_BIN") == "" && os.Getenv("CHROME_BINARY") == "" {
- cfg.ChromeBinary = fc.Chrome.ChromeBinary
+ if fc.InstanceDefaults.MaxParallelTabs != nil {
+ cfg.MaxParallelTabs = *fc.InstanceDefaults.MaxParallelTabs
}
- if fc.Chrome.ChromeExtraFlags != "" && os.Getenv("CHROME_FLAGS") == "" {
- cfg.ChromeExtraFlags = fc.Chrome.ChromeExtraFlags
+ if fc.InstanceDefaults.UserAgent != "" {
+ cfg.UserAgent = fc.InstanceDefaults.UserAgent
}
- if len(fc.Chrome.ExtensionPaths) > 0 && os.Getenv("CHROME_EXTENSION_PATHS") == "" {
- cfg.ExtensionPaths = fc.Chrome.ExtensionPaths
+ if fc.InstanceDefaults.NoAnimations != nil {
+ cfg.NoAnimations = *fc.InstanceDefaults.NoAnimations
}
- if fc.Chrome.UserAgent != "" && !envMigrateIsSet("PINCHTAB_USER_AGENT", "BRIDGE_USER_AGENT") {
- cfg.UserAgent = fc.Chrome.UserAgent
+ if fc.InstanceDefaults.StealthLevel != "" {
+ cfg.StealthLevel = fc.InstanceDefaults.StealthLevel
}
- if fc.Chrome.NoAnimations != nil && !envMigrateIsSet("PINCHTAB_NO_ANIMATIONS", "BRIDGE_NO_ANIMATIONS") {
- cfg.NoAnimations = *fc.Chrome.NoAnimations
+ if fc.InstanceDefaults.TabEvictionPolicy != "" {
+ cfg.TabEvictionPolicy = fc.InstanceDefaults.TabEvictionPolicy
}
- if fc.Chrome.StealthLevel != "" && !envMigrateIsSet("PINCHTAB_STEALTH", "BRIDGE_STEALTH") {
- cfg.StealthLevel = fc.Chrome.StealthLevel
+
+ // Profiles
+ if fc.Profiles.BaseDir != "" {
+ cfg.ProfilesBaseDir = fc.Profiles.BaseDir
}
- if fc.Chrome.TabEvictionPolicy != "" && os.Getenv("PINCHTAB_TAB_EVICTION_POLICY") == "" {
- cfg.TabEvictionPolicy = fc.Chrome.TabEvictionPolicy
+ if fc.Profiles.DefaultProfile != "" {
+ cfg.DefaultProfile = fc.Profiles.DefaultProfile
}
+ cfg.ProfileDir = ""
- // Orchestrator
- if fc.Orchestrator.Strategy != "" && os.Getenv("PINCHTAB_STRATEGY") == "" {
- cfg.Strategy = fc.Orchestrator.Strategy
+ // Multi-instance
+ if fc.MultiInstance.Strategy != "" {
+ cfg.Strategy = fc.MultiInstance.Strategy
}
- if fc.Orchestrator.AllocationPolicy != "" && os.Getenv("PINCHTAB_ALLOCATION_POLICY") == "" {
- cfg.AllocationPolicy = fc.Orchestrator.AllocationPolicy
+ if fc.MultiInstance.AllocationPolicy != "" {
+ cfg.AllocationPolicy = fc.MultiInstance.AllocationPolicy
+ }
+ if fc.MultiInstance.InstancePortStart != nil {
+ cfg.InstancePortStart = *fc.MultiInstance.InstancePortStart
+ }
+ if fc.MultiInstance.InstancePortEnd != nil {
+ cfg.InstancePortEnd = *fc.MultiInstance.InstancePortEnd
+ }
+
+ // Attach
+ if fc.Attach.Enabled != nil {
+ cfg.AttachEnabled = *fc.Attach.Enabled
+ }
+ if len(fc.Attach.AllowHosts) > 0 {
+ cfg.AttachAllowHosts = append([]string(nil), fc.Attach.AllowHosts...)
+ }
+ if len(fc.Attach.AllowSchemes) > 0 {
+ cfg.AttachAllowSchemes = append([]string(nil), fc.Attach.AllowSchemes...)
}
// Timeouts
- if fc.Timeouts.ActionSec > 0 && !envMigrateIsSet("PINCHTAB_TIMEOUT", "BRIDGE_TIMEOUT") {
+ if fc.Timeouts.ActionSec > 0 {
cfg.ActionTimeout = time.Duration(fc.Timeouts.ActionSec) * time.Second
}
- if fc.Timeouts.NavigateSec > 0 && !envMigrateIsSet("PINCHTAB_NAV_TIMEOUT", "BRIDGE_NAV_TIMEOUT") {
+ if fc.Timeouts.NavigateSec > 0 {
cfg.NavigateTimeout = time.Duration(fc.Timeouts.NavigateSec) * time.Second
}
- if fc.Timeouts.ShutdownSec > 0 && os.Getenv("PINCHTAB_SHUTDOWN_TIMEOUT") == "" {
+ if fc.Timeouts.ShutdownSec > 0 {
cfg.ShutdownTimeout = time.Duration(fc.Timeouts.ShutdownSec) * time.Second
}
- if fc.Timeouts.WaitNavMs > 0 && os.Getenv("PINCHTAB_WAIT_NAV_DELAY") == "" {
+ if fc.Timeouts.WaitNavMs > 0 {
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{
Server: ServerConfig{
- Port: "9867",
- Bind: "127.0.0.1",
- StateDir: userConfigDir(),
- InstancePortStart: &start,
- InstancePortEnd: &end,
+ Port: "9867",
+ Bind: "127.0.0.1",
+ StateDir: userConfigDir(),
},
- Chrome: ChromeConfig{
- Headless: &h,
- ProfileDir: filepath.Join(userConfigDir(), "chrome-profile"),
+ Browser: BrowserConfig{
+ ChromeVersion: "144.0.7559.133",
+ },
+ InstanceDefaults: InstanceDefaultsConfig{
+ Mode: "headless",
MaxTabs: &maxTabs,
StealthLevel: "light",
TabEvictionPolicy: "reject",
},
- Orchestrator: OrchestratorConfig{
- Strategy: "simple",
- AllocationPolicy: "fcfs",
+ Profiles: ProfilesConfig{
+ BaseDir: filepath.Join(userConfigDir(), "profiles"),
+ DefaultProfile: "default",
+ },
+ MultiInstance: MultiInstanceConfig{
+ Strategy: "simple",
+ AllocationPolicy: "fcfs",
+ InstancePortStart: &start,
+ InstancePortEnd: &end,
+ },
+ Attach: AttachConfig{
+ AllowHosts: []string{"127.0.0.1", "localhost", "::1"},
+ AllowSchemes: []string{"ws", "wss"},
},
Timeouts: TimeoutsConfig{
ActionSec: 30,
@@ -629,6 +643,95 @@ func DefaultFileConfig() FileConfig {
}
}
+// FileConfigFromRuntime converts the effective runtime configuration back into a
+// nested file configuration shape. This is primarily used when orchestrator-launched
+// child instances need a generated config file.
+func FileConfigFromRuntime(cfg *RuntimeConfig) FileConfig {
+ if cfg == nil {
+ return DefaultFileConfig()
+ }
+
+ noRestore := cfg.NoRestore
+ blockImages := cfg.BlockImages
+ blockMedia := cfg.BlockMedia
+ blockAds := cfg.BlockAds
+ maxTabs := cfg.MaxTabs
+ maxParallelTabs := cfg.MaxParallelTabs
+ noAnimations := cfg.NoAnimations
+ allowEvaluate := cfg.AllowEvaluate
+ allowMacro := cfg.AllowMacro
+ allowScreencast := cfg.AllowScreencast
+ allowDownload := cfg.AllowDownload
+ allowUpload := cfg.AllowUpload
+ attachEnabled := cfg.AttachEnabled
+ start := cfg.InstancePortStart
+ end := cfg.InstancePortEnd
+
+ mode := "headless"
+ if !cfg.Headless {
+ mode = "headed"
+ }
+
+ fc := FileConfig{
+ Server: ServerConfig{
+ Port: cfg.Port,
+ Bind: cfg.Bind,
+ Token: cfg.Token,
+ StateDir: cfg.StateDir,
+ },
+ Browser: BrowserConfig{
+ ChromeVersion: cfg.ChromeVersion,
+ ChromeBinary: cfg.ChromeBinary,
+ ChromeExtraFlags: cfg.ChromeExtraFlags,
+ ExtensionPaths: append([]string(nil), cfg.ExtensionPaths...),
+ },
+ InstanceDefaults: InstanceDefaultsConfig{
+ Mode: mode,
+ NoRestore: &noRestore,
+ Timezone: cfg.Timezone,
+ BlockImages: &blockImages,
+ BlockMedia: &blockMedia,
+ BlockAds: &blockAds,
+ MaxTabs: &maxTabs,
+ MaxParallelTabs: &maxParallelTabs,
+ UserAgent: cfg.UserAgent,
+ NoAnimations: &noAnimations,
+ StealthLevel: cfg.StealthLevel,
+ TabEvictionPolicy: cfg.TabEvictionPolicy,
+ },
+ Security: SecurityConfig{
+ AllowEvaluate: &allowEvaluate,
+ AllowMacro: &allowMacro,
+ AllowScreencast: &allowScreencast,
+ AllowDownload: &allowDownload,
+ AllowUpload: &allowUpload,
+ },
+ Profiles: ProfilesConfig{
+ BaseDir: cfg.ProfilesBaseDir,
+ DefaultProfile: cfg.DefaultProfile,
+ },
+ MultiInstance: MultiInstanceConfig{
+ Strategy: cfg.Strategy,
+ AllocationPolicy: cfg.AllocationPolicy,
+ InstancePortStart: &start,
+ InstancePortEnd: &end,
+ },
+ Attach: AttachConfig{
+ Enabled: &attachEnabled,
+ AllowHosts: append([]string(nil), cfg.AttachAllowHosts...),
+ AllowSchemes: append([]string(nil), cfg.AttachAllowSchemes...),
+ },
+ Timeouts: TimeoutsConfig{
+ ActionSec: int(cfg.ActionTimeout / time.Second),
+ NavigateSec: int(cfg.NavigateTimeout / time.Second),
+ ShutdownSec: int(cfg.ShutdownTimeout / time.Second),
+ WaitNavMs: int(cfg.WaitNavDelay / time.Millisecond),
+ },
+ }
+
+ return fc
+}
+
// HandleConfigCommand handles `pinchtab config <subcommand>`.
func HandleConfigCommand(cfg *RuntimeConfig) {
if len(os.Args) < 3 {
@@ -701,9 +804,12 @@ func handleConfigInit() {
"port": "9867",
"token": "your-secret-token"
},
- "chrome": {
- "headless": true,
+ "instanceDefaults": {
+ "mode": "headless",
"maxTabs": 20
+ },
+ "profiles": {
+ "defaultProfile": "default"
}
}`)
}
@@ -716,7 +822,6 @@ func handleConfigShow(cfg *RuntimeConfig) {
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:")
@@ -726,19 +831,26 @@ func handleConfigShow(cfg *RuntimeConfig) {
fmt.Printf(" Download: %v\n", cfg.AllowDownload)
fmt.Printf(" Upload: %v\n", cfg.AllowUpload)
fmt.Println()
- fmt.Println("Chrome:")
+ fmt.Println("Browser / Instance Defaults:")
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(" Profiles Dir: %s\n", cfg.ProfilesBaseDir)
+ fmt.Printf(" Default Profile: %s\n", cfg.DefaultProfile)
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.Println("Multi-Instance:")
fmt.Printf(" Strategy: %s\n", cfg.Strategy)
fmt.Printf(" Allocation: %s\n", cfg.AllocationPolicy)
fmt.Println()
+ fmt.Println("Attach:")
+ fmt.Printf(" Enabled: %v\n", cfg.AttachEnabled)
+ fmt.Printf(" Allow Hosts: %v\n", cfg.AttachAllowHosts)
+ fmt.Printf(" Allow Schemes: %v\n", cfg.AttachAllowSchemes)
+ fmt.Println()
fmt.Println("Timeouts:")
fmt.Printf(" Action: %v\n", cfg.ActionTimeout)
fmt.Printf(" Navigate: %v\n", cfg.NavigateTimeout)
@@ -746,7 +858,7 @@ func handleConfigShow(cfg *RuntimeConfig) {
}
func handleConfigPath() {
- configPath := envOrMigrate("PINCHTAB_CONFIG", "BRIDGE_CONFIG", filepath.Join(userConfigDir(), "config.json"))
+ configPath := envOr("PINCHTAB_CONFIG", filepath.Join(userConfigDir(), "config.json"))
fmt.Println(configPath)
}
@@ -756,10 +868,10 @@ func handleConfigSet() {
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(" pinchtab config set instanceDefaults.mode headed")
+ fmt.Println(" pinchtab config set multiInstance.strategy explicit")
fmt.Println()
- fmt.Println("Sections: server, chrome, security, orchestrator, timeouts")
+ fmt.Println("Sections: server, browser, instanceDefaults, security, profiles, multiInstance, attach, timeouts")
os.Exit(1)
}
@@ -806,7 +918,7 @@ func handleConfigPatch() {
fmt.Println()
fmt.Println("Examples:")
fmt.Println(` pinchtab config patch '{"server": {"port": "8080"}}'`)
- fmt.Println(` pinchtab config patch '{"chrome": {"headless": false, "maxTabs": 50}}'`)
+ fmt.Println(` pinchtab config patch '{"instanceDefaults": {"mode": "headed", "maxTabs": 50}}'`)
os.Exit(1)
}
@@ -847,7 +959,7 @@ func handleConfigPatch() {
}
func handleConfigValidate() {
- configPath := envOrMigrate("PINCHTAB_CONFIG", "BRIDGE_CONFIG", filepath.Join(userConfigDir(), "config.json"))
+ configPath := envOr("PINCHTAB_CONFIG", filepath.Join(userConfigDir(), "config.json"))
data, err := os.ReadFile(configPath)
if err != nil {
@@ -887,13 +999,6 @@ func handleConfigValidate() {
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 == "" {
diff --git a/internal/config/config_test.go b/internal/config/config_test.go
index d9b68aa0..56d31854 100644
--- a/internal/config/config_test.go
+++ b/internal/config/config_test.go
@@ -45,32 +45,6 @@ func TestEnvIntOr(t *testing.T) {
}
}
-func TestEnvBoolOr(t *testing.T) {
- key := "PINCHTAB_TEST_BOOL"
- fallback := true
-
- _ = os.Unsetenv(key)
- if got := envBoolOr(key, fallback); got != fallback {
- t.Errorf("envBoolOr() = %v, want %v", got, fallback)
- }
-
- tests := []struct {
- val string
- want bool
- }{
- {"1", true}, {"true", true}, {"yes", true}, {"on", true},
- {"0", false}, {"false", false}, {"no", false}, {"off", false},
- {"garbage", true}, // should return fallback
- }
-
- for _, tt := range tests {
- _ = os.Setenv(key, tt.val)
- if got := envBoolOr(key, fallback); got != tt.want {
- t.Errorf("envBoolOr(%q) = %v, want %v", tt.val, got, tt.want)
- }
- }
-}
-
func TestMaskToken(t *testing.T) {
tests := []struct {
token string
@@ -113,6 +87,12 @@ func TestLoadConfigDefaults(t *testing.T) {
if cfg.TabEvictionPolicy != "reject" {
t.Errorf("default TabEvictionPolicy = %v, want reject", cfg.TabEvictionPolicy)
}
+ if cfg.AttachEnabled {
+ t.Errorf("default AttachEnabled = %v, want false", cfg.AttachEnabled)
+ }
+ if len(cfg.AttachAllowSchemes) != 2 || cfg.AttachAllowSchemes[0] != "ws" || cfg.AttachAllowSchemes[1] != "wss" {
+ t.Errorf("default AttachAllowSchemes = %v, want [ws wss]", cfg.AttachAllowSchemes)
+ }
}
func TestLoadConfigEnvOverrides(t *testing.T) {
@@ -120,63 +100,50 @@ func TestLoadConfigEnvOverrides(t *testing.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")
+ _ = os.Setenv("PINCHTAB_BIND", "0.0.0.0")
+ _ = os.Setenv("PINCHTAB_TOKEN", "secret")
+ _ = os.Setenv("CHROME_BIN", "/tmp/chrome")
defer func() {
_ = os.Unsetenv("PINCHTAB_CONFIG")
_ = os.Unsetenv("PINCHTAB_PORT")
- _ = os.Unsetenv("PINCHTAB_ALLOW_EVALUATE")
- _ = os.Unsetenv("PINCHTAB_STRATEGY")
+ _ = os.Unsetenv("PINCHTAB_BIND")
+ _ = os.Unsetenv("PINCHTAB_TOKEN")
+ _ = os.Unsetenv("CHROME_BIN")
}()
cfg := Load()
if cfg.Port != "1234" {
t.Errorf("env Port = %v, want 1234", cfg.Port)
}
- if !cfg.AllowEvaluate {
- t.Errorf("env AllowEvaluate = %v, want true", cfg.AllowEvaluate)
+ if cfg.Bind != "0.0.0.0" {
+ t.Errorf("env Bind = %v, want 0.0.0.0", cfg.Bind)
}
- if cfg.Strategy != "explicit" {
- t.Errorf("env Strategy = %v, want explicit", cfg.Strategy)
+ if cfg.Token != "secret" {
+ t.Errorf("env Token = %v, want secret", cfg.Token)
}
-}
-
-func TestLegacyBridgeEnvFallback(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("BRIDGE_PORT", "5555")
- _ = os.Setenv("BRIDGE_ALLOW_EVALUATE", "true")
- defer func() {
- _ = os.Unsetenv("PINCHTAB_CONFIG")
- _ = os.Unsetenv("BRIDGE_PORT")
- _ = os.Unsetenv("BRIDGE_ALLOW_EVALUATE")
- }()
-
- cfg := Load()
- if cfg.Port != "5555" {
- t.Errorf("legacy fallback Port = %v, want 5555", cfg.Port)
- }
- if !cfg.AllowEvaluate {
- t.Errorf("legacy fallback AllowEvaluate = %v, want true", cfg.AllowEvaluate)
+ if cfg.ChromeBinary != "/tmp/chrome" {
+ t.Errorf("env ChromeBinary = %v, want /tmp/chrome", cfg.ChromeBinary)
}
}
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"))
+ tmpDir := t.TempDir()
+ configPath := filepath.Join(tmpDir, "config.json")
+ _ = os.Setenv("PINCHTAB_CONFIG", configPath)
_ = os.Setenv("PINCHTAB_PORT", "7777")
- _ = os.Setenv("BRIDGE_PORT", "8888")
defer func() {
_ = os.Unsetenv("PINCHTAB_CONFIG")
_ = os.Unsetenv("PINCHTAB_PORT")
- _ = os.Unsetenv("BRIDGE_PORT")
}()
+ if err := os.WriteFile(configPath, []byte(`{"server":{"port":"8888"}}`), 0644); err != nil {
+ t.Fatal(err)
+ }
+
cfg := Load()
if cfg.Port != "7777" {
- t.Errorf("precedence Port = %v, want 7777 (PINCHTAB_ should win)", cfg.Port)
+ t.Errorf("precedence Port = %v, want 7777", cfg.Port)
}
}
@@ -188,11 +155,14 @@ func TestDefaultFileConfig(t *testing.T) {
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.InstanceDefaults.Mode != "headless" {
+ t.Errorf("DefaultFileConfig.InstanceDefaults.Mode = %v, want headless", fc.InstanceDefaults.Mode)
+ }
+ if fc.MultiInstance.Strategy != "simple" {
+ t.Errorf("DefaultFileConfig.MultiInstance.Strategy = %v, want simple", fc.MultiInstance.Strategy)
}
- if fc.Orchestrator.Strategy != "simple" {
- t.Errorf("DefaultFileConfig.Orchestrator.Strategy = %v, want simple", fc.Orchestrator.Strategy)
+ if len(fc.Attach.AllowSchemes) != 2 || fc.Attach.AllowSchemes[0] != "ws" || fc.Attach.AllowSchemes[1] != "wss" {
+ t.Errorf("DefaultFileConfig.Attach.AllowSchemes = %v, want [ws wss]", fc.Attach.AllowSchemes)
}
}
@@ -212,8 +182,8 @@ func TestLoadNestedConfig(t *testing.T) {
"bind": "0.0.0.0",
"token": "secret123"
},
- "chrome": {
- "headless": false,
+ "instanceDefaults": {
+ "mode": "headed",
"maxTabs": 50,
"stealthLevel": "full",
"tabEvictionPolicy": "close_oldest"
@@ -221,10 +191,15 @@ func TestLoadNestedConfig(t *testing.T) {
"security": {
"allowEvaluate": true
},
- "orchestrator": {
+ "multiInstance": {
"strategy": "explicit",
"allocationPolicy": "round_robin"
},
+ "attach": {
+ "enabled": true,
+ "allowHosts": ["localhost", "chrome.internal"],
+ "allowSchemes": ["wss"]
+ },
"timeouts": {
"actionSec": 60,
"navigateSec": 120
@@ -247,7 +222,7 @@ func TestLoadNestedConfig(t *testing.T) {
t.Errorf("nested Token = %v, want secret123", cfg.Token)
}
- // Chrome
+ // Instance defaults
if cfg.Headless != false {
t.Errorf("nested Headless = %v, want false", cfg.Headless)
}
@@ -266,13 +241,22 @@ func TestLoadNestedConfig(t *testing.T) {
t.Errorf("nested AllowEvaluate = %v, want true", cfg.AllowEvaluate)
}
- // Orchestrator
+ // Multi-instance
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)
}
+ if cfg.AttachEnabled != true {
+ t.Errorf("nested AttachEnabled = %v, want true", cfg.AttachEnabled)
+ }
+ if len(cfg.AttachAllowHosts) != 2 || cfg.AttachAllowHosts[1] != "chrome.internal" {
+ t.Errorf("nested AttachAllowHosts = %v, want [localhost chrome.internal]", cfg.AttachAllowHosts)
+ }
+ if len(cfg.AttachAllowSchemes) != 1 || cfg.AttachAllowSchemes[0] != "wss" {
+ t.Errorf("nested AttachAllowSchemes = %v, want [wss]", cfg.AttachAllowSchemes)
+ }
// Timeouts
if cfg.ActionTimeout != 60*time.Second {
@@ -335,11 +319,9 @@ func TestEnvOverridesNestedConfig(t *testing.T) {
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
@@ -347,7 +329,7 @@ func TestEnvOverridesNestedConfig(t *testing.T) {
"server": {
"port": "8888"
},
- "orchestrator": {
+ "multiInstance": {
"strategy": "explicit"
}
}`
@@ -361,8 +343,8 @@ func TestEnvOverridesNestedConfig(t *testing.T) {
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)
+ if cfg.Strategy != "explicit" {
+ t.Errorf("file should supply Strategy = %v, want explicit", cfg.Strategy)
}
}
@@ -391,8 +373,13 @@ func TestIsLegacyConfig(t *testing.T) {
isLegacy: false,
},
{
- name: "nested format with chrome",
- json: `{"chrome": {"headless": true}}`,
+ name: "nested format with instanceDefaults",
+ json: `{"instanceDefaults": {"mode": "headless"}}`,
+ isLegacy: false,
+ },
+ {
+ name: "nested format with attach",
+ json: `{"attach": {"enabled": true}}`,
isLegacy: false,
},
{
@@ -445,11 +432,11 @@ func TestConvertLegacyConfig(t *testing.T) {
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.InstanceDefaults.Mode != "headed" {
+ t.Errorf("converted InstanceDefaults.Mode = %v, want headed", fc.InstanceDefaults.Mode)
}
- if *fc.Chrome.MaxTabs != 25 {
- t.Errorf("converted Chrome.MaxTabs = %v, want 25", *fc.Chrome.MaxTabs)
+ if *fc.InstanceDefaults.MaxTabs != 25 {
+ t.Errorf("converted InstanceDefaults.MaxTabs = %v, want 25", *fc.InstanceDefaults.MaxTabs)
}
if *fc.Security.AllowEvaluate != true {
t.Errorf("converted Security.AllowEvaluate = %v, want true", *fc.Security.AllowEvaluate)
@@ -479,8 +466,8 @@ func TestDefaultFileConfigJSON(t *testing.T) {
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)
+ if parsed.InstanceDefaults.Mode != "headless" {
+ t.Errorf("round-trip InstanceDefaults.Mode = %v, want headless", parsed.InstanceDefaults.Mode)
}
}
@@ -495,18 +482,7 @@ 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",
+ "CHROME_BIN",
}
for _, v := range envVars {
_ = os.Unsetenv(v)
diff --git a/internal/config/editor.go b/internal/config/editor.go
index 91c01b76..d44bda39 100644
--- a/internal/config/editor.go
+++ b/internal/config/editor.go
@@ -9,7 +9,7 @@ import (
"strings"
)
-// SetConfigValue sets a dotted path in FileConfig (e.g., "server.port", "chrome.headless").
+// SetConfigValue sets a dotted path in FileConfig (e.g., "server.port", "instanceDefaults.mode").
// Returns the updated FileConfig and any error.
func SetConfigValue(fc *FileConfig, path string, value string) error {
parts := strings.SplitN(path, ".", 2)
@@ -22,16 +22,22 @@ func SetConfigValue(fc *FileConfig, path string, value string) error {
switch section {
case "server":
return setServerField(&fc.Server, field, value)
- case "chrome":
- return setChromeField(&fc.Chrome, field, value)
+ case "browser":
+ return setBrowserField(&fc.Browser, field, value)
+ case "instanceDefaults":
+ return setInstanceDefaultsField(&fc.InstanceDefaults, field, value)
case "security":
return setSecurityField(&fc.Security, field, value)
- case "orchestrator":
- return setOrchestratorField(&fc.Orchestrator, field, value)
+ case "profiles":
+ return setProfilesField(&fc.Profiles, field, value)
+ case "multiInstance":
+ return setMultiInstanceField(&fc.MultiInstance, field, value)
+ case "attach":
+ return setAttachField(&fc.Attach, field, value)
case "timeouts":
return setTimeoutsField(&fc.Timeouts, field, value)
default:
- return fmt.Errorf("unknown section %q (valid: server, chrome, security, orchestrator, timeouts)", section)
+ return fmt.Errorf("unknown section %q (valid: server, browser, instanceDefaults, security, profiles, multiInstance, attach, timeouts)", section)
}
}
@@ -45,86 +51,74 @@ func setServerField(s *ServerConfig, field, value string) error {
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 {
+func setBrowserField(b *BrowserConfig, 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 "version":
+ b.ChromeVersion = value
+ case "binary":
+ b.ChromeBinary = value
+ case "extraFlags":
+ b.ChromeExtraFlags = value
+ default:
+ return fmt.Errorf("unknown field browser.%s", field)
+ }
+ return nil
+}
+
+func setInstanceDefaultsField(c *InstanceDefaultsConfig, field, value string) error {
+ switch field {
+ case "mode":
+ c.Mode = value
case "noRestore":
b, err := parseBool(value)
if err != nil {
- return fmt.Errorf("chrome.noRestore: %w", err)
+ return fmt.Errorf("instanceDefaults.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)
+ return fmt.Errorf("instanceDefaults.blockImages: %w", err)
}
c.BlockImages = &b
case "blockMedia":
b, err := parseBool(value)
if err != nil {
- return fmt.Errorf("chrome.blockMedia: %w", err)
+ return fmt.Errorf("instanceDefaults.blockMedia: %w", err)
}
c.BlockMedia = &b
case "blockAds":
b, err := parseBool(value)
if err != nil {
- return fmt.Errorf("chrome.blockAds: %w", err)
+ return fmt.Errorf("instanceDefaults.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)
+ return fmt.Errorf("instanceDefaults.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)
+ return fmt.Errorf("instanceDefaults.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)
+ return fmt.Errorf("instanceDefaults.noAnimations: %w", err)
}
c.NoAnimations = &b
case "stealthLevel":
@@ -132,7 +126,7 @@ func setChromeField(c *ChromeConfig, field, value string) error {
case "tabEvictionPolicy":
c.TabEvictionPolicy = value
default:
- return fmt.Errorf("unknown field chrome.%s", field)
+ return fmt.Errorf("unknown field instanceDefaults.%s", field)
}
return nil
}
@@ -160,14 +154,38 @@ func setSecurityField(s *SecurityConfig, field, value string) error {
return nil
}
-func setOrchestratorField(o *OrchestratorConfig, field, value string) error {
+func setProfilesField(p *ProfilesConfig, field, value string) error {
+ switch field {
+ case "baseDir":
+ p.BaseDir = value
+ case "defaultProfile":
+ p.DefaultProfile = value
+ default:
+ return fmt.Errorf("unknown field profiles.%s", field)
+ }
+ return nil
+}
+
+func setMultiInstanceField(o *MultiInstanceConfig, field, value string) error {
switch field {
case "strategy":
o.Strategy = value
case "allocationPolicy":
o.AllocationPolicy = value
+ case "instancePortStart":
+ n, err := strconv.Atoi(value)
+ if err != nil {
+ return fmt.Errorf("multiInstance.instancePortStart must be a number: %w", err)
+ }
+ o.InstancePortStart = &n
+ case "instancePortEnd":
+ n, err := strconv.Atoi(value)
+ if err != nil {
+ return fmt.Errorf("multiInstance.instancePortEnd must be a number: %w", err)
+ }
+ o.InstancePortEnd = &n
default:
- return fmt.Errorf("unknown field orchestrator.%s", field)
+ return fmt.Errorf("unknown field multiInstance.%s", field)
}
return nil
}
@@ -193,6 +211,24 @@ func setTimeoutsField(t *TimeoutsConfig, field, value string) error {
return nil
}
+func setAttachField(a *AttachConfig, field, value string) error {
+ switch field {
+ case "enabled":
+ b, err := parseBool(value)
+ if err != nil {
+ return fmt.Errorf("attach.enabled: %w", err)
+ }
+ a.Enabled = &b
+ case "allowHosts":
+ a.AllowHosts = parseCSVList(value)
+ case "allowSchemes":
+ a.AllowSchemes = parseCSVList(value)
+ default:
+ return fmt.Errorf("unknown field attach.%s", field)
+ }
+ return nil
+}
+
func parseBool(s string) (bool, error) {
switch strings.ToLower(strings.TrimSpace(s)) {
case "true", "1", "yes", "on":
@@ -204,6 +240,21 @@ func parseBool(s string) (bool, error) {
}
}
+func parseCSVList(s string) []string {
+ if strings.TrimSpace(s) == "" {
+ return nil
+ }
+ raw := strings.Split(s, ",")
+ out := make([]string, 0, len(raw))
+ for _, item := range raw {
+ item = strings.TrimSpace(item)
+ if item != "" {
+ out = append(out, item)
+ }
+ }
+ return out
+}
+
// 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 {
@@ -268,7 +319,7 @@ func deepMerge(dst, src map[string]interface{}) map[string]interface{} {
// 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"))
+ configPath := envOr("PINCHTAB_CONFIG", filepath.Join(userConfigDir(), "config.json"))
data, err := os.ReadFile(configPath)
if err != nil {
diff --git a/internal/config/editor_test.go b/internal/config/editor_test.go
index 79bcfa17..e30acaa2 100644
--- a/internal/config/editor_test.go
+++ b/internal/config/editor_test.go
@@ -17,9 +17,6 @@ func TestSetConfigValue_ServerFields(t *testing.T) {
{"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},
}
@@ -38,23 +35,24 @@ func TestSetConfigValue_ServerFields(t *testing.T) {
}
}
-func TestSetConfigValue_ChromeFields(t *testing.T) {
+func TestSetConfigValue_BrowserAndInstanceDefaultsFields(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},
+ {"browser.version", "144.0.7559.133", func(fc *FileConfig) bool { return fc.Browser.ChromeVersion == "144.0.7559.133" }, false},
+ {"browser.binary", "/tmp/chrome", func(fc *FileConfig) bool { return fc.Browser.ChromeBinary == "/tmp/chrome" }, false},
+ {"instanceDefaults.mode", "headed", func(fc *FileConfig) bool { return fc.InstanceDefaults.Mode == "headed" }, false},
+ {"instanceDefaults.maxTabs", "50", func(fc *FileConfig) bool { return *fc.InstanceDefaults.MaxTabs == 50 }, false},
+ {"instanceDefaults.stealthLevel", "full", func(fc *FileConfig) bool { return fc.InstanceDefaults.StealthLevel == "full" }, false},
+ {"instanceDefaults.tabEvictionPolicy", "close_lru", func(fc *FileConfig) bool { return fc.InstanceDefaults.TabEvictionPolicy == "close_lru" }, false},
+ {"instanceDefaults.blockAds", "yes", func(fc *FileConfig) bool { return *fc.InstanceDefaults.BlockAds == true }, false},
+ {"profiles.baseDir", "/tmp/profiles", func(fc *FileConfig) bool { return fc.Profiles.BaseDir == "/tmp/profiles" }, false},
+ {"instanceDefaults.noRestore", "maybe", nil, true},
+ {"instanceDefaults.maxTabs", "many", nil, true},
+ {"instanceDefaults.unknown", "value", nil, true},
}
for _, tt := range tests {
@@ -103,16 +101,50 @@ func TestSetConfigValue_SecurityFields(t *testing.T) {
}
}
-func TestSetConfigValue_OrchestratorFields(t *testing.T) {
+func TestSetConfigValue_MultiInstanceFields(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},
+ {"multiInstance.strategy", "explicit", func(fc *FileConfig) bool { return fc.MultiInstance.Strategy == "explicit" }, false},
+ {"multiInstance.allocationPolicy", "round_robin", func(fc *FileConfig) bool { return fc.MultiInstance.AllocationPolicy == "round_robin" }, false},
+ {"multiInstance.instancePortStart", "9900", func(fc *FileConfig) bool { return *fc.MultiInstance.InstancePortStart == 9900 }, false},
+ {"multiInstance.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_AttachFields(t *testing.T) {
+ tests := []struct {
+ path string
+ value string
+ check func(*FileConfig) bool
+ wantErr bool
+ }{
+ {"attach.enabled", "true", func(fc *FileConfig) bool { return fc.Attach.Enabled != nil && *fc.Attach.Enabled }, false},
+ {"attach.allowHosts", "localhost, chrome.internal", func(fc *FileConfig) bool {
+ return len(fc.Attach.AllowHosts) == 2 && fc.Attach.AllowHosts[1] == "chrome.internal"
+ }, false},
+ {"attach.allowSchemes", "ws,wss", func(fc *FileConfig) bool {
+ return len(fc.Attach.AllowSchemes) == 2 && fc.Attach.AllowSchemes[0] == "ws"
+ }, false},
+ {"attach.enabled", "maybe", nil, true},
+ {"attach.unknown", "value", nil, true},
}
for _, tt := range tests {
@@ -186,7 +218,7 @@ func TestPatchConfigJSON(t *testing.T) {
Port: "9867",
Bind: "127.0.0.1",
},
- Chrome: ChromeConfig{
+ InstanceDefaults: InstanceDefaultsConfig{
StealthLevel: "light",
},
}
@@ -207,32 +239,32 @@ func TestPatchConfigJSON(t *testing.T) {
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)
+ // InstanceDefaults.StealthLevel should be preserved
+ if fc.InstanceDefaults.StealthLevel != "light" {
+ t.Errorf("stealthLevel = %v, want light (should be preserved)", fc.InstanceDefaults.StealthLevel)
}
}
func TestPatchConfigJSON_NestedMerge(t *testing.T) {
fc := &FileConfig{
- Chrome: ChromeConfig{
+ InstanceDefaults: InstanceDefaultsConfig{
StealthLevel: "light",
TabEvictionPolicy: "reject",
},
}
- // Patch chrome section, should merge not replace
- patch := `{"chrome": {"stealthLevel": "full"}}`
+ // Patch instanceDefaults section, should merge not replace
+ patch := `{"instanceDefaults": {"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)
+ if fc.InstanceDefaults.StealthLevel != "full" {
+ t.Errorf("stealthLevel = %v, want full", fc.InstanceDefaults.StealthLevel)
}
// tabEvictionPolicy should be preserved
- if fc.Chrome.TabEvictionPolicy != "reject" {
- t.Errorf("tabEvictionPolicy = %v, want reject (should be preserved)", fc.Chrome.TabEvictionPolicy)
+ if fc.InstanceDefaults.TabEvictionPolicy != "reject" {
+ t.Errorf("tabEvictionPolicy = %v, want reject (should be preserved)", fc.InstanceDefaults.TabEvictionPolicy)
}
}
@@ -261,7 +293,7 @@ func TestLoadAndSaveFileConfig(t *testing.T) {
// Modify
fc.Server.Port = "8080"
- fc.Chrome.StealthLevel = "full"
+ fc.InstanceDefaults.StealthLevel = "full"
// Save
if err := SaveFileConfig(fc, path); err != nil {
@@ -277,8 +309,8 @@ func TestLoadAndSaveFileConfig(t *testing.T) {
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)
+ if fc2.InstanceDefaults.StealthLevel != "full" {
+ t.Errorf("loaded stealthLevel = %v, want full", fc2.InstanceDefaults.StealthLevel)
}
}
diff --git a/internal/config/validate.go b/internal/config/validate.go
index ac00261f..42899631 100644
--- a/internal/config/validate.go
+++ b/internal/config/validate.go
@@ -30,59 +30,75 @@ func ValidateFileConfig(fc *FileConfig) []error {
errs = append(errs, err)
}
}
- if fc.Server.InstancePortStart != nil && fc.Server.InstancePortEnd != nil {
- if *fc.Server.InstancePortStart > *fc.Server.InstancePortEnd {
+ if fc.MultiInstance.InstancePortStart != nil && fc.MultiInstance.InstancePortEnd != nil {
+ if *fc.MultiInstance.InstancePortStart > *fc.MultiInstance.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),
+ Field: "multiInstance.instancePortStart/End",
+ Message: fmt.Sprintf("start port (%d) must be <= end port (%d)", *fc.MultiInstance.InstancePortStart, *fc.MultiInstance.InstancePortEnd),
})
}
}
- // Chrome validation
- if fc.Chrome.StealthLevel != "" {
- if !isValidStealthLevel(fc.Chrome.StealthLevel) {
+ // Instance defaults validation
+ if fc.InstanceDefaults.Mode != "" && fc.InstanceDefaults.Mode != "headless" && fc.InstanceDefaults.Mode != "headed" {
+ errs = append(errs, ValidationError{
+ Field: "instanceDefaults.mode",
+ Message: fmt.Sprintf("invalid value %q (must be headless or headed)", fc.InstanceDefaults.Mode),
+ })
+ }
+ if fc.InstanceDefaults.StealthLevel != "" {
+ if !isValidStealthLevel(fc.InstanceDefaults.StealthLevel) {
errs = append(errs, ValidationError{
- Field: "chrome.stealthLevel",
- Message: fmt.Sprintf("invalid value %q (must be light, medium, or full)", fc.Chrome.StealthLevel),
+ Field: "instanceDefaults.stealthLevel",
+ Message: fmt.Sprintf("invalid value %q (must be light, medium, or full)", fc.InstanceDefaults.StealthLevel),
})
}
}
- if fc.Chrome.TabEvictionPolicy != "" {
- if !isValidEvictionPolicy(fc.Chrome.TabEvictionPolicy) {
+ if fc.InstanceDefaults.TabEvictionPolicy != "" {
+ if !isValidEvictionPolicy(fc.InstanceDefaults.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),
+ Field: "instanceDefaults.tabEvictionPolicy",
+ Message: fmt.Sprintf("invalid value %q (must be reject, close_oldest, or close_lru)", fc.InstanceDefaults.TabEvictionPolicy),
})
}
}
- if fc.Chrome.MaxTabs != nil && *fc.Chrome.MaxTabs < 1 {
+ if fc.InstanceDefaults.MaxTabs != nil && *fc.InstanceDefaults.MaxTabs < 1 {
errs = append(errs, ValidationError{
- Field: "chrome.maxTabs",
- Message: fmt.Sprintf("must be >= 1 (got %d)", *fc.Chrome.MaxTabs),
+ Field: "instanceDefaults.maxTabs",
+ Message: fmt.Sprintf("must be >= 1 (got %d)", *fc.InstanceDefaults.MaxTabs),
})
}
- if fc.Chrome.MaxParallelTabs != nil && *fc.Chrome.MaxParallelTabs < 0 {
+ if fc.InstanceDefaults.MaxParallelTabs != nil && *fc.InstanceDefaults.MaxParallelTabs < 0 {
errs = append(errs, ValidationError{
- Field: "chrome.maxParallelTabs",
- Message: fmt.Sprintf("must be >= 0 (got %d)", *fc.Chrome.MaxParallelTabs),
+ Field: "instanceDefaults.maxParallelTabs",
+ Message: fmt.Sprintf("must be >= 0 (got %d)", *fc.InstanceDefaults.MaxParallelTabs),
})
}
- // Orchestrator validation
- if fc.Orchestrator.Strategy != "" {
- if !isValidStrategy(fc.Orchestrator.Strategy) {
+ // Multi-instance validation
+ if fc.MultiInstance.Strategy != "" {
+ if !isValidStrategy(fc.MultiInstance.Strategy) {
+ errs = append(errs, ValidationError{
+ Field: "multiInstance.strategy",
+ Message: fmt.Sprintf("invalid value %q (must be simple, explicit, or simple-autorestart)", fc.MultiInstance.Strategy),
+ })
+ }
+ }
+ if fc.MultiInstance.AllocationPolicy != "" {
+ if !isValidAllocationPolicy(fc.MultiInstance.AllocationPolicy) {
errs = append(errs, ValidationError{
- Field: "orchestrator.strategy",
- Message: fmt.Sprintf("invalid value %q (must be simple, explicit, or simple-autorestart)", fc.Orchestrator.Strategy),
+ Field: "multiInstance.allocationPolicy",
+ Message: fmt.Sprintf("invalid value %q (must be fcfs, round_robin, or random)", fc.MultiInstance.AllocationPolicy),
})
}
}
- if fc.Orchestrator.AllocationPolicy != "" {
- if !isValidAllocationPolicy(fc.Orchestrator.AllocationPolicy) {
+
+ // Attach validation
+ for _, scheme := range fc.Attach.AllowSchemes {
+ if !isValidAttachScheme(scheme) {
errs = append(errs, ValidationError{
- Field: "orchestrator.allocationPolicy",
- Message: fmt.Sprintf("invalid value %q (must be fcfs, round_robin, or random)", fc.Orchestrator.AllocationPolicy),
+ Field: "attach.allowSchemes",
+ Message: fmt.Sprintf("invalid value %q (must be ws or wss)", scheme),
})
}
}
@@ -188,6 +204,15 @@ func isValidAllocationPolicy(policy string) bool {
}
}
+func isValidAttachScheme(scheme string) bool {
+ switch scheme {
+ case "ws", "wss":
+ return true
+ default:
+ return false
+ }
+}
+
// ValidStealthLevels returns all valid stealth level values.
func ValidStealthLevels() []string {
return []string{"light", "medium", "full"}
@@ -207,3 +232,8 @@ func ValidStrategies() []string {
func ValidAllocationPolicies() []string {
return []string{"fcfs", "round_robin", "random"}
}
+
+// ValidAttachSchemes returns all valid attach URL schemes.
+func ValidAttachSchemes() []string {
+ return []string{"ws", "wss"}
+}
diff --git a/internal/config/validate_test.go b/internal/config/validate_test.go
index f51a8ca2..541ba252 100644
--- a/internal/config/validate_test.go
+++ b/internal/config/validate_test.go
@@ -12,12 +12,13 @@ func TestValidateFileConfig_Valid(t *testing.T) {
Port: "9867",
Bind: "127.0.0.1",
},
- Chrome: ChromeConfig{
+ InstanceDefaults: InstanceDefaultsConfig{
+ Mode: "headless",
MaxTabs: &maxTabs,
StealthLevel: "light",
TabEvictionPolicy: "reject",
},
- Orchestrator: OrchestratorConfig{
+ MultiInstance: MultiInstanceConfig{
Strategy: "simple",
AllocationPolicy: "fcfs",
},
@@ -76,7 +77,7 @@ func TestValidateFileConfig_InvalidStealthLevel(t *testing.T) {
for _, tt := range tests {
fc := &FileConfig{
- Chrome: ChromeConfig{StealthLevel: tt.level},
+ InstanceDefaults: InstanceDefaultsConfig{StealthLevel: tt.level},
}
errs := ValidateFileConfig(fc)
hasErr := len(errs) > 0
@@ -101,7 +102,7 @@ func TestValidateFileConfig_InvalidEvictionPolicy(t *testing.T) {
for _, tt := range tests {
fc := &FileConfig{
- Chrome: ChromeConfig{TabEvictionPolicy: tt.policy},
+ InstanceDefaults: InstanceDefaultsConfig{TabEvictionPolicy: tt.policy},
}
errs := ValidateFileConfig(fc)
hasErr := len(errs) > 0
@@ -126,7 +127,7 @@ func TestValidateFileConfig_InvalidStrategy(t *testing.T) {
for _, tt := range tests {
fc := &FileConfig{
- Orchestrator: OrchestratorConfig{Strategy: tt.strategy},
+ MultiInstance: MultiInstanceConfig{Strategy: tt.strategy},
}
errs := ValidateFileConfig(fc)
hasErr := len(errs) > 0
@@ -151,7 +152,7 @@ func TestValidateFileConfig_InvalidAllocationPolicy(t *testing.T) {
for _, tt := range tests {
fc := &FileConfig{
- Orchestrator: OrchestratorConfig{AllocationPolicy: tt.policy},
+ MultiInstance: MultiInstanceConfig{AllocationPolicy: tt.policy},
}
errs := ValidateFileConfig(fc)
hasErr := len(errs) > 0
@@ -161,6 +162,30 @@ func TestValidateFileConfig_InvalidAllocationPolicy(t *testing.T) {
}
}
+func TestValidateFileConfig_InvalidAttachScheme(t *testing.T) {
+ tests := []struct {
+ schemes []string
+ wantErr bool
+ }{
+ {[]string{"ws"}, false},
+ {[]string{"wss"}, false},
+ {[]string{"ws", "wss"}, false},
+ {[]string{"http"}, true},
+ {[]string{"ws", "https"}, true},
+ }
+
+ for _, tt := range tests {
+ fc := &FileConfig{
+ Attach: AttachConfig{AllowSchemes: tt.schemes},
+ }
+ errs := ValidateFileConfig(fc)
+ hasErr := len(errs) > 0
+ if hasErr != tt.wantErr {
+ t.Errorf("allowSchemes=%v: got error=%v, want error=%v", tt.schemes, hasErr, tt.wantErr)
+ }
+ }
+}
+
func TestValidateFileConfig_InvalidMaxTabs(t *testing.T) {
zero := 0
negative := -1
@@ -180,7 +205,7 @@ func TestValidateFileConfig_InvalidMaxTabs(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
fc := &FileConfig{
- Chrome: ChromeConfig{MaxTabs: tt.maxTabs},
+ InstanceDefaults: InstanceDefaultsConfig{MaxTabs: tt.maxTabs},
}
errs := ValidateFileConfig(fc)
hasErr := len(errs) > 0
@@ -212,7 +237,8 @@ func TestValidateFileConfig_InstancePortRange(t *testing.T) {
end := 9800 // invalid: start > end
fc := &FileConfig{
- Server: ServerConfig{
+ Server: ServerConfig{},
+ MultiInstance: MultiInstanceConfig{
InstancePortStart: &start,
InstancePortEnd: &end,
},
@@ -233,12 +259,12 @@ func TestValidateFileConfig_MultipleErrors(t *testing.T) {
Server: ServerConfig{
Port: "99999", // invalid
},
- Chrome: ChromeConfig{
+ InstanceDefaults: InstanceDefaultsConfig{
MaxTabs: &zero, // invalid
StealthLevel: "superstealth", // invalid
TabEvictionPolicy: "delete_oldest", // invalid
},
- Orchestrator: OrchestratorConfig{
+ MultiInstance: MultiInstanceConfig{
Strategy: "magical", // invalid
AllocationPolicy: "balanced", // invalid
},
@@ -286,4 +312,10 @@ func TestValidEnumValues(t *testing.T) {
t.Errorf("ValidAllocationPolicies contains %q but isValidAllocationPolicy returns false", policy)
}
}
+
+ for _, scheme := range ValidAttachSchemes() {
+ if !isValidAttachScheme(scheme) {
+ t.Errorf("ValidAttachSchemes contains %q but isValidAttachScheme returns false", scheme)
+ }
+ }
}
diff --git a/internal/handlers/actions.go b/internal/handlers/actions.go
index d9e65d84..cbbf9089 100644
--- a/internal/handlers/actions.go
+++ b/internal/handlers/actions.go
@@ -484,7 +484,7 @@ func (h *Handlers) handleActionsBatch(w http.ResponseWriter, r *http.Request, re
func (h *Handlers) HandleMacro(w http.ResponseWriter, r *http.Request) {
if !h.Config.AllowMacro {
- web.ErrorCode(w, 403, "macro_disabled", "macro endpoint is disabled; set PINCHTAB_ALLOW_MACRO=1 to enable", false, nil)
+ web.ErrorCode(w, 403, "macro_disabled", "macro endpoint is disabled; enable it in config to use this endpoint", false, nil)
return
}
var req struct {
diff --git a/internal/handlers/download.go b/internal/handlers/download.go
index 39b9d71b..487027b2 100644
--- a/internal/handlers/download.go
+++ b/internal/handlers/download.go
@@ -57,7 +57,7 @@ func validateDownloadURL(rawURL string) error {
// GET /download?url=<url>[&tabId=<id>][&output=file&path=/tmp/file][&raw=true]
func (h *Handlers) HandleDownload(w http.ResponseWriter, r *http.Request) {
if !h.Config.AllowDownload {
- web.ErrorCode(w, 403, "download_disabled", "download endpoint is disabled; set PINCHTAB_ALLOW_DOWNLOAD=1 to enable", false, nil)
+ web.ErrorCode(w, 403, "download_disabled", "download endpoint is disabled; enable it in config to use this endpoint", false, nil)
return
}
dlURL := r.URL.Query().Get("url")
diff --git a/internal/handlers/evaluate.go b/internal/handlers/evaluate.go
index 968f61c0..38c2d47e 100644
--- a/internal/handlers/evaluate.go
+++ b/internal/handlers/evaluate.go
@@ -23,7 +23,7 @@ func (h *Handlers) evaluateEnabled() bool {
// @Endpoint POST /evaluate
func (h *Handlers) HandleEvaluate(w http.ResponseWriter, r *http.Request) {
if !h.evaluateEnabled() {
- web.ErrorCode(w, 403, "evaluate_disabled", "evaluate endpoint is disabled; set PINCHTAB_ALLOW_EVALUATE=1 to enable", false, nil)
+ web.ErrorCode(w, 403, "evaluate_disabled", "evaluate endpoint is disabled; enable it in config to use this endpoint", false, nil)
return
}
@@ -70,7 +70,7 @@ func (h *Handlers) HandleEvaluate(w http.ResponseWriter, r *http.Request) {
// @Endpoint POST /tabs/{id}/evaluate
func (h *Handlers) HandleTabEvaluate(w http.ResponseWriter, r *http.Request) {
if !h.evaluateEnabled() {
- web.ErrorCode(w, 403, "evaluate_disabled", "evaluate endpoint is disabled; set PINCHTAB_ALLOW_EVALUATE=1 to enable", false, nil)
+ web.ErrorCode(w, 403, "evaluate_disabled", "evaluate endpoint is disabled; enable it in config to use this endpoint", false, nil)
return
}
diff --git a/internal/handlers/health_tabs.go b/internal/handlers/health_tabs.go
index 3e2964e9..75064324 100644
--- a/internal/handlers/health_tabs.go
+++ b/internal/handlers/health_tabs.go
@@ -27,7 +27,7 @@ func (h *Handlers) HandleHealth(w http.ResponseWriter, r *http.Request) {
return
}
- resp := map[string]any{"status": "ok", "tabs": len(targets), "cdp": h.Config.CdpURL}
+ resp := map[string]any{"status": "ok", "tabs": len(targets)}
// Include crash logs if any
if crashLogs := h.Bridge.GetCrashLogs(); len(crashLogs) > 0 {
diff --git a/internal/handlers/health_tabs_test.go b/internal/handlers/health_tabs_test.go
index 2cbd27ff..d2b4619a 100644
--- a/internal/handlers/health_tabs_test.go
+++ b/internal/handlers/health_tabs_test.go
@@ -54,7 +54,7 @@ func TestHandleHealth_BridgeListTargetsError(t *testing.T) {
h := &Handlers{
Bridge: mockBridge,
- Config: &config.RuntimeConfig{CdpURL: "ws://localhost:9222"},
+ Config: &config.RuntimeConfig{},
}
req := httptest.NewRequest("GET", "/health", nil)
@@ -91,7 +91,7 @@ func TestHandleHealth_Success(t *testing.T) {
h := &Handlers{
Bridge: mockBridge,
- Config: &config.RuntimeConfig{CdpURL: "ws://localhost:9222"},
+ Config: &config.RuntimeConfig{},
}
req := httptest.NewRequest("GET", "/health", nil)
@@ -228,7 +228,7 @@ func TestHandleHealth_EnsureChromeSuccess(t *testing.T) {
h := &Handlers{
Bridge: mockBridge,
- Config: &config.RuntimeConfig{CdpURL: "ws://localhost:9222"},
+ Config: &config.RuntimeConfig{},
}
req := httptest.NewRequest("GET", "/health", nil)
diff --git a/internal/handlers/screencast.go b/internal/handlers/screencast.go
index 4cab3c5c..cfec5e76 100644
--- a/internal/handlers/screencast.go
+++ b/internal/handlers/screencast.go
@@ -20,7 +20,7 @@ import (
// Query params: tabId (required), quality (1-100, default 40), maxWidth (default 800), fps (1-30, default 5)
func (h *Handlers) HandleScreencast(w http.ResponseWriter, r *http.Request) {
if !h.Config.AllowScreencast {
- web.ErrorCode(w, 403, "screencast_disabled", "screencast endpoint is disabled; set PINCHTAB_ALLOW_SCREENCAST=1 to enable", false, nil)
+ web.ErrorCode(w, 403, "screencast_disabled", "screencast endpoint is disabled; enable it in config to use this endpoint", false, nil)
return
}
tabID := r.URL.Query().Get("tabId")
@@ -148,7 +148,7 @@ func (h *Handlers) HandleScreencast(w http.ResponseWriter, r *http.Request) {
// HandleScreencastAll returns info for building a multi-tab screencast view.
func (h *Handlers) HandleScreencastAll(w http.ResponseWriter, r *http.Request) {
if !h.Config.AllowScreencast {
- web.ErrorCode(w, 403, "screencast_disabled", "screencast endpoint is disabled; set PINCHTAB_ALLOW_SCREENCAST=1 to enable", false, nil)
+ web.ErrorCode(w, 403, "screencast_disabled", "screencast endpoint is disabled; enable it in config to use this endpoint", false, nil)
return
}
type tabInfo struct {
diff --git a/internal/handlers/upload.go b/internal/handlers/upload.go
index 1d928555..55a1f5e1 100644
--- a/internal/handlers/upload.go
+++ b/internal/handlers/upload.go
@@ -37,7 +37,7 @@ type uploadRequest struct {
// Both can be combined. Files are written to a temp dir and passed to CDP.
func (h *Handlers) HandleUpload(w http.ResponseWriter, r *http.Request) {
if !h.Config.AllowUpload {
- web.ErrorCode(w, 403, "upload_disabled", "upload endpoint is disabled; set PINCHTAB_ALLOW_UPLOAD=1 to enable", false, nil)
+ web.ErrorCode(w, 403, "upload_disabled", "upload endpoint is disabled; enable it in config to use this endpoint", false, nil)
return
}
tabID := r.URL.Query().Get("tabId")
diff --git a/internal/orchestrator/orchestrator.go b/internal/orchestrator/orchestrator.go
index c95a6ecb..aca61eaf 100644
--- a/internal/orchestrator/orchestrator.go
+++ b/internal/orchestrator/orchestrator.go
@@ -2,6 +2,7 @@ package orchestrator
import (
"context"
+ "encoding/json"
"fmt"
"io"
"log/slog"
@@ -17,32 +18,12 @@ import (
"github.com/pinchtab/pinchtab/internal/allocation"
"github.com/pinchtab/pinchtab/internal/api/types"
"github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/config"
"github.com/pinchtab/pinchtab/internal/idutil"
"github.com/pinchtab/pinchtab/internal/instance"
"github.com/pinchtab/pinchtab/internal/profiles"
)
-func envWithFallback(newKey, oldKey string) string {
- if v := os.Getenv(newKey); v != "" {
- return v
- }
- return os.Getenv(oldKey)
-}
-
-func envBoolWithFallback(newKey, oldKey string, fallback bool) bool {
- v := strings.TrimSpace(strings.ToLower(envWithFallback(newKey, oldKey)))
- switch v {
- case "1", "true", "yes", "on":
- return true
- case "0", "false", "no", "off":
- return false
- case "":
- return fallback
- default:
- return fallback
- }
-}
-
// InstanceEvent is emitted when instance state changes.
type InstanceEvent struct {
Type string `json:"type"` // "instance.started", "instance.stopped", "instance.error"
@@ -66,6 +47,7 @@ type Orchestrator struct {
idMgr *idutil.Manager
eventHandlers []EventHandler
instanceMgr *instance.Manager
+ runtimeCfg *config.RuntimeConfig
}
// OnEvent adds an event handler for instance lifecycle events.
@@ -148,8 +130,8 @@ func NewOrchestratorWithRunner(baseDir string, runner HostRunner) *Orchestrator
// - Short timeout (<5s) would break first-request scenarios
// See: internal/orchestrator/health.go (monitor), internal/bridge/init.go (InitChrome)
client: &http.Client{Timeout: 60 * time.Second},
- childAuthToken: envWithFallback("PINCHTAB_TOKEN", "BRIDGE_TOKEN"),
- allowEvaluate: envBoolWithFallback("PINCHTAB_ALLOW_EVALUATE", "BRIDGE_ALLOW_EVALUATE", false),
+ childAuthToken: "",
+ allowEvaluate: false,
portAllocator: NewPortAllocator(9868, 9968),
idMgr: idutil.NewManager(),
}
@@ -204,6 +186,23 @@ func (o *Orchestrator) SetProfileManager(pm *profiles.ProfileManager) {
o.profiles = pm
}
+func (o *Orchestrator) ApplyRuntimeConfig(cfg *config.RuntimeConfig) {
+ o.runtimeCfg = cfg
+ if cfg == nil {
+ o.childAuthToken = ""
+ o.allowEvaluate = false
+ return
+ }
+ o.childAuthToken = cfg.Token
+ o.allowEvaluate = cfg.AllowEvaluate
+ o.SetPortRange(cfg.InstancePortStart, cfg.InstancePortEnd)
+ if cfg.AllocationPolicy != "" {
+ if err := o.SetAllocationPolicy(cfg.AllocationPolicy); err != nil {
+ slog.Warn("failed to apply allocation policy", "policy", cfg.AllocationPolicy, "err", err)
+ }
+ }
+}
+
func (o *Orchestrator) SetPortRange(start, end int) {
o.portAllocator = NewPortAllocator(start, end)
}
@@ -281,23 +280,20 @@ func (o *Orchestrator) Launch(name, port string, headless bool, extensionPaths [
return nil, fmt.Errorf("create state dir: %w", err)
}
- headlessStr := "true"
- if !headless {
- headlessStr = "false"
+ childConfigPath, err := o.writeChildConfig(port, profilePath, instanceStateDir, headless, extensionPaths)
+ if err != nil {
+ return nil, fmt.Errorf("write child config: %w", err)
}
envOverrides := map[string]string{
- "PINCHTAB_PORT": port,
- "PINCHTAB_PROFILE_DIR": profilePath,
- "PINCHTAB_STATE_DIR": instanceStateDir,
- "PINCHTAB_HEADLESS": headlessStr,
- "PINCHTAB_NO_RESTORE": "true",
- "PINCHTAB_ONLY": "1",
+ "PINCHTAB_PORT": port,
+ "PINCHTAB_CONFIG": childConfigPath,
+ "PINCHTAB_ONLY": "1",
}
- if len(extensionPaths) > 0 {
- envOverrides["CHROME_EXTENSION_PATHS"] = strings.Join(extensionPaths, ",")
+ if o.runtimeCfg != nil && o.runtimeCfg.ChromeBinary != "" {
+ envOverrides["CHROME_BIN"] = o.runtimeCfg.ChromeBinary
}
- env := mergeEnvWithOverrides(os.Environ(), envOverrides)
+ env := mergeEnvWithOverrides(filterEnvWithPrefixes(os.Environ(), "BRIDGE_", "PINCHTAB_"), envOverrides)
logBuf := newRingBuffer(64 * 1024)
slog.Info("starting instance process", "id", instanceID, "profile", name, "port", port)
@@ -331,6 +327,34 @@ func (o *Orchestrator) Launch(name, port string, headless bool, extensionPaths [
return &inst.Instance, nil
}
+func (o *Orchestrator) writeChildConfig(port, profilePath, instanceStateDir string, headless bool, extensionPaths []string) (string, error) {
+ fc := config.FileConfigFromRuntime(o.runtimeCfg)
+ fc.Server.Port = port
+ fc.Server.StateDir = instanceStateDir
+ fc.Profiles.BaseDir = filepath.Dir(profilePath)
+ fc.Profiles.DefaultProfile = filepath.Base(profilePath)
+ if headless {
+ fc.InstanceDefaults.Mode = "headless"
+ } else {
+ fc.InstanceDefaults.Mode = "headed"
+ }
+ noRestore := true
+ fc.InstanceDefaults.NoRestore = &noRestore
+ if len(extensionPaths) > 0 {
+ fc.Browser.ExtensionPaths = append([]string(nil), extensionPaths...)
+ }
+
+ configPath := filepath.Join(instanceStateDir, "config.json")
+ data, err := json.MarshalIndent(fc, "", " ")
+ if err != nil {
+ return "", err
+ }
+ if err := os.WriteFile(configPath, data, 0644); err != nil {
+ return "", err
+ }
+ return configPath, nil
+}
+
func (o *Orchestrator) Stop(id string) error {
o.mu.Lock()
inst, ok := o.instances[id]
diff --git a/internal/orchestrator/process.go b/internal/orchestrator/process.go
index fe326aec..247ec8b9 100644
--- a/internal/orchestrator/process.go
+++ b/internal/orchestrator/process.go
@@ -90,6 +90,23 @@ func mergeEnvWithOverrides(base []string, overrides map[string]string) []string
return out
}
+func filterEnvWithPrefixes(env []string, prefixes ...string) []string {
+ out := make([]string, 0, len(env))
+ for _, e := range env {
+ skip := false
+ for _, p := range prefixes {
+ if strings.HasPrefix(e, p) {
+ skip = true
+ break
+ }
+ }
+ if !skip {
+ out = append(out, e)
+ }
+ }
+ return out
+}
+
type ringBuffer struct {
mu sync.Mutex
data []byte
diff --git a/tests/integration/config_cli_test.go b/tests/integration/config_cli_test.go
index 8ca4db34..0ffeaf93 100644
--- a/tests/integration/config_cli_test.go
+++ b/tests/integration/config_cli_test.go
@@ -46,8 +46,8 @@ func TestConfigCLI_Init(t *testing.T) {
if _, ok := cfg["server"]; !ok {
t.Error("expected 'server' section in config")
}
- if _, ok := cfg["chrome"]; !ok {
- t.Error("expected 'chrome' section in config")
+ if _, ok := cfg["browser"]; !ok {
+ t.Error("expected 'browser' section in config")
}
}
@@ -75,8 +75,8 @@ func TestConfigCLI_Show(t *testing.T) {
if !strings.Contains(output, "Server:") {
t.Errorf("expected output to contain 'Server:' section, got: %s", output)
}
- if !strings.Contains(output, "Chrome:") {
- t.Errorf("expected output to contain 'Chrome:' section, got: %s", output)
+ if !strings.Contains(output, "Browser / Instance Defaults:") {
+ t.Errorf("expected output to contain 'Browser / Instance Defaults:' section, got: %s", output)
}
}
@@ -151,7 +151,7 @@ func TestConfigCLI_Patch(t *testing.T) {
}
// Patch with JSON
- patchJSON := `{"server":{"port":"7777"},"chrome":{"maxTabs":100}}`
+ patchJSON := `{"server":{"port":"7777"},"instanceDefaults":{"maxTabs":100}}`
patchCmd := exec.Command(server.BinaryPath, "config", "patch", patchJSON)
patchCmd.Env = append(filterTestEnv(), "PINCHTAB_CONFIG="+configPath)
@@ -173,13 +173,13 @@ func TestConfigCLI_Patch(t *testing.T) {
t.Errorf("expected port 7777, got %v", server["port"])
}
- chrome, ok := cfg["chrome"].(map[string]any)
+ instanceDefaults, ok := cfg["instanceDefaults"].(map[string]any)
if !ok {
- t.Fatal("chrome section not found")
+ t.Fatal("instanceDefaults section not found")
}
// JSON unmarshals numbers as float64
- if chrome["maxTabs"] != float64(100) {
- t.Errorf("expected maxTabs 100, got %v", chrome["maxTabs"])
+ if instanceDefaults["maxTabs"] != float64(100) {
+ t.Errorf("expected maxTabs 100, got %v", instanceDefaults["maxTabs"])
}
}
@@ -191,8 +191,8 @@ func TestConfigCLI_Validate_Valid(t *testing.T) {
// Create a valid config
validConfig := `{
"server": {"port": "9867"},
- "chrome": {"stealthLevel": "light", "tabEvictionPolicy": "reject"},
- "orchestrator": {"strategy": "simple", "allocationPolicy": "fcfs"}
+ "instanceDefaults": {"stealthLevel": "light", "tabEvictionPolicy": "reject"},
+ "multiInstance": {"strategy": "simple", "allocationPolicy": "fcfs"}
}`
if err := os.WriteFile(configPath, []byte(validConfig), 0644); err != nil {
t.Fatal(err)
@@ -219,8 +219,8 @@ func TestConfigCLI_Validate_Invalid(t *testing.T) {
// Create an invalid config
invalidConfig := `{
"server": {"port": "99999"},
- "chrome": {"stealthLevel": "superstealth"},
- "orchestrator": {"strategy": "magical"}
+ "instanceDefaults": {"stealthLevel": "superstealth"},
+ "multiInstance": {"strategy": "magical"}
}`
if err := os.WriteFile(configPath, []byte(invalidConfig), 0644); err != nil {
t.Fatal(err)
diff --git a/tests/testutil/server.go b/tests/testutil/server.go
index 177377c3..718e0781 100644
--- a/tests/testutil/server.go
+++ b/tests/testutil/server.go
@@ -13,6 +13,8 @@ import (
"strings"
"testing"
"time"
+
+ appconfig "github.com/pinchtab/pinchtab/internal/config"
)
const (
@@ -107,6 +109,11 @@ func StartServer(cfg ServerConfig) (*Server, error) {
}
}
+ if err := writeServerConfig(filepath.Join(s.Dir, "config.json"), s, cfg); err != nil {
+ s.Cleanup()
+ return nil, fmt.Errorf("write config: %w", err)
+ }
+
build := exec.Command("go", "build", "-o", s.BinaryPath, "./cmd/pinchtab/") // #nosec G204 -- BinaryPath is from os.MkdirTemp, not user input
build.Dir = FindRepoRoot()
build.Stdout = os.Stdout
@@ -119,43 +126,17 @@ func StartServer(cfg ServerConfig) (*Server, error) {
// Strip existing BRIDGE_*/PINCHTAB_* to avoid test pollution from host config
env := filterEnv(os.Environ(), "BRIDGE_", "PINCHTAB_")
- // Core server config
+ // Keep env limited to process wiring. Runtime behavior now comes from config.json.
env = append(env,
"PINCHTAB_PORT="+cfg.Port,
- "PINCHTAB_HEADLESS="+boolStr(cfg.Headless),
- "PINCHTAB_NO_RESTORE=true",
- "PINCHTAB_STEALTH="+cfg.Stealth,
- "PINCHTAB_STATE_DIR="+s.StateDir,
- "PINCHTAB_PROFILE_DIR="+s.ProfileDir,
"PINCHTAB_CONFIG="+filepath.Join(s.Dir, "config.json"), // Isolate from host config
)
- // Security flags from ServerConfig
- env = append(env,
- "PINCHTAB_ALLOW_EVALUATE="+boolStr(cfg.AllowEvaluate),
- "PINCHTAB_ALLOW_MACRO="+boolStr(cfg.AllowMacro),
- "PINCHTAB_ALLOW_SCREENCAST="+boolStr(cfg.AllowScreencast),
- "PINCHTAB_ALLOW_DOWNLOAD="+boolStr(cfg.AllowDownload),
- "PINCHTAB_ALLOW_UPLOAD="+boolStr(cfg.AllowUpload),
- )
-
- // Optional config overrides (only set if non-default)
- if cfg.TabEvictionPolicy != "" {
- env = append(env, "PINCHTAB_TAB_EVICTION_POLICY="+cfg.TabEvictionPolicy)
- }
- if cfg.Strategy != "" {
- env = append(env, "PINCHTAB_STRATEGY="+cfg.Strategy)
- }
- if cfg.AllocationPolicy != "" {
- env = append(env, "PINCHTAB_ALLOCATION_POLICY="+cfg.AllocationPolicy)
- }
- if cfg.MaxTabs > 0 {
- env = append(env, fmt.Sprintf("PINCHTAB_MAX_TABS=%d", cfg.MaxTabs))
- }
-
// Chrome binary from host (for CI environments)
- if bin := os.Getenv("CHROME_BINARY"); bin != "" {
- env = append(env, "CHROME_BINARY="+bin)
+ if bin := os.Getenv("CHROME_BIN"); bin != "" {
+ env = append(env, "CHROME_BIN="+bin)
+ } else if legacyBin := os.Getenv("CHROME_BINARY"); legacyBin != "" {
+ env = append(env, "CHROME_BIN="+legacyBin)
}
s.cmd = exec.Command(s.BinaryPath) // #nosec G204 -- BinaryPath is from os.MkdirTemp, not user input
@@ -181,6 +162,57 @@ func StartServer(cfg ServerConfig) (*Server, error) {
return s, nil
}
+func writeServerConfig(path string, srv *Server, cfg ServerConfig) error {
+ fc := appconfig.DefaultFileConfig()
+ fc.Server.Port = cfg.Port
+ fc.Server.StateDir = srv.StateDir
+ fc.Profiles.BaseDir = srv.ProfileDir
+ fc.Profiles.DefaultProfile = "default"
+
+ fc.InstanceDefaults.Mode = modeString(cfg.Headless)
+ noRestore := true
+ fc.InstanceDefaults.NoRestore = &noRestore
+ fc.InstanceDefaults.StealthLevel = cfg.Stealth
+ if cfg.MaxTabs > 0 {
+ maxTabs := cfg.MaxTabs
+ fc.InstanceDefaults.MaxTabs = &maxTabs
+ }
+ if cfg.TabEvictionPolicy != "" {
+ fc.InstanceDefaults.TabEvictionPolicy = cfg.TabEvictionPolicy
+ }
+
+ allowEvaluate := cfg.AllowEvaluate
+ allowMacro := cfg.AllowMacro
+ allowScreencast := cfg.AllowScreencast
+ allowDownload := cfg.AllowDownload
+ allowUpload := cfg.AllowUpload
+ fc.Security.AllowEvaluate = &allowEvaluate
+ fc.Security.AllowMacro = &allowMacro
+ fc.Security.AllowScreencast = &allowScreencast
+ fc.Security.AllowDownload = &allowDownload
+ fc.Security.AllowUpload = &allowUpload
+
+ if cfg.Strategy != "" {
+ fc.MultiInstance.Strategy = cfg.Strategy
+ }
+ if cfg.AllocationPolicy != "" {
+ fc.MultiInstance.AllocationPolicy = cfg.AllocationPolicy
+ }
+
+ data, err := json.MarshalIndent(fc, "", " ")
+ if err != nil {
+ return err
+ }
+ return os.WriteFile(path, data, 0o644)
+}
+
+func modeString(headless bool) string {
+ if headless {
+ return "headless"
+ }
+ return "headed"
+}
+
func (s *Server) Stop() {
if s.cmd != nil && s.cmd.Process != nil {
TerminateProcessGroup(s.cmd, ShutdownTimeout)
@@ -343,10 +375,3 @@ func filterEnv(env []string, prefixes ...string) []string {
}
return out
}
-
-func boolStr(b bool) string {
- if b {
- return "true"
- }
- return "false"
-}