Initial Navis client with NaiveProxy, profiles, ping and git updates

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Navis
2026-07-28 06:55:19 +03:00
co-authored by Cursor
commit 595bc3d70d
40 changed files with 3412 additions and 0 deletions
+192
View File
@@ -0,0 +1,192 @@
package naive
import (
"archive/zip"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"runtime"
"strings"
"time"
)
const githubAPILatest = "https://api.github.com/repos/klzgrad/naiveproxy/releases/latest"
// ResolveBinary finds naive.exe/naive in binDir or PATH.
func ResolveBinary(binDir string) (string, error) {
name := "naive"
if runtime.GOOS == "windows" {
name = "naive.exe"
}
candidates := []string{
filepath.Join(binDir, name),
filepath.Join(binDir, "naiveproxy", name),
}
if exe, err := os.Executable(); err == nil {
candidates = append(candidates, filepath.Join(filepath.Dir(exe), name))
candidates = append(candidates, filepath.Join(filepath.Dir(exe), "bin", name))
}
for _, c := range candidates {
if st, err := os.Stat(c); err == nil && !st.IsDir() {
return c, nil
}
}
return "", fmt.Errorf("naive binary not found (looked in %s); run: vpnclient install-core", binDir)
}
// EnsureBinary downloads the official Windows/Linux/macOS release if missing.
func EnsureBinary(binDir string) (string, error) {
if path, err := ResolveBinary(binDir); err == nil {
return path, nil
}
if err := os.MkdirAll(binDir, 0o755); err != nil {
return "", err
}
pattern, err := assetNameForPlatform()
if err != nil {
return "", err
}
fmt.Fprintf(os.Stderr, "downloading official naiveproxy release (%s)...\n", pattern)
assetName, url, err := findReleaseAsset(pattern)
if err != nil {
return "", err
}
zipPath := filepath.Join(binDir, assetName)
if err := downloadFile(zipPath, url); err != nil {
return "", err
}
defer os.Remove(zipPath)
if err := unzipNaive(zipPath, binDir); err != nil {
return "", err
}
return ResolveBinary(binDir)
}
func assetNameForPlatform() (string, error) {
switch {
case runtime.GOOS == "windows" && runtime.GOARCH == "amd64":
return "naiveproxy-*-win-x64.zip", nil
case runtime.GOOS == "windows" && runtime.GOARCH == "arm64":
return "naiveproxy-*-win-arm64.zip", nil
case runtime.GOOS == "linux" && runtime.GOARCH == "amd64":
return "naiveproxy-*-linux-x64.zip", nil
case runtime.GOOS == "darwin" && runtime.GOARCH == "amd64":
return "naiveproxy-*-mac-x64.tar.xz", nil
case runtime.GOOS == "darwin" && runtime.GOARCH == "arm64":
return "naiveproxy-*-mac-arm64.tar.xz", nil
default:
return "", fmt.Errorf("unsupported platform %s/%s for auto-download; place naive binary in bin/", runtime.GOOS, runtime.GOARCH)
}
}
type ghRelease struct {
TagName string `json:"tag_name"`
Assets []struct {
Name string `json:"name"`
BrowserDownloadURL string `json:"browser_download_url"`
} `json:"assets"`
}
func findReleaseAsset(pattern string) (name, downloadURL string, err error) {
client := &http.Client{Timeout: 60 * time.Second}
req, err := http.NewRequest(http.MethodGet, githubAPILatest, nil)
if err != nil {
return "", "", err
}
req.Header.Set("Accept", "application/vnd.github+json")
req.Header.Set("User-Agent", "vpnclient-go")
resp, err := client.Do(req)
if err != nil {
return "", "", fmt.Errorf("github api: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(io.LimitReader(resp.Body, 512))
return "", "", fmt.Errorf("github api: %s: %s", resp.Status, string(body))
}
var rel ghRelease
if err := json.NewDecoder(resp.Body).Decode(&rel); err != nil {
return "", "", err
}
prefix := strings.Split(pattern, "*")[0]
suffix := ""
if parts := strings.Split(pattern, "*"); len(parts) == 2 {
suffix = parts[1]
}
for _, a := range rel.Assets {
if strings.HasPrefix(a.Name, prefix) && strings.HasSuffix(a.Name, suffix) {
if strings.Contains(a.Name, ".tar.") {
return "", "", fmt.Errorf("auto-extract of %s not implemented; download manually from %s", a.Name, a.BrowserDownloadURL)
}
return a.Name, a.BrowserDownloadURL, nil
}
}
return "", "", fmt.Errorf("no asset matching %s in release %s", pattern, rel.TagName)
}
func downloadFile(path, url string) error {
client := &http.Client{Timeout: 10 * time.Minute}
resp, err := client.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("download %s: %s", url, resp.Status)
}
f, err := os.Create(path)
if err != nil {
return err
}
defer f.Close()
_, err = io.Copy(f, resp.Body)
return err
}
func unzipNaive(zipPath, destDir string) error {
r, err := zip.OpenReader(zipPath)
if err != nil {
return err
}
defer r.Close()
want := "naive"
if runtime.GOOS == "windows" {
want = "naive.exe"
}
var found bool
for _, f := range r.File {
base := filepath.Base(f.Name)
if base != want {
continue
}
if err := extractFile(f, filepath.Join(destDir, want)); err != nil {
return err
}
found = true
break
}
if !found {
return fmt.Errorf("zip does not contain %s", want)
}
return nil
}
func extractFile(f *zip.File, dest string) error {
rc, err := f.Open()
if err != nil {
return err
}
defer rc.Close()
out, err := os.OpenFile(dest, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o755)
if err != nil {
return err
}
defer out.Close()
_, err = io.Copy(out, rc)
return err
}
+221
View File
@@ -0,0 +1,221 @@
package naive
import (
"context"
"encoding/json"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"sync"
"time"
"vpnclient/internal/config"
)
// Engine runs the official Chromium-based naive binary.
// NaiveProxy cannot be reimplemented in pure Go: TLS/H2 fingerprints
// must match Chrome, which requires the upstream naive.exe.
type Engine struct {
mu sync.Mutex
cmd *exec.Cmd
cancel context.CancelFunc
done chan struct{}
workdir string
profile config.Profile
stderr io.Writer
running bool
}
func New(stderr io.Writer) *Engine {
if stderr == nil {
stderr = os.Stderr
}
return &Engine{stderr: stderr}
}
func (e *Engine) Protocol() config.Protocol { return config.ProtocolNaive }
func (e *Engine) Start(ctx context.Context, profile config.Profile, binDir string) error {
e.mu.Lock()
defer e.mu.Unlock()
if e.running {
return fmt.Errorf("naive: already running")
}
bin, err := ResolveBinary(binDir)
if err != nil {
return err
}
workdir, err := os.MkdirTemp("", "vpnclient-naive-*")
if err != nil {
return fmt.Errorf("naive: temp dir: %w", err)
}
cfgPath := filepath.Join(workdir, "config.json")
if err := writeRuntimeConfig(cfgPath, profile); err != nil {
os.RemoveAll(workdir)
return err
}
runCtx, cancel := context.WithCancel(context.Background())
cmd := exec.CommandContext(runCtx, bin, cfgPath)
cmd.Dir = workdir
cmd.Stdout = e.stderr
cmd.Stderr = e.stderr
applySysProcAttr(cmd)
env := os.Environ()
for k, v := range profile.Env {
env = append(env, k+"="+v)
}
cmd.Env = env
if err := cmd.Start(); err != nil {
cancel()
os.RemoveAll(workdir)
return fmt.Errorf("naive: start %s: %w", bin, err)
}
done := make(chan struct{})
e.cmd = cmd
e.cancel = cancel
e.done = done
e.workdir = workdir
e.profile = profile
e.running = true
go func() {
err := cmd.Wait()
if err != nil {
fmt.Fprintf(e.stderr, "naive: process ended: %v\n", err)
}
e.mu.Lock()
e.cleanupLocked()
e.mu.Unlock()
close(done)
}()
// Release lock while waiting so the Wait goroutine can clean up.
e.mu.Unlock()
timer := time.NewTimer(800 * time.Millisecond)
defer timer.Stop()
var startErr error
select {
case <-done:
startErr = fmt.Errorf("naive: process exited immediately; check proxy URI, credentials, and binary")
case <-ctx.Done():
_ = e.Stop()
startErr = ctx.Err()
case <-timer.C:
e.mu.Lock()
alive := e.running
e.mu.Unlock()
if !alive {
startErr = fmt.Errorf("naive: process exited during startup")
}
}
e.mu.Lock()
return startErr
}
func (e *Engine) Stop() error {
e.mu.Lock()
defer e.mu.Unlock()
return e.stopLocked()
}
func (e *Engine) stopLocked() error {
if !e.running || e.cmd == nil {
return nil
}
done := e.done
if e.cancel != nil {
e.cancel()
}
proc := e.cmd.Process
e.mu.Unlock()
select {
case <-done:
case <-time.After(2 * time.Second):
if proc != nil {
_ = proc.Kill()
}
<-done
}
e.mu.Lock()
return nil
}
func (e *Engine) cleanupLocked() {
if e.workdir != "" {
_ = os.RemoveAll(e.workdir)
e.workdir = ""
}
e.cmd = nil
e.cancel = nil
e.running = false
}
func (e *Engine) Running() bool {
e.mu.Lock()
defer e.mu.Unlock()
return e.running
}
func (e *Engine) LocalHTTPProxy() (string, bool) {
e.mu.Lock()
defer e.mu.Unlock()
if !e.running {
return "", false
}
return e.profile.HTTPListenHostPort()
}
func (e *Engine) LocalSOCKSProxy() (string, bool) {
e.mu.Lock()
defer e.mu.Unlock()
if !e.running {
return "", false
}
return e.profile.SOCKSListenHostPort()
}
type runtimeConfig struct {
Listen any `json:"listen"`
Proxy string `json:"proxy"`
InsecureConcurrency int `json:"insecure-concurrency,omitempty"`
ExtraHeaders string `json:"extra-headers,omitempty"`
HostResolverRules string `json:"host-resolver-rules,omitempty"`
Log string `json:"log,omitempty"`
NoPostQuantum bool `json:"no-post-quantum,omitempty"`
}
func writeRuntimeConfig(path string, profile config.Profile) error {
listen := profile.DefaultListen()
var listenField any = listen
if len(listen) == 1 {
listenField = listen[0]
}
proxy, err := NormalizeProxyURI(profile.Proxy)
if err != nil {
return err
}
rc := runtimeConfig{
Listen: listenField,
Proxy: proxy,
InsecureConcurrency: profile.InsecureConcurrency,
ExtraHeaders: profile.ExtraHeaders,
HostResolverRules: profile.HostResolverRules,
Log: profile.Log,
NoPostQuantum: profile.NoPostQuantum,
}
data, err := json.MarshalIndent(rc, "", " ")
if err != nil {
return err
}
data = append(data, '\n')
return os.WriteFile(path, data, 0o600)
}
+7
View File
@@ -0,0 +1,7 @@
//go:build !windows
package naive
import "os/exec"
func applySysProcAttr(cmd *exec.Cmd) {}
+12
View File
@@ -0,0 +1,12 @@
//go:build windows
package naive
import (
"os/exec"
"syscall"
)
func applySysProcAttr(cmd *exec.Cmd) {
cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
}
+68
View File
@@ -0,0 +1,68 @@
package naive
import (
"fmt"
"net/url"
"strings"
)
// NormalizeProxyURI converts share links and aliases into a naive --proxy URI.
//
// Supported inputs:
// - https://user:pass@host:443
// - quic://user:pass@host
// - naive+https://user:pass@host:443#remark
// - naive+quic://user:pass@host#remark
func NormalizeProxyURI(raw string) (string, error) {
uri, _, err := ParseShareLink(raw)
return uri, err
}
// ParseShareLink returns a normalized proxy URI and optional remark from #fragment.
func ParseShareLink(raw string) (proxyURI, remark string, err error) {
raw = strings.TrimSpace(raw)
if raw == "" {
return "", "", fmt.Errorf("empty proxy URI")
}
if i := strings.IndexByte(raw, '#'); i >= 0 {
remark = strings.TrimSpace(raw[i+1:])
raw = raw[:i]
}
lower := strings.ToLower(raw)
switch {
case strings.HasPrefix(lower, "naive+https://"):
raw = "https://" + raw[len("naive+https://"):]
case strings.HasPrefix(lower, "naive+quic://"):
raw = "quic://" + raw[len("naive+quic://"):]
case strings.HasPrefix(lower, "naive://"):
raw = "https://" + raw[len("naive://"):]
}
u, err := url.Parse(raw)
if err != nil {
return "", "", fmt.Errorf("parse proxy URI: %w", err)
}
switch strings.ToLower(u.Scheme) {
case "https", "quic", "http":
default:
return "", "", fmt.Errorf("unsupported proxy scheme %q (use https://, quic:// or naive+https://)", u.Scheme)
}
if u.Host == "" {
return "", "", fmt.Errorf("proxy URI missing host")
}
if u.User == nil || u.User.Username() == "" {
return "", "", fmt.Errorf("proxy URI missing username")
}
if _, ok := u.User.Password(); !ok {
return "", "", fmt.Errorf("proxy URI missing password")
}
out := &url.URL{
Scheme: strings.ToLower(u.Scheme),
User: u.User,
Host: u.Host,
}
return out.String(), remark, nil
}
+23
View File
@@ -0,0 +1,23 @@
package naive
import "testing"
func TestNormalizeProxyURI(t *testing.T) {
in := "naive+https://user:pass@de50.example.com:443#site_u1_s454"
got, err := NormalizeProxyURI(in)
if err != nil {
t.Fatal(err)
}
want := "https://user:pass@de50.example.com:443"
if got != want {
t.Fatalf("got %q want %q", got, want)
}
got, err = NormalizeProxyURI("quic://user:pass@host")
if err != nil {
t.Fatal(err)
}
if got != "quic://user:pass@host" {
t.Fatalf("got %q", got)
}
}