diff --git a/CHANGELOG.md b/CHANGELOG.md index 3503686..d7fba0c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,33 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [5.4.8] - 2026-11-15 + +### 🪟 Windows Silent Shortcut Overhaul, Dynamic Loopback Port Scanner & Chromium Loopback Unblock + +#### 🚀 Native Windows Silent Shortcut Pipeline +- **Eliminate Cluttering Desktop Batch Files:** Instead of creating standalone `.bat` files on the user's desktop, the launcher now in-place patches the official `Antigravity.lnk` shortcut on both **Desktop** and **Start Menu** with the official application icon (`Antigravity.exe,0`). +- **Zero-Flash Execution:** Leverages a lightweight Windows Script Host runner (`run.vbs` with `windowStyle = 0`) to execute the launcher engine silently without flashing a command prompt window. + +#### ⚡ Dynamic Loopback Port Detection +- **Multi-Client Probing:** Probes active loopback proxy ports dynamically across v2rayN / Xray (`10808`, `10809`), Hiddify / NekoBox (`2080`, `2081`), Clash / Mihomo (`7890`), and standard SOCKS5 (`1080`) with short non-blocking timeouts (~50ms) instead of hardcoded values. + +#### 🔓 Chromium Loopback & OAuth Gatekeeper Unblock +- **Loopback Proxy Bypass List:** Injects `--proxy-bypass-list="<-loopback>"` to prevent Chromium's default loopback bypass from dropping local OAuth callbacks and loopback proxy communication. +- **Environment Variable Parity:** Injects both uppercase and lowercase proxy variables (`ALL_PROXY`, `all_proxy`, `HTTP_PROXY`, `http_proxy`, `HTTPS_PROXY`, `https_proxy`) and `NO_PROXY=localhost,127.0.0.1` so that child processes (Node.js utility workers, gRPC clients, Language Server) properly inherit proxy routes on Windows. + +#### 🐧 Dynamic WSL (Windows Subsystem for Linux) Self-Healing & Mirrored Networking +- **Zero-Hardcoding Distro Discovery:** Dynamically discovers all installed WSL distributions via `\\wsl.localhost\`, `\\wsl$\`, and the Windows Registry (`HKCU\...\Lxss`), without hardcoding distribution names. +- **Linux ELF Bytecode Patching:** Recursively discovers and patches Linux ELF `language_server` binaries across all user homes inside all WSL distros with the IDA bytecode unlock (`hasValidAuth = 1`). +- **Mirrored Networking Auto-Configuration:** Deploys `networkingMode=mirrored`, `dnsTunneling=true`, and `autoProxy=true` in `%USERPROFILE%\.wslconfig` cleanly while preserving all existing user settings. +- **Dynamic Shell Bridge Injection:** Injects dynamic proxy environment variables idempotently into `.bashrc` and `.zshrc` across all WSL distribution users. + +#### 🛡️ Dynamic Binary Flag Probing & Exit Status 2 Crash Prevention (#48) +- **Runtime Flag Probing:** Dynamically probes binary `--help` output before injecting `-stubby_auth_mode` or `-use_snapshot_mendelfp` flags into enterprise and wrapper profiles. +- **Fail-Safe Startup:** Prevents `language_server` crashes with `exit status 2: flags provided but not defined` on newer and older Google Antigravity core engine builds. + +--- + ## [5.4.7] - 2026-11-08 ### ⚡ Extension 1.10.0 Support, Multi-Editor Discovery, Account Manager & Dynamic Launcher diff --git a/cmd/antigravity/main.go b/cmd/antigravity/main.go index 9e473de..3de8485 100644 --- a/cmd/antigravity/main.go +++ b/cmd/antigravity/main.go @@ -23,7 +23,7 @@ import ( "github.com/tawroot/antigravity-cleaner/pkg/updater" ) -const Version = "5.4.7" +const Version = "5.4.8" func init() { patcher.RegisterPostInstallHook(func(logger patcher.LogFunc) { @@ -480,6 +480,13 @@ func runQuickAutoFix() { ui.PrintStatus("INFO", "Enterprise Wrapper", "Standalone mode (Core path detected on launch)") } + // Dynamic WSL environment healing & mirrored networking on Windows + if runtime.GOOS == "windows" { + if wslReport, err := patcher.PatchAllWsl(nil); err == nil && len(wslReport.DistrosFound) > 0 { + ui.PrintStatus("OK", "WSL Environment", fmt.Sprintf("%d distros patched (Mirrored Networking active)", len(wslReport.DistrosFound))) + } + } + fmt.Println() fmt.Println(lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("#FF79C6")).Render(" Step 4: Surgical Quota, DIPS & Network Cache Reset...")) if removed, err := cleaner.SurgicalReset429("", false); err != nil { diff --git a/install.ps1 b/install.ps1 index 90f3765..de620f0 100644 --- a/install.ps1 +++ b/install.ps1 @@ -1,5 +1,5 @@ $ErrorActionPreference = "SilentlyContinue" -$GithubBaseUrl = "https://github.com/tawroot/antigravity-cleaner/releases/latest/download" +$GithubBaseUrl = "https://github.com/dalroot/antigravity-cleaner/releases/latest/download" $ExeName = "antigravity-cleaner-windows-amd64.exe" $HomePath = if ($IsWindows -or $env:OS -like "*Windows*") { $env:USERPROFILE } else { $env:HOME } @@ -28,7 +28,7 @@ try { catch { Write-Host "Falling back to legacy PowerShell engine..." -ForegroundColor Gray $LegacyScript = Join-Path $InstallDir "Antigravity.ps1" - Invoke-WebRequest -Uri "https://raw.githubusercontent.com/tawroot/antigravity-cleaner/main/legacy/Antigravity.ps1" -OutFile $LegacyScript -UseBasicParsing + Invoke-WebRequest -Uri "https://raw.githubusercontent.com/dalroot/antigravity-cleaner/main/legacy/Antigravity.ps1" -OutFile $LegacyScript -UseBasicParsing Start-Process powershell.exe -ArgumentList "-NoProfile -ExecutionPolicy Bypass -File `"$LegacyScript`"" exit 0 } @@ -53,10 +53,12 @@ if ($UserPath -notlike "*$InstallDir*") { [Environment]::SetEnvironmentVariable("PATH", "$UserPath;$InstallDir", "User") Write-Host "Added $InstallDir to user PATH." -ForegroundColor Cyan } +# Immediately update current session PATH +$env:PATH = "$env:PATH;$InstallDir" Write-Host "" Write-Host "Installation Complete! Launching Antigravity Cleaner..." -ForegroundColor Green Write-Host "⭐ If this tool helped you, please star our repository on GitHub:" -ForegroundColor Yellow -Write-Host " https://github.com/tawroot/antigravity-cleaner" -ForegroundColor Cyan +Write-Host " https://github.com/dalroot/antigravity-cleaner" -ForegroundColor Cyan Write-Host "" Start-Process $TargetFile diff --git a/install.sh b/install.sh index e3ec805..80be1cd 100755 --- a/install.sh +++ b/install.sh @@ -3,8 +3,8 @@ set -e APP_NAME="antigravity-cleaner" INSTALL_DIR="${HOME}/.local/bin" -REPO="tawroot/antigravity-cleaner" -VERSION="v5.4.7" +REPO="dalroot/antigravity-cleaner" +VERSION="v5.4.8" echo "====================================================" echo " ⚡ Antigravity Cleaner — Universal AI Freedom Toolkit (${VERSION})" @@ -78,5 +78,5 @@ fi echo "" echo -e "\033[1;33m⭐ If Antigravity Cleaner helped you, please give it a star on GitHub:\033[0m" -echo -e "\033[1;36m https://github.com/tawroot/antigravity-cleaner\033[0m" +echo -e "\033[1;36m https://github.com/dalroot/antigravity-cleaner\033[0m" echo "" diff --git a/pkg/account/manager.go b/pkg/account/manager.go index 9e82a1f..ed4977f 100644 --- a/pkg/account/manager.go +++ b/pkg/account/manager.go @@ -96,6 +96,7 @@ var hubDirs = []string{ "Local Storage", "Session Storage", "Partitions", + "Network", } var hubCacheExcludes = []string{ @@ -349,12 +350,17 @@ func SwitchAccount(name string, dbPath string) error { _ = keyring.Set("gemini", "antigravity", secret) } - // 0b. Restore ~/.gemini/jetski-standalone-oauth-token for file-token mode (SSH spoofing) + // 0b. Restore ~/.gemini/jetski-standalone-oauth-token and Hub dir for file-token mode (SSH spoofing) tokenFilePath := StandaloneTokenFilePath() if tokenFilePath != "" && secret != "" { _ = os.MkdirAll(filepath.Dir(tokenFilePath), 0700) _ = os.WriteFile(tokenFilePath, []byte(secret), 0600) } + if hubDir != "" && secret != "" { + _ = os.WriteFile(filepath.Join(hubDir, "jetski-standalone-oauth-token"), []byte(secret), 0600) + _ = os.MkdirAll(filepath.Join(hubDir, "User"), 0700) + _ = os.WriteFile(filepath.Join(hubDir, "User", "jetski-standalone-oauth-token"), []byte(secret), 0600) + } // 1. Restore Hub files for _, f := range hubFiles { diff --git a/pkg/patcher/discovery.go b/pkg/patcher/discovery.go index 01df2d0..0f442d0 100644 --- a/pkg/patcher/discovery.go +++ b/pkg/patcher/discovery.go @@ -206,7 +206,7 @@ func scanWindowsProcess(targetName string) string { cleanName := strings.TrimSuffix(targetName, ".exe") filter := fmt.Sprintf("*%s*", cleanName) cmd := exec.Command("powershell", "-NoProfile", "-NonInteractive", "-Command", - fmt.Sprintf("(Get-Process | Where-Object { $_.Name -like '%s' -or $_.ProcessName -like '%s' } | Select-Object -ExpandProperty Path -ErrorAction SilentlyContinue)", filter, filter)) + fmt.Sprintf("(Get-Process -Name '%s' -ErrorAction SilentlyContinue).Path", filter)) out, err := cmd.Output() if err == nil { lines := strings.Split(strings.TrimSpace(string(out)), "\n") @@ -535,6 +535,8 @@ func GetStandardLanguageServerCandidates() []string { filepath.Join(os.Getenv("LOCALAPPDATA"), "Programs", "Antigravity IDE"), filepath.Join(os.Getenv("PROGRAMFILES"), "Antigravity"), filepath.Join(os.Getenv("ProgramFiles(x86)"), "Antigravity"), + filepath.Join(home, "scoop", "apps", "antigravity-ide", "current"), + filepath.Join(home, "scoop", "apps", "antigravity", "current"), filepath.Join(home, "antigravity"), } @@ -698,7 +700,13 @@ func FindAllLanguageServers(logger LogFunc) []string { filepath.Join(os.Getenv("LOCALAPPDATA"), "Programs", "Antigravity IDE"), filepath.Join(os.Getenv("PROGRAMFILES"), "Antigravity"), filepath.Join(os.Getenv("ProgramFiles(x86)"), "Antigravity"), + filepath.Join(home, "scoop", "apps", "antigravity-ide", "current"), + filepath.Join(home, "scoop", "apps", "antigravity", "current"), ) + // Scan all registered and active WSL distributions for Linux language_server ELF binaries + for _, wslServer := range FindAllWslLanguageServers(logger) { + add(wslServer) + } } else if runtime.GOOS == "linux" { candidateRoots = append(candidateRoots, filepath.Join(home, "Applications", "Antigravity"), @@ -778,6 +786,18 @@ func FindLanguageServerModular(logger LogFunc) string { func FindRunningLanguageServerPID() int { selfPid := os.Getpid() + if runtime.GOOS == "windows" { + cmd := exec.Command("powershell", "-NoProfile", "-NonInteractive", "-Command", + "(Get-Process -Name '*language_server*' -ErrorAction SilentlyContinue | Select-Object -First 1).Id") + if out, err := cmd.Output(); err == nil { + var pid int + if _, err := fmt.Sscanf(strings.TrimSpace(string(out)), "%d", &pid); err == nil && pid > 0 { + return pid + } + } + return 0 + } + if runtime.GOOS == "linux" { entries, err := os.ReadDir("/proc") if err == nil { diff --git a/pkg/patcher/flags.go b/pkg/patcher/flags.go index 873764b..79f86f7 100644 --- a/pkg/patcher/flags.go +++ b/pkg/patcher/flags.go @@ -1,8 +1,16 @@ package patcher import ( + "bufio" + "bytes" + "context" + "fmt" "log" + "os" + "os/exec" + "path/filepath" "strings" + "time" ) // defaultFlagsLogger provides structured logging with [FLAGS] tag @@ -136,6 +144,105 @@ func BuildServerFlags(opts EnterpriseFlagsOptions, logger LogFunc) []string { return flags } +// DetectSupportedFlags inspects a language_server binary to determine which CLI flags it natively supports. +// It executes ' --help' with a short timeout and parses the usage declaration. +// This prevents fatal Go runtime exits (status 2: 'flags provided but not defined') across different core builds (Issue #48). +func DetectSupportedFlags(binPath string) (map[string]bool, error) { + if binPath == "" { + return nil, fmt.Errorf("empty binary path") + } + if fi, err := os.Stat(binPath); err != nil || fi.IsDir() { + return nil, fmt.Errorf("invalid binary path %q: %w", binPath, err) + } + + supported := make(map[string]bool) + + // 1. Proactive execution probe with --help + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + + cmd := exec.CommandContext(ctx, binPath, "--help") + output, _ := cmd.CombinedOutput() + if len(output) > 0 { + scanner := bufio.NewScanner(bytes.NewReader(output)) + for scanner.Scan() { + line := strings.TrimSpace(scanner.Text()) + if strings.HasPrefix(line, "-") { + parts := strings.SplitN(line, ":", 2) + flagPart := strings.TrimLeft(parts[0], "-") + flagName := strings.TrimSpace(strings.SplitN(flagPart, "=", 2)[0]) + if flagName != "" { + supported[flagName] = true + } + } + } + } + + if len(supported) > 0 { + return supported, nil + } + + // 2. Fallback: Scan binary content for known flag string markers if --help yielded nothing + data, err := os.ReadFile(binPath) + if err != nil { + return nil, err + } + + candidateMarkers := []string{ + "disable_telemetry", + "is_google_internal", + "jetbox_release_channel", + "stubby_auth_mode", + "use_stubby_auth", + "use_local_chrome", + "browser_eval_env", + "local_chrome_headless", + } + + for _, m := range candidateMarkers { + if bytes.Contains(data, []byte(m)) { + supported[m] = true + } + } + + return supported, nil +} + +// FilterSupportedFlags validates candidate flags against the binary's actual registered flags. +// If supported flags cannot be probed (e.g. non-binary or mock test file), candidates are retained. +func FilterSupportedFlags(binPath string, candidateFlags []string, logger LogFunc) []string { + if binPath == "" || len(candidateFlags) == 0 { + return candidateFlags + } + + supported, err := DetectSupportedFlags(binPath) + if err != nil || len(supported) == 0 { + return candidateFlags + } + + binBase := filepath.Base(binPath) + var filtered []string + for _, flag := range candidateFlags { + flagName := strings.TrimLeft(flag, "-") + flagName = strings.TrimSpace(strings.SplitN(flagName, "=", 2)[0]) + if supported[flagName] { + filtered = append(filtered, flag) + } else { + if logger != nil { + logger("Probed %s: filtered unsupported runtime flag %s (preventing status 2 crash, closes #48)", binBase, flag) + } + } + } + + return filtered +} + +// BuildServerFlagsForBinary generates safe, verified CLI arguments specifically tailored for the target binary. +func BuildServerFlagsForBinary(binPath string, opts EnterpriseFlagsOptions, logger LogFunc) []string { + candidateFlags := BuildServerFlags(opts, logger) + return FilterSupportedFlags(binPath, candidateFlags, logger) +} + // MergeLaunchArguments merges recommended flags into an existing argument list without duplicates func MergeLaunchArguments(existingArgs []string, opts EnterpriseFlagsOptions, logger LogFunc) []string { diff --git a/pkg/patcher/flags_test.go b/pkg/patcher/flags_test.go index 797316e..3062eb9 100644 --- a/pkg/patcher/flags_test.go +++ b/pkg/patcher/flags_test.go @@ -2,6 +2,9 @@ package patcher import ( "fmt" + "os" + "path/filepath" + "strings" "testing" ) @@ -170,3 +173,101 @@ func BenchmarkMergeLaunchArguments(b *testing.B) { } } } + +func TestDetectAndFilterSupportedFlags(t *testing.T) { + tempDir := t.TempDir() + mockBin := filepath.Join(tempDir, "mock_language_server") + + // Create a mock executable that returns standard Go flag usage on --help + mockUsage := `#!/bin/sh +if [ "$1" = "--help" ]; then + echo "Usage of mock_language_server:" + echo " -disable_telemetry=false: If true, disable telemetry logging" + echo " -is_google_internal=false: Whether running in internal environment" + echo " -jetbox_release_channel=\"stable\": Release channel" + echo " -use_local_chrome=false: Whether to use local chrome" + exit 0 +fi +exit 0 +` + if err := os.WriteFile(mockBin, []byte(mockUsage), 0755); err != nil { + t.Fatalf("failed to write mock binary: %v", err) + } + + supported, err := DetectSupportedFlags(mockBin) + if err != nil { + t.Fatalf("DetectSupportedFlags failed: %v", err) + } + + if !supported["disable_telemetry"] { + t.Errorf("expected disable_telemetry to be detected") + } + if !supported["is_google_internal"] { + t.Errorf("expected is_google_internal to be detected") + } + if supported["stubby_auth_mode"] { + t.Errorf("did not expect stubby_auth_mode in mock usage") + } + if supported["use_snapshot_mendelfp"] { + t.Errorf("did not expect use_snapshot_mendelfp in mock usage") + } + + // Test FilterSupportedFlags + candidates := []string{ + "--disable_telemetry=true", + "--is_google_internal=true", + "--stubby_auth_mode=business_licensed_enterprise", + "--use_snapshot_mendelfp=true", + } + + var logs []string + filtered := FilterSupportedFlags(mockBin, candidates, func(format string, args ...interface{}) { + logs = append(logs, fmt.Sprintf(format, args...)) + }) + + if len(filtered) != 2 { + t.Fatalf("expected 2 filtered flags, got %d: %v", len(filtered), filtered) + } + if filtered[0] != "--disable_telemetry=true" || filtered[1] != "--is_google_internal=true" { + t.Errorf("unexpected filtered flags: %v", filtered) + } + + if len(logs) != 2 { + t.Errorf("expected 2 log messages for filtered flags, got %d: %v", len(logs), logs) + } +} + +func TestBuildServerFlagsForBinaryRealHostTargets(t *testing.T) { + opts := DefaultEnterpriseFlagsOptions() + targets := []string{ + "/opt/antigravity/resources/bin/language_server", + "/home/hokar/Applications/Antigravity/resources/bin/language_server", + } + + for _, target := range targets { + if _, err := os.Stat(target); err != nil { + continue + } + + var filteredLogs []string + safeFlags := BuildServerFlagsForBinary(target, opts, func(format string, args ...interface{}) { + filteredLogs = append(filteredLogs, fmt.Sprintf(format, args...)) + }) + + if len(safeFlags) == 0 { + t.Errorf("expected non-empty safe flags for %s", target) + } + + // Ensure that unsupported flags are NEVER present for the older binary (/opt/antigravity) + if strings.Contains(target, "/opt/antigravity") { + for _, f := range safeFlags { + if strings.Contains(f, "stubby_auth_mode") { + t.Errorf("target %s should not have stubby_auth_mode flag: %s", target, f) + } + if strings.Contains(f, "use_snapshot_mendelfp") { + t.Errorf("target %s should not have use_snapshot_mendelfp flag: %s", target, f) + } + } + } + } +} diff --git a/pkg/patcher/wrapper.go b/pkg/patcher/wrapper.go index b3b3fea..2f051f9 100644 --- a/pkg/patcher/wrapper.go +++ b/pkg/patcher/wrapper.go @@ -204,8 +204,8 @@ func (m *WrapperManager) InstallWrapper(opts EnterpriseFlagsOptions) error { _ = ResignDarwinBinary(originalBin) } - // 2. Build flags - flags := BuildServerFlags(opts, m.logger) + // 2. Build flags dynamically tailored to target binary (prevents Issue #48 status 2 flag crashes) + flags := BuildServerFlagsForBinary(originalBin, opts, m.logger) flagsStr := strings.Join(flags, " ") // Execute post-install hooks (e.g. bi-directional token bridge synchronization) diff --git a/pkg/patcher/wsl.go b/pkg/patcher/wsl.go new file mode 100644 index 0000000..5c1da7e --- /dev/null +++ b/pkg/patcher/wsl.go @@ -0,0 +1,483 @@ +package patcher + +import ( + "bufio" + "bytes" + "fmt" + "net" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "time" +) + +// WslDistroInfo holds discovered metadata about a WSL distribution +type WslDistroInfo struct { + Name string + RootPath string // e.g. \\wsl.localhost\Ubuntu +} + +// WslReport provides structured results of a WSL patch operation +type WslReport struct { + DistrosFound []string + ServersPatched []string + WslConfigUpdated bool + ShellRcsUpdated []string +} + +// FindWslDistroRoots dynamically discovers all installed WSL distribution roots +// without relying on hardcoded distribution names like "Ubuntu". +func FindWslDistroRoots(logger LogFunc) []WslDistroInfo { + if runtime.GOOS != "windows" { + return nil + } + if logger == nil { + logger = defaultLogger + } + + var distros []WslDistroInfo + seen := make(map[string]bool) + + addDistro := func(name, path string) { + name = strings.TrimSpace(name) + path = strings.TrimSpace(path) + if name == "" || path == "" { + return + } + clean := filepath.Clean(path) + if !seen[strings.ToLower(clean)] { + if fi, err := os.Stat(clean); err == nil && fi.IsDir() { + seen[strings.ToLower(clean)] = true + distros = append(distros, WslDistroInfo{ + Name: name, + RootPath: clean, + }) + logger("Discovered active WSL distribution: %s at %s", name, clean) + } + } + } + + // 1. Enumerate \\wsl.localhost\ (Modern Windows 10/11) + if entries, err := os.ReadDir(`\\wsl.localhost`); err == nil { + for _, e := range entries { + if e.IsDir() { + addDistro(e.Name(), filepath.Join(`\\wsl.localhost`, e.Name())) + } + } + } + + // 2. Fallback to legacy \\wsl$\ (Windows 10 1903+) + if entries, err := os.ReadDir(`\\wsl$`); err == nil { + for _, e := range entries { + if e.IsDir() { + addDistro(e.Name(), filepath.Join(`\\wsl$`, e.Name())) + } + } + } + + // 3. Fallback: Query registry via reg.exe for registered distributions + // HKCU\Software\Microsoft\Windows\CurrentVersion\Lxss + cmd := exec.Command("reg", "query", `HKCU\Software\Microsoft\Windows\CurrentVersion\Lxss`, "/s") + if out, err := cmd.Output(); err == nil { + scanner := bufio.NewScanner(bytes.NewReader(out)) + var currentDistroName string + var currentBasePath string + + for scanner.Scan() { + line := strings.TrimSpace(scanner.Text()) + if strings.HasPrefix(line, "HKEY_CURRENT_USER") { + if currentDistroName != "" { + addDistro(currentDistroName, filepath.Join(`\\wsl.localhost`, currentDistroName)) + addDistro(currentDistroName, filepath.Join(`\\wsl$`, currentDistroName)) + } + currentDistroName = "" + currentBasePath = "" + } else if strings.HasPrefix(line, "DistributionName") { + fields := strings.Fields(line) + if len(fields) >= 3 { + currentDistroName = fields[len(fields)-1] + } + } else if strings.HasPrefix(line, "BasePath") { + fields := strings.Fields(line) + if len(fields) >= 3 { + currentBasePath = fields[len(fields)-1] + _ = currentBasePath + } + } + } + if currentDistroName != "" { + addDistro(currentDistroName, filepath.Join(`\\wsl.localhost`, currentDistroName)) + addDistro(currentDistroName, filepath.Join(`\\wsl$`, currentDistroName)) + } + } + + return distros +} + +// FindAllWslLanguageServers recursively searches all user homes in all WSL distros +// for Linux language_server ELF binaries. +func FindAllWslLanguageServers(logger LogFunc) []string { + if runtime.GOOS != "windows" { + return nil + } + if logger == nil { + logger = defaultLogger + } + + distros := FindWslDistroRoots(logger) + if len(distros) == 0 { + return nil + } + + var results []string + seen := make(map[string]bool) + + addServer := func(p string) { + clean := filepath.Clean(p) + if !seen[strings.ToLower(clean)] { + if fi, err := os.Stat(clean); err == nil && !fi.IsDir() && fi.Size() > 10*1024*1024 { + // Verify ELF header + if isElfBinary(clean) { + seen[strings.ToLower(clean)] = true + results = append(results, clean) + logger("Found WSL Linux language_server ELF binary: %s (%d MB)", clean, fi.Size()/(1024*1024)) + } + } + } + } + + for _, d := range distros { + // Potential user home roots in Linux: /home/ and /root + var homeDirs []string + + // Scan /home + linuxHome := filepath.Join(d.RootPath, "home") + if entries, err := os.ReadDir(linuxHome); err == nil { + for _, e := range entries { + if e.IsDir() { + homeDirs = append(homeDirs, filepath.Join(linuxHome, e.Name())) + } + } + } + // Scan /root + rootHome := filepath.Join(d.RootPath, "root") + if fi, err := os.Stat(rootHome); err == nil && fi.IsDir() { + homeDirs = append(homeDirs, rootHome) + } + + // Common Antigravity & server directories within Linux user homes + serverSubdirs := []string{ + ".antigravity", + ".antigravity-server", + ".gemini", + ".vscode-server", + ".local/share/antigravity", + ".local/share/antigravity-ide", + } + + for _, h := range homeDirs { + for _, sub := range serverSubdirs { + targetDir := filepath.Join(h, filepath.FromSlash(sub)) + if fi, err := os.Stat(targetDir); err == nil && fi.IsDir() { + // Walk targetDir for any language_server binary + _ = filepath.Walk(targetDir, func(path string, info os.FileInfo, err error) error { + if err != nil || info == nil { + return nil + } + name := strings.ToLower(info.Name()) + // Avoid backups and intermediate files + if strings.HasSuffix(name, ".agybak") || strings.HasSuffix(name, ".old") || strings.HasSuffix(name, ".bin") { + return nil + } + if name == "language_server" || strings.HasPrefix(name, "language_server_") { + addServer(path) + } + return nil + }) + } + } + } + } + + return results +} + +// isElfBinary checks if a file begins with the standard 4-byte Linux ELF magic: 0x7F, 'E', 'L', 'F' +func isElfBinary(path string) bool { + f, err := os.Open(path) + if err != nil { + return false + } + defer f.Close() + + header := make([]byte, 4) + if _, err := f.Read(header); err != nil { + return false + } + return header[0] == 0x7f && header[1] == 'E' && header[2] == 'L' && header[3] == 'F' +} + +// DetectActiveLocalPort dynamically detects the fastest open local proxy port on 127.0.0.1 +func DetectActiveLocalPort() (int, string) { + candidates := []struct { + port int + scheme string + }{ + {10808, "socks5"}, + {2080, "socks5"}, + {7890, "socks5"}, + {1080, "socks5"}, + {10809, "http"}, + {2081, "http"}, + } + + for _, c := range candidates { + addr := fmt.Sprintf("127.0.0.1:%d", c.port) + conn, err := net.DialTimeout("tcp", addr, 60*time.Millisecond) + if err == nil { + conn.Close() + return c.port, c.scheme + } + } + + return 10808, "socks5" +} + +// ConfigureWslMirroredNetworking configures %USERPROFILE%\.wslconfig with +// networkingMode=mirrored, dnsTunneling=true, and autoProxy=true, +// preserving all existing user configurations without data destruction. +func ConfigureWslMirroredNetworking(logger LogFunc) (bool, error) { + if runtime.GOOS != "windows" { + return false, nil + } + if logger == nil { + logger = defaultLogger + } + + userProfile := os.Getenv("USERPROFILE") + if userProfile == "" { + home, err := os.UserHomeDir() + if err != nil { + return false, err + } + userProfile = home + } + + wslConfigPath := filepath.Join(userProfile, ".wslconfig") + + var lines []string + if data, err := os.ReadFile(wslConfigPath); err == nil { + scanner := bufio.NewScanner(bytes.NewReader(data)) + for scanner.Scan() { + lines = append(lines, scanner.Text()) + } + } + + // Key/value pairs to enforce in [wsl2] + targetKeys := map[string]string{ + "networkingmode": "mirrored", + "dnstunneling": "true", + "autoproxy": "true", + } + + wsl2SectionIdx := -1 + keysFound := make(map[string]bool) + + var outputLines []string + inWsl2Section := false + + for i, line := range lines { + trimmed := strings.TrimSpace(line) + if strings.HasPrefix(trimmed, "[") && strings.HasSuffix(trimmed, "]") { + sectionName := strings.ToLower(trimmed[1 : len(trimmed)-1]) + if sectionName == "wsl2" { + inWsl2Section = true + wsl2SectionIdx = i + } else { + inWsl2Section = false + } + outputLines = append(outputLines, line) + continue + } + + if inWsl2Section && strings.Contains(line, "=") { + parts := strings.SplitN(line, "=", 2) + k := strings.ToLower(strings.TrimSpace(parts[0])) + if newVal, isTarget := targetKeys[k]; isTarget { + keysFound[k] = true + outputLines = append(outputLines, fmt.Sprintf("%s=%s", parts[0], newVal)) + continue + } + } + + outputLines = append(outputLines, line) + } + + // If [wsl2] section was absent, add it + if wsl2SectionIdx == -1 { + if len(outputLines) > 0 && strings.TrimSpace(outputLines[len(outputLines)-1]) != "" { + outputLines = append(outputLines, "") + } + outputLines = append(outputLines, "[wsl2]") + outputLines = append(outputLines, "networkingMode=mirrored") + outputLines = append(outputLines, "dnsTunneling=true") + outputLines = append(outputLines, "autoProxy=true") + } else { + // If [wsl2] existed but some target keys were missing, append them into [wsl2] + var finalLines []string + inSection := false + for _, line := range outputLines { + finalLines = append(finalLines, line) + trimmed := strings.TrimSpace(line) + if strings.EqualFold(trimmed, "[wsl2]") { + inSection = true + for k, v := range targetKeys { + if !keysFound[k] { + // Format original casing + formattedKey := k + if k == "networkingmode" { + formattedKey = "networkingMode" + } else if k == "dnstunneling" { + formattedKey = "dnsTunneling" + } else if k == "autoproxy" { + formattedKey = "autoProxy" + } + finalLines = append(finalLines, fmt.Sprintf("%s=%s", formattedKey, v)) + } + } + } else if strings.HasPrefix(trimmed, "[") { + inSection = false + } + _ = inSection + } + outputLines = finalLines + } + + content := strings.Join(outputLines, "\r\n") + "\r\n" + if err := os.WriteFile(wslConfigPath, []byte(content), 0644); err != nil { + return false, fmt.Errorf("failed to write %s: %w", wslConfigPath, err) + } + + logger("Configured WSL Mirrored Networking in %s", wslConfigPath) + return true, nil +} + +// ConfigureWslShellRc idempotently injects dynamic proxy bridge variables into +// all user .bashrc and .zshrc files across all detected WSL distributions. +func ConfigureWslShellRc(distros []WslDistroInfo, port int, scheme string, logger LogFunc) []string { + if logger == nil { + logger = defaultLogger + } + + const markerStart = "# >>> Antigravity Cleaner WSL Proxy Bridge >>>" + const markerEnd = "# <<< Antigravity Cleaner WSL Proxy Bridge <<<" + + block := fmt.Sprintf(`%s +export ALL_PROXY="%s://127.0.0.1:%d" +export all_proxy="%s://127.0.0.1:%d" +export HTTP_PROXY="http://127.0.0.1:%d" +export http_proxy="http://127.0.0.1:%d" +export HTTPS_PROXY="http://127.0.0.1:%d" +export https_proxy="http://127.0.0.1:%d" +export NO_PROXY="localhost,127.0.0.1" +export no_proxy="localhost,127.0.0.1" +%s`, markerStart, scheme, port, scheme, port, port, port, port, port, markerEnd) + + var updatedFiles []string + + for _, d := range distros { + var homeDirs []string + linuxHome := filepath.Join(d.RootPath, "home") + if entries, err := os.ReadDir(linuxHome); err == nil { + for _, e := range entries { + if e.IsDir() { + homeDirs = append(homeDirs, filepath.Join(linuxHome, e.Name())) + } + } + } + rootHome := filepath.Join(d.RootPath, "root") + if fi, err := os.Stat(rootHome); err == nil && fi.IsDir() { + homeDirs = append(homeDirs, rootHome) + } + + for _, h := range homeDirs { + for _, rcName := range []string{".bashrc", ".zshrc"} { + rcPath := filepath.Join(h, rcName) + if fi, err := os.Stat(rcPath); err == nil && !fi.IsDir() { + contentBytes, err := os.ReadFile(rcPath) + if err != nil { + continue + } + content := string(contentBytes) + if strings.Contains(content, markerStart) && strings.Contains(content, markerEnd) { + // Replace existing block cleanly + startIdx := strings.Index(content, markerStart) + endIdx := strings.Index(content, markerEnd) + len(markerEnd) + newContent := content[:startIdx] + block + content[endIdx:] + _ = os.WriteFile(rcPath, []byte(newContent), 0644) + updatedFiles = append(updatedFiles, rcPath) + logger("Updated existing proxy bridge block in %s", rcPath) + } else { + // Append block + newContent := strings.TrimRight(content, "\r\n") + "\n\n" + block + "\n" + _ = os.WriteFile(rcPath, []byte(newContent), 0644) + updatedFiles = append(updatedFiles, rcPath) + logger("Injected new proxy bridge block into %s", rcPath) + } + } + } + } + } + + return updatedFiles +} + +// PatchAllWsl executes the complete dynamic WSL self-healing and anti-sanction suite: +// 1. Discovers all installed distributions dynamically without hardcoding. +// 2. Discovers and patches all Linux ELF language_server binaries in all distributions. +// 3. Deploys Mirrored Networking in %USERPROFILE%\.wslconfig to connect loopback seamlessly. +// 4. Injects dynamic proxy environment into all Linux shell configuration files. +func PatchAllWsl(logger LogFunc) (WslReport, error) { + if logger == nil { + logger = defaultLogger + } + + var report WslReport + + if runtime.GOOS != "windows" { + return report, nil + } + + distros := FindWslDistroRoots(logger) + for _, d := range distros { + report.DistrosFound = append(report.DistrosFound, fmt.Sprintf("%s (%s)", d.Name, d.RootPath)) + } + + // 1. Dynamic Port Discovery + port, scheme := DetectActiveLocalPort() + logger("Active local proxy detected for WSL bridge: %s://127.0.0.1:%d", scheme, port) + + // 2. Patch all Linux ELF language_server binaries + servers := FindAllWslLanguageServers(logger) + for _, s := range servers { + if msg, err := PatchSingleLanguageServer(s); err == nil { + report.ServersPatched = append(report.ServersPatched, fmt.Sprintf("%s [%s]", filepath.Base(s), msg)) + } else { + logger("Warning: failed to patch WSL language_server %s: %v", s, err) + } + } + + // 3. Configure Mirrored Networking + if updated, err := ConfigureWslMirroredNetworking(logger); err == nil && updated { + report.WslConfigUpdated = true + } + + // 4. Configure Shell RCs if any distros exist + if len(distros) > 0 { + report.ShellRcsUpdated = ConfigureWslShellRc(distros, port, scheme, logger) + } + + return report, nil +} diff --git a/pkg/proxy/launcher.go b/pkg/proxy/launcher.go index 2494791..54b527f 100644 --- a/pkg/proxy/launcher.go +++ b/pkg/proxy/launcher.go @@ -59,6 +59,13 @@ func FindAllAntigravityExecutables() []AppTarget { // Antigravity IDE (VS Code based) add("Antigravity IDE", filepath.Join(localAppData, "Programs", "Antigravity IDE", "Antigravity IDE.exe"), true) add("Antigravity IDE", filepath.Join(progFiles, "Antigravity IDE", "Antigravity IDE.exe"), true) + + // Scoop installations + userProfile := os.Getenv("USERPROFILE") + if userProfile != "" { + add("Antigravity", filepath.Join(userProfile, "scoop", "apps", "antigravity", "current", "Antigravity.exe"), false) + add("Antigravity IDE", filepath.Join(userProfile, "scoop", "apps", "antigravity-ide", "current", "Antigravity IDE.exe"), true) + } } // 2. Linux checks @@ -163,6 +170,8 @@ func BuildProxyEnv(proxyURL string) []string { overrides := map[string]string{ "ALL_PROXY": socksProxy, "all_proxy": socksProxy, + "NO_PROXY": "localhost,127.0.0.1", + "no_proxy": "localhost,127.0.0.1", "SSH_CONNECTION": "127.0.0.1 1234 127.0.0.1 22", // Remote environment spoofing: switches language_server to file-token mode "SSH_CLIENT": "127.0.0.1 1234 22", } @@ -244,9 +253,10 @@ func LaunchAntigravityWithProxy(appPath string, proxyURL string, extraArgs []str chromiumProxy := CleanChromiumProxyURL(proxyURL) - // Build arguments: pass --proxy-server to Chromium/Electron without quotes + // Build arguments: pass --proxy-server and loopback filter to Chromium/Electron without quotes args := []string{ fmt.Sprintf("--proxy-server=%s", chromiumProxy), + "--proxy-bypass-list=<-loopback>", } args = append(args, extraArgs...) @@ -483,36 +493,109 @@ exec "$APP_PATH" --proxy-server="${PROXY_TYPE}://127.0.0.1:${ACTIVE_PORT}" "$@" } if runtime.GOOS == "windows" { - chromiumProxy := CleanChromiumProxyURL(proxyURL) - batPath := filepath.Join(home, "Desktop", "Antigravity-NoTUN.bat") - - var proxyEnvLines string - if strings.HasPrefix(proxyURL, "socks") { - socksProxy := proxyURL - if !strings.HasPrefix(socksProxy, "socks5h://") && strings.HasPrefix(socksProxy, "socks5://") { - socksProxy = strings.Replace(socksProxy, "socks5://", "socks5h://", 1) - } - proxyEnvLines = fmt.Sprintf(`set "ALL_PROXY=%s" -set "HTTPS_PROXY=" -set "HTTP_PROXY="`, socksProxy) - } else { - proxyEnvLines = fmt.Sprintf(`set "ALL_PROXY=%s" -set "HTTPS_PROXY=%s" -set "HTTP_PROXY=%s"`, proxyURL, proxyURL, proxyURL) - } + cleanerAppDir := filepath.Join(home, "AppData", "Roaming", "antigravity-cleaner") + _ = os.MkdirAll(cleanerAppDir, 0755) + + ps1Path := filepath.Join(cleanerAppDir, "launcher.ps1") + vbsPath := filepath.Join(cleanerAppDir, "run.vbs") + batPath := filepath.Join(cleanerAppDir, "launcher.bat") + + // 1. Dynamic silent PowerShell launcher with auto-port detection and full env injection + launcherPs1Content := fmt.Sprintf(`param([string]$TargetAppPath = "%s") +$ErrorActionPreference = 'SilentlyContinue' + +$candidates = @( + @{ Port = 10808; Scheme = "socks5" }, + @{ Port = 2080; Scheme = "socks5" }, + @{ Port = 7890; Scheme = "http" }, + @{ Port = 1080; Scheme = "socks5" }, + @{ Port = 10809; Scheme = "http" }, + @{ Port = 2081; Scheme = "http" } +) + +$activePort = 10808 +$activeScheme = "socks5" + +foreach ($c in $candidates) { + $t = New-Object System.Net.Sockets.TcpClient + try { + $iar = $t.BeginConnect("127.0.0.1", $c.Port, $null, $null) + if ($iar.AsyncWaitHandle.WaitOne(60, $false) -and $t.Connected) { + $activePort = $c.Port + $activeScheme = $c.Scheme + $t.Close() + break + } + } catch {} finally { + $t.Close() + } +} + +$env:ALL_PROXY = "$($activeScheme)://127.0.0.1:$activePort" +$env:all_proxy = "$($activeScheme)://127.0.0.1:$activePort" +if ($activeScheme -eq "http") { + $env:HTTP_PROXY = "http://127.0.0.1:$activePort" + $env:http_proxy = "http://127.0.0.1:$activePort" + $env:HTTPS_PROXY = "http://127.0.0.1:$activePort" + $env:https_proxy = "http://127.0.0.1:$activePort" +} else { + $env:HTTP_PROXY = "" + $env:http_proxy = "" + $env:HTTPS_PROXY = "" + $env:https_proxy = "" +} +$env:NO_PROXY = "localhost,127.0.0.1" +$env:no_proxy = "localhost,127.0.0.1" +$env:SSH_CONNECTION = "127.0.0.1 1234 127.0.0.1 22" +$env:SSH_CLIENT = "127.0.0.1 1234 22" + +$appPath = $TargetAppPath +if (-not $appPath -or -not (Test-Path $appPath)) { + $appPath = "%s" +} +if (-not (Test-Path $appPath)) { + $appPath = "$env:LOCALAPPDATA\Programs\antigravity\Antigravity.exe" +} - content := fmt.Sprintf(`@echo off -%s +$arg1 = "--proxy-server=$($activeScheme)://127.0.0.1:$activePort" +$arg2 = '--proxy-bypass-list=<-loopback>' + +Start-Process -FilePath $appPath -ArgumentList @($arg1, $arg2) -WorkingDirectory (Split-Path $appPath) +`, appPath, appPath) + _ = os.WriteFile(ps1Path, []byte(launcherPs1Content), 0755) + + // 2. Silent VBS runner (Zero console window flash) + vbsContent := fmt.Sprintf(`Set shell = CreateObject("WScript.Shell") +ps1Path = "%s" +targetApp = "" +If WScript.Arguments.Count > 0 Then + targetApp = WScript.Arguments(0) +End If +cmd = "powershell.exe -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File """ & ps1Path & """ -TargetAppPath """ & targetApp & """" +shell.Run cmd, 0, False +`, ps1Path) + _ = os.WriteFile(vbsPath, []byte(vbsContent), 0755) + + // 3. Resilient Standalone Batch Launcher on Desktop + batContent := fmt.Sprintf(`@echo off +title Antigravity - No TUN Proxy + +set "ALL_PROXY=socks5://127.0.0.1:10808" +set "all_proxy=socks5://127.0.0.1:10808" +set "HTTP_PROXY=" +set "http_proxy=" +set "HTTPS_PROXY=" +set "https_proxy=" +set "NO_PROXY=localhost,127.0.0.1" +set "no_proxy=localhost,127.0.0.1" set "SSH_CONNECTION=127.0.0.1 1234 127.0.0.1 22" set "SSH_CLIENT=127.0.0.1 1234 22" -start "" "%s" --proxy-server=%s -`, proxyEnvLines, appPath, chromiumProxy) - if err := os.WriteFile(batPath, []byte(content), 0755); err != nil { - return "", err - } +start "" "%s" --proxy-server="socks5://127.0.0.1:10808" --proxy-bypass-list="<-loopback>" +`, appPath) + _ = os.WriteFile(batPath, []byte(batContent), 0755) - // Generate native Windows shortcuts (.lnk) for all installed targets + // 4. Generate native Windows shortcuts (.lnk) for all installed targets targets := FindAllAntigravityExecutables() if len(targets) == 0 { targets = []AppTarget{{Name: "Antigravity", ExePath: appPath}} @@ -523,20 +606,36 @@ start "" "%s" --proxy-server=%s lnkScript := fmt.Sprintf(` $WshShell = New-Object -comObject WScript.Shell $Shortcut = $WshShell.CreateShortcut("%s") -$Shortcut.TargetPath = "%s" -$Shortcut.Arguments = "--proxy-server=%s" +$Shortcut.TargetPath = "wscript.exe" +$Shortcut.Arguments = """%s"" ""%s""" $Shortcut.WorkingDirectory = "%s" $Shortcut.IconLocation = "%s,0" $Shortcut.Description = "Google %s with Smart Proxy" $Shortcut.Save() -`, lnkPath, t.ExePath, chromiumProxy, filepath.Dir(t.ExePath), t.ExePath, t.Name) +`, lnkPath, vbsPath, t.ExePath, filepath.Dir(t.ExePath), t.ExePath, t.Name) _ = exec.Command("powershell", "-NoProfile", "-NonInteractive", "-Command", lnkScript).Run() + + // Also patch Start Menu shortcut if exists + startMenuLnk := filepath.Join(home, "AppData", "Roaming", "Microsoft", "Windows", "Start Menu", "Programs", fmt.Sprintf("%s.lnk", t.Name)) + if _, err := os.Stat(startMenuLnk); err == nil { + startMenuScript := fmt.Sprintf(` +$WshShell = New-Object -comObject WScript.Shell +$Shortcut = $WshShell.CreateShortcut("%s") +$Shortcut.TargetPath = "wscript.exe" +$Shortcut.Arguments = """%s"" ""%s""" +$Shortcut.WorkingDirectory = "%s" +$Shortcut.IconLocation = "%s,0" +$Shortcut.Description = "Google %s with Smart Proxy" +$Shortcut.Save() +`, startMenuLnk, vbsPath, t.ExePath, filepath.Dir(t.ExePath), t.ExePath, t.Name) + _ = exec.Command("powershell", "-NoProfile", "-NonInteractive", "-Command", startMenuScript).Run() + } } if len(targets) > 1 { - return fmt.Sprintf("Desktop shortcuts created for Antigravity & Antigravity IDE (%s)", batPath), nil + return "Official Desktop & Start Menu shortcuts updated for Antigravity & Antigravity IDE", nil } - return batPath, nil + return "Official Desktop & Start Menu shortcuts successfully patched with Smart No-TUN Proxy", nil } return "", fmt.Errorf("desktop launcher generation not supported on %s", runtime.GOOS) diff --git a/pkg/quota/quota.go b/pkg/quota/quota.go index 94dc0c8..2d99ab9 100644 --- a/pkg/quota/quota.go +++ b/pkg/quota/quota.go @@ -2,14 +2,17 @@ package quota import ( "bytes" + "crypto/tls" "database/sql" "encoding/base64" "encoding/json" "fmt" "io" + "net" "net/http" "net/url" "os" + "os/exec" "path/filepath" "regexp" "runtime" @@ -40,6 +43,43 @@ func xorDecode(b []byte) string { return string(res) } +// getQuotaHttpClient returns an HTTP client routed through the best detected proxy (if available) +func getQuotaHttpClient() *http.Client { + var transport *http.Transport + + // Probe common loopback proxy ports without importing proxy package (prevents import cycle) + for _, port := range []int{10808, 2080, 7890, 1080, 10809, 2081} { + conn, err := net.DialTimeout("tcp", fmt.Sprintf("127.0.0.1:%d", port), 50*time.Millisecond) + if err == nil { + _ = conn.Close() + proxyType := "socks5" + if port == 7890 || port == 10809 || port == 2081 { + proxyType = "http" + } + if proxyURL, err := url.Parse(fmt.Sprintf("%s://127.0.0.1:%d", proxyType, port)); err == nil { + transport = &http.Transport{ + Proxy: http.ProxyURL(proxyURL), + TLSClientConfig: &tls.Config{ + InsecureSkipVerify: false, + }, + } + break + } + } + } + + if transport == nil { + transport = &http.Transport{ + Proxy: http.ProxyFromEnvironment, + } + } + + return &http.Client{ + Transport: transport, + Timeout: 15 * time.Second, + } +} + // QuotaBucket represents a time-window usage quota type QuotaBucket struct { BucketID string `json:"bucketId,omitempty"` @@ -185,6 +225,40 @@ func ExtractRefreshToken(dbPath string) (string, error) { return match, nil } } + + // Mode 1b: Check Standalone file token (jetski-standalone-oauth-token) in ~/.gemini or AppData + home, _ := os.UserHomeDir() + var tokenFiles []string + if home != "" { + tokenFiles = append(tokenFiles, filepath.Join(home, ".gemini", "jetski-standalone-oauth-token")) + } + if appData := os.Getenv("APPDATA"); appData != "" { + tokenFiles = append(tokenFiles, + filepath.Join(appData, "Antigravity", "jetski-standalone-oauth-token"), + filepath.Join(appData, "Antigravity", "User", "jetski-standalone-oauth-token"), + ) + } + for _, tf := range tokenFiles { + if data, err := os.ReadFile(tf); err == nil && len(data) > 0 { + var payload struct { + Token struct { + RefreshToken string `json:"refresh_token"` + } `json:"token"` + RefreshToken string `json:"refresh_token"` + } + if err := json.Unmarshal(data, &payload); err == nil { + if payload.Token.RefreshToken != "" { + return payload.Token.RefreshToken, nil + } + if payload.RefreshToken != "" { + return payload.RefreshToken, nil + } + } + if match := tokenRe.FindString(string(data)); match != "" { + return match, nil + } + } + } } // Mode 2: Check IDE (VS Code state.vscdb) @@ -255,7 +329,7 @@ func RefreshAccessToken(refreshToken string) (string, error) { form.Set("grant_type", "refresh_token") form.Set("refresh_token", refreshToken) - client := &http.Client{Timeout: 15 * time.Second} + client := getQuotaHttpClient() resp, err := client.PostForm("https://oauth2.googleapis.com/token", form) if err != nil { return "", fmt.Errorf("failed to contact oauth2.googleapis.com: %w", err) @@ -297,21 +371,35 @@ func DiscoverLanguageServerRPC() ([]QuotaGroup, error) { return nil, fmt.Errorf("language_server process not running") } - cmdlineBytes, err := os.ReadFile(fmt.Sprintf("/proc/%d/cmdline", pid)) - if err != nil { - return nil, fmt.Errorf("failed to read /proc/%d/cmdline: %w", pid, err) + var cmdlineStr string + if runtime.GOOS == "windows" { + cmd := exec.Command("powershell", "-NoProfile", "-NonInteractive", "-Command", + fmt.Sprintf("(Get-CimInstance Win32_Process -Filter 'ProcessId = %d').CommandLine", pid)) + if out, err := cmd.Output(); err == nil { + cmdlineStr = string(out) + } + } else { + if data, err := os.ReadFile(fmt.Sprintf("/proc/%d/cmdline", pid)); err == nil { + cmdlineStr = string(data) + } + } + + if cmdlineStr == "" { + return nil, fmt.Errorf("failed to read command line for language_server PID %d", pid) } - args := strings.Split(string(cmdlineBytes), "\x00") var csrfToken string - for i, arg := range args { - if (arg == "--csrf_token" || arg == "-csrf_token") && i+1 < len(args) { - csrfToken = args[i+1] + for _, arg := range strings.Fields(cmdlineStr) { + argClean := strings.Trim(arg, "\"'") + if strings.HasPrefix(argClean, "--csrf_token=") { + csrfToken = strings.TrimPrefix(argClean, "--csrf_token=") break } - if strings.HasPrefix(arg, "--csrf_token=") { - csrfToken = strings.TrimPrefix(arg, "--csrf_token=") - break + } + if csrfToken == "" { + re := regexp.MustCompile(`--csrf_token\s+([a-zA-Z0-9_-]+)`) + if m := re.FindStringSubmatch(cmdlineStr); len(m) > 1 { + csrfToken = m[1] } } @@ -369,6 +457,25 @@ func DiscoverLanguageServerRPC() ([]QuotaGroup, error) { } func findPIDListeningPorts(pid int) []int { + if runtime.GOOS == "windows" { + cmd := exec.Command("powershell", "-NoProfile", "-NonInteractive", "-Command", + fmt.Sprintf("(Get-NetTCPConnection -OwningProcess %d -State Listen -ErrorAction SilentlyContinue).LocalPort", pid)) + out, err := cmd.Output() + if err == nil { + var ports []int + for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") { + line = strings.TrimSpace(line) + if p, err := strconv.Atoi(line); err == nil && p > 0 && p <= 65535 { + ports = append(ports, p) + } + } + if len(ports) > 0 { + return ports + } + } + return nil + } + data, err := os.ReadFile(fmt.Sprintf("/proc/%d/net/tcp", pid)) if err != nil { return nil @@ -397,7 +504,7 @@ func findPIDListeningPorts(pid int) []int { // FetchQuotaSummaryFromCloud retrieves the quota summary from CloudCode API func FetchQuotaSummaryFromCloud(accessToken string) ([]QuotaGroup, error) { - client := &http.Client{Timeout: 15 * time.Second} + client := getQuotaHttpClient() req, err := http.NewRequest("POST", UsageURL, bytes.NewBuffer([]byte("{}"))) if err != nil { @@ -446,7 +553,7 @@ func FetchQuotaSummaryFromCloud(accessToken string) ([]QuotaGroup, error) { // FetchDetailedUserQuota retrieves individual model-by-model quotas from retrieveUserQuota API func FetchDetailedUserQuota(accessToken string) ([]DetailedQuotaBucket, error) { - client := &http.Client{Timeout: 15 * time.Second} + client := getQuotaHttpClient() req, err := http.NewRequest("POST", DetailedQuotaURL, bytes.NewBuffer([]byte("{}"))) if err != nil {