dsh-plugin-mesh 0.5.13 → 0.5.15

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.
@@ -0,0 +1,191 @@
1
+ /**
2
+ * 「在我这台机器上,怎么才能真的打开对端的 DSH 界面」—— 纯决策,不做 IO。
3
+ *
4
+ * 为什么需要单独一层:对端 `GET /mesh/v1/web-url` 的自报地址是**站在它自己角度**
5
+ * 算出来的(`preferredAddress()`),手机在移动数据下那会是运营商 CGNAT 的 10.x;
6
+ * 它再顺带自报一个 `lanReachable`(判据只是"我绑了 0.0.0.0")。这两样都不是
7
+ * "观看端能不能到"的证据,照单全收的结果就是面板永远 502:
8
+ *
9
+ * 连不上对端 10.12.225.124:3080:socket hang up
10
+ *
11
+ * 所以判断权必须留在观看端:
12
+ * 1. 地址能拨通(真的拿到 HTTP 响应)→ 直接用它,行为和以前一致;
13
+ * 2. 拨不通,但对端有一条 tailnet 通道 → 在本机开一个回环端口,由 sidecar
14
+ * 把字节流打进 tailnet(宿主机路由不到 100.x,且 WebSocket 升级也走这条);
15
+ * 3. 两条都不可用 → 如实说"哪一条试过、怎么失败的",不许把探测失败伪装成
16
+ * 对端已关闭(AGENTS.md 硬约束 1)。
17
+ *
18
+ * @typedef {{ prefix: string, ticket: string, header: string } | null} TunnelInfo
19
+ * @typedef {{ mode: "direct" | "stream" | "none", remoteBase?: string, address?: string,
20
+ * prefix?: string, ticket?: string, header?: string, note: string }} WebTargetPlan
21
+ */
22
+
23
+ /**
24
+ * 从对端给的 tunnel 描述里取出**相对前缀**。
25
+ *
26
+ * 新版本对端发 `{ prefix: "/mesh/peer-web", ticket }`;老版本发的是一条绝对地址
27
+ * `{ url: "http://<它自己的地址>:<mesh端口>/mesh/peer-web/" }` —— 那种地址的主机
28
+ * 部分同样可能是不可达的 10.x,所以**只取路径**,主机由观看端用自己的通道决定。
29
+ * @returns {string} 带前导斜杠、不带尾斜杠的前缀;无则空串。
30
+ */
31
+ export function tunnelPrefixOf(tunnel) {
32
+ if (!tunnel || typeof tunnel !== "object") return "";
33
+ const raw = String(tunnel.prefix ?? "").trim();
34
+ if (raw) {
35
+ const withSlash = raw.startsWith("/") ? raw : `/${raw}`;
36
+ return withSlash.replace(/\/+$/, "");
37
+ }
38
+ const url = String(tunnel.url ?? "").trim();
39
+ if (!url) return "";
40
+ try {
41
+ return new URL(url).pathname.replace(/\/+$/, "");
42
+ } catch {
43
+ // 解析不了的地址当"没有前缀",不要凭空猜一个出来。
44
+ return "";
45
+ }
46
+ }
47
+
48
+ /**
49
+ * 决定观看端用哪条路。
50
+ *
51
+ * @param {object} input
52
+ * @param {string} input.reportedBase 对端自报的绝对地址(`http://host:port/`)
53
+ * @param {number} [input.reportedPort] 对端 GUI 端口,缺省取地址里的端口
54
+ * @param {boolean} [input.reachable] 本机真的拨通过没有;`undefined` = 没测(按可达处理,保持旧行为)
55
+ * @param {TunnelInfo} [input.tunnel] 对端 mesh 口隧道
56
+ * @param {string} [input.tsnetHost] 对端的 tailnet 地址(100.64/10);没有就走不了公网
57
+ * @param {number} [input.meshPort] 对端 mesh 口端口(隧道挂在它上面)
58
+ * @param {boolean} [input.guiBoundEverywhere] 对端 GUI 是否绑在所有网卡(bind=0.0.0.0);
59
+ * `undefined` = 对端没报(老版本),按"绑了"处理以保持旧行为
60
+ * @param {string} [input.probeNote] 探测失败时的原始描述,需原样带进 note
61
+ * @returns {WebTargetPlan}
62
+ */
63
+ export function planWebTarget({
64
+ reportedBase,
65
+ reportedPort,
66
+ reachable,
67
+ tunnel = null,
68
+ tsnetHost = "",
69
+ meshPort = 0,
70
+ guiBoundEverywhere,
71
+ probeNote = "",
72
+ } = {}) {
73
+ const base = String(reportedBase ?? "");
74
+ const port = Number(reportedPort) || portOf(base) || 0;
75
+ const reportedHost = hostOf(base);
76
+
77
+ // 对端自报 `127.0.0.1` 表示「我的 GUI 只听回环」——那不是本机能直连的地址,
78
+ // 直连过去只会打到**本机自己**的 3080(一个非常难查的假成功)。
79
+ // 所以这类地址一律不按直连处理,只能走它给的 mesh 口隧道。
80
+ const loopbackReport = isLoopbackHost(reportedHost);
81
+ const direct = reachable !== false && !loopbackReport;
82
+
83
+ // 没探测 / 探测通过 → 照旧直连。局域网路径上不多花一毫秒。
84
+ if (direct) {
85
+ return { mode: "direct", remoteBase: base, note: "" };
86
+ }
87
+
88
+ const host = String(tsnetHost ?? "").trim();
89
+ if (!host) {
90
+ return {
91
+ mode: "none",
92
+ remoteBase: base,
93
+ note: loopbackReport
94
+ ? `对端只报了回环地址 ${base}(它的 GUI 只听 127.0.0.1),且没有 tailnet 通道可用`
95
+ : `对端自报地址 ${base} 从本机拨不通(${probeNote || "无响应"}),且没有 tailnet 通道可用`,
96
+ };
97
+ }
98
+
99
+ const prefix = tunnelPrefixOf(tunnel);
100
+ const ticket = String(tunnel?.ticket ?? "");
101
+ const header = String(tunnel?.header ?? "x-dsh-peer-web");
102
+
103
+ // 隧道挂在**对端的 mesh 口**上:目标是对端 mesh 端口 + 相对前缀。
104
+ // 这条路把 Host/Origin/会话 cookie 的改写留在对端进程里完成,所以对端 GUI
105
+ // 只绑回环也能看;WebSocket(/api/remote.mux)同样走这条。
106
+ if (prefix && ticket && meshPort > 0) {
107
+ return {
108
+ mode: "stream",
109
+ address: `${host}:${meshPort}`,
110
+ prefix,
111
+ ticket,
112
+ header,
113
+ note: `经对端 mesh 口隧道(对端自报地址 ${base} 不可达)`,
114
+ };
115
+ }
116
+
117
+ // 没有隧道(对端认为它"局域网可达",其实只有运营商地址):直接打通它的 GUI。
118
+ // 前提是**对端 GUI 真的绑在所有网卡上**(它报的 bind=0.0.0.0)。只绑回环的
119
+ // 宿主连它自己的 tailnet 地址都不听,拨过去只会被拒。
120
+ const boundEverywhere = guiBoundEverywhere !== false;
121
+ if (port > 0 && boundEverywhere && !loopbackReport) {
122
+ return {
123
+ mode: "stream",
124
+ address: `${host}:${port}`,
125
+ prefix: "",
126
+ ticket: "",
127
+ header,
128
+ note: `经本机 tailnet 通道直连对端 GUI ${host}:${port}(对端自报地址 ${base} 不可达)`,
129
+ };
130
+ }
131
+
132
+ return {
133
+ mode: "none",
134
+ remoteBase: base,
135
+ note: loopbackReport || !boundEverywhere
136
+ ? `对端 GUI 只听回环(${base}),且没给 mesh 口隧道 —— 需要把对端插件升级到带隧道的版本`
137
+ : `对端自报地址 ${base} 从本机拨不通(${probeNote || "无响应"}),且没拿到对端 GUI 端口`,
138
+ };
139
+ }
140
+
141
+ /** 从 `http://host:port/` 里取主机名;取不到返回空串。 */
142
+ function hostOf(base) {
143
+ try {
144
+ return new URL(String(base ?? "")).hostname;
145
+ } catch {
146
+ return "";
147
+ }
148
+ }
149
+
150
+ /** 这个主机名是不是"本机回环"(对端自称只听回环时会给它)。 */
151
+ export function isLoopbackHost(host) {
152
+ const text = String(host ?? "").trim().toLowerCase();
153
+ if (!text) return false;
154
+ if (text === "localhost" || text.endsWith(".localhost")) return true;
155
+ if (text === "::1" || text === "0:0:0:0:0:0:0:1") return true;
156
+ if (/^127\./.test(text)) return true;
157
+ return false;
158
+ }
159
+
160
+ /** 从 `http://host:port/` 里取端口;取不到返回 0。 */
161
+ function portOf(base) {
162
+ try {
163
+ const parsed = new URL(base);
164
+ if (parsed.port) return Number(parsed.port);
165
+ return parsed.protocol === "https:" ? 443 : 80;
166
+ } catch {
167
+ return 0;
168
+ }
169
+ }
170
+
171
+ /**
172
+ * 这个主机名需不需要先探测一次可达性。
173
+ *
174
+ * 只用来决定"要不要探测":同网段地址拨不通会在面板里立刻明确报出来,没必要
175
+ * 每次都先花 1.5 秒探测;跨网段的地址(运营商 CGNAT、别的子网)才是对端自报
176
+ * 地址最容易骗人的地方 —— 10.x 尤其:手机在移动数据下的自报地址就长这样。
177
+ * @param {string} host
178
+ * @param {string[]} localAddresses 本机 IPv4 列表
179
+ */
180
+ export function needsReachabilityProbe(host, localAddresses = []) {
181
+ const m = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(String(host ?? ""));
182
+ if (!m) return true;
183
+ if (m[1] === "127") return false;
184
+ const wanted = `${m[1]}.${m[2]}.${m[3]}`;
185
+ for (const address of localAddresses) {
186
+ const n = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.\d{1,3}$/.exec(String(address ?? ""));
187
+ if (!n) continue;
188
+ if (`${n[1]}.${n[2]}.${n[3]}` === wanted) return false;
189
+ }
190
+ return true;
191
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-plugin-mesh",
3
- "version": "0.5.13",
3
+ "version": "0.5.15",
4
4
  "type": "module",
5
5
  "description": "把跑不完的活交给另一台电脑;跑完,结果回到你面前。两台装了 DSH 的电脑各装一次,自动互相发现,任务派过去由对端的 agent 执行,结果派回来。Hand a long task to another machine: your DSH instances find each other, the peer runs it, and the result comes back. No pairing codes, no IPs, no Tailscale client.",
6
6
  "license": "MIT",
@@ -69,8 +69,8 @@
69
69
  "selftest:update": "node lib/_selftest-update.mjs",
70
70
  "selftest:upgrade": "node lib/_selftest-upgrade.mjs",
71
71
  "selftest:approval": "node lib/_selftest-approval.mjs",
72
- "test": "npm run check && npm run selftest && npm run selftest:prompt && npm run selftest:at && npm run selftest:at:host && npm run selftest:pairing && npm run selftest:approval && npm run selftest:switch && npm run selftest:client && npm run selftest:caps && npm run selftest:release && npm run selftest:reply && npm run selftest:reasoning && npm run selftest:resume && npm run selftest:persist && npm run selftest:layout && npm run selftest:diagnostics && npm run selftest:osinfo && npm run selftest:peerweb && npm run selftest:update && npm run selftest:upgrade",
73
- "check": "node scripts/check-version.mjs && node scripts/check-tdz.mjs && node --check lib/index.js && node --check lib/layout.js && node --check lib/discovery.js && node --check lib/conversation.js && node --check lib/identity.js && node --check lib/capabilities.js && node --check lib/prompt.js && node --check lib/at-mention.js && node --check lib/pairing.js && node --check lib/switch.js && node --check lib/scan.js && node --check lib/update.js && node --check lib/upgrade.js && node --check lib/peer-web.js && node --check lib/tsnet/download.js && node --check lib/tsnet/manager.js && node --check lib/tsnet/bridge.js && node --check lib/tsnet/channels.js && node --check client/client.js && node --check scripts/release-plan.mjs && npm run check:loadable && npm run check:docs",
72
+ "test": "npm run check && npm run selftest && npm run selftest:prompt && npm run selftest:at && npm run selftest:at:host && npm run selftest:pairing && npm run selftest:approval && npm run selftest:switch && npm run selftest:client && npm run selftest:caps && npm run selftest:release && npm run selftest:reply && npm run selftest:reasoning && npm run selftest:resume && npm run selftest:persist && npm run selftest:layout && npm run selftest:diagnostics && npm run selftest:osinfo && npm run selftest:peerweb && npm run selftest:webtarget && npm run selftest:sshtarget && npm run selftest:update && npm run selftest:upgrade",
73
+ "check": "node scripts/check-version.mjs && node scripts/check-tdz.mjs && node --check lib/index.js && node --check lib/layout.js && node --check lib/discovery.js && node --check lib/conversation.js && node --check lib/identity.js && node --check lib/capabilities.js && node --check lib/prompt.js && node --check lib/at-mention.js && node --check lib/pairing.js && node --check lib/switch.js && node --check lib/scan.js && node --check lib/update.js && node --check lib/upgrade.js && node --check lib/peer-web.js && node --check lib/web-target.js && node --check lib/ssh-target.js && node --check lib/tsnet/download.js && node --check lib/tsnet/manager.js && node --check lib/tsnet/bridge.js && node --check lib/tsnet/channels.js && node --check client/client.js && node --check scripts/release-plan.mjs && npm run check:loadable && npm run check:docs",
74
74
  "build:sidecar": "bash scripts/build-sidecar.sh",
75
75
  "verify:mirror": "node scripts/verify-lan-mirror.mjs",
76
76
  "release:plan": "node scripts/release-plan.mjs",
@@ -84,7 +84,9 @@
84
84
  "selftest:switch": "node lib/_selftest-switch.mjs",
85
85
  "selftest:at": "node lib/_selftest-at-mention.mjs",
86
86
  "selftest:at:host": "node --experimental-vm-modules lib/_selftest-at-mention-host.mjs",
87
- "selftest:peerweb": "node lib/_selftest-peer-web.mjs"
87
+ "selftest:peerweb": "node lib/_selftest-peer-web.mjs",
88
+ "selftest:webtarget": "node lib/_selftest-web-target.mjs",
89
+ "selftest:sshtarget": "node lib/_selftest-ssh-target.mjs"
88
90
  },
89
91
  "publishConfig": {
90
92
  "registry": "https://registry.npmjs.org/",
@@ -19,7 +19,9 @@ DIST_DIR="$REPO_ROOT/dist/sidecar"
19
19
 
20
20
  # The release tag is tied to the sidecar control-API protocol, not the plugin
21
21
  # version: the plugin pins a protocol number and refuses mismatched binaries.
22
- PROTOCOL_VERSION=1
22
+ # 必须与 sidecar/main.go 的 ProtocolVersion、lib/tsnet/download.js 的
23
+ # SIDECAR_PROTOCOL 三处一致(脚本里自己会校验前两者)。
24
+ PROTOCOL_VERSION=2
23
25
  RELEASE_TAG="sidecar-v${PROTOCOL_VERSION}"
24
26
  # 发布目标仓库。必须与 lib/tsnet/download.js 里的 REPO 一致,否则插件会去
25
27
  # 另一个仓库找二进制。
package/sidecar/main.go CHANGED
@@ -51,7 +51,11 @@ import (
51
51
 
52
52
  // ProtocolVersion is bumped whenever the control API changes shape, so the
53
53
  // plugin can refuse a stale cached binary instead of failing in confusing ways.
54
- const ProtocolVersion = 1
54
+ //
55
+ // v2:新增出站流 /__tsnet/dial + /__tsnet/undial(SSH 走 tailnet 的前提)和
56
+ // 入站 /__tsnet/listen(把本机端口暴露到 tailnet)。v1 的二进制没有这两个端点,
57
+ // 而老插件钉的是 v1 那批 sha256 —— 所以只能新开 sidecar-v2,不能覆盖 v1 资产。
58
+ const ProtocolVersion = 2
55
59
 
56
60
  var (
57
61
  flHostname = flag.String("hostname", "", "tailnet node name (DNS label); required")
@@ -154,6 +158,8 @@ type sidecar struct {
154
158
 
155
159
  mu sync.Mutex
156
160
  forwards map[int]net.Listener
161
+ dials map[int]net.Listener
162
+ listens map[int]net.Listener
157
163
  diagnostics []string
158
164
  }
159
165
 
@@ -293,7 +299,7 @@ func main() {
293
299
  os.Exit(1)
294
300
  }
295
301
 
296
- sc := &sidecar{token: *flToken, hostname: hostname, forwards: map[int]net.Listener{}}
302
+ sc := &sidecar{token: *flToken, hostname: hostname, forwards: map[int]net.Listener{}, dials: map[int]net.Listener{}, listens: map[int]net.Listener{}}
297
303
 
298
304
  // 解析器**必须在这里**装,早于任何可能启动 tsnet 的代码。
299
305
  //
@@ -445,6 +451,14 @@ func (sc *sidecar) shutdown() {
445
451
  _ = ln.Close()
446
452
  delete(sc.forwards, port)
447
453
  }
454
+ for port, ln := range sc.dials {
455
+ _ = ln.Close()
456
+ delete(sc.dials, port)
457
+ }
458
+ for port, ln := range sc.listens {
459
+ _ = ln.Close()
460
+ delete(sc.listens, port)
461
+ }
448
462
  sc.mu.Unlock()
449
463
  if sc.srv != nil {
450
464
  _ = sc.srv.Close()
@@ -510,6 +524,10 @@ func (sc *sidecar) controlMux() http.Handler {
510
524
  mux.HandleFunc("/__tsnet/fetch", sc.auth(sc.handleFetch))
511
525
  mux.HandleFunc("/__tsnet/forward", sc.auth(sc.handleForward))
512
526
  mux.HandleFunc("/__tsnet/unforward", sc.auth(sc.handleUnforward))
527
+ mux.HandleFunc("/__tsnet/dial", sc.auth(sc.handleDial))
528
+ mux.HandleFunc("/__tsnet/undial", sc.auth(sc.handleUndial))
529
+ mux.HandleFunc("/__tsnet/listen", sc.auth(sc.handleListen))
530
+ mux.HandleFunc("/__tsnet/unlisten", sc.auth(sc.handleUnlisten))
513
531
  mux.HandleFunc("/__tsnet/shutdown", sc.auth(func(w http.ResponseWriter, r *http.Request) {
514
532
  writeJSON(w, 200, map[string]any{"ok": true})
515
533
  go func() {
@@ -758,6 +776,233 @@ func (sc *sidecar) handleUnforward(w http.ResponseWriter, r *http.Request) {
758
776
  writeJSON(w, 200, map[string]any{"ok": true, "port": req.Port})
759
777
  }
760
778
 
779
+ // ---------------------------------------------------------------------------
780
+ // outbound raw streams
781
+ // ---------------------------------------------------------------------------
782
+
783
+ // dialRequest asks for a loopback listener whose accepted connections are piped
784
+ // byte-for-byte into a TCP address reachable only through the tailnet.
785
+ type dialRequest struct {
786
+ Address string `json:"address"`
787
+ }
788
+
789
+ // handleDial is the raw-stream counterpart of handleForward.
790
+ //
791
+ // Why it has to exist: /__tsnet/fetch buffers a whole response (32 MB cap) and
792
+ // speaks one HTTP transaction, so it cannot carry a WebSocket upgrade or a
793
+ // long-lived stream. The plugin's "open the peer's DSH GUI" path needs both
794
+ // (`/api/remote.mux` is a WS). Rather than teach the control API about HTTP
795
+ // semantics, hand the caller a loopback TCP port and move bytes: every accepted
796
+ // connection is dialed through tsnet and spliced in both directions.
797
+ func (sc *sidecar) handleDial(w http.ResponseWriter, r *http.Request) {
798
+ if r.Method != http.MethodPost {
799
+ writeJSON(w, http.StatusMethodNotAllowed, map[string]any{"ok": false, "error": "POST required"})
800
+ return
801
+ }
802
+ var req dialRequest
803
+ if err := json.NewDecoder(io.LimitReader(r.Body, 1<<20)).Decode(&req); err != nil {
804
+ writeJSON(w, 200, map[string]any{"ok": false, "error": err.Error()})
805
+ return
806
+ }
807
+ host, port, err := net.SplitHostPort(strings.TrimSpace(req.Address))
808
+ if err != nil || host == "" || port == "" {
809
+ writeJSON(w, 200, map[string]any{"ok": false, "error": "address must be host:port, got " + strconv.Quote(req.Address)})
810
+ return
811
+ }
812
+ if _, err := strconv.Atoi(port); err != nil {
813
+ writeJSON(w, 200, map[string]any{"ok": false, "error": "port is not numeric: " + port})
814
+ return
815
+ }
816
+ if sc.srv == nil {
817
+ writeJSON(w, 200, map[string]any{"ok": false, "error": "tailnet node is not started"})
818
+ return
819
+ }
820
+
821
+ ln, err := net.Listen("tcp", "127.0.0.1:0")
822
+ if err != nil {
823
+ writeJSON(w, 200, map[string]any{"ok": false, "error": "listen: " + err.Error()})
824
+ return
825
+ }
826
+ localPort := ln.Addr().(*net.TCPAddr).Port
827
+
828
+ sc.mu.Lock()
829
+ sc.dials[localPort] = ln
830
+ sc.mu.Unlock()
831
+
832
+ go sc.serveDial(ln, req.Address)
833
+ sc.note("dialing tailnet %s via loopback :%d", req.Address, localPort)
834
+ writeJSON(w, 200, map[string]any{"ok": true, "port": localPort, "address": req.Address})
835
+ }
836
+
837
+ // serveDial accepts on the loopback listener and splices each connection to the
838
+ // tailnet. Failures are per-connection: one refused dial must not kill the
839
+ // listener, because the plugin keeps the port for the lifetime of a panel.
840
+ func (sc *sidecar) serveDial(ln net.Listener, address string) {
841
+ for {
842
+ conn, err := ln.Accept()
843
+ if err != nil {
844
+ // A closed listener is the normal shutdown path (undial / shutdown).
845
+ return
846
+ }
847
+ go func() {
848
+ defer conn.Close()
849
+ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
850
+ up, err := sc.srv.Dial(ctx, "tcp", address)
851
+ cancel()
852
+ if err != nil {
853
+ sc.note("dial %s failed: %v", address, err)
854
+ return
855
+ }
856
+ defer up.Close()
857
+ done := make(chan struct{}, 2)
858
+ go func() { _, _ = io.Copy(up, conn); done <- struct{}{} }()
859
+ go func() { _, _ = io.Copy(conn, up); done <- struct{}{} }()
860
+ // 两条方向都结束才算这条连接完;单方向 EOF 时先把另一端关掉,
861
+ // 否则 io.Copy 的另一半会永远等(HTTP keep-alive 场景很常见)。
862
+ <-done
863
+ _ = up.Close()
864
+ _ = conn.Close()
865
+ <-done
866
+ }()
867
+ }
868
+ }
869
+
870
+ // handleUndial closes one outbound stream listener by its loopback port.
871
+ func (sc *sidecar) handleUndial(w http.ResponseWriter, r *http.Request) {
872
+ if r.Method != http.MethodPost {
873
+ writeJSON(w, http.StatusMethodNotAllowed, map[string]any{"ok": false, "error": "POST required"})
874
+ return
875
+ }
876
+ var body struct {
877
+ Port int `json:"port"`
878
+ }
879
+ if err := json.NewDecoder(io.LimitReader(r.Body, 1<<20)).Decode(&body); err != nil {
880
+ writeJSON(w, 200, map[string]any{"ok": false, "error": err.Error()})
881
+ return
882
+ }
883
+ sc.mu.Lock()
884
+ ln, exists := sc.dials[body.Port]
885
+ if exists {
886
+ delete(sc.dials, body.Port)
887
+ }
888
+ sc.mu.Unlock()
889
+ if !exists {
890
+ writeJSON(w, 200, map[string]any{"ok": true, "absent": true, "port": body.Port})
891
+ return
892
+ }
893
+ _ = ln.Close()
894
+ sc.note("stopped dialing loopback :%d", body.Port)
895
+ writeJSON(w, 200, map[string]any{"ok": true, "port": body.Port})
896
+ }
897
+
898
+ // ---------------------------------------------------------------------------
899
+ // inbound raw streams (tailnet -> loopback)
900
+ // ---------------------------------------------------------------------------
901
+
902
+ // handleListen is the raw-TCP counterpart of handleForward.
903
+ //
904
+ // handleForward reverse-proxies *HTTP* from the tailnet to loopback, so an SSH
905
+ // handshake (bare `SSH-2.0-...` bytes) gets rejected as a malformed request.
906
+ // This one just moves bytes: listen on the tailnet, dial 127.0.0.1:port, splice.
907
+ // It is the mirror image of handleDial, and the pair is what makes "SSH over
908
+ // tailnet" possible in both directions without any system-level tailscaled.
909
+ func (sc *sidecar) handleListen(w http.ResponseWriter, r *http.Request) {
910
+ if r.Method != http.MethodPost {
911
+ writeJSON(w, http.StatusMethodNotAllowed, map[string]any{"ok": false, "error": "POST required"})
912
+ return
913
+ }
914
+ var body struct {
915
+ Port int `json:"port"`
916
+ }
917
+ if err := json.NewDecoder(io.LimitReader(r.Body, 1<<20)).Decode(&body); err != nil {
918
+ writeJSON(w, 200, map[string]any{"ok": false, "error": err.Error()})
919
+ return
920
+ }
921
+ if body.Port <= 0 || body.Port > 65535 {
922
+ writeJSON(w, 200, map[string]any{"ok": false, "error": "port out of range"})
923
+ return
924
+ }
925
+ if sc.srv == nil {
926
+ writeJSON(w, 200, map[string]any{"ok": false, "error": "tailnet node is not started"})
927
+ return
928
+ }
929
+ sc.mu.Lock()
930
+ _, exists := sc.listens[body.Port]
931
+ sc.mu.Unlock()
932
+ if exists {
933
+ writeJSON(w, 200, map[string]any{"ok": true, "already": true, "port": body.Port})
934
+ return
935
+ }
936
+ ln, err := sc.srv.Listen("tcp", ":"+strconv.Itoa(body.Port))
937
+ if err != nil {
938
+ writeJSON(w, 200, map[string]any{"ok": false, "error": "listen: " + err.Error()})
939
+ return
940
+ }
941
+ sc.mu.Lock()
942
+ sc.listens[body.Port] = ln
943
+ sc.mu.Unlock()
944
+ go sc.serveListen(ln, body.Port)
945
+ sc.note("exposing tailnet :%d -> 127.0.0.1:%d", body.Port, body.Port)
946
+ writeJSON(w, 200, map[string]any{"ok": true, "port": body.Port})
947
+ }
948
+
949
+ // serveListen accepts on the tailnet listener and splices each connection to
950
+ // the same port on loopback. Per-connection failures stay per-connection: the
951
+ // local sshd being down must not tear down the tailnet listener.
952
+ func (sc *sidecar) serveListen(ln net.Listener, port int) {
953
+ target := "127.0.0.1:" + strconv.Itoa(port)
954
+ for {
955
+ conn, err := ln.Accept()
956
+ if err != nil {
957
+ return
958
+ }
959
+ go func() {
960
+ defer conn.Close()
961
+ up, err := net.DialTimeout("tcp", target, 10*time.Second)
962
+ if err != nil {
963
+ sc.note("listen :%d dial %s failed: %v", port, target, err)
964
+ return
965
+ }
966
+ defer up.Close()
967
+ done := make(chan struct{}, 2)
968
+ go func() { _, _ = io.Copy(up, conn); done <- struct{}{} }()
969
+ go func() { _, _ = io.Copy(conn, up); done <- struct{}{} }()
970
+ <-done
971
+ _ = up.Close()
972
+ _ = conn.Close()
973
+ <-done
974
+ }()
975
+ }
976
+ }
977
+
978
+ // handleUnlisten stops exposing one port on the tailnet.
979
+ func (sc *sidecar) handleUnlisten(w http.ResponseWriter, r *http.Request) {
980
+ if r.Method != http.MethodPost {
981
+ writeJSON(w, http.StatusMethodNotAllowed, map[string]any{"ok": false, "error": "POST required"})
982
+ return
983
+ }
984
+ var body struct {
985
+ Port int `json:"port"`
986
+ }
987
+ if err := json.NewDecoder(io.LimitReader(r.Body, 1<<20)).Decode(&body); err != nil {
988
+ writeJSON(w, 200, map[string]any{"ok": false, "error": err.Error()})
989
+ return
990
+ }
991
+ sc.mu.Lock()
992
+ ln, exists := sc.listens[body.Port]
993
+ if exists {
994
+ delete(sc.listens, body.Port)
995
+ }
996
+ sc.mu.Unlock()
997
+ if !exists {
998
+ writeJSON(w, 200, map[string]any{"ok": true, "absent": true, "port": body.Port})
999
+ return
1000
+ }
1001
+ _ = ln.Close()
1002
+ sc.note("stopped exposing tailnet :%d", body.Port)
1003
+ writeJSON(w, 200, map[string]any{"ok": true, "port": body.Port})
1004
+ }
1005
+
761
1006
  // ---------------------------------------------------------------------------
762
1007
  // small helpers
763
1008
  // ---------------------------------------------------------------------------