From d55098846661cee6614b25e73e544ac6d5900d8d Mon Sep 17 00:00:00 2001 From: tawroot Date: Sun, 15 Nov 2026 14:55:53 +0330 Subject: [PATCH 01/10] fix(windows): native silent shortcut overhaul, dynamic port scanner and loopback unblock --- CHANGELOG.md | 17 +++++ cmd/antigravity/main.go | 2 +- pkg/proxy/launcher.go | 146 +++++++++++++++++++++++++++++++--------- 3 files changed, 133 insertions(+), 32 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3503686..8264e43 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,23 @@ 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. + +--- + ## [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..94924c5 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) { diff --git a/pkg/proxy/launcher.go b/pkg/proxy/launcher.go index 2494791..7bfacc0 100644 --- a/pkg/proxy/launcher.go +++ b/pkg/proxy/launcher.go @@ -163,6 +163,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", } @@ -173,6 +175,13 @@ func BuildProxyEnv(proxyURL string) []string { overrides["HTTP_PROXY"] = httpProxy overrides["http_proxy"] = httpProxy overrides["GRPC_PROXY"] = httpProxy + } else if isSocks { + cleanAddr := CleanHostPort(proxyURL) + httpLoopback := fmt.Sprintf("http://%s", cleanAddr) + overrides["HTTPS_PROXY"] = httpLoopback + overrides["https_proxy"] = httpLoopback + overrides["HTTP_PROXY"] = httpLoopback + overrides["http_proxy"] = httpLoopback } // Filter existing proxy envs and sensitive leak variables @@ -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,94 @@ 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(`$ErrorActionPreference = 'SilentlyContinue' + +$candidates = @( + @{ Port = 10808; Scheme = "socks5" }, + @{ Port = 2080; Scheme = "socks5" }, + @{ Port = 7890; Scheme = "socks5" }, + @{ 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() + } +} - content := fmt.Sprintf(`@echo off -%s +$env:ALL_PROXY = "$($activeScheme)://127.0.0.1:$activePort" +$env:all_proxy = "$($activeScheme)://127.0.0.1:$activePort" +$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" +$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 = "%s" +if (-not (Test-Path $appPath)) { + $appPath = "$env:LOCALAPPDATA\Programs\antigravity\Antigravity.exe" +} + +$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) + _ = os.WriteFile(ps1Path, []byte(launcherPs1Content), 0755) + + // 2. Silent VBS runner (Zero console window flash) + vbsContent := fmt.Sprintf(`Set shell = CreateObject("WScript.Shell") +ps1Path = "%s" +cmd = "powershell.exe -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File """ & ps1Path & """" +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=http://127.0.0.1:10808" +set "http_proxy=http://127.0.0.1:10808" +set "HTTPS_PROXY=http://127.0.0.1:10808" +set "https_proxy=http://127.0.0.1:10808" +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 +591,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""" $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, 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""" +$Shortcut.WorkingDirectory = "%s" +$Shortcut.IconLocation = "%s,0" +$Shortcut.Description = "Google %s with Smart Proxy" +$Shortcut.Save() +`, startMenuLnk, vbsPath, 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) From 795e4962062c578249b0c6a737ee8dc13a9eedac Mon Sep 17 00:00:00 2001 From: tawroot Date: Sun, 15 Nov 2026 15:16:18 +0330 Subject: [PATCH 02/10] feat(wsl): dynamic zero-hardcoding WSL distro discovery, ELF bytecode patch and mirrored networking --- CHANGELOG.md | 6 + cmd/antigravity/main.go | 7 + pkg/patcher/discovery.go | 4 + pkg/patcher/wsl.go | 483 +++++++++++++++++++++++++++++++++++++++ 4 files changed, 500 insertions(+) create mode 100644 pkg/patcher/wsl.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 8264e43..5e4e806 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **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. + --- ## [5.4.7] - 2026-11-08 diff --git a/cmd/antigravity/main.go b/cmd/antigravity/main.go index 94924c5..3de8485 100644 --- a/cmd/antigravity/main.go +++ b/cmd/antigravity/main.go @@ -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/pkg/patcher/discovery.go b/pkg/patcher/discovery.go index 01df2d0..3576aee 100644 --- a/pkg/patcher/discovery.go +++ b/pkg/patcher/discovery.go @@ -699,6 +699,10 @@ func FindAllLanguageServers(logger LogFunc) []string { filepath.Join(os.Getenv("PROGRAMFILES"), "Antigravity"), filepath.Join(os.Getenv("ProgramFiles(x86)"), "Antigravity"), ) + // 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"), 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 +} From 3aa77fb9c993dda9d62e8bab0efc78b81ab3407d Mon Sep 17 00:00:00 2001 From: tawroot Date: Sun, 15 Nov 2026 15:30:14 +0330 Subject: [PATCH 03/10] fix(windows): backup Chromium Network dir and support Standalone token in quota monitor --- pkg/account/manager.go | 8 +++++++- pkg/quota/quota.go | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) 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/quota/quota.go b/pkg/quota/quota.go index 94dc0c8..34e8a26 100644 --- a/pkg/quota/quota.go +++ b/pkg/quota/quota.go @@ -185,6 +185,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) From 3c11cc2292d0862e5a610fc5a6b2c8d1ee208683 Mon Sep 17 00:00:00 2001 From: tawroot Date: Sun, 15 Nov 2026 15:56:45 +0330 Subject: [PATCH 04/10] feat(discovery): add Scoop installation roots for Antigravity on Windows --- pkg/patcher/discovery.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/pkg/patcher/discovery.go b/pkg/patcher/discovery.go index 3576aee..334e5c8 100644 --- a/pkg/patcher/discovery.go +++ b/pkg/patcher/discovery.go @@ -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,6 +700,8 @@ 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) { From 33fb04c8c21be258a65727270bf935a71abed5ea Mon Sep 17 00:00:00 2001 From: tawroot Date: Sun, 15 Nov 2026 16:05:22 +0330 Subject: [PATCH 05/10] fix(windows): optimize process scanning and add Scoop target paths in launcher --- pkg/patcher/discovery.go | 2 +- pkg/proxy/launcher.go | 7 +++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/pkg/patcher/discovery.go b/pkg/patcher/discovery.go index 334e5c8..9cb70d9 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") diff --git a/pkg/proxy/launcher.go b/pkg/proxy/launcher.go index 7bfacc0..82b821a 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 From 821d37708e7174b489285a3adbd78effb3fe2548 Mon Sep 17 00:00:00 2001 From: tawroot Date: Sun, 15 Nov 2026 16:17:58 +0330 Subject: [PATCH 06/10] fix(installer): update repository URLs to dalroot and auto-refresh session PATH on Windows --- install.ps1 | 10 ++++++---- install.sh | 4 ++-- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/install.ps1 b/install.ps1 index 90f3765..ccc2ac4 100644 --- a/install.ps1 +++ b/install.ps1 @@ -1,5 +1,5 @@ -$ErrorActionPreference = "SilentlyContinue" -$GithubBaseUrl = "https://github.com/tawroot/antigravity-cleaner/releases/latest/download" +$ErrorActionPreference = "SilentlyContinue" +$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..078fecc 100755 --- a/install.sh +++ b/install.sh @@ -3,7 +3,7 @@ set -e APP_NAME="antigravity-cleaner" INSTALL_DIR="${HOME}/.local/bin" -REPO="tawroot/antigravity-cleaner" +REPO="dalroot/antigravity-cleaner" VERSION="v5.4.7" echo "====================================================" @@ -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 "" From f0df73a0c8fd9d71c174396c73ff87902bdb7bd1 Mon Sep 17 00:00:00 2001 From: tawroot Date: Sun, 15 Nov 2026 16:46:15 +0330 Subject: [PATCH 07/10] fix(quota): route CloudCode API through loopback proxy and support Windows language_server RPC --- pkg/patcher/discovery.go | 12 ++++++ pkg/quota/quota.go | 88 ++++++++++++++++++++++++++++++++++------ 2 files changed, 87 insertions(+), 13 deletions(-) diff --git a/pkg/patcher/discovery.go b/pkg/patcher/discovery.go index 9cb70d9..0f442d0 100644 --- a/pkg/patcher/discovery.go +++ b/pkg/patcher/discovery.go @@ -786,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/quota/quota.go b/pkg/quota/quota.go index 34e8a26..9c652f9 100644 --- a/pkg/quota/quota.go +++ b/pkg/quota/quota.go @@ -2,6 +2,7 @@ package quota import ( "bytes" + "crypto/tls" "database/sql" "encoding/base64" "encoding/json" @@ -10,6 +11,7 @@ import ( "net/http" "net/url" "os" + "os/exec" "path/filepath" "regexp" "runtime" @@ -18,6 +20,7 @@ import ( "time" "github.com/tawroot/antigravity-cleaner/pkg/patcher" + "github.com/tawroot/antigravity-cleaner/pkg/proxy" "github.com/zalando/go-keyring" _ "modernc.org/sqlite" ) @@ -40,6 +43,32 @@ 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 { + bestProxy, _ := proxy.GetBestProxy() + var transport *http.Transport + if bestProxy != nil { + if proxyURL, err := url.Parse(bestProxy.URL); err == nil { + transport = &http.Transport{ + Proxy: http.ProxyURL(proxyURL), + TLSClientConfig: &tls.Config{ + InsecureSkipVerify: false, + }, + } + } + } + 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"` @@ -289,7 +318,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) @@ -331,21 +360,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] } } @@ -403,6 +446,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 @@ -431,7 +493,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 { @@ -480,7 +542,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 { From 25804350e4685aa20cfcfe898ca21fa670d1ad57 Mon Sep 17 00:00:00 2001 From: tawroot Date: Sun, 15 Nov 2026 17:01:13 +0330 Subject: [PATCH 08/10] fix(quota): resolve import cycle and route quota HTTP client through loopback proxy --- pkg/quota/quota.go | 29 ++++++++++++++++++++--------- 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/pkg/quota/quota.go b/pkg/quota/quota.go index 9c652f9..2d99ab9 100644 --- a/pkg/quota/quota.go +++ b/pkg/quota/quota.go @@ -8,6 +8,7 @@ import ( "encoding/json" "fmt" "io" + "net" "net/http" "net/url" "os" @@ -20,7 +21,6 @@ import ( "time" "github.com/tawroot/antigravity-cleaner/pkg/patcher" - "github.com/tawroot/antigravity-cleaner/pkg/proxy" "github.com/zalando/go-keyring" _ "modernc.org/sqlite" ) @@ -45,18 +45,29 @@ func xorDecode(b []byte) string { // getQuotaHttpClient returns an HTTP client routed through the best detected proxy (if available) func getQuotaHttpClient() *http.Client { - bestProxy, _ := proxy.GetBestProxy() var transport *http.Transport - if bestProxy != nil { - if proxyURL, err := url.Parse(bestProxy.URL); err == nil { - transport = &http.Transport{ - Proxy: http.ProxyURL(proxyURL), - TLSClientConfig: &tls.Config{ - InsecureSkipVerify: false, - }, + + // 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, From 858bb955f5bb75d8c9caca939eacffab48e85058 Mon Sep 17 00:00:00 2001 From: dalroot Date: Tue, 10 Nov 2026 20:06:37 +0330 Subject: [PATCH 09/10] fix(patcher): dynamically probe binary CLI flags to prevent exit status 2 crashes (closes #48) --- pkg/patcher/flags.go | 107 ++++++++++++++++++++++++++++++++++++++ pkg/patcher/flags_test.go | 101 +++++++++++++++++++++++++++++++++++ pkg/patcher/wrapper.go | 4 +- 3 files changed, 210 insertions(+), 2 deletions(-) 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) From cd95eef30b7154b1354881645e7c0de74b8264c2 Mon Sep 17 00:00:00 2001 From: dalroot Date: Mon, 16 Nov 2026 00:32:12 +0330 Subject: [PATCH 10/10] fix(proxy): isolate socks proxy env, fix multi-target shortcut dispatching and bump v5.4.8 --- CHANGELOG.md | 4 ++++ install.ps1 | 2 +- install.sh | 2 +- pkg/proxy/launcher.go | 56 ++++++++++++++++++++++++------------------- 4 files changed, 38 insertions(+), 26 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5e4e806..d7fba0c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **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 diff --git a/install.ps1 b/install.ps1 index ccc2ac4..de620f0 100644 --- a/install.ps1 +++ b/install.ps1 @@ -1,4 +1,4 @@ -$ErrorActionPreference = "SilentlyContinue" +$ErrorActionPreference = "SilentlyContinue" $GithubBaseUrl = "https://github.com/dalroot/antigravity-cleaner/releases/latest/download" $ExeName = "antigravity-cleaner-windows-amd64.exe" diff --git a/install.sh b/install.sh index 078fecc..80be1cd 100755 --- a/install.sh +++ b/install.sh @@ -4,7 +4,7 @@ set -e APP_NAME="antigravity-cleaner" INSTALL_DIR="${HOME}/.local/bin" REPO="dalroot/antigravity-cleaner" -VERSION="v5.4.7" +VERSION="v5.4.8" echo "====================================================" echo " ⚡ Antigravity Cleaner — Universal AI Freedom Toolkit (${VERSION})" diff --git a/pkg/proxy/launcher.go b/pkg/proxy/launcher.go index 82b821a..54b527f 100644 --- a/pkg/proxy/launcher.go +++ b/pkg/proxy/launcher.go @@ -182,13 +182,6 @@ func BuildProxyEnv(proxyURL string) []string { overrides["HTTP_PROXY"] = httpProxy overrides["http_proxy"] = httpProxy overrides["GRPC_PROXY"] = httpProxy - } else if isSocks { - cleanAddr := CleanHostPort(proxyURL) - httpLoopback := fmt.Sprintf("http://%s", cleanAddr) - overrides["HTTPS_PROXY"] = httpLoopback - overrides["https_proxy"] = httpLoopback - overrides["HTTP_PROXY"] = httpLoopback - overrides["http_proxy"] = httpLoopback } // Filter existing proxy envs and sensitive leak variables @@ -508,12 +501,13 @@ exec "$APP_PATH" --proxy-server="${PROXY_TYPE}://127.0.0.1:${ACTIVE_PORT}" "$@" batPath := filepath.Join(cleanerAppDir, "launcher.bat") // 1. Dynamic silent PowerShell launcher with auto-port detection and full env injection - launcherPs1Content := fmt.Sprintf(`$ErrorActionPreference = 'SilentlyContinue' + launcherPs1Content := fmt.Sprintf(`param([string]$TargetAppPath = "%s") +$ErrorActionPreference = 'SilentlyContinue' $candidates = @( @{ Port = 10808; Scheme = "socks5" }, @{ Port = 2080; Scheme = "socks5" }, - @{ Port = 7890; Scheme = "socks5" }, + @{ Port = 7890; Scheme = "http" }, @{ Port = 1080; Scheme = "socks5" }, @{ Port = 10809; Scheme = "http" }, @{ Port = 2081; Scheme = "http" } @@ -539,16 +533,26 @@ foreach ($c in $candidates) { $env:ALL_PROXY = "$($activeScheme)://127.0.0.1:$activePort" $env:all_proxy = "$($activeScheme)://127.0.0.1:$activePort" -$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" +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 = "%s" +$appPath = $TargetAppPath +if (-not $appPath -or -not (Test-Path $appPath)) { + $appPath = "%s" +} if (-not (Test-Path $appPath)) { $appPath = "$env:LOCALAPPDATA\Programs\antigravity\Antigravity.exe" } @@ -557,13 +561,17 @@ $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, 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" -cmd = "powershell.exe -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File """ & ps1Path & """" +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) @@ -574,10 +582,10 @@ 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=http://127.0.0.1:10808" -set "http_proxy=http://127.0.0.1:10808" -set "HTTPS_PROXY=http://127.0.0.1:10808" -set "https_proxy=http://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" @@ -599,12 +607,12 @@ start "" "%s" --proxy-server="socks5://127.0.0.1:10808" --proxy-bypass-list="<-l $WshShell = New-Object -comObject WScript.Shell $Shortcut = $WshShell.CreateShortcut("%s") $Shortcut.TargetPath = "wscript.exe" -$Shortcut.Arguments = """%s""" +$Shortcut.Arguments = """%s"" ""%s""" $Shortcut.WorkingDirectory = "%s" $Shortcut.IconLocation = "%s,0" $Shortcut.Description = "Google %s with Smart Proxy" $Shortcut.Save() -`, lnkPath, vbsPath, 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 @@ -614,12 +622,12 @@ $Shortcut.Save() $WshShell = New-Object -comObject WScript.Shell $Shortcut = $WshShell.CreateShortcut("%s") $Shortcut.TargetPath = "wscript.exe" -$Shortcut.Arguments = """%s""" +$Shortcut.Arguments = """%s"" ""%s""" $Shortcut.WorkingDirectory = "%s" $Shortcut.IconLocation = "%s,0" $Shortcut.Description = "Google %s with Smart Proxy" $Shortcut.Save() -`, startMenuLnk, vbsPath, filepath.Dir(t.ExePath), t.ExePath, t.Name) +`, startMenuLnk, vbsPath, t.ExePath, filepath.Dir(t.ExePath), t.ExePath, t.Name) _ = exec.Command("powershell", "-NoProfile", "-NonInteractive", "-Command", startMenuScript).Run() } }