Repository navigation
Expand file tree
/
Copy pathapp.go
More file actions
3445 lines (3283 loc) · 117 KB
/
Copy pathapp.go
File metadata and controls
3445 lines (3283 loc) · 117 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"archive/tar"
"archive/zip"
"bufio"
"bytes"
"compress/gzip"
"context"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
goruntime "runtime"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/wailsapp/wails/v2/pkg/runtime"
"golang.org/x/crypto/curve25519"
"golang.org/x/crypto/ssh"
)
type App struct {
ctx context.Context
mu sync.Mutex
allowQuit bool
}
type SSHProfile struct {
ID string `json:"id"`
Name string `json:"name"`
Host string `json:"host"`
User string `json:"user"`
Username string `json:"username"`
Port int `json:"port"`
Password string `json:"password"`
}
type DeployConfig struct {
ProfileID string `json:"profileId"`
NodeName string `json:"nodeName"`
Selected []string `json:"selected"`
Ports map[string]int `json:"ports"`
PublicPorts map[string]int `json:"publicPorts"`
WebPort int `json:"webPort"`
PublicWebPort int `json:"publicWebPort"`
Token string `json:"token"`
Rule string `json:"rule"`
SNI string `json:"sni"`
}
type DeployEvent struct {
Type string `json:"type"`
Percent int `json:"percent,omitempty"`
Message string `json:"message"`
}
type CommandResult struct {
Code int `json:"code"`
Stdout string `json:"stdout"`
Stderr string `json:"stderr"`
}
type AppState struct {
Profiles []SSHProfile `json:"profiles"`
DeployConfig DeployConfig `json:"deployConfig"`
ActiveClient string `json:"activeClient"`
UpdatedAt string `json:"updatedAt"`
Extra map[string]any `json:"extra,omitempty"`
}
func NewApp() *App {
return &App{}
}
func proxyDataRoot() (string, error) {
if goruntime.GOOS == "windows" {
if base := strings.TrimSpace(os.Getenv("LOCALAPPDATA")); base != "" {
return filepath.Join(base, "proxy-installer"), nil
}
}
base, err := os.UserConfigDir()
if err != nil {
return "", err
}
return filepath.Join(base, "proxy-installer"), nil
}
func proxyDirs() (map[string]string, error) {
root, err := proxyDataRoot()
if err != nil {
return nil, err
}
return map[string]string{
"root": root,
"app": filepath.Join(root, "app"),
"data": filepath.Join(root, "data"),
"profiles": filepath.Join(root, "profiles"),
"reports": filepath.Join(root, "reports"),
"logs": filepath.Join(root, "logs"),
"cache": filepath.Join(root, "cache"),
"runtime": filepath.Join(root, "runtime"),
"webview": filepath.Join(root, "webview"),
}, nil
}
func ensureProxyDirs() (map[string]string, error) {
dirs, err := proxyDirs()
if err != nil {
return nil, err
}
for _, key := range []string{"data", "profiles", "reports", "logs", "cache", "runtime", "webview"} {
if err := os.MkdirAll(dirs[key], 0700); err != nil {
return nil, err
}
}
return dirs, nil
}
func appStatePath() (string, error) {
dirs, err := proxyDirs()
if err != nil {
return "", err
}
return filepath.Join(dirs["data"], "state.json"), nil
}
func (a *App) startup(ctx context.Context) {
a.ctx = ctx
_, _ = ensureProxyDirs()
}
func (a *App) beforeClose(ctx context.Context) bool {
a.mu.Lock()
allowQuit := a.allowQuit
a.mu.Unlock()
if allowQuit {
return false
}
runtime.WindowHide(ctx)
return true
}
func (a *App) showMainWindow() {
if a.ctx == nil {
return
}
runtime.Show(a.ctx)
runtime.WindowShow(a.ctx)
}
func (a *App) quitFromTray() {
a.mu.Lock()
a.allowQuit = true
a.mu.Unlock()
if a.ctx != nil {
runtime.Quit(a.ctx)
}
}
func (a *App) LoadAppState() (map[string]any, error) {
path, err := appStatePath()
if err != nil {
return nil, err
}
dirs, _ := ensureProxyDirs()
data, err := os.ReadFile(path)
if os.IsNotExist(err) {
return map[string]any{
"ok": true,
"path": path,
"dirs": dirs,
"profiles": []SSHProfile{},
}, nil
}
if err != nil {
return nil, err
}
var state AppState
if err := json.Unmarshal(data, &state); err != nil {
return nil, fmt.Errorf("读取本地配置失败: %w", err)
}
return map[string]any{
"ok": true,
"path": path,
"dirs": dirs,
"profiles": state.Profiles,
"deployConfig": state.DeployConfig,
"activeClient": state.ActiveClient,
"updatedAt": state.UpdatedAt,
"extra": state.Extra,
}, nil
}
func (a *App) SaveAppState(state AppState) (map[string]any, error) {
path, err := appStatePath()
if err != nil {
return nil, err
}
dirs, _ := ensureProxyDirs()
state.UpdatedAt = time.Now().Format(time.RFC3339)
if state.Extra == nil {
state.Extra = map[string]any{}
}
if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {
return nil, err
}
data, err := json.MarshalIndent(state, "", " ")
if err != nil {
return nil, err
}
tmp := path + ".tmp"
if err := os.WriteFile(tmp, data, 0600); err != nil {
return nil, err
}
if err := os.Rename(tmp, path); err != nil {
_ = os.Remove(tmp)
return nil, err
}
return map[string]any{"ok": true, "path": path, "dirs": dirs, "updatedAt": state.UpdatedAt}, nil
}
func savedProfileCount() int {
path, err := appStatePath()
if err != nil {
return 0
}
data, err := os.ReadFile(path)
if err != nil {
return 0
}
var state AppState
if json.Unmarshal(data, &state) != nil {
return 0
}
return len(state.Profiles)
}
func (a *App) TestConnection(profile SSHProfile) (map[string]any, error) {
client, err := a.connect(profile)
if err != nil {
return nil, err
}
defer client.Close()
result, err := runCommand(client, `printf 'ok:%s@%s\n' "$(whoami)" "$(hostname)"`, 10*time.Second)
if err != nil {
return nil, err
}
return map[string]any{"ok": true, "message": strings.TrimSpace(result.Stdout)}, nil
}
func (a *App) InspectVPS(profile SSHProfile) (map[string]any, error) {
client, err := a.connect(profile)
if err != nil {
return nil, err
}
defer client.Close()
result, err := runCommand(client, "bash -lc "+shellQuote(detectScript()), 45*time.Second)
if err != nil {
return nil, err
}
return map[string]any{
"ok": true,
"report": parseDetect(result.Stdout),
"raw": result.Stdout,
}, nil
}
func (a *App) CheckPorts(profile SSHProfile, ports []int) (map[string]any, error) {
client, err := a.connect(profile)
if err != nil {
return nil, err
}
defer client.Close()
var checks []string
for _, port := range ports {
if port < 1 || port > 65535 {
continue
}
checks = append(checks, fmt.Sprintf(`if (ss -lntup 2>/dev/null || netstat -lntup 2>/dev/null || true) | grep -Eq '[:.]%d([[:space:]]|$)'; then printf '%d=busy\n'; else printf '%d=free\n'; fi`, port, port, port))
}
script := "set +e\n" + strings.Join(checks, "\n")
result, err := runCommand(client, "bash -lc "+shellQuote(script), 20*time.Second)
if err != nil {
return nil, err
}
statuses := map[string]string{}
for _, line := range strings.Split(result.Stdout, "\n") {
parts := strings.SplitN(strings.TrimSpace(line), "=", 2)
if len(parts) == 2 {
statuses[parts[0]] = parts[1]
}
}
return map[string]any{"ok": true, "statuses": statuses}, nil
}
func (a *App) MeasureLatency(profile SSHProfile, config DeployConfig) (map[string]any, error) {
host := normalizeHostLiteral(profile.Host)
if host == "" {
return nil, fmt.Errorf("请输入 VPS 主机/IP")
}
if len(config.Selected) == 0 {
config.Selected = []string{"ss"}
}
config.Selected = filterSupportedProtocols(config.Selected)
if config.WebPort == 0 {
config.WebPort = 8080
}
if config.PublicWebPort == 0 {
config.PublicWebPort = config.WebPort
}
if config.Token == "" {
config.Token = "starter2026"
}
if config.Rule == "" {
config.Rule = "/sub/{token}/{client}"
}
var items []map[string]any
for _, id := range config.Selected {
def := protocolDefaults()[id]
port := publicPortOrDefault(config, id, def)
latency, status := probeTCP(host, port, 3, 4*time.Second)
items = append(items, map[string]any{
"kind": "node",
"protocol": protocolLabel(id),
"target": net.JoinHostPort(host, strconv.Itoa(port)),
"port": port,
"latencyMs": latency,
"status": status,
})
}
url := buildSubscriptionURL(host, config, "shadowrocket")
latency, status := probeHTTP(url, 6*time.Second)
items = append(items, map[string]any{
"kind": "subscription",
"protocol": "Shadowrocket 订阅",
"target": url,
"port": publicWebPortOrDefault(config),
"latencyMs": latency,
"status": status,
})
return map[string]any{"ok": true, "items": items, "checkedAt": time.Now().Format(time.RFC3339)}, nil
}
func (a *App) RunSpeedTest(profile SSHProfile) (map[string]any, error) {
client, err := a.connect(profile)
if err != nil {
return nil, err
}
defer client.Close()
script := `
set +e
if ! command -v curl >/dev/null 2>&1; then
printf 'error=missing curl\n'
exit 3
fi
last="curl_failed"
for family in "-4" "-6" ""; do
label="${family:-auto}"
if [ -n "$family" ]; then
out="$(curl "$family" -LfsS --connect-timeout 8 --max-time 28 -o /dev/null -w 'family='"$label"'\nhttp_code=%{http_code}\ntime_total=%{time_total}\nspeed_download=%{speed_download}\nremote_ip=%{remote_ip}\n' 'https://speed.cloudflare.com/__down?bytes=25000000' 2>/tmp/proxy-installer-speed.err)"
else
out="$(curl -LfsS --connect-timeout 8 --max-time 28 -o /dev/null -w 'family='"$label"'\nhttp_code=%{http_code}\ntime_total=%{time_total}\nspeed_download=%{speed_download}\nremote_ip=%{remote_ip}\n' 'https://speed.cloudflare.com/__down?bytes=25000000' 2>/tmp/proxy-installer-speed.err)"
fi
code=$?
if [ "$code" -eq 0 ]; then
printf '%s\n' "$out"
exit 0
fi
last="curl_${code}_${label}"
done
printf 'error=%s\n' "$last"
exit 7
`
result, err := runCommand(client, "bash -lc "+shellQuote(script), 32*time.Second)
if err != nil {
return nil, err
}
kv := parseKeyValue(result.Stdout)
if result.Code != 0 {
if kv["error"] != "" {
return nil, fmt.Errorf("%s", kv["error"])
}
return nil, fmt.Errorf("测速失败: %s", strings.TrimSpace(result.Stderr))
}
speedBytes, _ := strconv.ParseFloat(kv["speed_download"], 64)
totalSeconds, _ := strconv.ParseFloat(kv["time_total"], 64)
return map[string]any{
"ok": true,
"target": "speed.cloudflare.com",
"httpCode": kv["http_code"],
"timeSeconds": totalSeconds,
"downloadMbps": speedBytes * 8 / 1000 / 1000,
"downloadMBps": speedBytes / 1000 / 1000,
"remoteIp": kv["remote_ip"],
"family": kv["family"],
"checkedAt": time.Now().Format(time.RFC3339),
}, nil
}
func (a *App) RunNodeSpeedTest(profile SSHProfile, config DeployConfig) (map[string]any, error) {
host := normalizeHostLiteral(profile.Host)
if host == "" {
return nil, fmt.Errorf("请输入 VPS 主机/IP")
}
config.Selected = filterSupportedProtocols(config.Selected)
if len(config.Selected) == 0 {
return nil, fmt.Errorf("请选择至少一个协议")
}
bin, err := ensureLocalSingBox()
if err != nil {
return map[string]any{
"ok": false,
"skipped": true,
"reason": err.Error(),
"checkedAt": time.Now().Format(time.RFC3339),
}, nil
}
if config.Token == "" {
config.Token = "starter2026"
}
if config.SNI == "" {
config.SNI = "www.bing.com"
}
{
nodeName := safeName(config.NodeName, "starter-node")
token := safeToken(config.Token)
password := "Pwd_" + token + "_2026"
uuid := stableUUID(token)
_, realityPublic, realityShortID := realityKeys(token)
var protocols []map[string]any
var best map[string]any
for _, id := range config.Selected {
item := runSingleNodeSpeed(bin, host, config, id, nodeName, password, uuid, realityPublic, realityShortID)
protocols = append(protocols, item)
if item["ok"] == true {
if best == nil || floatFromAny(item["downloadMbps"]) > floatFromAny(best["downloadMbps"]) {
best = item
}
}
}
if best == nil {
return map[string]any{
"ok": false,
"via": "node",
"protocols": protocols,
"error": "所有协议节点测速均失败,请查看每个协议的错误详情",
"singBox": bin,
"checkedAt": time.Now().Format(time.RFC3339),
}, nil
}
return map[string]any{
"ok": true,
"via": "node",
"bestProtocol": best["protocol"],
"bestProtocolID": best["protocolID"],
"downloadMbps": best["downloadMbps"],
"downloadMBps": best["downloadMBps"],
"target": best["target"],
"protocols": protocols,
"singBox": bin,
"checkedAt": time.Now().Format(time.RFC3339),
}, nil
}
nodeName := safeName(config.NodeName, "starter-node")
token := safeToken(config.Token)
password := "Pwd_" + token + "_2026"
uuid := stableUUID(token)
_, realityPublic, realityShortID := realityKeys(token)
proxyPort, err := getFreeLocalPort()
if err != nil {
return nil, err
}
cfg, cfgSource, cfgWarning := nodeSpeedClientConfig(host, config, nodeName, password, uuid, realityPublic, realityShortID, proxyPort)
dir, err := os.MkdirTemp("", "proxy-installer-singbox-*")
if err != nil {
return nil, err
}
defer os.RemoveAll(dir)
configPath := filepath.Join(dir, "client.json")
if err := os.WriteFile(configPath, []byte(cfg), 0600); err != nil {
return nil, err
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
cmd := exec.CommandContext(ctx, bin, "run", "-c", configPath)
cmd.Env = filteredProxyEnv(os.Environ())
var stderr bytes.Buffer
cmd.Stderr = &stderr
if err := cmd.Start(); err != nil {
return nil, fmt.Errorf("启动本机 sing-box 失败: %w", err)
}
done := make(chan error, 1)
go func() { done <- cmd.Wait() }()
defer func() {
cancel()
killProcessTree(cmd.Process)
select {
case <-done:
case <-time.After(2 * time.Second):
}
}()
if err := waitLocalPort(proxyPort, 8*time.Second); err != nil {
select {
case runErr := <-done:
return nil, fmt.Errorf("本机 sing-box 退出: %v %s", runErr, strings.TrimSpace(stderr.String()))
default:
}
return nil, fmt.Errorf("本机代理未启动: %w %s", err, strings.TrimSpace(stderr.String()))
}
proxyURL := fmt.Sprintf("http://127.0.0.1:%d", proxyPort)
probe, err := runHTTPProbe(proxyURL, 12*time.Second)
if err != nil {
extra := ""
if cfgWarning != "" {
extra += ";" + cfgWarning
}
if msg := strings.TrimSpace(stderr.String()); msg != "" {
extra += ";sing-box: " + trimForMessage(msg, 400)
}
if usesUDPProtocol(config.Selected) {
extra += ";HY2/TUIC 需要公网 UDP 转发;如果是 NAT 机器,请确认公网 UDP 端口映射到 VPS 内部端口,并确认订阅端口返回的是配置而不是空响应。"
}
return nil, fmt.Errorf("%w%s", err, extra)
}
speed, err := runHTTPDownloadSpeed(proxyURL, 60*time.Second)
if err != nil {
return nil, err
}
speed["ok"] = true
speed["via"] = "node"
speed["probe"] = probe
speed["configSource"] = cfgSource
speed["configWarning"] = cfgWarning
speed["proxy"] = proxyURL
speed["singBox"] = bin
speed["checkedAt"] = time.Now().Format(time.RFC3339)
return speed, nil
}
func runSingleNodeSpeed(bin, host string, config DeployConfig, protocolID, nodeName, password, uuid, realityPublic, realityShortID string) map[string]any {
proxyPort, err := getFreeLocalPort()
if err != nil {
return nodeSpeedFailure(protocolID, config, fmt.Errorf("获取本地代理端口失败: %w", err), "", "")
}
single := config
single.Selected = []string{protocolID}
cfg := buildSingboxClientWithListen(host, single, nodeName, password, uuid, realityPublic, realityShortID, proxyPort)
cfgSource := "generated-protocol"
cfgWarning := ""
dir, err := os.MkdirTemp("", "proxy-installer-singbox-*")
if err != nil {
return nodeSpeedFailure(protocolID, config, err, cfgSource, cfgWarning)
}
defer os.RemoveAll(dir)
configPath := filepath.Join(dir, "client.json")
if err := os.WriteFile(configPath, []byte(cfg), 0600); err != nil {
return nodeSpeedFailure(protocolID, config, err, cfgSource, cfgWarning)
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
cmd := exec.CommandContext(ctx, bin, "run", "-c", configPath)
cmd.Env = filteredProxyEnv(os.Environ())
var stderr bytes.Buffer
cmd.Stderr = &stderr
if err := cmd.Start(); err != nil {
return nodeSpeedFailure(protocolID, config, fmt.Errorf("启动本地 sing-box 失败: %w", err), cfgSource, cfgWarning)
}
done := make(chan error, 1)
go func() { done <- cmd.Wait() }()
defer func() {
cancel()
killProcessTree(cmd.Process)
select {
case <-done:
case <-time.After(2 * time.Second):
}
}()
if err := waitLocalPort(proxyPort, 8*time.Second); err != nil {
select {
case runErr := <-done:
return nodeSpeedFailure(protocolID, config, fmt.Errorf("本地 sing-box 退出: %v %s", runErr, strings.TrimSpace(stderr.String())), cfgSource, cfgWarning)
default:
}
return nodeSpeedFailure(protocolID, config, fmt.Errorf("本地代理未启动: %w %s", err, strings.TrimSpace(stderr.String())), cfgSource, cfgWarning)
}
proxyURL := fmt.Sprintf("http://127.0.0.1:%d", proxyPort)
probe, err := runHTTPProbe(proxyURL, 12*time.Second)
if err != nil {
extra := ""
if cfgWarning != "" {
extra += ";" + cfgWarning
}
if msg := strings.TrimSpace(stderr.String()); msg != "" {
extra += ";sing-box: " + trimForMessage(msg, 400)
}
if usesUDPProtocol([]string{protocolID}) {
extra += ";HY2/TUIC 需要公网 UDP 转发,如果是 NAT 机器,请确认公网 UDP 端口已映射到 VPS 内部端口"
}
return nodeSpeedFailure(protocolID, config, fmt.Errorf("%w%s", err, extra), cfgSource, cfgWarning)
}
speed, err := runHTTPDownloadSpeed(proxyURL, 60*time.Second)
if err != nil {
return nodeSpeedFailure(protocolID, config, err, cfgSource, cfgWarning)
}
speed["ok"] = true
speed["via"] = "node"
speed["protocolID"] = protocolID
speed["protocol"] = protocolLabel(protocolID)
speed["port"] = publicPortOrDefault(config, protocolID, protocolDefaults()[protocolID])
speed["status"] = "ok"
speed["probe"] = probe
speed["configSource"] = cfgSource
speed["configWarning"] = cfgWarning
speed["proxy"] = proxyURL
speed["singBox"] = bin
speed["checkedAt"] = time.Now().Format(time.RFC3339)
return speed
}
func nodeSpeedFailure(protocolID string, config DeployConfig, err error, cfgSource, cfgWarning string) map[string]any {
return map[string]any{
"ok": false,
"via": "node",
"protocolID": protocolID,
"protocol": protocolLabel(protocolID),
"port": publicPortOrDefault(config, protocolID, protocolDefaults()[protocolID]),
"status": "failed",
"error": trimForMessage(strings.TrimSpace(err.Error()), 800),
"configSource": cfgSource,
"configWarning": cfgWarning,
"checkedAt": time.Now().Format(time.RFC3339),
}
}
func floatFromAny(value any) float64 {
switch v := value.(type) {
case float64:
return v
case float32:
return float64(v)
case int:
return float64(v)
case int64:
return float64(v)
case json.Number:
n, _ := v.Float64()
return n
default:
return 0
}
}
func (a *App) RunIPQuality(profile SSHProfile) (map[string]any, error) {
client, err := a.connect(profile)
if err != nil {
return nil, err
}
defer client.Close()
result, err := runCommand(client, "bash -lc "+shellQuote(ipQualityScript()), 110*time.Second)
if err != nil {
return nil, err
}
if result.Code != 0 {
kv := parseKeyValue(result.Stdout)
if kv["error"] != "" {
return nil, fmt.Errorf("%s", kv["error"])
}
return nil, fmt.Errorf("IP 纯净度检测失败: %s", strings.TrimSpace(result.Stderr))
}
raw, sourceErrors := parseIPQualitySources(result.Stdout)
if len(raw) == 0 && len(sourceErrors) == 0 {
return nil, fmt.Errorf("IP 纯净度检测失败: 没有拿到可解析的检测结果")
}
summary, sites, sections := buildQualityReport(raw, sourceErrors)
return map[string]any{
"ok": true,
"summary": summary,
"sites": sites,
"sections": sections,
"raw": raw,
"errors": sourceErrors,
"checkedAt": time.Now().Format(time.RFC3339),
}, nil
}
func (a *App) ScanFootprint(profile SSHProfile) (map[string]any, error) {
client, err := a.connect(profile)
if err != nil {
return nil, err
}
defer client.Close()
result, err := runCommand(client, "bash -lc "+shellQuote(footprintScanScript()), 35*time.Second)
if err != nil {
return nil, err
}
return parseFootprint(result.Stdout), nil
}
func (a *App) UninstallStarter(profile SSHProfile, removeRuntime bool) (map[string]any, error) {
client, err := a.connect(profile)
if err != nil {
return nil, err
}
defer client.Close()
result, err := runCommand(client, "bash -lc "+shellQuote(uninstallScript(removeRuntime)), 90*time.Second)
if err != nil {
return nil, err
}
logs := []string{}
for _, line := range strings.Split(result.Stdout, "\n") {
line = strings.TrimSpace(line)
if strings.HasPrefix(line, "LOG=") {
logs = append(logs, strings.TrimPrefix(line, "LOG="))
}
}
if result.Code != 0 {
return nil, fmt.Errorf("清理失败: %s", strings.TrimSpace(result.Stderr))
}
after, _ := runCommand(client, "bash -lc "+shellQuote(footprintScanScript()), 35*time.Second)
report := parseFootprint(after.Stdout)
report["logs"] = logs
report["ok"] = true
return report, nil
}
func (a *App) CleanupSelectedFootprint(profile SSHProfile, protocolIDs []string, removeRuntime bool) (map[string]any, error) {
ids := filterSupportedProtocols(protocolIDs)
if len(ids) == 0 {
return nil, fmt.Errorf("请选择要清理的协议")
}
client, err := a.connect(profile)
if err != nil {
return nil, err
}
defer client.Close()
result, err := runCommand(client, "bash -lc "+shellQuote(cleanupSelectedScript(ids, removeRuntime)), 90*time.Second)
if err != nil {
return nil, err
}
logs := []string{}
for _, line := range strings.Split(result.Stdout, "\n") {
line = strings.TrimSpace(line)
if strings.HasPrefix(line, "LOG=") {
logs = append(logs, strings.TrimPrefix(line, "LOG="))
}
}
if result.Code != 0 {
return nil, fmt.Errorf("清理选中协议失败: %s", strings.TrimSpace(result.Stderr))
}
after, _ := runCommand(client, "bash -lc "+shellQuote(footprintScanScript()), 35*time.Second)
report := parseFootprint(after.Stdout)
report["logs"] = logs
report["ok"] = true
return report, nil
}
func (a *App) StartDeploy(profile SSHProfile, config DeployConfig) (map[string]any, error) {
client, err := a.connect(profile)
if err != nil {
a.emit("error", 0, err.Error())
return nil, err
}
defer client.Close()
if config.SNI == "" {
config.SNI = "www.bing.com"
}
if config.WebPort == 0 {
config.WebPort = 8080
}
if config.Token == "" {
config.Token = "starter2026"
}
if config.Rule == "" {
config.Rule = "/sub/{token}/{client}"
}
if len(config.Selected) == 0 {
config.Selected = []string{"ss"}
}
script, err := buildDeployScript(profile, config)
if err != nil {
a.emit("error", 0, err.Error())
return nil, err
}
a.emit("progress", 2, "连接成功,开始远程部署")
code, err := a.runStreaming(client, "bash -lc "+shellQuote(script))
if err != nil {
a.emit("error", 0, err.Error())
return nil, err
}
if code == 11 {
a.emit("progress", 34, "远端下载 sing-box 失败,尝试由本机上传 Linux 二进制")
if uploadErr := a.installSingBoxViaUpload(client); uploadErr != nil {
msg := "本机上传 sing-box 兜底失败: " + uploadErr.Error()
a.emit("error", 34, msg)
return map[string]any{"ok": false, "code": code, "uploadError": uploadErr.Error()}, nil
}
a.emit("progress", 36, "sing-box 已上传,重新执行远程部署")
code, err = a.runStreaming(client, "bash -lc "+shellQuote(script))
if err != nil {
a.emit("error", 0, err.Error())
return nil, err
}
}
if code != 0 {
msg := fmt.Sprintf("部署失败,退出码 %d", code)
a.emit("error", 0, msg)
return map[string]any{"ok": false, "code": code}, nil
}
a.emit("done", 100, "部署完成")
return map[string]any{"ok": true, "code": 0}, nil
}
func (a *App) connect(profile SSHProfile) (*ssh.Client, error) {
host := normalizeHostLiteral(profile.Host)
if host == "" {
return nil, fmt.Errorf("请输入 VPS 主机/IP")
}
user := strings.TrimSpace(profile.User)
if user == "" {
user = strings.TrimSpace(profile.Username)
}
if user == "" {
user = "root"
}
port := profile.Port
if port == 0 {
port = 22
}
if profile.Password == "" {
return nil, fmt.Errorf("请输入 SSH 密码")
}
config := &ssh.ClientConfig{
User: user,
Auth: []ssh.AuthMethod{ssh.Password(profile.Password)},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
Timeout: 18 * time.Second,
}
addr := net.JoinHostPort(host, strconv.Itoa(port))
return ssh.Dial("tcp", addr, config)
}
func (a *App) emit(kind string, percent int, message string) {
if a.ctx == nil {
return
}
runtime.EventsEmit(a.ctx, "deploy:event", DeployEvent{Type: kind, Percent: percent, Message: message})
}
func (a *App) runStreaming(client *ssh.Client, command string) (int, error) {
session, err := client.NewSession()
if err != nil {
return -1, err
}
defer session.Close()
stdout, err := session.StdoutPipe()
if err != nil {
return -1, err
}
stderr, err := session.StderrPipe()
if err != nil {
return -1, err
}
var wg sync.WaitGroup
wg.Add(2)
go a.scanDeployStream(stdout, "log", &wg)
go a.scanDeployStream(stderr, "log", &wg)
if err := session.Start(command); err != nil {
return -1, err
}
err = session.Wait()
wg.Wait()
if err == nil {
return 0, nil
}
if exitErr, ok := err.(*ssh.ExitError); ok {
return exitErr.ExitStatus(), nil
}
return -1, err
}
func (a *App) scanDeployStream(reader io.Reader, fallbackType string, wg *sync.WaitGroup) {
defer wg.Done()
scanner := bufio.NewScanner(reader)
scanner.Buffer(make([]byte, 4096), 1024*1024)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line == "" {
continue
}
if strings.HasPrefix(line, "__VPS_STARTER_EVENT__|") {
parts := strings.SplitN(line, "|", 4)
if len(parts) == 4 {
percent, _ := strconv.Atoi(parts[2])
messageBytes, err := base64.StdEncoding.DecodeString(parts[3])
if err == nil {
a.emit(parts[1], percent, string(messageBytes))
continue
}
}
}
var event DeployEvent
if err := json.Unmarshal([]byte(line), &event); err == nil && event.Type != "" {
a.emit(event.Type, event.Percent, event.Message)
continue
}
a.emit(fallbackType, 0, line)
}
}
func runCommand(client *ssh.Client, command string, timeout time.Duration) (CommandResult, error) {
session, err := client.NewSession()
if err != nil {
return CommandResult{}, err
}
defer session.Close()
var stdout, stderr bytes.Buffer
session.Stdout = &stdout
session.Stderr = &stderr
done := make(chan error, 1)
go func() { done <- session.Run(command) }()
select {
case err := <-done:
code := 0
if err != nil {
if exitErr, ok := err.(*ssh.ExitError); ok {
code = exitErr.ExitStatus()
} else {
return CommandResult{}, err
}
}
return CommandResult{Code: code, Stdout: stdout.String(), Stderr: stderr.String()}, nil
case <-time.After(timeout):
_ = session.Signal(ssh.SIGKILL)
return CommandResult{}, fmt.Errorf("远程命令超时")
}
}
func parseDetect(text string) map[string]any {
kv := map[string]string{}
for _, line := range strings.Split(text, "\n") {
parts := strings.SplitN(line, "=", 2)
if len(parts) == 2 {
kv[parts[0]] = strings.Trim(parts[1], `"`)
}
}
return map[string]any{
"os": map[string]any{
"prettyName": kv["OS_PRETTY_NAME"],
"id": kv["OS_ID"],
"kernel": kv["KERNEL"],
"arch": kv["ARCH"],
"packageManager": packageManager(kv),