dsh-plugin-weapp-gateway 0.8.65 → 0.8.66

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -6,6 +6,14 @@
6
6
 
7
7
  `dsh-plugin-weapp-gateway` · DeepSeek Harness 移动客户端连接插件
8
8
 
9
+ ### v0.8.66 · 内嵌节点代理、HTTPS 与单实例稳定性
10
+
11
+ - **内嵌节点支持 HTTP 代理**:`tailscaleProxy` 可显式指定本机代理,设为 `off` 可彻底关闭探测;未配置时自动探测本机 24 个常见 HTTP CONNECT / SOCKS5 端口,适配 fake-ip 代理环境(如 Clash)。配置说明见 [docs/tailscale-node.md](docs/tailscale-node.md)。
12
+ - **443/wss 与 TLS 重试**:新增 `tailscaleHttps` 开关(默认开),关闭后只提供 tailnet 内的 ws 地址;TLS(443) 监听失败会重试,并在状态中暴露 `httpsError`,避免证书签发滞后时静默不可用。
13
+ - **单实例与自动重拉**:helper 改用 flock 单实例锁(进程被 SIGKILL 自动释放),并复核 pid 存活、异常退出自动重拉,修复同 key 双进程触发 Duplicate node key 的问题;内嵌节点使用独立状态目录,配对载荷纳入配置入口。
14
+ - **依赖升级**:内嵌 tsnet 升级到 tailscale.com v1.104.7。
15
+ - 新增「首次使用(安装 → 授权 → 扫码)」章节与内嵌节点安装/授权指引。
16
+
9
17
  ### v0.8.65 · 版本号与远端 tag 对齐
10
18
 
11
19
  - 远端已有 v0.8.62/63/64 三个 tag(Tailscale 迭代),但 `package.json` 仍停在 0.8.61;本版把版本号推进到 0.8.65 并补发 npm,避免 tag 与包版本错位。内容与 v0.8.62 发布说明一致(Tailscale 内嵌节点 + 面板重排 + lan 测试修正)。
@@ -328,6 +336,20 @@ DeepSeek Harness 的设备鉴权移动连接插件,支持会话与实时事件
328
336
  >
329
337
  > v0.7.2:新增独立对话/控制连接、空 Session 创建、停止生成与稍后继续、排队消息同步及编辑/删除/Steer,以及 Session 归档和重命名的双向同步。
330
338
 
339
+
340
+ ## 首次使用(安装 → 授权 → 扫码)
341
+
342
+ 1. **安装/升级插件后重启 DSH**(插件在 DSH 启动时加载,否则面板里看不到 Tailscale 卡片)。
343
+ 2. 面板 → Tailscale → 点「启动隧道」:
344
+ - 有系统 Tailscale 会直接复用;
345
+ - 没有则自动启动内嵌轻量节点(无需管理员权限、不占系统 VPN),10–20 秒后变成「需要授权」;
346
+ - 点「去授权」在浏览器登录自己的 Tailscale 账号;无头机器可改填 Auth Key。
347
+ 3. 节点 Running 后重新生成配对二维码 → 手机扫一次即可。二维码会同时带上
348
+ `wss://<节点>.<tailnet>.ts.net`、Cloudflare、局域网等候选地址,客户端按网关下发的顺序选路。
349
+
350
+ > 只有第一次需要授权,之后重启 DSH / 升级插件都不用再来一遍。详见 [docs/tailscale-node.md](docs/tailscale-node.md)。
351
+
352
+
331
353
  ## 协议与 DSH 兼容层
332
354
 
333
355
  移动端连接的是本项目维护的 `dsh-mobile-v1`,不是 DSH 的内部 Remote 协议。当前 Host Adapter 基线为 DSH 0.2.1-rc.2 / Session format 4;Session、Workspace、Settings、Commands、Goals、Schedule、Permission Presets 与新增上传/子会话路由的 Remote 参数只存在于适配层。旧 Host 不满足本版硬依赖时不能加载此版插件;移动端新增功能仍需按 `hello.capabilities` 判定是否启用。Plugin Manager 系列请求帧经配对设备连接管理插件目录、安装、启停、设置与版本豁免,方案见 [DSH 0.2.0 插件管理对接方案](docs/dsh-0.2.0-rc.2-plugin-management-mobile-integration.md)。模型配置请求(`llm-discover-models`、`model-credential-describe`、`model-credential-set`)同样走配对设备控制连接,转发 Host `llm/discoverModels` 与 `credentials/describe|set`;凭据值只上行,响应与日志都不回显,见 [PROTOCOL.md 第 8 节](PROTOCOL.md#模型发现与模型凭据llm-model-config-v1)。
@@ -51,3 +51,65 @@
51
51
  `/mgw/status` 的 `tailscale` 字段包含 `nodeSource`(system / embedded / none)与 `serve`
52
52
  快照(state、loginUrl、dnsName、ipv4、urls、error)。`GET /mgw/tailscale` 返回同一快照,
53
53
  `GET /mgw/tailscale/login` 302 到登录链接。
54
+
55
+ ## 安装与首次授权(用户指引)
56
+
57
+ > 普通用户从安装插件到手机连上,一共 3 步;只有**第一次**需要授权,之后节点身份保存在本地状态目录里,重启/升级插件都不用再授权。
58
+
59
+ ### 第 1 步:安装插件后重启 DSH
60
+
61
+ 插件在 **DSH 启动时加载**,所以:
62
+
63
+ - 新装插件 → 必须重启一次 DSH,面板里才会出现 Tailscale 卡片;
64
+ - 升级插件(覆盖安装)→ 也建议重启一次,确保新的 helper 被识别。
65
+
66
+ 重启后打开面板,看到 `Tailscale` 区域即为生效。
67
+
68
+ ### 第 2 步:启动节点并授权(二选一)
69
+
70
+ | 方式 | 适用 | 操作 |
71
+ |---|---|---|
72
+ | **浏览器登录**(推荐) | 有显示器、能开浏览器 | 面板点「启动隧道」→ 等 10–20 秒状态变成「需要授权」→ 点「去授权」→ 在弹出的 Tailscale 页面登录并允许 |
73
+ | **Auth Key** | 无头服务器 / 无人值守 | 在 Tailscale 管理台生成 Auth Key(建议 reusable)→ 填到面板的 Auth Key 输入框 → 点「连接」 |
74
+
75
+ 授权成功后状态变为 `Running`,面板会显示节点名与 `wss://<节点>.<tailnet>.ts.net` 地址。
76
+
77
+ ### 第 3 步:手机扫码配对
78
+
79
+ - Tailscale 就绪后,配对二维码里会**同时**包含:
80
+ - `wss://<节点>.<tailnet>.ts.net/ws/mobile`(Tailscale,公网可用、仅 tailnet 内可达)
81
+ - Cloudflare / 局域网地址(如已开启)
82
+ - 手机端扫一次码即可;之后重启 App 会自动重连,不需要再扫码。
83
+
84
+ ### 本机有代理(Clash / Surge / fake-ip TUN)时
85
+
86
+ tsnet 的控制面(`controlplane.tailscale.com`)和日志上报走的是独立连接,**不会自动走系统代理**,
87
+ 在 fake-ip 代理环境下会表现为节点一直 `Starting`,日志里是:
88
+
89
+ ```
90
+ control: TryLogin: register request: Post "https://controlplane.tailscale.com/machine/register": context deadline exceeded
91
+ logtail: dial "log.tailscale.com:443" failed: dial tcp 198.18.x.x:443: i/o timeout
92
+ ```
93
+
94
+ 解决办法:配置插件的 `tailscaleProxy` 指向本机 HTTP 代理端口(Clash Verge 默认是 7897):
95
+
96
+ ```yaml
97
+ tailscaleProxy: http://127.0.0.1:7897
98
+ ```
99
+
100
+ 插件 spawn helper 时会把它注入 `HTTP_PROXY/HTTPS_PROXY/ALL_PROXY`,节点即可完成注册并给出登录链接。
101
+ 未显式配置时也会读取环境变量 `HTTPS_PROXY`。
102
+
103
+ ### 常见问题
104
+
105
+ | 现象 | 原因 / 处理 |
106
+ |---|---|
107
+ | 状态 `Failed`,错误 `tailscale helper not found` | 插件包缺少对应平台的 helper 二进制:确认 `helper/tsnet-node/bin/<os>-<arch>/dsh-tailscale-node` 存在;源码包可用 `GO_BIN=/path/to/go bash helper/tsnet-node/build.sh` 自行构建 |
108
+ | 一直停在「需要授权」 | 浏览器授权没完成;重开「去授权」链接,或改用 Auth Key |
109
+ | 授权后手机仍连不上 ts.net | 检查手机端 Tailscale 是否登录**同一个 tailnet**;不同 tailnet 无法互通 |
110
+ | 卸载重装插件后要重新授权吗 | 不需要:节点状态在插件的状态目录里;只有手动清空状态目录才需要重新授权 |
111
+
112
+ ### 支持的 helper 平台
113
+
114
+ 插件包内置:`darwin-arm64`、`linux-amd64`、`linux-arm64`、`windows-amd64`。
115
+ 其他平台请用源码自行构建。
@@ -1,8 +1,8 @@
1
1
  module dsh-tailscale-node
2
2
 
3
- go 1.27.3
3
+ go 1.27.4
4
4
 
5
- require tailscale.com v1.104.5
5
+ require tailscale.com v1.104.7
6
6
 
7
7
  require (
8
8
  filippo.io/edwards25519 v1.2.0 // indirect
@@ -32,7 +32,7 @@ require (
32
32
  github.com/tailscale/hujson v0.0.0-20260727124030-b80ff77dac4f // indirect
33
33
  github.com/tailscale/peercred v0.0.0-20250107143737-35a0c7bd7edc // indirect
34
34
  github.com/tailscale/web-client-prebuilt v0.0.0-20260917222731-e0ed2d0d0fea // indirect
35
- github.com/tailscale/wireguard-go v0.0.0-20260928213032-417aef361226 // indirect
35
+ github.com/tailscale/wireguard-go v0.0.0-20261106233718-9e0ab45c16ca // indirect
36
36
  github.com/x448/float16 v0.8.4 // indirect
37
37
  go4.org/mem v0.0.0-20240501181205-ae6ca9944745 // indirect
38
38
  go4.org/netipx v0.0.0-20260823151212-3075585bcbeb // indirect
@@ -176,6 +176,8 @@ github.com/tailscale/wf v0.0.0-20240214030419-6fbb0a674ee6 h1:l10Gi6w9jxvinoiq15
176
176
  github.com/tailscale/wf v0.0.0-20240214030419-6fbb0a674ee6/go.mod h1:ZXRML051h7o4OcI0d3AaILDIad/Xw0IkXaHM17dic1Y=
177
177
  github.com/tailscale/wireguard-go v0.0.0-20260928213032-417aef361226 h1:v3Lpj2iHPWQDqeCwemQPz4fWweIEMLqBkwJqCjRyJQc=
178
178
  github.com/tailscale/wireguard-go v0.0.0-20260928213032-417aef361226/go.mod h1:rUelGmuK4UnSJYM5gl5Mknp6YbwwcL8+VAPMhNYe+jg=
179
+ github.com/tailscale/wireguard-go v0.0.0-20261106233718-9e0ab45c16ca h1:m34ObTyPjPiDaSFWeMk7FBQR8my9wpT98t1EXp5c5X0=
180
+ github.com/tailscale/wireguard-go v0.0.0-20261106233718-9e0ab45c16ca/go.mod h1:rUelGmuK4UnSJYM5gl5Mknp6YbwwcL8+VAPMhNYe+jg=
179
181
  github.com/tailscale/xnet v0.0.0-20240729143630-8497ac4dab2e h1:zOGKqN5D5hHhiYUp091JqK7DPCqSARyUfduhGUY8Bek=
180
182
  github.com/tailscale/xnet v0.0.0-20240729143630-8497ac4dab2e/go.mod h1:orPd6JZXXRyuDusYilywte7k094d7dycXXU5YnWsrwg=
181
183
  github.com/tc-hib/winres v0.3.1 h1:CwRjEGrKdbi5CvZ4ID+iyVhgyfatxFoizjPhzez9Io4=
@@ -237,3 +239,5 @@ software.sslmate.com/src/go-pkcs12 v0.7.3 h1:JBQD3FDqYjTeyDAeZQklj2ar88ykBLtALlo
237
239
  software.sslmate.com/src/go-pkcs12 v0.7.3/go.mod h1:Qiz0EyvDRJjjxGyUQa2cCNZn/wMyzrRJ/qcDXOQazLI=
238
240
  tailscale.com v1.104.5 h1:TLemRww20+bcQ0FEVTTZ7yMtVDZ4pOpSCL86Oo9g3mA=
239
241
  tailscale.com v1.104.5/go.mod h1:Hq4zB8UpaxMW1fvqO30CLVQo3A7Ith0t9MnvEyiuoSA=
242
+ tailscale.com v1.104.7 h1:YqImcXyNIe25x7Qwei8PgbtkjFd3pKed9cFY0Flkitc=
243
+ tailscale.com v1.104.7/go.mod h1:pNl682NgUoac2/Um3khv8pduX3D1YPBZTL067+zo8wY=
@@ -0,0 +1,30 @@
1
+ //go:build !windows
2
+
3
+ package main
4
+
5
+ import (
6
+ "fmt"
7
+ "os"
8
+ "path/filepath"
9
+ "syscall"
10
+ )
11
+
12
+ // acquireInstanceLock 用 flock 占锁:进程即使被 SIGKILL,内核也会释放,不会留下僵尸锁。
13
+ func acquireInstanceLock(stateDir string) (func(), error) {
14
+ lockPath := filepath.Join(stateDir, "helper.lock")
15
+ f, err := os.OpenFile(lockPath, os.O_CREATE|os.O_RDWR, 0o600)
16
+ if err != nil {
17
+ return nil, err
18
+ }
19
+ if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
20
+ _ = f.Close()
21
+ return nil, fmt.Errorf("another dsh-tailscale-node is already running for %s", stateDir)
22
+ }
23
+ _ = f.Truncate(0)
24
+ _, _ = f.WriteString(fmt.Sprintf("%d\n", os.Getpid()))
25
+ return func() {
26
+ _ = syscall.Flock(int(f.Fd()), syscall.LOCK_UN)
27
+ _ = f.Close()
28
+ _ = os.Remove(lockPath)
29
+ }, nil
30
+ }
@@ -0,0 +1,46 @@
1
+ //go:build windows
2
+
3
+ package main
4
+
5
+ import (
6
+ "fmt"
7
+ "os"
8
+ "path/filepath"
9
+ "strings"
10
+ )
11
+
12
+ // acquireInstanceLock(Windows):用 PID 文件做单实例判断。
13
+ func acquireInstanceLock(stateDir string) (func(), error) {
14
+ lockPath := filepath.Join(stateDir, "helper.lock")
15
+ for attempt := 0; attempt < 2; attempt++ {
16
+ f, err := os.OpenFile(lockPath, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600)
17
+ if err == nil {
18
+ _, _ = f.WriteString(fmt.Sprintf("%d\n", os.Getpid()))
19
+ _ = f.Close()
20
+ return func() { _ = os.Remove(lockPath) }, nil
21
+ }
22
+ data, readErr := os.ReadFile(lockPath)
23
+ if readErr != nil {
24
+ return nil, err
25
+ }
26
+ pidText := strings.TrimSpace(string(data))
27
+ if pid, perr := os.FindProcess(atoiSafe(pidText)); perr == nil && pid != nil {
28
+ if pid.Signal(os.Signal(nil)) == nil {
29
+ return nil, fmt.Errorf("another dsh-tailscale-node is already running (pid %s) for %s", pidText, stateDir)
30
+ }
31
+ }
32
+ _ = os.Remove(lockPath)
33
+ }
34
+ return nil, fmt.Errorf("could not acquire instance lock in %s", stateDir)
35
+ }
36
+
37
+ func atoiSafe(text string) int {
38
+ value := 0
39
+ for _, ch := range text {
40
+ if ch < '0' || ch > '9' {
41
+ return value
42
+ }
43
+ value = value*10 + int(ch-'0')
44
+ }
45
+ return value
46
+ }
@@ -42,6 +42,8 @@ type statusFile struct {
42
42
  ListenPort int `json:"listenPort"`
43
43
  HTTPSPort int `json:"httpsPort"`
44
44
  HTTPSUrl string `json:"httpsUrl"`
45
+ PID int `json:"pid"`
46
+ HTTPSError string `json:"httpsError,omitempty"`
45
47
  Hostname string `json:"hostname"`
46
48
  ControlURL string `json:"controlUrl"`
47
49
  UpdatedAt int64 `json:"updatedAt"`
@@ -56,6 +58,8 @@ var (
56
58
  targetPort = flag.Int("target-port", 0, "转发目标端口,0 表示与 listen-port 相同(本机 127.0.0.1)")
57
59
  httpsPort = flag.Int("https-port", 0, "可选:ts.net HTTPS 监听端口(wss 入口),0 关闭")
58
60
  statusPath = flag.String("status-file", "", "状态文件路径,默认 <state-dir>/embedded-node.json")
61
+ proxyAddr = flag.String("proxy", "", "HTTP/SOCKS5 proxy for control plane (empty = auto detect)")
62
+ proxyAutoFlag = flag.Bool("proxy-auto", true, "auto detect local proxy ports when --proxy is empty")
59
63
  verbose = flag.Bool("verbose", false, "输出 tsnet 详细日志")
60
64
  statusMu sync.Mutex
61
65
  current = statusFile{Schema: schemaVersion, State: "starting"}
@@ -163,14 +167,7 @@ func startListeners(srv *tsnet.Server) {
163
167
  })
164
168
  if *httpsPort > 0 {
165
169
  httpsOnce.Do(func() {
166
- listener, err := srv.ListenTLS("tcp", fmt.Sprintf(":%d", *httpsPort))
167
- if err != nil {
168
- httpsErr.Store(err.Error())
169
- logf("ts.net ListenTLS :%d failed: %v", *httpsPort, err)
170
- return
171
- }
172
- logf("ts.net TLS listener ready on :%d -> %s", *httpsPort, target)
173
- go serveListener(listener, target)
170
+ go startTLSListener(srv, target, context.Background())
174
171
  })
175
172
  }
176
173
  statusMu.Lock()
@@ -183,6 +180,33 @@ func startListeners(srv *tsnet.Server) {
183
180
  writeStatus()
184
181
  }
185
182
 
183
+ // TLS(443) 监听:证书由 Tailscale 控制面按需签发,刚登录时可能还取不到,
184
+ // 因此失败后要重试,而不是一次性放弃(否则 httpsUrl 永远为空)。
185
+ func startTLSListener(srv *tsnet.Server, target string, ctx context.Context) {
186
+ for attempt := 1; attempt <= 30; attempt++ {
187
+ listener, err := srv.ListenTLS("tcp", fmt.Sprintf(":%d", *httpsPort))
188
+ if err == nil {
189
+ statusMu.Lock()
190
+ current.HTTPSError = ""
191
+ statusMu.Unlock()
192
+ logf("ts.net TLS listener ready on :%d -> %s", *httpsPort, target)
193
+ writeStatus()
194
+ serveListener(listener, target)
195
+ return
196
+ }
197
+ statusMu.Lock()
198
+ current.HTTPSError = err.Error()
199
+ statusMu.Unlock()
200
+ writeStatus()
201
+ logf("ts.net ListenTLS :%d failed (attempt %d/30): %v", *httpsPort, attempt, err)
202
+ select {
203
+ case <-ctx.Done():
204
+ return
205
+ case <-time.After(5 * time.Second):
206
+ }
207
+ }
208
+ }
209
+
186
210
  func pollLoop(ctx context.Context, srv *tsnet.Server) {
187
211
  ticker := time.NewTicker(2 * time.Second)
188
212
  defer ticker.Stop()
@@ -242,8 +266,99 @@ func pollLoop(ctx context.Context, srv *tsnet.Server) {
242
266
  }
243
267
  }
244
268
 
269
+ // ---------- 本机代理自动探测 ----------
270
+ // tsnet 的控制面/DERP 连接不读系统代理,fake-ip 代理环境下必须显式给 HTTP(S)_PROXY。
271
+ // 不同代理软件的端口不一样(Clash 7897/7890、V2Ray 1080/10808、Surge 6152…),
272
+ // 这里按常见端口逐个探测,谁能代理到控制面就用谁。
273
+
274
+ var proxyPorts = []int{
275
+ 7897, 7890, 7891, 7892, 7893, 7899,
276
+ 1080, 1081, 1087, 10808, 10809, 10810,
277
+ 6152, 6153, 8118, 8080, 8081, 8888, 8889,
278
+ 20171, 20172, 20170, 9090,
279
+ }
280
+
281
+ func firstNonEmpty(values ...string) string {
282
+ for _, value := range values {
283
+ if strings.TrimSpace(value) != "" {
284
+ return strings.TrimSpace(value)
285
+ }
286
+ }
287
+ return ""
288
+ }
289
+
290
+ func probeHTTPProxy(port int) bool {
291
+ addr := fmt.Sprintf("127.0.0.1:%d", port)
292
+ conn, err := net.DialTimeout("tcp", addr, 250*time.Millisecond)
293
+ if err != nil {
294
+ return false
295
+ }
296
+ defer conn.Close()
297
+ _ = conn.SetDeadline(time.Now().Add(1500 * time.Millisecond))
298
+ req := "CONNECT controlplane.tailscale.com:443 HTTP/1.1\r\nHost: controlplane.tailscale.com:443\r\nProxy-Connection: keep-alive\r\n\r\n"
299
+ if _, err := conn.Write([]byte(req)); err != nil {
300
+ return false
301
+ }
302
+ buf := make([]byte, 96)
303
+ n, err := conn.Read(buf)
304
+ if err != nil || n <= 0 {
305
+ return false
306
+ }
307
+ head := string(buf[:n])
308
+ return strings.HasPrefix(head, "HTTP/1.") && strings.Contains(head, " 200")
309
+ }
310
+
311
+ func probeSOCKS5(port int) bool {
312
+ addr := fmt.Sprintf("127.0.0.1:%d", port)
313
+ conn, err := net.DialTimeout("tcp", addr, 250*time.Millisecond)
314
+ if err != nil {
315
+ return false
316
+ }
317
+ defer conn.Close()
318
+ _ = conn.SetDeadline(time.Now().Add(1200 * time.Millisecond))
319
+ if _, err := conn.Write([]byte{0x05, 0x01, 0x00}); err != nil {
320
+ return false
321
+ }
322
+ buf := make([]byte, 2)
323
+ if _, err := io.ReadFull(conn, buf); err != nil {
324
+ return false
325
+ }
326
+ return buf[0] == 0x05 && buf[1] == 0x00
327
+ }
328
+
329
+ func detectProxy() string {
330
+ for _, port := range proxyPorts {
331
+ if probeHTTPProxy(port) {
332
+ return fmt.Sprintf("http://127.0.0.1:%d", port)
333
+ }
334
+ }
335
+ for _, port := range proxyPorts {
336
+ if probeSOCKS5(port) {
337
+ return fmt.Sprintf("socks5://127.0.0.1:%d", port)
338
+ }
339
+ }
340
+ return ""
341
+ }
342
+
343
+ func applyProxyEnv(proxy string) {
344
+ if proxy == "" {
345
+ return
346
+ }
347
+ for _, key := range []string{"HTTP_PROXY", "HTTPS_PROXY", "http_proxy", "https_proxy", "ALL_PROXY", "all_proxy"} {
348
+ _ = os.Setenv(key, proxy)
349
+ }
350
+ logf("proxy: using %s", proxy)
351
+ }
352
+
245
353
  func main() {
246
354
  flag.Parse()
355
+ // 显式代理优先;否则自动探测常见端口(也可以用 HTTPS_PROXY 环境变量覆盖)。
356
+ explicitProxy := firstNonEmpty(*proxyAddr, os.Getenv("HTTPS_PROXY"), os.Getenv("https_proxy"), os.Getenv("ALL_PROXY"), os.Getenv("all_proxy"))
357
+ if explicitProxy != "" {
358
+ applyProxyEnv(explicitProxy)
359
+ } else if *proxyAutoFlag {
360
+ applyProxyEnv(detectProxy())
361
+ }
247
362
  if *stateDir == "" {
248
363
  logf("-state-dir is required")
249
364
  os.Exit(2)
@@ -259,11 +374,18 @@ func main() {
259
374
  logf("mkdir state dir: %v", err)
260
375
  os.Exit(2)
261
376
  }
377
+ releaseLock, lockErr := acquireInstanceLock(*stateDir)
378
+ if lockErr != nil {
379
+ logf("instance lock: %v", lockErr)
380
+ os.Exit(3)
381
+ }
382
+ defer releaseLock()
262
383
  authMode := "login"
263
384
  if strings.TrimSpace(*authKey) != "" {
264
385
  authMode = "authkey"
265
386
  }
266
387
  statusMu.Lock()
388
+ current.PID = os.Getpid()
267
389
  current.AuthMode = authMode
268
390
  current.Hostname = *hostname
269
391
  current.ControlURL = *controlURL
package/lib/index.mjs CHANGED
@@ -329,6 +329,9 @@ const Config = Schema.object({
329
329
  tailscaleMode: Schema.string().default('auto'),
330
330
  tailscaleControlUrl: Schema.string().default('https://controlplane.tailscale.com'),
331
331
  tailscaleHelperPath: Schema.string().default(''),
332
+ tailscaleProxy: Schema.string().default(''),
333
+ tailscaleHttpsPort: Schema.natural().min(1).max(65535).default(443),
334
+ tailscaleHttps: Schema.boolean().default(true),
332
335
  logFile: Schema.string().default(''),
333
336
  })
334
337
 
@@ -3908,6 +3911,9 @@ const plugin = {
3908
3911
  isPublicSecureEndpoint(serveTailscaleUrl) ? [serveTailscaleUrl] : []
3909
3912
  const appEndpoints = [...new Set([
3910
3913
  ...(clientRoute !== 'lan' && clientRoute !== 'tailscale' && hasPublicRoute ? [publicUrl] : []),
3914
+ // 运营者配置的固定入口(例如手动 tailscaled 的 ts.net serve 地址):
3915
+ // 必须进配对载荷,否则客户端只能自己猜。
3916
+ ...configuredEndpoints,
3911
3917
  ...tailscaleServeEndpoints,
3912
3918
  ...lanEndpoints,
3913
3919
  ])].slice(0, 16)
@@ -4538,13 +4544,15 @@ const plugin = {
4538
4544
 
4539
4545
  tailscaleServe = createTailscaleNode({
4540
4546
  mode: options.tailscaleMode,
4541
- stateDir: path.join(os.homedir(), '.dsh', 'tailscale'),
4547
+ stateDir: path.join(os.homedir(), '.dsh', 'tailscale', 'embedded'),
4542
4548
  wsPath,
4543
4549
  listenPort: options.tailscaleServePort,
4544
4550
  hostname: options.tailscaleHostname,
4545
4551
  authKey: options.tailscaleAuthKey,
4546
4552
  controlUrl: options.tailscaleControlUrl,
4547
4553
  helperPath: options.tailscaleHelperPath,
4554
+ httpsPort: options.tailscaleHttps === false ? 0 : options.tailscaleHttpsPort,
4555
+ proxy: options.tailscaleProxy,
4548
4556
  forceEmbedded: options.tailscaleEnabled === true,
4549
4557
  log,
4550
4558
  })
@@ -67,12 +67,20 @@ export function detectSystemTailscale({ port = 3081, wsPath = '/ws/mobile', host
67
67
  export function createTailscaleNode(options = {}) {
68
68
  const log = typeof options.log === 'function' ? options.log : () => {}
69
69
  const mode = normalizeMode(options.mode)
70
- const stateDir = options.stateDir || path.join(os.homedir(), '.dsh', 'tailscale')
70
+ // 内嵌节点必须用自己的状态目录:与系统/手动 tailscaled 共用同一个目录会复用同一份节点密钥,
71
+ // 控制面会把两个进程当成同一个节点互相踢,表现就是永远 Starting。
72
+ const stateDir = options.stateDir || path.join(os.homedir(), '.dsh', 'tailscale', 'embedded')
71
73
  const statusFile = options.statusFile || path.join(stateDir, EMBEDDED_STATUS)
72
74
  const snapshotFile = options.snapshotFile || path.join(stateDir, 'tailscale-node.json')
73
75
  const wsPath = options.wsPath || '/ws/mobile'
74
76
  const listenPort = Number(options.listenPort) || 3081
75
77
  const httpsPort = Number(options.httpsPort) || 0
78
+ // 本机若有 HTTP 代理(Clash/Surge 等),tsnet 的控制面/DERP 必须显式走代理,
79
+ // 否则在 fake-ip 代理环境下 controlplane 注册会超时(表现:一直 Starting)。
80
+ const configuredProxy = String(options.proxy || '').trim()
81
+ // 显式填 off/none/disabled 可彻底关闭代理(不探测、不注入环境变量)
82
+ const proxyDisabled = /^(off|none|disabled|0|false)$/i.test(configuredProxy)
83
+ const proxy = proxyDisabled ? '' : (configuredProxy || String(process.env.HTTPS_PROXY || process.env.https_proxy || '').trim())
76
84
  function defaultHostname() {
77
85
  const platform = process.platform === 'win32' ? 'win' : (process.platform === 'darwin' ? 'mac' : (process.platform === 'linux' ? 'linux' : 'os'))
78
86
  return 'dsh-gateway-' + platform
@@ -89,6 +97,8 @@ export function createTailscaleNode(options = {}) {
89
97
  let child = null
90
98
  let timer = null
91
99
  let stopping = false
100
+ let lastRespawnAt = 0
101
+ let startedAt = Date.now()
92
102
  let last = {
93
103
  enabled: false,
94
104
  mode,
@@ -134,10 +144,48 @@ export function createTailscaleNode(options = {}) {
134
144
  }
135
145
  }
136
146
 
147
+ function pidAlive(pid) {
148
+ if (!Number.isInteger(pid) || pid <= 0) return false
149
+ try {
150
+ process.kill(pid, 0)
151
+ return true
152
+ } catch (error) {
153
+ return false
154
+ }
155
+ }
156
+
157
+ // 进程被杀(例如 DSH 重启)后状态文件会被保留成 "running":
158
+ // 必须按 pid 复核存活,否则面板显示已连接但实际不可用,也不会重新拉起。
159
+ function statusPidAlive(state) {
160
+ const pid = Number(state && state.pid)
161
+ if (Number.isInteger(pid) && pid > 0) return pidAlive(pid)
162
+ return false
163
+ }
164
+
137
165
  function applyEmbedded() {
138
166
  const state = readEmbedded()
167
+ const childAlive = child !== null && child.exitCode === null
139
168
  if (!state) {
140
- if (child && child.exitCode === null) return
169
+ // 启动过但一直没有状态文件,且子进程也不在:重试拉起(DSH 重启后锁文件残留等场景)
170
+ if (!childAlive && !stopping && Date.now() - startedAt > 8000 && Date.now() - lastRespawnAt > 8000) {
171
+ lastRespawnAt = Date.now()
172
+ log('tailscale-node: no status file and no child, retrying start')
173
+ start().catch(() => {})
174
+ }
175
+ return
176
+ }
177
+ const stateName = String(state.state || 'starting')
178
+ const aliveByPid = statusPidAlive(state)
179
+ // 状态文件里的 pid 已死但文件仍写着 running/starting:进程被外部杀掉(典型是 DSH 重启)。
180
+ // 旧实现直接信任状态文件,于是面板显示已连接、实际上没有任何进程在跑。
181
+ if (!aliveByPid && !childAlive && (stateName === 'running' || stateName === 'starting') &&
182
+ Date.now() - lastRespawnAt > 5000) {
183
+ lastRespawnAt = Date.now()
184
+ log('tailscale-node: helper pid is gone, respawning')
185
+ last = { ...last, state: 'starting', backendState: 'Starting', publicUrl: '', urls: [], error: '' }
186
+ try { fs.rmSync(statusFile, { force: true }) } catch (error) { /* ignore */ }
187
+ persist()
188
+ start().catch(() => {})
141
189
  return
142
190
  }
143
191
  const urls = embeddedUrls(state)
@@ -251,8 +299,24 @@ export function createTailscaleNode(options = {}) {
251
299
  ]
252
300
  if (httpsPort > 0) args.push('--https-port', String(httpsPort))
253
301
  if (authKey) args.push('--auth-key', authKey)
302
+ if (proxy) args.push('--proxy', proxy)
303
+ if (proxyDisabled) args.push('--proxy-auto=false')
304
+ // 防止重复 spawn:残留的 helper 会和新进程抢同一份状态,导致永远 Starting
305
+ if (child !== null) {
306
+ try { child.kill('SIGTERM') } catch (error) { /* ignore */ }
307
+ child = null
308
+ }
254
309
  log('tailscale-node: spawning embedded helper ' + helperPath)
255
- child = spawn(helperPath, args, { stdio: ['ignore', 'pipe', 'pipe'] })
310
+ const childEnv = { ...process.env }
311
+ if (proxy) {
312
+ childEnv.HTTP_PROXY = proxy
313
+ childEnv.HTTPS_PROXY = proxy
314
+ childEnv.http_proxy = proxy
315
+ childEnv.https_proxy = proxy
316
+ childEnv.ALL_PROXY = proxy
317
+ childEnv.all_proxy = proxy
318
+ }
319
+ child = spawn(helperPath, args, { stdio: ['ignore', 'pipe', 'pipe'], env: childEnv })
256
320
  child.stdout.on('data', (chunk) => log('tsnet-node: ' + String(chunk).trim()))
257
321
  child.stderr.on('data', (chunk) => log('tsnet-node: ' + String(chunk).trim()))
258
322
  child.on('error', (error) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-plugin-weapp-gateway",
3
- "version": "0.8.65",
3
+ "version": "0.8.66",
4
4
  "description": "鲸尾网关助手:DeepSeek Harness 移动客户端连接与会话同步,支持安全配对、远程访问、上下文、编队、额度和语音输入",
5
5
  "main": "lib/index.mjs",
6
6
  "files": [