dsh-plugin-mesh 0.5.11 → 0.5.13
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.en.md +6 -5
- package/README.md +6 -4
- package/client/client.js +1 -1
- package/cordis.patch.yml +0 -6
- package/lib/_selftest-approval.mjs +22 -16
- package/lib/_selftest-peer-web.mjs +317 -0
- package/lib/approval.js +9 -7
- package/lib/discovery.js +41 -1
- package/lib/index.js +542 -19
- package/lib/index.js.ws.bak +4589 -0
- package/lib/peer-web.js +226 -0
- package/lib/web-peers.js +187 -0
- package/lib/web-proxy.js +57 -6
- package/llms.txt +29 -3
- package/package.json +5 -4
package/lib/peer-web.js
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 经 **mesh 口**把自己这台机器的 DSH Web GUI 转发给对端 —— 零证书、零新端口。
|
|
3
|
+
*
|
|
4
|
+
* 为什么需要它:DSH 的 Web GUI 默认只监听 127.0.0.1,而 DSH Desktop **连改都不让改**
|
|
5
|
+
* (`desktopWebServerHost()` 硬编码回环,LAN 意图只作用于它的 HTTPS 边缘)。于是
|
|
6
|
+
* "在另一台机器的面板里打开对端界面"这件事,靠"对端开个端口"是做不到的 —— 除非
|
|
7
|
+
* 额外起一个 web profile,或者让用户去装一张自签证书用 HTTPS 边缘。
|
|
8
|
+
*
|
|
9
|
+
* 这条通道走的是**本来就在局域网上**的 mesh 口:
|
|
10
|
+
* · 观看端:`GET http://<对端>:<mesh端口>/mesh/peer-web/<原路径>`,
|
|
11
|
+
* 带一枚 `/mesh/v1/web-url` 下发的票据(`x-dsh-peer-web` 头,或 `?t=`)。
|
|
12
|
+
* · 被看端:校验票据 → 转发到 `127.0.0.1:<本地 Web 端口>`,顺手把
|
|
13
|
+
* Host/Origin/Referer 改写成回环同源、并签好本机的会话 cookie。
|
|
14
|
+
*
|
|
15
|
+
* 票据 = `base64url(expiresAt).HMAC-SHA256(mesh 密钥, "peer-web:"+body)`,12 小时。
|
|
16
|
+
* 密钥是本机 state.json 里的 mesh 密钥;票据只在**过了鉴权**的 `/mesh/v1/web-url`
|
|
17
|
+
* 上发放(`requirePairing` 打开时就是配对过的对端)。
|
|
18
|
+
*
|
|
19
|
+
* 边界:这不是 TLS —— 局域网明文,和 mesh 通道本身同级;不可信网络请开配对码,
|
|
20
|
+
* 或者自己套 SSH/反代。转发只发生在被看端进程内部,所以它的 GUI 不必对外开端口。
|
|
21
|
+
*
|
|
22
|
+
* **鉴权策略与 mesh 口的其它路由完全一致**(不另立一套):
|
|
23
|
+
* · 一键关闭(局域网/互联网 mesh 关掉)时整条隧道跟着 503 —— 它在 mesh server
|
|
24
|
+
* 的请求处理里,和任务路由共用同一个闸门;
|
|
25
|
+
* · `requirePairing` 打开时,每个隧道请求都要带共享密钥(`x-dsh-mesh-token`,
|
|
26
|
+
* 由观看端代理附着),和派发任务同权;
|
|
27
|
+
* · 票据是额外一层:只在**鉴权之后**的 `/mesh/v1/web-url` 发放、12 小时过期,
|
|
28
|
+
* 用来把"见过地址"和"能长期用"分开;它不替代上面两道。
|
|
29
|
+
* 共享密钥与票据都**不转发给上游 GUI**(见 rewrite())。
|
|
30
|
+
*/
|
|
31
|
+
import { createHmac, timingSafeEqual } from "node:crypto";
|
|
32
|
+
import { request as httpRequest } from "node:http";
|
|
33
|
+
import { connect as netConnect } from "node:net";
|
|
34
|
+
import { signSessionCookie } from "./desktop-auth.js";
|
|
35
|
+
|
|
36
|
+
/** 隧道前缀(挂在 mesh 口上,和 Web 口上的 /mesh/web 不是一回事)。 */
|
|
37
|
+
export const PEER_WEB_PREFIX = "/mesh/peer-web";
|
|
38
|
+
/** 票据头:观看端每个请求都带;也接受 `?t=` 方便 curl 手工验证。 */
|
|
39
|
+
export const PEER_WEB_TICKET_HEADER = "x-dsh-peer-web";
|
|
40
|
+
/** 票据有效期:一次浏览会话足够长,又不至于永久。 */
|
|
41
|
+
export const PEER_WEB_TICKET_TTL_MS = 12 * 3600 * 1000;
|
|
42
|
+
|
|
43
|
+
function b64u(buffer) {
|
|
44
|
+
return Buffer.from(buffer).toString("base64url");
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* 签一枚隧道票据。
|
|
49
|
+
* @param secret - mesh 密钥(state.json 里那条)
|
|
50
|
+
* @param options.ttlMs - 有效期,默认 12 小时
|
|
51
|
+
* @param options.now - 注入时间便于测试
|
|
52
|
+
* @returns {string} `body.signature`
|
|
53
|
+
*/
|
|
54
|
+
export function createPeerWebTicket(secret, { ttlMs = PEER_WEB_TICKET_TTL_MS, now = Date.now() } = {}) {
|
|
55
|
+
const body = b64u(Buffer.from(String(now + ttlMs), "utf8"));
|
|
56
|
+
const signature = b64u(createHmac("sha256", String(secret)).update(`peer-web:${body}`).digest());
|
|
57
|
+
return `${body}.${signature}`;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* 校验一枚隧道票据。
|
|
62
|
+
*
|
|
63
|
+
* 三条独立的拒绝理由都要能分开(AGENTS.md 硬约束 1:别把探测失败当成否定事实):
|
|
64
|
+
* 格式不对 / 签名不对 / 过期 —— 前两条是"不是我们发的",最后一条是"发过但超时"。
|
|
65
|
+
* @returns {{ ok: boolean, reason?: "malformed" | "signature" | "expired" }}
|
|
66
|
+
*/
|
|
67
|
+
export function inspectPeerWebTicket(secret, ticket, { now = Date.now() } = {}) {
|
|
68
|
+
const text = String(ticket ?? "");
|
|
69
|
+
const cut = text.lastIndexOf(".");
|
|
70
|
+
if (cut <= 0 || cut === text.length - 1) return { ok: false, reason: "malformed" };
|
|
71
|
+
const body = text.slice(0, cut);
|
|
72
|
+
const signature = text.slice(cut + 1);
|
|
73
|
+
const expected = createHmac("sha256", String(secret)).update(`peer-web:${body}`).digest();
|
|
74
|
+
let given;
|
|
75
|
+
try {
|
|
76
|
+
given = Buffer.from(signature, "base64url");
|
|
77
|
+
} catch {
|
|
78
|
+
return { ok: false, reason: "malformed" };
|
|
79
|
+
}
|
|
80
|
+
if (given.byteLength !== expected.byteLength || !timingSafeEqual(given, expected)) {
|
|
81
|
+
return { ok: false, reason: "signature" };
|
|
82
|
+
}
|
|
83
|
+
const expiresAt = Number(Buffer.from(body, "base64url").toString("utf8"));
|
|
84
|
+
if (!Number.isFinite(expiresAt) || expiresAt <= now) return { ok: false, reason: "expired" };
|
|
85
|
+
return { ok: true };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** 便捷布尔版(路由里只关心能不能过)。 */
|
|
89
|
+
export function verifyPeerWebTicket(secret, ticket, options) {
|
|
90
|
+
return inspectPeerWebTicket(secret, ticket, options).ok;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* 把 `/mesh/peer-web/...` 还原成对端 Web 口上的原路径,并抹掉票据参数。
|
|
95
|
+
*
|
|
96
|
+
* ⚠️ 这里**必须按原字符串处理**,不能 `new URL()` + `searchParams` 转一圈:
|
|
97
|
+
* DSH 的插件脚本地址是 `/plugins/??a/client.js,b/client.js&rev=…` 这种
|
|
98
|
+
* 多问号 + 逗号的非常规形式,`URLSearchParams.toString()` 会把 `?` 编码成 `%3F`、
|
|
99
|
+
* `@`→`%40`、`/`→`%2F`,对端静态路由就匹配不上,兜底返回 index.html ——
|
|
100
|
+
* 浏览器拿到 HTML 当脚本解析,前端只报一句
|
|
101
|
+
* `client-modules: HTML did not preload @deepseek-ai/dsh-client-modules/client.js`。
|
|
102
|
+
* @returns {string | undefined} `undefined` 表示不在这个前缀下
|
|
103
|
+
*/
|
|
104
|
+
export function peerWebRemainder(url) {
|
|
105
|
+
const text = String(url ?? "/");
|
|
106
|
+
const at = text.indexOf("?");
|
|
107
|
+
const pathname = at === -1 ? text : text.slice(0, at);
|
|
108
|
+
if (pathname !== PEER_WEB_PREFIX && !pathname.startsWith(`${PEER_WEB_PREFIX}/`)) return undefined;
|
|
109
|
+
const rest = pathname.slice(PEER_WEB_PREFIX.length) || "/";
|
|
110
|
+
if (at === -1) return rest;
|
|
111
|
+
// 只摘掉我们自己的票据参数(`t` / `t=`),其余逐字节保留。
|
|
112
|
+
const kept = text
|
|
113
|
+
.slice(at + 1)
|
|
114
|
+
.split("&")
|
|
115
|
+
.filter((part) => part !== "t" && !part.startsWith("t="));
|
|
116
|
+
return kept.length ? `${rest}?${kept.join("&")}` : rest;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* 造一个「转发到本机 Web GUI」的处理器。
|
|
121
|
+
*
|
|
122
|
+
* 与 `desktop-web.js` 的区别只有一个:那里目标是**另一个**引擎的固定端口,
|
|
123
|
+
* 这里目标是**本进程自己的** Web 口,而且端口可能在运行期才确定(所以传函数)。
|
|
124
|
+
* 认证照旧在服务端完成:按目标 authority 签会话 cookie,浏览器侧永远不见 token。
|
|
125
|
+
*
|
|
126
|
+
* @param options.portOf - 返回本机 Web 端口(0/缺省表示没有 GUI)
|
|
127
|
+
* @param options.secretOf - 返回浏览器会话密钥(Buffer)
|
|
128
|
+
* @param options.log - 正常日志
|
|
129
|
+
* @param options.warn - 异常日志
|
|
130
|
+
* @returns {{ handle: (req, res) => void, upgrade: (req, socket, head) => void }}
|
|
131
|
+
*/
|
|
132
|
+
export function createPeerWebForwarder({ portOf, secretOf, log = () => {}, warn = () => {} }) {
|
|
133
|
+
/**
|
|
134
|
+
* 把入站请求改写成"本机浏览器直接打开对端 GUI"的样子。
|
|
135
|
+
*
|
|
136
|
+
* 三件事缺一不可:
|
|
137
|
+
* 1. Host 换回环 —— 对端围栏按 Host 判断"是不是自己的 authority";
|
|
138
|
+
* 2. Origin/Referer 同步改写 —— 围栏要求 `new URL(origin).host === host.host`,
|
|
139
|
+
* 不改就会被判跨站 403(实测:Cordis 清单接口 403、`/api/remote.mux` 升级被拒,
|
|
140
|
+
* 界面停在「重新连接中…」);
|
|
141
|
+
* 3. 自己签会话 cookie —— 浏览器那条路要走 token 才能换到 cookie。
|
|
142
|
+
*/
|
|
143
|
+
function rewrite(incoming, authority) {
|
|
144
|
+
const headers = { ...incoming, host: authority };
|
|
145
|
+
headers.origin = `http://${authority}`;
|
|
146
|
+
if (headers.referer !== undefined) headers.referer = `http://${authority}/`;
|
|
147
|
+
if (String(headers["sec-fetch-site"] ?? "") === "cross-site") headers["sec-fetch-site"] = "same-origin";
|
|
148
|
+
delete headers[PEER_WEB_TICKET_HEADER];
|
|
149
|
+
// mesh 密钥只属于 mesh 层,别带进上游 GUI 的请求/日志里。
|
|
150
|
+
delete headers["x-dsh-mesh-token"];
|
|
151
|
+
// 隧道票据不是给上游看的,Cookie 也由这里全权维护(浏览器那侧没有 token)。
|
|
152
|
+
const secret = secretOf();
|
|
153
|
+
if (secret) headers.cookie = signSessionCookie(secret, authority).header;
|
|
154
|
+
else delete headers.cookie;
|
|
155
|
+
return headers;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function handle(req, res) {
|
|
159
|
+
const port = portOf();
|
|
160
|
+
const path = peerWebRemainder(req.url ?? "/");
|
|
161
|
+
if (!port) {
|
|
162
|
+
res.writeHead(503, { "content-type": "text/plain; charset=utf-8" });
|
|
163
|
+
res.end("本端没有可用的 Web GUI(不是 web profile)。\n");
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
if (path === undefined) {
|
|
167
|
+
res.writeHead(404, { "content-type": "text/plain; charset=utf-8" });
|
|
168
|
+
res.end("not found\n");
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
const authority = `127.0.0.1:${port}`;
|
|
172
|
+
const up = httpRequest(
|
|
173
|
+
{ host: "127.0.0.1", port, method: req.method, path, headers: rewrite(req.headers, authority) },
|
|
174
|
+
(reply) => {
|
|
175
|
+
const out = { ...reply.headers };
|
|
176
|
+
// 会话由本转发维护,别把 Set-Cookie 泄到隧道外(观看端没有对应的 authority)。
|
|
177
|
+
delete out["set-cookie"];
|
|
178
|
+
delete out["transfer-encoding"];
|
|
179
|
+
res.writeHead(reply.statusCode ?? 502, out);
|
|
180
|
+
reply.pipe(res);
|
|
181
|
+
},
|
|
182
|
+
);
|
|
183
|
+
up.on("error", (error) => {
|
|
184
|
+
warn(`对端 GUI 隧道转发失败(${authority}):${error?.message ?? error}`);
|
|
185
|
+
if (res.headersSent) {
|
|
186
|
+
res.destroy();
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
res.writeHead(502, { "content-type": "text/plain; charset=utf-8" });
|
|
190
|
+
res.end("连不上本机 Web GUI。\n");
|
|
191
|
+
});
|
|
192
|
+
if (req.readableEnded) up.end();
|
|
193
|
+
else req.pipe(up);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** 流式载波(`/api/remote.mux`):HTTP 代理不管 WS,必须单独搬字节。 */
|
|
197
|
+
function upgrade(req, socket, head) {
|
|
198
|
+
const port = portOf();
|
|
199
|
+
const path = peerWebRemainder(req.url ?? "/");
|
|
200
|
+
if (!port || path === undefined) {
|
|
201
|
+
socket.destroy();
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
const authority = `127.0.0.1:${port}`;
|
|
205
|
+
const headers = rewrite(req.headers, authority);
|
|
206
|
+
const target = netConnect(port, "127.0.0.1", () => {
|
|
207
|
+
log(`对端 GUI 隧道已接通 ${path}`);
|
|
208
|
+
const lines = [`${req.method} ${path} HTTP/1.1`];
|
|
209
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
210
|
+
if (value === undefined) continue;
|
|
211
|
+
for (const item of Array.isArray(value) ? value : [value]) lines.push(`${key}: ${item}`);
|
|
212
|
+
}
|
|
213
|
+
target.write(`${lines.join("\r\n")}\r\n\r\n`);
|
|
214
|
+
if (head && head.length) target.write(head);
|
|
215
|
+
target.pipe(socket);
|
|
216
|
+
socket.pipe(target);
|
|
217
|
+
});
|
|
218
|
+
target.on("error", (error) => {
|
|
219
|
+
warn(`对端 GUI 隧道升级失败(${authority}):${error?.message ?? error}`);
|
|
220
|
+
socket.destroy();
|
|
221
|
+
});
|
|
222
|
+
socket.on("error", () => target.destroy());
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
return { handle, upgrade };
|
|
226
|
+
}
|
package/lib/web-peers.js
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 页面里的发现:汇合点名单 + WebSocket 探测 + 手填。
|
|
3
|
+
*
|
|
4
|
+
* 浏览器拿不到 group 播组,也没有能被别人连进来的端口,所以「发现」在页面里
|
|
5
|
+
* 只能反过来做:页面主动往外连。可行的手段只有三种,按代价从小到大——
|
|
6
|
+
*
|
|
7
|
+
* 1. 问汇合点(它提供本页面,也提供 `/__mesh/api/peers`):一次 HTTP 请求
|
|
8
|
+
* 2. 主动探测:对候选地址开一条 WebSocket,用 `hello` 帧问对面是谁
|
|
9
|
+
* 3. 手填:用户自己写 `192.168.1.9:45917`
|
|
10
|
+
*
|
|
11
|
+
* 每条探测都走汇合点的同源隧道(`/__mesh/tunnel?target=`),因为页面常常是
|
|
12
|
+
* https,而桌面是明文 ws —— 混合内容策略不允许页面直接连 `ws://`。
|
|
13
|
+
*
|
|
14
|
+
* 结果是**喂给 discovery**,而不是另建一份名单:这样主面板、派任务、端点冷却
|
|
15
|
+
* 全都不用改,页面里的节点和真机器长得一样。
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
/** 一条探测结果的形状,与 `discovery.note()` 期望的记录一致。 */
|
|
19
|
+
const APPS = "dsh-mesh";
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* 把汇合点的地址拼成页面能用的 ws 隧道 URL。
|
|
23
|
+
* @param {string} target - `host:port`。
|
|
24
|
+
* @param {string} hubBase - 汇合点 origin(页面自己的 origin)。
|
|
25
|
+
* @param {string} token - 隧道令牌,没有则不带。
|
|
26
|
+
* @returns {string} ws(s) URL。
|
|
27
|
+
*/
|
|
28
|
+
export function tunnelUrl(target, hubBase, token = "") {
|
|
29
|
+
const url = new URL("/__mesh/tunnel", hubBase);
|
|
30
|
+
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
|
31
|
+
url.searchParams.set("target", target);
|
|
32
|
+
if (token !== "") url.searchParams.set("t", token);
|
|
33
|
+
return url.href;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* 打开一条隧道并完成 hello 握手。
|
|
38
|
+
* @param {string} target - `host:port`。
|
|
39
|
+
* @param {object} options - `hubBase`、`token`、`timeoutMs`。
|
|
40
|
+
* @returns {Promise<object|null>} 对端自述的名片,或 null(超时/不像 DSH)。
|
|
41
|
+
*/
|
|
42
|
+
export function probePeer(target, { hubBase, token = "", timeoutMs = 900 } = {}) {
|
|
43
|
+
return new Promise((resolve) => {
|
|
44
|
+
let socket;
|
|
45
|
+
let settled = false;
|
|
46
|
+
const finish = (value) => {
|
|
47
|
+
if (settled) return;
|
|
48
|
+
settled = true;
|
|
49
|
+
clearTimeout(timer);
|
|
50
|
+
try { socket?.close(); } catch { /* 已经关了 */ }
|
|
51
|
+
resolve(value);
|
|
52
|
+
};
|
|
53
|
+
const timer = setTimeout(() => finish(null), timeoutMs);
|
|
54
|
+
try {
|
|
55
|
+
socket = new WebSocket(tunnelUrl(target, hubBase, token));
|
|
56
|
+
} catch {
|
|
57
|
+
finish(null);
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
socket.onopen = () => socket.send(JSON.stringify({ type: "hello", token: "" }));
|
|
61
|
+
socket.onmessage = (event) => {
|
|
62
|
+
let message;
|
|
63
|
+
try { message = JSON.parse(String(event.data)); } catch { return; }
|
|
64
|
+
// 隧道自己会回 `{type:"error"}`(不在私网段、端口不对、对端拒连)。
|
|
65
|
+
if (message?.type === "error") { finish(null); return; }
|
|
66
|
+
if (message?.type !== "hello") return;
|
|
67
|
+
if (message.app !== APPS || !message.id) { finish(null); return; }
|
|
68
|
+
finish(message);
|
|
69
|
+
};
|
|
70
|
+
socket.onerror = () => finish(null);
|
|
71
|
+
socket.onclose = () => finish(null);
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* 从汇合点的地址推出要扫的 /24。
|
|
77
|
+
*
|
|
78
|
+
* 页面拿不到网络拓扑,但知道自己是从哪台机器加载的——那台机器就在同一个
|
|
79
|
+
* 局域网里,所以它的 /24 就是最合理的猜测。扫不到也不影响什么:手填兜底。
|
|
80
|
+
* @param {URL} hub - 汇合点地址。
|
|
81
|
+
* @returns {string[]} 254 个候选地址。
|
|
82
|
+
*/
|
|
83
|
+
export function subnetCandidates(hub) {
|
|
84
|
+
const parts = hub.hostname.split(".").map(Number);
|
|
85
|
+
if (parts.length !== 4 || parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255)) return [];
|
|
86
|
+
const prefix = parts.slice(0, 3).join(".");
|
|
87
|
+
const self = parts[3];
|
|
88
|
+
const out = [];
|
|
89
|
+
for (let host = 1; host < 255; host += 1) {
|
|
90
|
+
if (host === self) continue;
|
|
91
|
+
out.push(`${prefix}.${host}`);
|
|
92
|
+
}
|
|
93
|
+
return out;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* 发现页面能连的桌面节点,并把它们记进 discovery。
|
|
98
|
+
*
|
|
99
|
+
* 顺序即优先级:先问汇合点(一次请求,最快),再扫网段(并发有上限,最慢),
|
|
100
|
+
* 手填的地址永远参与(用户明确说了那里有东西,不要再替他决定)。
|
|
101
|
+
* @param options.hubBase - 汇合点 origin。
|
|
102
|
+
* @param options.discovery - MeshDiscovery 实例。
|
|
103
|
+
* @param options.port - 对端 mesh 端口,默认 45917。
|
|
104
|
+
* @param options.manual - 手填的 `host:port` 列表。
|
|
105
|
+
* @param options.scan - 是否扫网段,默认 true。
|
|
106
|
+
* @param options.token - 隧道令牌。
|
|
107
|
+
* @param options.concurrency - 并发探测数,默认 30(手机端建议 10)。
|
|
108
|
+
* @param options.onProgress - 每探到一个就回调一次。
|
|
109
|
+
* @returns {Promise<{hub: number, scanned: number, manual: number, found: string[]}>}
|
|
110
|
+
*/
|
|
111
|
+
export async function discoverWebPeers({
|
|
112
|
+
hubBase,
|
|
113
|
+
discovery,
|
|
114
|
+
port = 45917,
|
|
115
|
+
manual = [],
|
|
116
|
+
scan = true,
|
|
117
|
+
token = "",
|
|
118
|
+
concurrency = 30,
|
|
119
|
+
onProgress,
|
|
120
|
+
} = {}) {
|
|
121
|
+
const hub = new URL(hubBase);
|
|
122
|
+
const found = [];
|
|
123
|
+
let fromHub = 0;
|
|
124
|
+
let scanned = 0;
|
|
125
|
+
let fromManual = 0;
|
|
126
|
+
|
|
127
|
+
/** 记一条:名片来自对端,地址是我们观察到的。 */
|
|
128
|
+
const remember = (record, host) => {
|
|
129
|
+
if (record.id === undefined) return false;
|
|
130
|
+
const changed = discovery.note(record, host, {
|
|
131
|
+
transport: "ws",
|
|
132
|
+
channel: `ws:${host}`,
|
|
133
|
+
port: Number(record.port) || port,
|
|
134
|
+
probeIntervalMs: 60_000,
|
|
135
|
+
});
|
|
136
|
+
if (changed) {
|
|
137
|
+
found.push(`${record.machine || host} (${host})`);
|
|
138
|
+
onProgress?.(record, host);
|
|
139
|
+
}
|
|
140
|
+
return changed;
|
|
141
|
+
};
|
|
142
|
+
|
|
143
|
+
// ── 1. 汇合点名单 ──────────────────────────────────────────────────────
|
|
144
|
+
try {
|
|
145
|
+
const response = await fetch(new URL("/__mesh/api/peers", hub), { cache: "no-store" });
|
|
146
|
+
if (response.ok) {
|
|
147
|
+
const body = await response.json();
|
|
148
|
+
// 汇合点列出的**桌面**节点:它们自己登记过,地址就是 registry 里那个。
|
|
149
|
+
for (const entry of body?.desktops ?? []) {
|
|
150
|
+
if (!entry?.address) continue;
|
|
151
|
+
const record = { app: APPS, id: entry.id, machine: entry.machine, port: port, transports: ["ws"] };
|
|
152
|
+
if (remember(record, String(entry.address).split(":")[0])) fromHub += 1;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
} catch {
|
|
156
|
+
// 汇合点不可达不影响后面两步
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// ── 2. 手填 ────────────────────────────────────────────────────────────
|
|
160
|
+
for (const entry of manual ?? []) {
|
|
161
|
+
const [host, rawPort] = String(entry).split(":");
|
|
162
|
+
const target = `${host}:${Number(rawPort) || port}`;
|
|
163
|
+
const card = await probePeer(target, { hubBase, token });
|
|
164
|
+
scanned += 1;
|
|
165
|
+
if (card === null) continue;
|
|
166
|
+
if (remember({ ...card, port: Number(rawPort) || port }, host)) fromManual += 1;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// ── 3. 扫网段(并发上限,探到就停) ────────────────────────────────────
|
|
170
|
+
if (scan) {
|
|
171
|
+
const candidates = subnetCandidates(hub);
|
|
172
|
+
for (let index = 0; index < candidates.length; index += concurrency) {
|
|
173
|
+
const batch = candidates.slice(index, index + concurrency);
|
|
174
|
+
const results = await Promise.all(batch.map(async (host) => {
|
|
175
|
+
const card = await probePeer(`${host}:${port}`, { hubBase, token });
|
|
176
|
+
return card === null ? null : { host, card };
|
|
177
|
+
}));
|
|
178
|
+
for (const hit of results) {
|
|
179
|
+
if (hit === null || hit === undefined) continue;
|
|
180
|
+
scanned += 1;
|
|
181
|
+
remember({ ...hit.card, port }, hit.host);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
return { hub: fromHub, scanned, manual: fromManual, found };
|
|
187
|
+
}
|
package/lib/web-proxy.js
CHANGED
|
@@ -92,7 +92,8 @@ function hasGate(req, nonce) {
|
|
|
92
92
|
/**
|
|
93
93
|
* 起一个指向 `remoteBase` 的回环代理。
|
|
94
94
|
* @param options - remoteBase(对端 http://host:port/)、token(启动 token,可空)、
|
|
95
|
-
* nonce、initialCookie(上次持久化下来的对端会话 cookie)、onCookie(换到新 cookie 时的落盘回调)、
|
|
95
|
+
* nonce、initialCookie(上次持久化下来的对端会话 cookie)、onCookie(换到新 cookie 时的落盘回调)、
|
|
96
|
+
* upstreamHeaders(每个转发请求都要附带的额外头,例如 mesh 口隧道的票据)、log、warn
|
|
96
97
|
* @returns {Promise<{ port: number, url: string, remote: string, hasSession: () => boolean, close: () => Promise<void> }>}
|
|
97
98
|
*/
|
|
98
99
|
export async function createWebProxy({
|
|
@@ -103,6 +104,7 @@ export async function createWebProxy({
|
|
|
103
104
|
onCookie = () => {},
|
|
104
105
|
pathPrefix = "",
|
|
105
106
|
passthrough = false,
|
|
107
|
+
upstreamHeaders = {},
|
|
106
108
|
log = () => {},
|
|
107
109
|
warn = () => {},
|
|
108
110
|
}) {
|
|
@@ -115,6 +117,14 @@ export async function createWebProxy({
|
|
|
115
117
|
// 对端 cookie 是 30 天、由对端持久密钥签名的,跨对端重启仍有效 —— 所以
|
|
116
118
|
// 优先复用上次存下来的,token 只在"没 cookie 或 cookie 被拒"时才需要。
|
|
117
119
|
const prefix = String(pathPrefix || "").replace(/\/+$/, "");
|
|
120
|
+
|
|
121
|
+
/** 隧道票据一类的固定头:值为空的一律不发(别把 "undefined" 写进请求)。 */
|
|
122
|
+
const extraHeaders = () =>
|
|
123
|
+
Object.fromEntries(
|
|
124
|
+
Object.entries(upstreamHeaders ?? {}).filter(
|
|
125
|
+
([name, value]) => typeof name === "string" && name && value !== undefined && value !== null && value !== "",
|
|
126
|
+
),
|
|
127
|
+
);
|
|
118
128
|
let cookie = initialCookie || "";
|
|
119
129
|
// cookie 在手里不等于对端认它:真收到 401 才翻成 false,供 UI 如实提示。
|
|
120
130
|
let healthy = true;
|
|
@@ -152,9 +162,47 @@ export async function createWebProxy({
|
|
|
152
162
|
return minting;
|
|
153
163
|
}
|
|
154
164
|
|
|
155
|
-
/**
|
|
165
|
+
/**
|
|
166
|
+
* 把「浏览器来源」改写成对端自己的源。
|
|
167
|
+
*
|
|
168
|
+
* 浏览器访问的是本机回环代理(`http://127.0.0.1:<port>`),而对端的
|
|
169
|
+
* browser-trust 围栏是拿 `Origin` 与 `Host` 比同源的
|
|
170
|
+
* (`dsh-client-connection` 的 `isTrustedApiRequest`:`new URL(origin).host === host.host`)。
|
|
171
|
+
* 只换 Host 不换 Origin,等于告诉对端"这个请求来自别的站点",会被拒成 403:
|
|
172
|
+
* · `/api/dynamicCordisRunner/*` → 403,Cordis/插件面板读不到清单;
|
|
173
|
+
* · `/api/remote.mux` 的 WebSocket 升级被拒 → 界面永远停在「重新连接中…」。
|
|
174
|
+
* 我们本来就是**替浏览器**发请求(`desktop-web.js` 对另一个引擎做的是同一件事),
|
|
175
|
+
* 所以这里照那个写法把来源也改写掉。
|
|
176
|
+
*/
|
|
177
|
+
function rewriteProvenance(headers, upstreamOrigin) {
|
|
178
|
+
headers.origin = upstreamOrigin;
|
|
179
|
+
if (headers.referer !== undefined) headers.referer = `${upstreamOrigin}/`;
|
|
180
|
+
if (String(headers["sec-fetch-site"] ?? "") === "cross-site") headers["sec-fetch-site"] = "same-origin";
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* 把门禁参数 `k` 从转发路径里摘掉。
|
|
185
|
+
*
|
|
186
|
+
* 它是**本机**回环代理的一次性令牌,对上游没有任何意义:留着等于把我们的
|
|
187
|
+
* nonce 送进对端的访问日志与 URL 解析。其余参数原样保留。
|
|
188
|
+
*/
|
|
189
|
+
function stripGate(rawUrl) {
|
|
190
|
+
const text = String(rawUrl ?? "/");
|
|
191
|
+
const at = text.indexOf("?");
|
|
192
|
+
if (at === -1) return text;
|
|
193
|
+
const query = text.slice(at + 1);
|
|
194
|
+
// 只认一个**完整**的 k 参数;其余部分逐字节保留 —— 对端的插件脚本地址是
|
|
195
|
+
// `/plugins/??a,b&rev=…` 这种多问号/逗号形式,用 URLSearchParams 重写会把它编码坏。
|
|
196
|
+
if (!/(^|&)k=/.test(query)) return text;
|
|
197
|
+
const kept = query.split("&").filter((part) => part !== "k" && !part.startsWith("k="));
|
|
198
|
+
return kept.length ? `${text.slice(0, at)}?${kept.join("&")}` : text.slice(0, at);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** 一次转发;不改写路径,只是把 Host/Cookie/来源换掉。 */
|
|
156
202
|
function forward(req, res, retried = false) {
|
|
157
|
-
|
|
203
|
+
// upstreamHeaders 每次都要带(例如 mesh 口隧道的票据);浏览器的同名头不能覆盖它。
|
|
204
|
+
const headers = { ...req.headers, ...extraHeaders(), host: authority };
|
|
205
|
+
rewriteProvenance(headers, `http://${authority}`);
|
|
158
206
|
const merged = mergeCookie(cookie, headers.cookie);
|
|
159
207
|
if (merged) headers.cookie = merged;
|
|
160
208
|
else delete headers.cookie;
|
|
@@ -163,7 +211,7 @@ export async function createWebProxy({
|
|
|
163
211
|
if (wantsHtml) headers["accept-encoding"] = "identity";
|
|
164
212
|
|
|
165
213
|
const up = httpRequest(
|
|
166
|
-
{ host: hostname, port: remotePort, method: req.method, path: `${prefix}${req.url
|
|
214
|
+
{ host: hostname, port: remotePort, method: req.method, path: `${prefix}${stripGate(req.url)}`, headers },
|
|
167
215
|
(reply) => {
|
|
168
216
|
// 401 = 我们的服务端 cookie 过期/轮换过:换一次再重试(只重试幂等方法)。
|
|
169
217
|
const idempotent = req.method === "GET" || req.method === "HEAD";
|
|
@@ -284,8 +332,11 @@ export async function createWebProxy({
|
|
|
284
332
|
const target = netConnect(remotePort, hostname, () => {
|
|
285
333
|
audit(`UPGRADE-CONNECTED upstream=${hostname}:${remotePort} path=${prefix}${req.url}`);
|
|
286
334
|
// 前缀必须带上,否则对端的 upgrade 路由匹配不上(WS 直接握手失败)
|
|
287
|
-
const lines = [`${req.method} ${prefix}${req.url
|
|
288
|
-
|
|
335
|
+
const lines = [`${req.method} ${prefix}${stripGate(req.url)} HTTP/1.1`];
|
|
336
|
+
// 升级请求同样要过对端的同源围栏:Origin 不改写就会被拒,前端一直"重新连接中"。
|
|
337
|
+
const clean = { ...req.headers, ...extraHeaders() };
|
|
338
|
+
rewriteProvenance(clean, `http://${authority}`);
|
|
339
|
+
for (const [key, value] of Object.entries(clean)) {
|
|
289
340
|
if (value === undefined) continue;
|
|
290
341
|
const name = key.toLowerCase();
|
|
291
342
|
if (name === "host" || name === "cookie") continue;
|
package/llms.txt
CHANGED
|
@@ -36,7 +36,7 @@ Verify after restart: `GET http://127.0.0.1:45917/mesh/v1/health` returns JSON c
|
|
|
36
36
|
- 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.
|
|
37
37
|
- **First-contact approval (default on).** An inbound task from a machine that is not in `state.json`'s `approvedPeers` is stored with `status: "needs-approval"` and answered with **HTTP 202** `{ok:true,pendingApproval:true}`; no agent session is created. The owner allows or denies it in the panel (`POST /mesh/api/approval` `{id,action:"allow"|"deny"}`); allowing adds the peer to `approvedPeers` and immediately runs the stored task. `POST /mesh/api/approval/revoke` `{machine}` removes trust. Replies (a task whose `thread` matches an outbound dispatch to the same machine) bypass the gate — otherwise the result would never come back. With `requirePairing` on (or the pairing switch enabled) the gate is skipped: pairing is the stronger trust gesture.
|
|
38
38
|
- `GET /mesh/api/demo` returns a read-only snapshot of this machine (platform, CPU, memory, load, uptime, a few runtimes) used by the panel's single-machine demo. It contains no secrets and changes no state.
|
|
39
|
-
- `/mesh/api/state` additionally exposes `
|
|
39
|
+
- `/mesh/api/state` additionally exposes `approvals[]` (pending first-contact tasks, only present when the debug gate below is on) and `approvedPeers[]` (`{machine,address,at}`).
|
|
40
40
|
|
|
41
41
|
## Usage patterns (agent to agent)
|
|
42
42
|
|
|
@@ -124,6 +124,33 @@ the home board, enabled while the peer is online):
|
|
|
124
124
|
- The private key and credentials live under the profile's mesh directory (mode 0600);
|
|
125
125
|
they are never broadcast and never included in the peer card.
|
|
126
126
|
|
|
127
|
+
### Viewing a peer whose GUI only listens on loopback
|
|
128
|
+
|
|
129
|
+
A DSH Web GUI usually binds `127.0.0.1` — and DSH Desktop hardcodes that
|
|
130
|
+
(`desktopWebServerHost()` ignores `networkExposure`), so a profile patch cannot
|
|
131
|
+
change it. In that case `GET /mesh/v1/web-url` also returns a `tunnel` object and
|
|
132
|
+
the panel reaches the peer through the **already-open mesh port** instead:
|
|
133
|
+
|
|
134
|
+
```
|
|
135
|
+
viewer -> <peer>:<mesh port>/mesh/peer-web/<original path> (header: x-dsh-peer-web)
|
|
136
|
+
peer -> 127.0.0.1:<its own GUI port> (Host/Origin rewritten,
|
|
137
|
+
session cookie signed here)
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
- No certificate, no extra listener, no second profile: forwarding happens inside the
|
|
141
|
+
peer process, so a loopback-only GUI (including DSH Desktop) can be viewed.
|
|
142
|
+
- The ticket is **minted by the viewed machine** (`HMAC` with its own mesh secret),
|
|
143
|
+
lives 12 hours, is never persisted, and is only handed out by the authenticated
|
|
144
|
+
`/mesh/v1/web-url`. Changing the pairing code invalidates it immediately.
|
|
145
|
+
- Security policy is the **same as every other mesh route**: the one-click LAN/internet
|
|
146
|
+
kill switch answers 503; with `requirePairing` on, every tunnel request must carry the
|
|
147
|
+
shared secret (`x-dsh-mesh-token`, attached by the viewer's proxy). Neither the ticket
|
|
148
|
+
nor that secret is forwarded to the upstream GUI.
|
|
149
|
+
- Transport is plaintext HTTP — the same level as the mesh port itself. Use a pairing
|
|
150
|
+
code (or an SSH/tunnel wrapper) on untrusted networks.
|
|
151
|
+
- Both ends must run a version that knows the tunnel: an older peer never reports one,
|
|
152
|
+
so the panel falls back to the loopback URL and fails with `ECONNREFUSED`.
|
|
153
|
+
|
|
127
154
|
## Configuration
|
|
128
155
|
|
|
129
156
|
Override by id in the profile's `cordis.patch.yml`:
|
|
@@ -152,7 +179,6 @@ Override by id in the profile's `cordis.patch.yml`:
|
|
|
152
179
|
| `pingIntervalMs` | natural | `10000` | LAN health probe period |
|
|
153
180
|
| `tsnetProbeIntervalMs` | natural | `60000` | Tailnet health probe period |
|
|
154
181
|
| `requirePairing` | boolean | `false` | **Default off: the peer API accepts unauthenticated task POSTs.** Setting it `true` here pins pairing on; otherwise the Mesh panel's pairing switch (persisted in `state.json`) decides |
|
|
155
|
-
| `requireApproval` | boolean | `true` | First task from an unknown machine is held as `needs-approval` until the owner clicks Allow. Set `false` to restore fully unattended dispatch. Ignored (no prompt) when pairing is on |
|
|
156
182
|
| `agentPreset` | string | `"standard"` | Agent preset for auto-created sessions |
|
|
157
183
|
| `permissionPreset` | string | `"workspace-write"` | Permission preset for auto-created sessions |
|
|
158
184
|
| `workspaceRoot` | string | `""` | |
|
|
@@ -190,7 +216,7 @@ Outbound dispatch tries LAN first, then each tailnet channel in order.
|
|
|
190
216
|
|
|
191
217
|
- Ports: TCP `45917` (peer HTTP), UDP `45892` (multicast group `239.255.42.99`).
|
|
192
218
|
- Discovery is intentionally public: any host on the same L2 network can see the machine and its self-reported card.
|
|
193
|
-
-
|
|
219
|
+
- A task from any machine that can reach the port wakes an agent and runs, with no prompt. The per-machine first-contact approval gate (`needs-approval` + `POST /mesh/api/approval`) is **debug-only**, not a config key: start the host with `DSH_MESH_REQUIRE_APPROVAL=1` to test it. Pairing is the supported gate.
|
|
194
220
|
- With `requirePairing: false` (the default) there is still no cryptographic authentication of the sender: the trust decision is per-machine, made by the owner, not by a shared secret. On untrusted networks turn on the pairing switch in the Mesh panel (immediate, no restart) or set `requirePairing: true`, and make both machines share one secret. The token travels in a plain HTTP header — it guards against stray devices, not against a network sniffer.
|
|
195
221
|
- The shared secret is stored in `~/.dsh/mesh/state.json` (mode 0600) alongside `machineName`, the persisted `instanceIds`, and the tsnet auth key. It is never included in the multicast card.
|
|
196
222
|
- Persistent identity is a UUID per profile; the OS machine fingerprint is used only to reclaim a reinstalled device (same name, or the old record already offline). Two live instances on one physical machine are kept separate.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-plugin-mesh",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.13",
|
|
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: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/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: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",
|
|
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",
|
|
@@ -83,7 +83,8 @@
|
|
|
83
83
|
"selftest:pairing": "node lib/_selftest-pairing.mjs",
|
|
84
84
|
"selftest:switch": "node lib/_selftest-switch.mjs",
|
|
85
85
|
"selftest:at": "node lib/_selftest-at-mention.mjs",
|
|
86
|
-
"selftest:at:host": "node --experimental-vm-modules lib/_selftest-at-mention-host.mjs"
|
|
86
|
+
"selftest:at:host": "node --experimental-vm-modules lib/_selftest-at-mention-host.mjs",
|
|
87
|
+
"selftest:peerweb": "node lib/_selftest-peer-web.mjs"
|
|
87
88
|
},
|
|
88
89
|
"publishConfig": {
|
|
89
90
|
"registry": "https://registry.npmjs.org/",
|