dsh-plugin-mesh 0.5.5 → 0.5.7

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,333 @@
1
+ /**
2
+ * 对端 DSH Web 的回环反向代理。
3
+ *
4
+ * 为什么需要它:手机上"在应用内看对端 DSH"有两条路都被堵死——
5
+ * 1) 壳的浏览器 WebView 在本机不可用(browserWebViewAvailable=false),
6
+ * sidebar 的 browser 页签只会显示"浏览器不可用";
7
+ * 2) 直接 iframe 对端地址会卡在 401:对端的会话 cookie 是 SameSite=Strict,
8
+ * 跨站 iframe 里不发送;token 又会随对端重启轮换。
9
+ *
10
+ * 所以把认证搬到服务端:
11
+ * · 代理用 token 换一次对端的签名 cookie,之后每一个转发请求都自己带;
12
+ * · 浏览器只跟本机的这个回环端口说话,不需要任何 token、也没有 SameSite 问题;
13
+ * · 页面挂在**独立端口**上(不是 /mesh/... 子路径),所以对端 SPA 里的
14
+ * 绝对路径 /api、/plugins 天然落在代理上,不用改写任何压缩后的 JS。
15
+ *
16
+ * 安全:只监听 127.0.0.1,并且首次访问必须带一次性 k=<nonce>(换一枚
17
+ * HttpOnly cookie)。本机其它 App 拿不到 nonce 就用不了这条通道。
18
+ * 这不是"安全方案",只是别让它成为同机任意 App 的免费后门;
19
+ * 真正的边界在"谁能碰到这台手机"。
20
+ */
21
+ import { createServer, request as httpRequest } from "node:http";
22
+ import { appendFileSync } from "node:fs";
23
+ import { join } from "node:path";
24
+ import { homedir } from "node:os";
25
+ import { connect as netConnect } from "node:net";
26
+
27
+ /** 我们自己发的门禁 cookie:名字固定,值就是 nonce。 */
28
+ const GATE_COOKIE = "dshmesh-web";
29
+
30
+ /**
31
+ * 老 WebView 垫片:Chrome 122 之前没有 `Iterator` 全局对象。
32
+ *
33
+ * 对端前端里有些库会这样"补方法":`"function" != typeof Iterator.prototype.join
34
+ * && (Iterator.prototype.join = ...)` —— 守卫只看了 `.join`,没先看 `Iterator`
35
+ * 本身,于是在缺少 Iterator 的引擎上直接 ReferenceError,整个插件装不上
36
+ * (实测报错:failed to import loader entry …documentpreview: Iterator is not defined)。
37
+ *
38
+ * 垫片只在真的没有 Iterator 时生效,现代引擎上是空转。
39
+ */
40
+ const ITERATOR_SHIM =
41
+ '<script>(function(){' +
42
+ // 老 WebView 兼容层:这三类 API 缺一个,对端前端就会在启动阶段抛异常
43
+ 'try{if(typeof globalThis.Iterator!=="function"){var It=function Iterator(){throw new TypeError("Iterator is not constructible")};It.prototype={};globalThis.Iterator=It;}}catch(e){}' +
44
+ 'try{if(!Promise.withResolvers){Promise.withResolvers=function(){var res,rej;var p=new Promise(function(a,b){res=a;rej=b;});return{promise:p,resolve:res,reject:rej};};}}catch(e){}' +
45
+ 'try{if(!AbortSignal.any){AbortSignal.any=function(list){var c=new AbortController();var l=Array.prototype.slice.call(list||[]);function onAbort(){var hit=null;for(var i=0;i<l.length;i++){if(l[i]&&l[i].aborted){hit=l[i];break;}}cleanup();c.abort(hit?hit.reason:undefined);}function cleanup(){for(var i=0;i<l.length;i++){try{l[i].removeEventListener("abort",onAbort);}catch(e){}}}for(var i=0;i<l.length;i++){var sig=l[i];if(!sig)continue;if(sig.aborted){c.abort(sig.reason);return c.signal;}sig.addEventListener("abort",onAbort);}return c.signal;};}}catch(e){}' +
46
+ 'try{if(!AbortSignal.timeout){AbortSignal.timeout=function(ms){var c=new AbortController();setTimeout(function(){c.abort(new DOMException("signal timed out","TimeoutError"));},ms);return c.signal;};}}catch(e){}' +
47
+ 'try{var ap=Array.prototype;if(!ap.toSorted){ap.toSorted=function(f){return Array.prototype.slice.call(this).sort(f);};}if(!ap.toReversed){ap.toReversed=function(){return Array.prototype.slice.call(this).reverse();};}if(!ap.with){ap.with=function(i,v){var a=Array.prototype.slice.call(this);a[i<0?a.length+i:i]=v;return a;};}if(!ap.findLast){ap.findLast=function(fn,th){for(var i=this.length-1;i>=0;i--){if(fn.call(th,this[i],i,this))return this[i];}return undefined;};}}catch(e){}' +
48
+ 'try{if(!Object.groupBy){Object.groupBy=function(items,key){var out=Object.create(null);for(var it of items){var k=String(typeof key==="function"?key(it):it[key]);if(!out[k])out[k]=[];out[k].push(it);}return out;};}}catch(e){}' +
49
+ // 前端错误回传:被控端看不到控制台时,只能靠这条通道排障
50
+ 'function rep(kind,msg){try{fetch("/__clientlog",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({kind:kind,msg:String(msg).slice(0,600),url:location.href})});}catch(e){}}' +
51
+ 'addEventListener("error",function(e){rep("error",(e.message||"")+" @"+(e.filename||"")+":"+(e.lineno||0));});' +
52
+ 'addEventListener("unhandledrejection",function(e){rep("rejection",(e.reason&&(e.reason.stack||e.reason.message))||e.reason);});' +
53
+ 'var ce=console.error;console.error=function(){try{rep("console",Array.prototype.join.call(arguments," "));}catch(e){}return ce.apply(console,arguments);};' +
54
+ '})();</script>';
55
+
56
+ /** 把垫片插到 <head> 之后(越早越好:模块脚本是 defer,但内联脚本会先跑)。 */
57
+ function injectShim(html) {
58
+ const at = html.indexOf("<head>");
59
+ if (at === -1) return ITERATOR_SHIM + html;
60
+ const cut = at + "<head>".length;
61
+ return html.slice(0, cut) + ITERATOR_SHIM + html.slice(cut);
62
+ }
63
+
64
+ /** 从 Set-Cookie 头里取 name=value 对(Node 20 有 getSetCookie,旧版退化到 raw)。 */
65
+ function setCookiePairs(headers) {
66
+ const list = typeof headers.getSetCookie === "function" ? headers.getSetCookie() : (headers.raw?.()["set-cookie"] ?? []);
67
+ return list.map((line) => String(line).split(";")[0].trim()).filter((pair) => pair.includes("="));
68
+ }
69
+
70
+ /** 把服务端持有的对端 cookie 与请求自带的(我们自己的门禁 cookie 要剔除)合并。 */
71
+ function mergeCookie(serverCookie, incoming) {
72
+ const kept = String(incoming ?? "")
73
+ .split(";")
74
+ .map((part) => part.trim())
75
+ .filter((part) => part && !part.startsWith(`${GATE_COOKIE}=`));
76
+ return [serverCookie, ...kept].filter(Boolean).join("; ");
77
+ }
78
+
79
+ function hasGate(req, nonce) {
80
+ const raw = String(req.headers.cookie ?? "");
81
+ for (const part of raw.split(";")) {
82
+ const [name, ...rest] = part.trim().split("=");
83
+ if (name === GATE_COOKIE && rest.join("=") === nonce) return true;
84
+ }
85
+ try {
86
+ return new URL(req.url ?? "/", "http://127.0.0.1").searchParams.get("k") === nonce;
87
+ } catch {
88
+ return false;
89
+ }
90
+ }
91
+
92
+ /**
93
+ * 起一个指向 `remoteBase` 的回环代理。
94
+ * @param options - remoteBase(对端 http://host:port/)、token(启动 token,可空)、
95
+ * nonce、initialCookie(上次持久化下来的对端会话 cookie)、onCookie(换到新 cookie 时的落盘回调)、log、warn
96
+ * @returns {Promise<{ port: number, url: string, remote: string, hasSession: () => boolean, close: () => Promise<void> }>}
97
+ */
98
+ export async function createWebProxy({
99
+ remoteBase,
100
+ token = "",
101
+ nonce,
102
+ initialCookie = "",
103
+ onCookie = () => {},
104
+ pathPrefix = "",
105
+ passthrough = false,
106
+ log = () => {},
107
+ warn = () => {},
108
+ }) {
109
+ const remote = new URL(remoteBase);
110
+ if (remote.protocol !== "http:") throw new Error(`只支持 http 对端,收到 ${remote.protocol}`);
111
+ const authority = remote.host;
112
+ const remotePort = Number(remote.port || 80);
113
+ const hostname = remote.hostname;
114
+
115
+ // 对端 cookie 是 30 天、由对端持久密钥签名的,跨对端重启仍有效 —— 所以
116
+ // 优先复用上次存下来的,token 只在"没 cookie 或 cookie 被拒"时才需要。
117
+ const prefix = String(pathPrefix || "").replace(/\/+$/, "");
118
+ let cookie = initialCookie || "";
119
+ // cookie 在手里不等于对端认它:真收到 401 才翻成 false,供 UI 如实提示。
120
+ let healthy = true;
121
+ let minting = null;
122
+
123
+ /** 用 token 换一枚对端签名 cookie(并发调用只换一次)。 */
124
+ async function mint() {
125
+ if (!token) return false;
126
+ if (minting) return minting;
127
+ minting = (async () => {
128
+ try {
129
+ const url = new URL(remote.origin);
130
+ url.searchParams.set("token", token);
131
+ const res = await fetch(url, { redirect: "manual", signal: AbortSignal.timeout(6000) });
132
+ const pairs = setCookiePairs(res.headers);
133
+ if (pairs.length === 0) {
134
+ warn(`换 cookie 没拿到 Set-Cookie(HTTP ${res.status})`);
135
+ return false;
136
+ }
137
+ cookie = pairs.join("; ");
138
+ try {
139
+ onCookie(cookie);
140
+ } catch (error) {
141
+ warn(`保存对端 cookie 失败:${error?.message ?? error}`);
142
+ }
143
+ log(`已换到对端会话 cookie(HTTP ${res.status})`);
144
+ return true;
145
+ } catch (error) {
146
+ warn(`换 cookie 失败:${error?.message ?? error}`);
147
+ return false;
148
+ } finally {
149
+ minting = null;
150
+ }
151
+ })();
152
+ return minting;
153
+ }
154
+
155
+ /** 一次转发;不改写路径,只是把 Host/Cookie 换掉。 */
156
+ function forward(req, res, retried = false) {
157
+ const headers = { ...req.headers, host: authority };
158
+ const merged = mergeCookie(cookie, headers.cookie);
159
+ if (merged) headers.cookie = merged;
160
+ else delete headers.cookie;
161
+ // 文档要改写(插垫片),所以这一条必须拿明文;静态资源照旧走压缩。
162
+ const wantsHtml = String(headers.accept ?? "").includes("text/html");
163
+ if (wantsHtml) headers["accept-encoding"] = "identity";
164
+
165
+ const up = httpRequest(
166
+ { host: hostname, port: remotePort, method: req.method, path: `${prefix}${req.url ?? "/"}`, headers },
167
+ (reply) => {
168
+ // 401 = 我们的服务端 cookie 过期/轮换过:换一次再重试(只重试幂等方法)。
169
+ const idempotent = req.method === "GET" || req.method === "HEAD";
170
+ if (reply.statusCode === 401 && !retried && idempotent && token && !passthrough) {
171
+ reply.resume();
172
+ mint()
173
+ .then((ok) => {
174
+ if (!ok) {
175
+ res.writeHead(502, { "content-type": "text/plain; charset=utf-8" });
176
+ res.end("对端拒绝认证,且无法用 token 重新换取会话。\n");
177
+ return;
178
+ }
179
+ forward(req, res, true);
180
+ })
181
+ .catch(() => {
182
+ res.writeHead(502, { "content-type": "text/plain; charset=utf-8" });
183
+ res.end("对端认证重试失败。\n");
184
+ });
185
+ return;
186
+ }
187
+
188
+ if (reply.statusCode === 401) healthy = false;
189
+ else if ((reply.statusCode ?? 0) < 400) healthy = true;
190
+
191
+ const out = { ...reply.headers };
192
+ // 认证由服务端维护,别把对端的 Set-Cookie 泄到浏览器上(会覆盖/堆积)。
193
+ delete out["set-cookie"];
194
+ delete out["transfer-encoding"];
195
+ // 绝对 Location 指回对端时改成本代理的相对路径。
196
+ if (typeof out.location === "string" && out.location.startsWith(remote.origin)) {
197
+ const tail = out.location.slice(remote.origin.length);
198
+ out.location = tail.startsWith("/") ? tail : `/${tail}`;
199
+ }
200
+
201
+ // 文档:读完再插垫片(此时 accept-encoding 已被压成 identity,是明文)。
202
+ const type = String(reply.headers["content-type"] ?? "");
203
+ if (reply.statusCode === 200 && type.startsWith("text/html") && (req.method === "GET" || req.method === "HEAD")) {
204
+ const chunks = [];
205
+ reply.on("data", (chunk) => chunks.push(chunk));
206
+ reply.on("end", () => {
207
+ try {
208
+ const body = Buffer.from(injectShim(Buffer.concat(chunks).toString("utf8")), "utf8");
209
+ delete out["content-encoding"];
210
+ out["content-length"] = String(body.length);
211
+ res.writeHead(200, out);
212
+ res.end(req.method === "HEAD" ? undefined : body);
213
+ log(`已给文档注入兼容垫片(${body.length}B)`);
214
+ } catch (error) {
215
+ warn(`文档注入失败,按原样返回:${error?.message ?? error}`);
216
+ if (!res.headersSent) res.writeHead(200, out);
217
+ res.end(req.method === "HEAD" ? undefined : Buffer.concat(chunks));
218
+ }
219
+ });
220
+ reply.on("error", () => res.destroy());
221
+ return;
222
+ }
223
+
224
+ res.writeHead(reply.statusCode ?? 502, out);
225
+ reply.pipe(res);
226
+ },
227
+ );
228
+
229
+ up.on("error", (error) => {
230
+ warn(`转发失败:${error?.message ?? error}`);
231
+ if (res.headersSent) {
232
+ res.destroy();
233
+ return;
234
+ }
235
+ res.writeHead(502, { "content-type": "text/plain; charset=utf-8" });
236
+ res.end(`连不上对端 ${authority}:${error?.message ?? error}\n`);
237
+ });
238
+
239
+ // 请求体直接流过去;没有 body 时 end(),避免挂住。
240
+ if (req.readableEnded) up.end();
241
+ else req.pipe(up);
242
+ }
243
+
244
+ const audit = (line) => {
245
+ try {
246
+ appendFileSync(join(homedir(), "tmp/webpanel-access.log"), `${new Date().toISOString()} ${line}\n`);
247
+ } catch {
248
+ /* 日志失败不影响转发 */
249
+ }
250
+ };
251
+
252
+ const server = createServer((req, res) => {
253
+ // 前端错误回传:被控端看不到控制台,这是唯一的排障通道
254
+ if (req.url === "/__clientlog" && req.method === "POST") {
255
+ const chunks = [];
256
+ req.on("data", (c) => chunks.push(c));
257
+ req.on("end", () => {
258
+ audit(`CLIENT ${Buffer.concat(chunks).toString("utf8").slice(0, 900)}`);
259
+ res.writeHead(204);
260
+ res.end();
261
+ });
262
+ return;
263
+ }
264
+ audit(`${req.method} ${req.url} gate=${hasGate(req, nonce)}`);
265
+ if (!hasGate(req, nonce)) {
266
+ res.writeHead(403, { "content-type": "text/plain; charset=utf-8" });
267
+ res.end("这个端口只服务于 DSH 的 Web 面板,请从应用里打开。\n");
268
+ return;
269
+ }
270
+ // 首次带 ?k= 进来时种下门禁 cookie,之后(包括 SPA 的绝对路径请求)都能过。
271
+ if (req.url && req.url.includes("k=")) {
272
+ res.setHeader("set-cookie", `${GATE_COOKIE}=${nonce}; Path=/; HttpOnly; SameSite=Strict`);
273
+ }
274
+ forward(req, res);
275
+ });
276
+
277
+ /** WebSocket 升级:对端的会话流全靠它,HTTP 代理不管用。 */
278
+ server.on("upgrade", (req, socket, head) => {
279
+ audit(`UPGRADE ${req.url} gate=${hasGate(req, nonce)}`);
280
+ if (!hasGate(req, nonce)) {
281
+ socket.destroy();
282
+ return;
283
+ }
284
+ const target = netConnect(remotePort, hostname, () => {
285
+ audit(`UPGRADE-CONNECTED upstream=${hostname}:${remotePort} path=${prefix}${req.url}`);
286
+ // 前缀必须带上,否则对端的 upgrade 路由匹配不上(WS 直接握手失败)
287
+ const lines = [`${req.method} ${prefix}${req.url ?? "/"} HTTP/1.1`];
288
+ for (const [key, value] of Object.entries(req.headers)) {
289
+ if (value === undefined) continue;
290
+ const name = key.toLowerCase();
291
+ if (name === "host" || name === "cookie") continue;
292
+ for (const item of Array.isArray(value) ? value : [value]) lines.push(`${key}: ${item}`);
293
+ }
294
+ lines.push(`host: ${authority}`);
295
+ const merged = mergeCookie(cookie, req.headers.cookie);
296
+ if (merged) lines.push(`cookie: ${merged}`);
297
+ target.write(`${lines.join("\r\n")}\r\n\r\n`);
298
+ if (head && head.length) target.write(head);
299
+ target.pipe(socket);
300
+ socket.pipe(target);
301
+ });
302
+ target.on("error", (error) => {
303
+ audit(`UPGRADE-ERROR upstream=${hostname}:${remotePort} ${error?.message ?? error}`);
304
+ warn(`WebSocket 转发失败:${error?.message ?? error}`);
305
+ socket.destroy();
306
+ });
307
+ socket.on("error", () => target.destroy());
308
+ });
309
+
310
+ await new Promise((resolve, reject) => {
311
+ server.once("error", reject);
312
+ server.listen(0, "127.0.0.1", () => {
313
+ server.off("error", reject);
314
+ resolve();
315
+ });
316
+ });
317
+
318
+ // 没有可用 cookie 时才去换:让第一次点开就是已登录状态,而不是先吃一个 401。
319
+ if (!passthrough && !cookie) await mint();
320
+
321
+ const port = server.address().port;
322
+ const url = `http://127.0.0.1:${port}/?k=${encodeURIComponent(nonce)}`;
323
+ log(`代理已启动 ${url} → ${remote.origin}`);
324
+
325
+ return {
326
+ port,
327
+ url,
328
+ remote: remote.origin,
329
+ // 直通模式(对端自己负责认证)我们不持有 cookie,按"正常"处理。
330
+ hasSession: () => (passthrough ? healthy : cookie !== "" && healthy),
331
+ close: () => new Promise((resolve) => server.close(() => resolve())),
332
+ };
333
+ }
package/lib/ws-mini.js ADDED
@@ -0,0 +1,156 @@
1
+ /**
2
+ * 极简 WebSocket 服务端(只做终端需要的部分)。
3
+ *
4
+ * 为什么不引 ws 依赖:这个插件是"复制即用"的(包里没有构建步骤、没有运行时依赖
5
+ * 之外的东西),多一个依赖就多一次装包事故的机会 —— 这次 npm 误删就是这么来的。
6
+ * 终端只用文本帧 + ping/pong + close,自己实现 100 行比装一个包更可控。
7
+ */
8
+ import { createHash, randomBytes } from "node:crypto";
9
+
10
+ const GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
11
+ const MAX_FRAME = 8 * 1024 * 1024;
12
+
13
+ /** 计算握手应答的 Sec-WebSocket-Accept。 */
14
+ function acceptKey(key) {
15
+ return createHash("sha1").update(key + GUID).digest("base64");
16
+ }
17
+
18
+ /** 组一个服务端发往客户端的帧(服务端帧不掩码)。 */
19
+ export function encodeFrame(text) {
20
+ const payload = Buffer.from(text, "utf8");
21
+ const len = payload.length;
22
+ let head;
23
+ if (len < 126) head = Buffer.from([0x81, len]);
24
+ else if (len < 65536) {
25
+ head = Buffer.alloc(4);
26
+ head[0] = 0x81;
27
+ head[1] = 126;
28
+ head.writeUInt16BE(len, 2);
29
+ } else {
30
+ head = Buffer.alloc(10);
31
+ head[0] = 0x81;
32
+ head[1] = 127;
33
+ head.writeBigUInt64BE(BigInt(len), 2);
34
+ }
35
+ return Buffer.concat([head, payload]);
36
+ }
37
+
38
+ /**
39
+ * 接受一次 WebSocket 升级,并返回收发原语。
40
+ * @param req - HTTP upgrade 请求
41
+ * @param socket - 已建立的 TCP 连接
42
+ * @param head - 升级时可能已读到的首段数据
43
+ * @param handlers - { onMessage(text), onClose() }
44
+ * @returns {{ send: (text: string) => void, close: () => void } | undefined}
45
+ */
46
+ export function acceptUpgrade(req, socket, head, handlers = {}) {
47
+ const key = req.headers["sec-websocket-key"];
48
+ if (typeof key !== "string" || key === "") {
49
+ socket.destroy();
50
+ return undefined;
51
+ }
52
+ socket.write(
53
+ "HTTP/1.1 101 Switching Protocols\r\n" +
54
+ "Upgrade: websocket\r\n" +
55
+ "Connection: Upgrade\r\n" +
56
+ `Sec-WebSocket-Accept: ${acceptKey(key)}\r\n\r\n`,
57
+ );
58
+
59
+ let buffer = head && head.length ? Buffer.from(head) : Buffer.alloc(0);
60
+ let closed = false;
61
+
62
+ const destroy = () => {
63
+ if (closed) return;
64
+ closed = true;
65
+ try {
66
+ socket.destroy();
67
+ } catch {
68
+ /* 已经关了 */
69
+ }
70
+ handlers.onClose?.();
71
+ };
72
+
73
+ const send = (text) => {
74
+ if (closed) return;
75
+ try {
76
+ socket.write(encodeFrame(text));
77
+ } catch {
78
+ destroy();
79
+ }
80
+ };
81
+
82
+ const pong = (payload) => {
83
+ if (closed) return;
84
+ const head2 = payload.length < 126 ? Buffer.from([0x8a, payload.length]) : Buffer.from([0x8a, 126, 0, payload.length]);
85
+ try {
86
+ socket.write(Buffer.concat([head2, payload]));
87
+ } catch {
88
+ destroy();
89
+ }
90
+ };
91
+
92
+ socket.on("data", (chunk) => {
93
+ buffer = Buffer.concat([buffer, chunk]);
94
+ while (buffer.length >= 2) {
95
+ const fin = (buffer[0] & 0x80) !== 0;
96
+ const opcode = buffer[0] & 0x0f;
97
+ const masked = (buffer[1] & 0x80) !== 0;
98
+ let len = buffer[1] & 0x7f;
99
+ let offset = 2;
100
+ if (len === 126) {
101
+ if (buffer.length < 4) return;
102
+ len = buffer.readUInt16BE(2);
103
+ offset = 4;
104
+ } else if (len === 127) {
105
+ if (buffer.length < 10) return;
106
+ const big = buffer.readBigUInt64BE(2);
107
+ if (big > BigInt(MAX_FRAME)) {
108
+ destroy();
109
+ return;
110
+ }
111
+ len = Number(big);
112
+ offset = 10;
113
+ }
114
+ if (len > MAX_FRAME) {
115
+ destroy();
116
+ return;
117
+ }
118
+ const need = offset + (masked ? 4 : 0) + len;
119
+ if (buffer.length < need) return;
120
+ let mask;
121
+ if (masked) {
122
+ mask = buffer.subarray(offset, offset + 4);
123
+ offset += 4;
124
+ }
125
+ const payload = Buffer.from(buffer.subarray(offset, offset + len));
126
+ if (masked) for (let i = 0; i < payload.length; i += 1) payload[i] ^= mask[i % 4];
127
+ buffer = buffer.subarray(offset + len);
128
+ if (!fin) continue; // 终端只用单帧,分片帧直接丢弃后半段
129
+
130
+ if (opcode === 0x8) {
131
+ destroy();
132
+ return;
133
+ }
134
+ if (opcode === 0x9) {
135
+ pong(payload);
136
+ continue;
137
+ }
138
+ if (opcode === 0xa) continue;
139
+ if (opcode === 0x1) {
140
+ try {
141
+ handlers.onMessage?.(payload.toString("utf8"));
142
+ } catch {
143
+ /* 单个业务消息失败不打断通道 */
144
+ }
145
+ }
146
+ }
147
+ });
148
+
149
+ socket.on("error", destroy);
150
+ socket.on("close", () => {
151
+ closed = true;
152
+ handlers.onClose?.();
153
+ });
154
+
155
+ return { send, close: destroy, id: randomBytes(4).toString("hex") };
156
+ }
package/llms.txt CHANGED
@@ -30,6 +30,8 @@ Verify after restart: `GET http://127.0.0.1:45917/mesh/v1/health` returns JSON c
30
30
  - Auto-creates an agent session on the receiving machine when a task arrives, then routes that task to a new or reused session.
31
31
  - Reports a structured `osInfo` card entry (host) and a `systems[]` array: host first, then environments such as WSL distros on Windows (`kind: "wsl"`, Linux `platform`, distro name/version). Older peers only send `os`, and the UI falls back to parsing it; purely display data, at most 4 systems.
32
32
  - On Windows, probes runtimes inside **running** WSL distros (`wsl.exe -d <name> -e sh -lc …`) and reports them as `capabilities.wsl[]`; stopped distros are never started just to probe. Host and WSL runtimes are displayed separately.
33
+ - Home-page header exposes two compact text links (no cards): **问题反馈** opens a prefilled GitHub issue, and **检查更新** calls `GET /mesh/api/update`. The update route asks the npm registry (`registry.npmjs.org`, falling back to `registry.npmmirror.com`, 5 s per source, 30 min host-side cache) and compares with the running `VERSION`. A failed check returns `{ok:false,error,failures[]}` and is shown as "检查失败" — never as "已是最新". When a newer version exists, clicking the inline "新版本 vX" copies the exact release asset command with this installation's plugin dir filled in (a restart is required for it to take effect).
34
+ - The prefilled feedback issue carries the same diagnostics text as the diagnostics section; `buildDiagnostics()` deliberately excludes secrets (pairing code, tsnet auth key). The author's email (`geekstartup@163.com`) is the fallback when GitHub is unreachable.
33
35
 
34
36
  ## Tools registered (callable by the agent)
35
37
 
@@ -85,6 +87,27 @@ the kill-switch section. Most common cause on a machine with a local proxy: the
85
87
  sidecar dials raw TCP/UDP, so an "HTTP clients only" proxy setting does not cover
86
88
  it (`register request: … context deadline exceeded`).
87
89
 
90
+ ## Remote panel and SSH terminal
91
+
92
+ Two per-peer entry points in the Mesh panel (device page and the device card on
93
+ the home board, enabled while the peer is online):
94
+
95
+ | Entry | What it does | Requires |
96
+ |---|---|---|
97
+ | **访问 Web** | Opens the peer's DSH Web GUI inside the panel | Peer runs a web profile; the URL + token come from `GET /mesh/v1/web-url` on demand |
98
+ | **SSH** | In-app interactive shell (PTY, ring buffer, resize) | sshd on the peer (default port 22) |
99
+
100
+ - Remote web has two modes: by default it opens the peer's current engine; if that
101
+ machine also runs a second engine (the desktop app with the history), set
102
+ `desktopWebPort` there and `<peer>:<port>/mesh/web/...` is forwarded to it. Auth is
103
+ completed server-side, so the launch token never appears in the URL bar.
104
+ - SSH key auto-deploy: first connection uses username + password; on success the
105
+ plugin generates an RSA key (PKCS#1 PEM — ssh2 cannot read Node's ed25519 export),
106
+ appends the public key to the peer's `authorized_keys` idempotently, then proves it
107
+ with a fresh private-key-only connection. A different username falls back to password.
108
+ - The private key and credentials live under the profile's mesh directory (mode 0600);
109
+ they are never broadcast and never included in the peer card.
110
+
88
111
  ## Configuration
89
112
 
90
113
  Override by id in the profile's `cordis.patch.yml`:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-plugin-mesh",
3
- "version": "0.5.5",
3
+ "version": "0.5.7",
4
4
  "type": "module",
5
5
  "description": "DSH Mesh:局域网自动发现同网段的 DSH 实例、显示每台机器上报的能力,并双向派发任务;可用内置的用户态 Tailscale 节点跨互联网组网。Discovers other DSH instances on the LAN, shows the capabilities each one reports, and dispatches tasks between machines in both directions, with an optional userspace Tailscale node for links across networks.",
6
6
  "license": "MIT",
@@ -66,8 +66,9 @@
66
66
  "selftest:layout": "node lib/_selftest-layout.mjs",
67
67
  "selftest:diagnostics": "node lib/_selftest-diagnostics.mjs",
68
68
  "selftest:osinfo": "node lib/_selftest-osinfo.mjs",
69
- "test": "npm run check && npm run selftest && npm run selftest:prompt && npm run selftest:pairing && 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",
70
- "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/pairing.js && node --check lib/switch.js && node --check lib/scan.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",
69
+ "selftest:update": "node lib/_selftest-update.mjs",
70
+ "test": "npm run check && npm run selftest && npm run selftest:prompt && npm run selftest:pairing && 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:update",
71
+ "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/pairing.js && node --check lib/switch.js && node --check lib/scan.js && node --check lib/update.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",
71
72
  "build:sidecar": "bash scripts/build-sidecar.sh",
72
73
  "verify:mirror": "node scripts/verify-lan-mirror.mjs",
73
74
  "release:plan": "node scripts/release-plan.mjs",
@@ -132,5 +133,8 @@
132
133
  },
133
134
  "engines": {
134
135
  "node": ">=20"
136
+ },
137
+ "dependencies": {
138
+ "ssh2": "^1.16.0"
135
139
  }
136
140
  }
@@ -23,7 +23,7 @@ import { fileURLToPath } from "node:url";
23
23
  import { dirname, join } from "node:path";
24
24
 
25
25
  const root = join(dirname(fileURLToPath(import.meta.url)), "..");
26
- const files = ["lib/index.js", "lib/discovery.js", "lib/conversation.js", "lib/identity.js"];
26
+ const files = ["lib/index.js", "lib/discovery.js", "lib/conversation.js", "lib/identity.js", "lib/update.js"];
27
27
  let problems = 0;
28
28
 
29
29
  /** 逐行计算花括号深度(粗略:不解析字符串/模板串,够用) */