Skip to content

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

9.3 KB
Raw Blame
package config

import (
	"strconv"
	"strings"
)

// CurrentConfigVersion is bumped when config schema changes require migration or wizard re-run.
const CurrentConfigVersion = "0.8.0"

const configSchemaRawBaseURL = "https://raw.githubusercontent.com/pinchtab/pinchtab"

// ConfigSchemaURL is the source-checkout/default JSON Schema URL. Released
// binaries replace this with their own release tag at command startup.
const ConfigSchemaURL = configSchemaRawBaseURL + "/main/schema/config.json"

var currentConfigSchemaURL = ConfigSchemaURL

// publishedConfigSchemaVersions lists release tags known to contain
// schema/config.json. Keep this empty until the first schema-bearing release is
// published; unknown versions fall back to main rather than broken old tags.
var publishedConfigSchemaVersions []string

// SetConfigSchemaVersion switches generated configs to the schema hosted on
// the release tag for a concrete release build. Non-release builds keep main,
// which avoids pointing at old config-version tags that predate the schema.
func SetConfigSchemaVersion(version string) {
	currentConfigSchemaURL = schemaURLForVersion(version)
}

// CurrentConfigSchemaURL returns the schema URL generated by this process.
func CurrentConfigSchemaURL() string {
	return currentConfigSchemaURL
}

func schemaURLForVersion(version string) string {
	version = strings.TrimPrefix(strings.TrimSpace(version), "v")
	if !isReleaseVersion(version) {
		return ConfigSchemaURL
	}
	schemaVersion, ok := closestPublishedConfigSchemaVersion(version)
	if !ok {
		return ConfigSchemaURL
	}
	return configSchemaRawBaseURL + "/v" + schemaVersion + "/schema/config.json"
}

func isReleaseVersion(version string) bool {
	_, ok := parseSemver(version)
	return ok
}

func closestPublishedConfigSchemaVersion(version string) (string, bool) {
	target, ok := parseSemver(version)
	if !ok {
		return "", false
	}

	// Use an older-or-equal schema so generated configs never point at rules
	// from a future PinchTab release.
	closest := ""
	for _, candidate := range publishedConfigSchemaVersions {
		parsed, ok := parseSemver(candidate)
		if !ok || compareSemver(parsed, target) > 0 {
			continue
		}
		if closest == "" {
			closest = candidate
			continue
		}
		closestParsed, _ := parseSemver(closest)
		if compareSemver(parsed, closestParsed) > 0 {
			closest = candidate
		}
	}
	return closest, closest != ""
}

func parseSemver(version string) ([3]int, bool) {
	var out [3]int
	parts := strings.Split(strings.TrimPrefix(strings.TrimSpace(version), "v"), ".")
	if len(parts) != 3 {
		return out, false
	}
	for i, part := range parts {
		if part == "" {
			return out, false
		}
		n, err := strconv.Atoi(part)
		if err != nil {
			return out, false
		}
		out[i] = n
	}
	return out, true
}

func compareSemver(a, b [3]int) int {
	for i := range a {
		if a[i] < b[i] {
			return -1
		}
		if a[i] > b[i] {
			return 1
		}
	}
	return 0
}

// DefaultFileConfig returns a FileConfig with sensible defaults (nested format).
func DefaultFileConfig() FileConfig {
	start := 9868
	end := 9968
	quarantineKeep := DefaultProfileQuarantineKeep
	restartMaxRestarts := 20
	restartInitBackoffSec := 2
	restartMaxBackoffSec := 60
	restartStableAfterSec := 300
	maxTabs := 20
	captureAllowActivation := true
	allowEvaluate := false
	allowMacro := false
	allowScreencast := false
	allowDownload := false
	allowCookies := false
	allowNetworkIntercept := false
	allowMemory := false
	downloadMaxBytes := DefaultDownloadMaxBytes
	memorySnapshotMaxBytes := DefaultMemorySnapshotMaxBytes
	allowUpload := false
	allowClipboard := false
	allowStateExport := false
	uploadMaxRequestBytes := DefaultUploadMaxRequestBytes
	uploadMaxFiles := DefaultUploadMaxFiles
	uploadMaxFileBytes := DefaultUploadMaxFileBytes
	uploadMaxTotalBytes := DefaultUploadMaxTotalBytes
	maxRedirects := -1
	trustLoopbackProxy := false
	attachEnabled := false
	attachForwardProxyAuth := false
	activityEnabled := true
	activitySessionIdleSec := 1800
	activityRetentionDays := 30
	activityDashboardEvents := false
	activityServerEvents := false
	activityBridgeEvents := false
	activityOrchestratorEvents := false
	activitySchedulerEvents := false
	activityMCPEvents := false
	activityOtherEvents := false
	dashboardSessionPersist := true
	dashboardSessionIdleSec := 7 * 24 * 60 * 60
	dashboardSessionMaxLifetimeSec := 7 * 24 * 60 * 60
	dashboardSessionElevationWindowSec := 15 * 60
	dashboardSessionPersistElevationAcrossRestart := false
	dashboardSessionRequireElevation := false
	// Locals only so the shared defaults can be pointer-wrapped; the values come
	// from defaultAutoSolverConfig, not from a second transcription of them.
	autoSolver := defaultAutoSolverConfig()
	return FileConfig{
		Schema:        CurrentConfigSchemaURL(),
		ConfigVersion: CurrentConfigVersion,
		Server: ServerConfig{
			Port:     defaultPort,
			Bind:     "127.0.0.1",
			StateDir: userConfigDir(),
		},
		Browser: BrowserConfig{
			// BrowserVersion is left unset so the persona probes the launched binary
			// for its real version; a default here would pin it and the probe would
			// never fire. TestTheConfigDefaultsLeaveBrowserVersionUnset guards this.
			ExtensionPaths: []string{defaultExtensionsDir(userConfigDir())},
		},
		Browsers: BrowsersConfig{
			Default: DefaultBrowserForSystem(),
		},
		InstanceDefaults: InstanceDefaultsConfig{
			Mode:                   "headless",
			MaxTabs:                &maxTabs,
			CaptureAllowActivation: &captureAllowActivation,
			StealthLevel:           "light",
			TabEvictionPolicy:      "close_lru",
		},
		Security: SecurityConfig{
			AllowEvaluate:          &allowEvaluate,
			AllowMacro:             &allowMacro,
			AllowScreencast:        &allowScreencast,
			AllowDownload:          &allowDownload,
			AllowCookies:           &allowCookies,
			AllowNetworkIntercept:  &allowNetworkIntercept,
			AllowMemory:            &allowMemory,
			DownloadAllowedDomains: []string{},
			DownloadMaxBytes:       &downloadMaxBytes,
			MemorySnapshotMaxBytes: &memorySnapshotMaxBytes,
			AllowUpload:            &allowUpload,
			AllowClipboard:         &allowClipboard,
			AllowStateExport:       &allowStateExport,
			UploadMaxRequestBytes:  &uploadMaxRequestBytes,
			UploadMaxFiles:         &uploadMaxFiles,
			UploadMaxFileBytes:     &uploadMaxFileBytes,
			UploadMaxTotalBytes:    &uploadMaxTotalBytes,
			MaxRedirects:           &maxRedirects,
			TrustLoopbackProxy:     &trustLoopbackProxy,
			Attach: AttachConfig{
				Enabled:          &attachEnabled,
				AllowHosts:       []string{"127.0.0.1", "localhost", "::1"},
				AllowSchemes:     []string{"ws", "wss", "http", "https"},
				ForwardProxyAuth: &attachForwardProxyAuth,
			},
			IDPI: &IDPIConfig{
				Enabled:        true,
				StrictMode:     true,
				ScanContent:    true,
				WrapContent:    true,
				ScanTimeoutSec: 5,
			},
		},
		// BaseDir is deliberately empty. Pre-filling it with an absolute
		// userConfigDir() path did two things: it baked a host home directory into any
		// config that got written, and it made finalizeProfileConfig's
		// filepath.Join(StateDir, "profiles") fallback unreachable, so server.stateDir
		// could never relocate profiles. Left empty, the fallback is the live path and
		// resolves to the same place for a default install, because StateDir itself
		// defaults to userConfigDir().
		Profiles: ProfilesConfig{
			DefaultProfile: "default",
			QuarantineKeep: &quarantineKeep,
		},
		MultiInstance: MultiInstanceConfig{
			Strategy:          "always-on",
			AllocationPolicy:  "fcfs",
			InstancePortStart: &start,
			InstancePortEnd:   &end,
			Restart: MultiInstanceRestartConfig{
				MaxRestarts:    &restartMaxRestarts,
				InitBackoffSec: &restartInitBackoffSec,
				MaxBackoffSec:  &restartMaxBackoffSec,
				StableAfterSec: &restartStableAfterSec,
			},
		},
		Timeouts: TimeoutsConfig{
			ActionSec:   30,
			NavigateSec: 60,
			ShutdownSec: 10,
			WaitNavMs:   1000,
		},
		Observability: ObservabilityFileConfig{
			Activity: ActivityFileConfig{
				Enabled:        &activityEnabled,
				SessionIdleSec: &activitySessionIdleSec,
				RetentionDays:  &activityRetentionDays,
				StateDir:       "",
				Events: ActivityEventsFileConfig{
					Dashboard:    &activityDashboardEvents,
					Server:       &activityServerEvents,
					Bridge:       &activityBridgeEvents,
					Orchestrator: &activityOrchestratorEvents,
					Scheduler:    &activitySchedulerEvents,
					MCP:          &activityMCPEvents,
					Other:        &activityOtherEvents,
				},
			},
		},
		Sessions: SessionsFileConfig{
			Dashboard: DashboardSessionFileConfig{
				Persist:                       &dashboardSessionPersist,
				IdleTimeoutSec:                &dashboardSessionIdleSec,
				MaxLifetimeSec:                &dashboardSessionMaxLifetimeSec,
				ElevationWindowSec:            &dashboardSessionElevationWindowSec,
				PersistElevationAcrossRestart: &dashboardSessionPersistElevationAcrossRestart,
				RequireElevation:              &dashboardSessionRequireElevation,
			},
		},
		AutoSolver: AutoSolverFileConfig{
			Enabled:           &autoSolver.Enabled,
			AutoTrigger:       &autoSolver.AutoTrigger,
			TriggerOnNavigate: &autoSolver.TriggerOnNavigate,
			TriggerOnAction:   &autoSolver.TriggerOnAction,
			MaxAttempts:       &autoSolver.MaxAttempts,
			SolverTimeoutSec:  &autoSolver.SolverTimeoutSec,
			RetryBaseDelayMs:  &autoSolver.RetryBaseDelayMs,
			RetryMaxDelayMs:   &autoSolver.RetryMaxDelayMs,
			Solvers:           autoSolver.Solvers,
			LLMFallback:       &autoSolver.LLMFallback,
		},
	}
}