dsh-plugin-mesh 0.5.16 → 0.5.18

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/client/client.js CHANGED
@@ -4389,6 +4389,9 @@ window.__ModuleLoader__.load({
4389
4389
  "aria-modal": "true",
4390
4390
  "aria-label": `${name} 的 DSH Web`,
4391
4391
  "data-mesh-view": "web",
4392
+ // 收起来的面板只隐藏、不卸载:卸载会销毁 iframe,对端页面要重新加载,
4393
+ // 会话状态和滚动位置全丢。宿主侧同时保留代理宽限期,两边配套。
4394
+ style: panel.hidden ? { display: "none" } : undefined,
4392
4395
  },
4393
4396
  h(
4394
4397
  "div",
@@ -8355,9 +8358,29 @@ window.__ModuleLoader__.load({
8355
8358
  * 也不受对端 cookie 的 SameSite=Strict 影响。
8356
8359
  * 反代起不来时才退回老的"浏览器页签 / 外部浏览器"那条链。
8357
8360
  */
8358
- const openWeb = async (peer) => {
8361
+ const openWeb = async (peer, opts) => {
8362
+ const force = !!(opts && opts.force);
8359
8363
  const name = (peer && peer.machine) || "对端";
8360
- setWebPanel({ peer, name, state: "loading", reloadKey: 0 });
8364
+ const key = (peer && (peer.machine || peer.id)) || "";
8365
+ const cachedKey =
8366
+ webPanel && webPanel.peer ? webPanel.peer.machine || webPanel.peer.id || "" : "";
8367
+ // 之前收起来的同一台设备:直接显示,不请求宿主、不重建 iframe。
8368
+ // 页面状态、滚动位置、对端会话原样还在(宿主那边代理也在宽限期内)。
8369
+ // 超过宽限期就不再走快路——那时宿主可能已经把代理回收了,直接显示
8370
+ // 只会看到一个连不上的 iframe。
8371
+ const hiddenFor = webPanel && webPanel.hiddenAt ? Date.now() - webPanel.hiddenAt : Infinity;
8372
+ if (!force && webPanel && webPanel.url && cachedKey && cachedKey === key && hiddenFor < 8 * 60 * 1000) {
8373
+ setWebPanel((prev) => ({ ...(prev || { peer, name }), peer, name, hidden: false, hiddenAt: 0, state: "ready" }));
8374
+ return;
8375
+ }
8376
+ // force = 用户点「重新加载面板」:保留同一个代理地址,只让 iframe 重载
8377
+ setWebPanel((prev) => ({
8378
+ peer,
8379
+ name,
8380
+ state: "loading",
8381
+ hidden: false,
8382
+ reloadKey: force && prev && prev.url ? (prev.reloadKey || 0) + 1 : 0,
8383
+ }));
8361
8384
  try {
8362
8385
  const r = await api("/web-panel", { peer: (peer && (peer.machine || peer.id)) || "" });
8363
8386
  if (r && r.ok === true && typeof r.url === "string") {
@@ -8368,7 +8391,8 @@ window.__ModuleLoader__.load({
8368
8391
  remote: r.remote || "",
8369
8392
  hasSession: r.hasSession !== false,
8370
8393
  note: r.note || "",
8371
- reloadKey: 0,
8394
+ hidden: false,
8395
+ reloadKey: (prev && prev.reloadKey) || 0,
8372
8396
  }));
8373
8397
  if (r.hasSession === false) {
8374
8398
  push("warn", `${name} 那边没给出可用 token,面板可能停在登录页。`);
@@ -8437,7 +8461,9 @@ window.__ModuleLoader__.load({
8437
8461
  */
8438
8462
  const closeWebPanel = () => {
8439
8463
  const machine = webPanel && webPanel.peer ? webPanel.peer.machine || webPanel.peer.id || "" : "";
8440
- setWebPanel(null);
8464
+ // 只收起、不卸载:iframe 留着,对端页面的会话状态和滚动位置都还在;
8465
+ // 宿主收到 close 只把它标记成空闲,宽限期内不拆代理和出站流。
8466
+ setWebPanel((prev) => (prev ? { ...prev, hidden: true, hiddenAt: Date.now() } : null));
8441
8467
  if (!machine) return;
8442
8468
  api("/web-panel/close", { peer: machine }).catch(() => {
8443
8469
  /* 关闭是尽力而为 */
@@ -8448,7 +8474,7 @@ window.__ModuleLoader__.load({
8448
8474
  const reloadWebPanel = () => {
8449
8475
  const peer = webPanel && webPanel.peer;
8450
8476
  if (!peer) return;
8451
- void openWeb(peer);
8477
+ void openWeb(peer, { force: true });
8452
8478
  };
8453
8479
 
8454
8480
  /** 派发成功的统一收尾:toast + 让轮询立刻刷新。
package/lib/index.js CHANGED
@@ -129,7 +129,7 @@ import {
129
129
  export const name = "dsh-plugin-mesh";
130
130
  export const inject = ["tools", "webServer"];
131
131
 
132
- const VERSION = "0.5.16";
132
+ const VERSION = "0.5.18";
133
133
  // 诊断用:进程启动时间 + 入口真实路径。磁盘上的版本**不在这里缓存** ——
134
134
  // 升级之后进程还跑旧代码,版本号必须现读磁盘才能立刻反映出来(真踩过:
135
135
  // 磁盘升到 0.5.1,进程还在 0.5.0,界面显示 0.5.0)。
@@ -4868,6 +4868,16 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
4868
4868
  void closeWebPanels();
4869
4869
  });
4870
4870
 
4871
+ // 空闲面板的定期回收:宽限期到了才真的关代理、收回 tailnet 出站流。
4872
+ // 60 秒扫一次足够——宽限期是分钟级的,不需要更细。
4873
+ ctx.effect(() => {
4874
+ const timer = setInterval(() => {
4875
+ void sweepWebPanels();
4876
+ }, 60 * 1000);
4877
+ if (typeof timer.unref === "function") timer.unref();
4878
+ return () => clearInterval(timer);
4879
+ });
4880
+
4871
4881
  /** 取对端的 Web 地址与启动 token;老版本对端只能退回按约定拼地址。 */
4872
4882
  /**
4873
4883
  * 取对端的 Web 地址与启动 token。
@@ -5096,6 +5106,35 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
5096
5106
  return 0;
5097
5107
  }
5098
5108
 
5109
+ /**
5110
+ * 面板关掉后代理与出站流**保留多久**。
5111
+ *
5112
+ * 为什么不是立刻销毁:关掉面板/切走再回来只隔几秒,重新解析目标 + 重新拨
5113
+ * tailnet 出站流 + 重新握手,代价是好几秒(移动网络下更久),页面还要重新
5114
+ * 渲染一遍。留一段宽限期,期间再打开直接复用同一个代理和端口,页面只是
5115
+ * iframe 重新加载,会话 cookie 也还在。
5116
+ */
5117
+ const WEB_PANEL_IDLE_MS = (() => {
5118
+ const raw = Number(process.env.DSH_MESH_WEBPANEL_IDLE_MS);
5119
+ return Number.isFinite(raw) && raw >= 0 ? raw : 10 * 60 * 1000;
5120
+ })();
5121
+
5122
+ /** 关掉超时的面板代理(保留期内不动)。 */
5123
+ async function sweepWebPanels() {
5124
+ const now = Date.now();
5125
+ for (const [machine, entry] of [...webPanels.entries()]) {
5126
+ if (now - (entry.lastUsedAt ?? now) < WEB_PANEL_IDLE_MS) continue;
5127
+ webPanels.delete(machine);
5128
+ try {
5129
+ await entry.proxy.close();
5130
+ } catch (err) {
5131
+ warn(`回收超时 Web 面板代理失败:${err?.message ?? err}`);
5132
+ }
5133
+ await closePanelStream(entry);
5134
+ log(`Web 面板代理已回收(空闲超过 ${Math.round(WEB_PANEL_IDLE_MS / 1000)}s):${machine}`);
5135
+ }
5136
+ }
5137
+
5099
5138
  post("/mesh/api/web-panel", async (req, res) => {
5100
5139
  const body = await readJson(req);
5101
5140
  const found = findPeer(String(body?.peer ?? "").trim());
@@ -5103,6 +5142,22 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
5103
5142
  const target = found.peer;
5104
5143
  const machine = target.machine || String(body?.peer ?? "");
5105
5144
 
5145
+ // 快速复用:宽限期内再次打开,连目标都不重新解析 —— 解析本身就要打一次
5146
+ // 对端 /mesh/v1/web-url,出站流重建更贵。这里是"秒开"的关键。
5147
+ const reused = webPanels.get(machine);
5148
+ if (reused && Date.now() - (reused.lastUsedAt ?? 0) < WEB_PANEL_IDLE_MS) {
5149
+ reused.lastUsedAt = Date.now();
5150
+ return send(res, 200, {
5151
+ ok: true,
5152
+ url: reused.proxy.url,
5153
+ remote: reused.proxy.remote,
5154
+ hasSession: reused.proxy.hasSession(),
5155
+ note: "复用上一次的面板代理(未重新建连)",
5156
+ lanReachable: true,
5157
+ reused: true,
5158
+ });
5159
+ }
5160
+
5106
5161
  const resolved = await resolveWebTarget(
5107
5162
  target,
5108
5163
  typeof body?.token === "string" ? body.token.trim() : "",
@@ -5150,7 +5205,7 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
5150
5205
  log,
5151
5206
  warn,
5152
5207
  });
5153
- webPanels.set(machine, { proxy, remote: resolved.remoteBase, signature, stream: resolved.stream });
5208
+ webPanels.set(machine, { proxy, remote: resolved.remoteBase, signature, stream: resolved.stream, lastUsedAt: Date.now() });
5154
5209
  return send(res, 200, {
5155
5210
  ok: true,
5156
5211
  url: proxy.url,
@@ -5168,7 +5223,11 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
5168
5223
  const body = await readJson(req);
5169
5224
  const machine = String(body?.peer ?? "").trim();
5170
5225
  const entry = webPanels.get(machine);
5171
- if (entry) {
5226
+ if (!entry) return send(res, 200, { ok: true });
5227
+ // 关面板 ≠ 立刻拆连接:留一段宽限期,短时间再打开直接复用(秒开,
5228
+ // 会话 cookie 也还在)。真正的回收交给 sweepWebPanels 按空闲时长做。
5229
+ // 需要立刻释放的调用方显式传 force:true。
5230
+ if (body?.force === true) {
5172
5231
  webPanels.delete(machine);
5173
5232
  try {
5174
5233
  await entry.proxy.close();
@@ -5176,8 +5235,15 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
5176
5235
  warn(`关闭 Web 面板代理失败:${err?.message ?? err}`);
5177
5236
  }
5178
5237
  await closePanelStream(entry);
5238
+ return send(res, 200, { ok: true, closed: true });
5179
5239
  }
5180
- return send(res, 200, { ok: true });
5240
+ entry.lastUsedAt = Date.now();
5241
+ entry.idle = true;
5242
+ return send(res, 200, {
5243
+ ok: true,
5244
+ kept: true,
5245
+ idleMs: WEB_PANEL_IDLE_MS,
5246
+ });
5181
5247
  });
5182
5248
 
5183
5249
  /** 关掉面板时顺手收回它用的 tailnet 出站流(端口不回收会一直挂着)。 */
package/lib/peer-web.js CHANGED
@@ -29,9 +29,14 @@
29
29
  * 共享密钥与票据都**不转发给上游 GUI**(见 rewrite())。
30
30
  */
31
31
  import { createHmac, timingSafeEqual } from "node:crypto";
32
- import { request as httpRequest } from "node:http";
32
+ import { Agent as HttpAgent, request as httpRequest } from "node:http";
33
33
  import { connect as netConnect } from "node:net";
34
34
  import { signSessionCookie } from "./desktop-auth.js";
35
+ import { createGzip } from "node:zlib";
36
+ // [mesh-keepalive] 复用上游连接:几十个 bundle 请求不该各建一次 TCP。
37
+ // tailnet 上每次握手就是一个 RTT;局域网/回环上也省掉握手与端口分配。
38
+ const upstreamAgent = new HttpAgent({ keepAlive: true, maxSockets: 16, maxFreeSockets: 8, timeout: 30000 });
39
+
35
40
 
36
41
  /** 隧道前缀(挂在 mesh 口上,和 Web 口上的 /mesh/web 不是一回事)。 */
37
42
  export const PEER_WEB_PREFIX = "/mesh/peer-web";
@@ -170,12 +175,26 @@ export function createPeerWebForwarder({ portOf, secretOf, log = () => {}, warn
170
175
  }
171
176
  const authority = `127.0.0.1:${port}`;
172
177
  const up = httpRequest(
173
- { host: "127.0.0.1", port, method: req.method, path, headers: rewrite(req.headers, authority) },
178
+ { host: "127.0.0.1", port, method: req.method, path, headers: rewrite(req.headers, authority), agent: upstreamAgent },
174
179
  (reply) => {
175
180
  const out = { ...reply.headers };
176
181
  // 会话由本转发维护,别把 Set-Cookie 泄到隧道外(观看端没有对应的 authority)。
177
182
  delete out["set-cookie"];
178
183
  delete out["transfer-encoding"];
184
+ // [mesh-gzip] 上游没压时在隧道这一跳压缩(tailnet 是细管,收益最大)
185
+ if (out["content-encoding"] === undefined
186
+ && String(req.headers["accept-encoding"] ?? "").includes("gzip")
187
+ // HTML 不压:观看端代理要往文档里注入垫片,必须拿到明文;
188
+ // 大文档也就几十 KB,压不压对总时长没有意义,而注入冲突是硬错误。
189
+ && /^text\/|javascript|json|svg|css/i.test(String(out["content-type"] ?? ""))
190
+ && !/^text\/html/i.test(String(out["content-type"] ?? ""))) {
191
+ out["content-encoding"] = "gzip";
192
+ out["vary"] = "accept-encoding";
193
+ delete out["content-length"];
194
+ res.writeHead(reply.statusCode ?? 502, out);
195
+ reply.pipe(createGzip({ level: 1 })).pipe(res);
196
+ return;
197
+ }
179
198
  res.writeHead(reply.statusCode ?? 502, out);
180
199
  reply.pipe(res);
181
200
  },
package/lib/web-proxy.js CHANGED
@@ -18,11 +18,14 @@
18
18
  * 这不是"安全方案",只是别让它成为同机任意 App 的免费后门;
19
19
  * 真正的边界在"谁能碰到这台手机"。
20
20
  */
21
- import { createServer, request as httpRequest } from "node:http";
21
+ import { Agent as HttpAgent, createServer, request as httpRequest } from "node:http";
22
22
  import { appendFileSync } from "node:fs";
23
23
  import { join } from "node:path";
24
24
  import { homedir } from "node:os";
25
25
  import { connect as netConnect } from "node:net";
26
+ // [mesh-keepalive] 复用上游连接:几十个 bundle 请求不该各建一次 TCP。
27
+ // tailnet 上每次握手就是一个 RTT;局域网/回环上也省掉握手与端口分配。
28
+ const upstreamAgent = new HttpAgent({ keepAlive: true, maxSockets: 16, maxFreeSockets: 8, timeout: 30000 });
26
29
 
27
30
  /** 我们自己发的门禁 cookie:名字固定,值就是 nonce。 */
28
31
  const GATE_COOKIE = "dshmesh-web";
@@ -211,7 +214,7 @@ export async function createWebProxy({
211
214
  if (wantsHtml) headers["accept-encoding"] = "identity";
212
215
 
213
216
  const up = httpRequest(
214
- { host: hostname, port: remotePort, method: req.method, path: `${prefix}${stripGate(req.url)}`, headers },
217
+ { host: hostname, port: remotePort, method: req.method, path: `${prefix}${stripGate(req.url)}`, headers, agent: upstreamAgent },
215
218
  (reply) => {
216
219
  // 401 = 我们的服务端 cookie 过期/轮换过:换一次再重试(只重试幂等方法)。
217
220
  const idempotent = req.method === "GET" || req.method === "HEAD";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-plugin-mesh",
3
- "version": "0.5.16",
3
+ "version": "0.5.18",
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",