dsh-plugin-mesh 0.5.12 → 0.5.14
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 +55 -9
- package/lib/_selftest-peer-web.mjs +317 -0
- package/lib/_selftest-ssh-target.mjs +106 -0
- package/lib/_selftest-web-target.mjs +218 -0
- package/lib/index.js +378 -22
- package/lib/index.js.ws.bak +4589 -0
- package/lib/peer-web.js +226 -0
- package/lib/ssh-host.js +124 -19
- package/lib/ssh-target.js +98 -0
- package/lib/tsnet/manager.js +119 -0
- package/lib/web-proxy.js +57 -6
- package/lib/web-target.js +191 -0
- package/llms.txt +27 -0
- package/package.json +7 -4
- package/sidecar/main.go +242 -1
package/client/client.js
CHANGED
|
@@ -3627,7 +3627,7 @@ window.__ModuleLoader__.load({
|
|
|
3627
3627
|
},
|
|
3628
3628
|
})
|
|
3629
3629
|
: null,
|
|
3630
|
-
// SSH 终端:与「访问 DSH Web
|
|
3630
|
+
// SSH 终端:与「访问 DSH Web」同一位置;端口默认 22,面板里可改
|
|
3631
3631
|
!isSelf && onSsh
|
|
3632
3632
|
? h(IconButton, {
|
|
3633
3633
|
icon: "terminal",
|
|
@@ -4459,6 +4459,8 @@ window.__ModuleLoader__.load({
|
|
|
4459
4459
|
const [phase, setPhase] = react.useState("form");
|
|
4460
4460
|
const [username, setUsername] = react.useState("");
|
|
4461
4461
|
const [password, setPassword] = react.useState("");
|
|
4462
|
+
// SSH 端口:默认 22,可改(对端 sshd 不一定在 22 上,比如手机侧是 8022)
|
|
4463
|
+
const [port, setPort] = react.useState("22");
|
|
4462
4464
|
const [hasKey, setHasKey] = react.useState(false);
|
|
4463
4465
|
// 密钥属于哪个用户名:换了用户名就不能再拿它去认证(否则只会得到认证失败)
|
|
4464
4466
|
const [keyUser, setKeyUser] = react.useState("");
|
|
@@ -4470,9 +4472,16 @@ window.__ModuleLoader__.load({
|
|
|
4470
4472
|
const wsRef = react.useRef(null);
|
|
4471
4473
|
const idRef = react.useRef("");
|
|
4472
4474
|
const outRef = react.useRef(null);
|
|
4475
|
+
// 自动连接的标记:同一台设备只自动试一次,失败了就停在表单上等人操作
|
|
4476
|
+
const autoRef = react.useRef("");
|
|
4477
|
+
// 上一次连接用的是密钥还是密码:失败时据此决定要不要直接把密码框摊开
|
|
4478
|
+
const usedKeyRef = react.useRef(false);
|
|
4473
4479
|
|
|
4480
|
+
// 点开面板就先连:这台设备已经记住用户名、且公钥已确认部署时,不需要再看表单。
|
|
4481
|
+
// 连不上才退回表单——错误会一起显示,并给「改用密码连接」的入口。
|
|
4474
4482
|
react.useEffect(() => {
|
|
4475
4483
|
let alive = true;
|
|
4484
|
+
autoRef.current = "";
|
|
4476
4485
|
api("/ssh/known", { machine })
|
|
4477
4486
|
.then((r) => {
|
|
4478
4487
|
if (!alive || !r || !r.ok) return;
|
|
@@ -4481,6 +4490,17 @@ window.__ModuleLoader__.load({
|
|
|
4481
4490
|
setKeyUser(r.username);
|
|
4482
4491
|
}
|
|
4483
4492
|
if (r.hasKey) setHasKey(true);
|
|
4493
|
+
// 记住上次用过的端口,下次连同一台设备不用重填
|
|
4494
|
+
if (Number(r.port) > 0) setPort(String(r.port));
|
|
4495
|
+
if (r.username && r.hasKey && autoRef.current !== machine) {
|
|
4496
|
+
autoRef.current = machine;
|
|
4497
|
+
// 用 known 里的值显式传参:此刻 setUsername/setPort 还没落地
|
|
4498
|
+
connect({
|
|
4499
|
+
username: r.username,
|
|
4500
|
+
port: Number(r.port) > 0 ? Number(r.port) : 22,
|
|
4501
|
+
useKey: true,
|
|
4502
|
+
});
|
|
4503
|
+
}
|
|
4484
4504
|
})
|
|
4485
4505
|
.catch(() => {});
|
|
4486
4506
|
return () => {
|
|
@@ -4505,7 +4525,15 @@ window.__ModuleLoader__.load({
|
|
|
4505
4525
|
|
|
4506
4526
|
react.useEffect(() => () => closeSocket(), []);
|
|
4507
4527
|
|
|
4508
|
-
const connect = () => {
|
|
4528
|
+
const connect = (next) => {
|
|
4529
|
+
// next 允许"自动连接"直接给定参数:那一刻 state 还没落地(setState 是异步的),
|
|
4530
|
+
// 靠 state 读到的还是空用户名/默认端口。
|
|
4531
|
+
const opts = next || {};
|
|
4532
|
+
const wantUser = String(opts.username ?? username).trim();
|
|
4533
|
+
const wantPort = Number(opts.port ?? port) > 0 ? Number(opts.port ?? port) : 22;
|
|
4534
|
+
const wantPassword = opts.password ?? password;
|
|
4535
|
+
const wantKey = opts.useKey ?? (keyApplies && !forcePassword);
|
|
4536
|
+
usedKeyRef.current = wantKey;
|
|
4509
4537
|
setError("");
|
|
4510
4538
|
setOutput("");
|
|
4511
4539
|
setPhase("connecting");
|
|
@@ -4525,9 +4553,9 @@ window.__ModuleLoader__.load({
|
|
|
4525
4553
|
type: "open",
|
|
4526
4554
|
machine,
|
|
4527
4555
|
host: peer.host || "",
|
|
4528
|
-
port:
|
|
4529
|
-
username:
|
|
4530
|
-
password:
|
|
4556
|
+
port: wantPort,
|
|
4557
|
+
username: wantUser,
|
|
4558
|
+
password: wantKey ? "" : wantPassword,
|
|
4531
4559
|
cols: 100,
|
|
4532
4560
|
rows: 30,
|
|
4533
4561
|
}),
|
|
@@ -4557,11 +4585,14 @@ window.__ModuleLoader__.load({
|
|
|
4557
4585
|
if (msg.type === "error") {
|
|
4558
4586
|
setError(String(msg.message || "未知错误"));
|
|
4559
4587
|
setPhase("error");
|
|
4588
|
+
// 这次是拿密钥试的,既然失败就直接把密码框展开,不用再点一次「改用密码连接」
|
|
4589
|
+
if (usedKeyRef.current) setForcePassword(true);
|
|
4560
4590
|
}
|
|
4561
4591
|
};
|
|
4562
4592
|
ws.onerror = () => {
|
|
4563
4593
|
setError("连接通道错误(WebSocket)");
|
|
4564
4594
|
setPhase("error");
|
|
4595
|
+
if (usedKeyRef.current) setForcePassword(true);
|
|
4565
4596
|
};
|
|
4566
4597
|
ws.onclose = () => {
|
|
4567
4598
|
setPhase((prev) => (prev === "error" ? prev : "closed"));
|
|
@@ -4614,13 +4645,28 @@ window.__ModuleLoader__.load({
|
|
|
4614
4645
|
h(
|
|
4615
4646
|
"div",
|
|
4616
4647
|
{ className: "mesh-ssh-note" },
|
|
4617
|
-
keyApplies
|
|
4648
|
+
keyApplies && !forcePassword
|
|
4618
4649
|
? "已部署本机公钥,直接连接即可(免密)。"
|
|
4619
|
-
: hasKey
|
|
4620
|
-
?
|
|
4621
|
-
:
|
|
4650
|
+
: forcePassword && hasKey
|
|
4651
|
+
? "密钥登录没通过;输入密码登录后会重新部署本机公钥,下次恢复免密。"
|
|
4652
|
+
: hasKey
|
|
4653
|
+
? `公钥属于 ${keyUser};当前用户名不同,请输入密码。`
|
|
4654
|
+
: "首次连接需要用户名和密码;成功后会自动把本机公钥写到对端,之后免密。",
|
|
4622
4655
|
),
|
|
4623
4656
|
h("label", { className: "mesh-ssh-field" }, h("span", null, "用户名"), h("input", { value: username, onChange: (e) => setUsername(e.target.value), autoCapitalize: "none", spellCheck: false })),
|
|
4657
|
+
h(
|
|
4658
|
+
"label",
|
|
4659
|
+
{ className: "mesh-ssh-field" },
|
|
4660
|
+
h("span", null, "端口"),
|
|
4661
|
+
h("input", {
|
|
4662
|
+
value: port,
|
|
4663
|
+
inputMode: "numeric",
|
|
4664
|
+
autoCapitalize: "none",
|
|
4665
|
+
spellCheck: false,
|
|
4666
|
+
placeholder: "22",
|
|
4667
|
+
onChange: (e) => setPort(e.target.value.replace(/[^0-9]/g, "")),
|
|
4668
|
+
}),
|
|
4669
|
+
),
|
|
4624
4670
|
keyApplies && !forcePassword
|
|
4625
4671
|
? null
|
|
4626
4672
|
: h("label", { className: "mesh-ssh-field" }, h("span", null, "密码"), h("input", { type: "password", value: password, onChange: (e) => setPassword(e.target.value) })),
|
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 「经 mesh 口转发对端 Web GUI」的自测。
|
|
3
|
+
*
|
|
4
|
+
* 断言的重点不是"能转发",而是**改写是否真的到位** —— 这条通道的全部难点都在
|
|
5
|
+
* 那三个头上:Host / Origin(对端围栏按它判同源,不改就 403)、Cookie(会话只能
|
|
6
|
+
* 由被看端自己签)。历史教训是"看着接好了、其实一用就 403",所以这里逐条验,
|
|
7
|
+
* 并且验票据被抹掉、Set-Cookie 不外泄。
|
|
8
|
+
*
|
|
9
|
+
* 全部无外网:上游与被测转发器都只监听 127.0.0.1,端口由系统分配。
|
|
10
|
+
*
|
|
11
|
+
* node lib/_selftest-peer-web.mjs
|
|
12
|
+
*/
|
|
13
|
+
import { strict as assert } from "node:assert";
|
|
14
|
+
import { createHmac } from "node:crypto";
|
|
15
|
+
import { createServer } from "node:http";
|
|
16
|
+
import { connect as netConnect } from "node:net";
|
|
17
|
+
import {
|
|
18
|
+
PEER_WEB_PREFIX,
|
|
19
|
+
PEER_WEB_TICKET_HEADER,
|
|
20
|
+
PEER_WEB_TICKET_TTL_MS,
|
|
21
|
+
createPeerWebForwarder,
|
|
22
|
+
createPeerWebTicket,
|
|
23
|
+
inspectPeerWebTicket,
|
|
24
|
+
peerWebRemainder,
|
|
25
|
+
verifyPeerWebTicket,
|
|
26
|
+
} from "./peer-web.js";
|
|
27
|
+
import { signSessionCookie } from "./desktop-auth.js";
|
|
28
|
+
import { createWebProxy } from "./web-proxy.js";
|
|
29
|
+
|
|
30
|
+
let passed = 0;
|
|
31
|
+
let failed = 0;
|
|
32
|
+
function test(name, fn) {
|
|
33
|
+
try {
|
|
34
|
+
const result = fn();
|
|
35
|
+
if (result instanceof Promise) return result.then(
|
|
36
|
+
() => { passed += 1; console.log(` ✓ ${name}`); },
|
|
37
|
+
(error) => { failed += 1; console.log(` ✗ ${name}\n ${error?.message ?? error}`); },
|
|
38
|
+
);
|
|
39
|
+
passed += 1;
|
|
40
|
+
console.log(` ✓ ${name}`);
|
|
41
|
+
} catch (error) {
|
|
42
|
+
failed += 1;
|
|
43
|
+
console.log(` ✗ ${name}\n ${error?.message ?? error}`);
|
|
44
|
+
}
|
|
45
|
+
return Promise.resolve();
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** 起一个只监听回环的服务器,返回 { port, close }。 */
|
|
49
|
+
function listen(server) {
|
|
50
|
+
return new Promise((resolvePromise) => {
|
|
51
|
+
server.listen(0, "127.0.0.1", () => {
|
|
52
|
+
resolvePromise({
|
|
53
|
+
port: server.address().port,
|
|
54
|
+
close: () => new Promise((done) => server.close(() => done())),
|
|
55
|
+
});
|
|
56
|
+
});
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const SECRET = "mesh-secret-for-test";
|
|
61
|
+
const WEB_SECRET = Buffer.from("browser-session-secret-for-test", "utf8");
|
|
62
|
+
|
|
63
|
+
console.log("── 票据 ──");
|
|
64
|
+
await test("合法票据:12 小时内有效", () => {
|
|
65
|
+
const ticket = createPeerWebTicket(SECRET, { now: 1_000_000 });
|
|
66
|
+
assert.deepEqual(inspectPeerWebTicket(SECRET, ticket, { now: 1_000_000 }), { ok: true });
|
|
67
|
+
assert.equal(verifyPeerWebTicket(SECRET, ticket, { now: 1_000_000 + PEER_WEB_TICKET_TTL_MS - 1 }), true);
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
await test("过期票据:报 expired,不报 malformed", () => {
|
|
71
|
+
const ticket = createPeerWebTicket(SECRET, { now: 1_000_000, ttlMs: 1000 });
|
|
72
|
+
// expiresAt = 1_001_000:到期那一刻就该拒绝(<= now)
|
|
73
|
+
assert.deepEqual(inspectPeerWebTicket(SECRET, ticket, { now: 1_001_000 }), { ok: false, reason: "expired" });
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
await test("换密钥签的票据:报 signature(不是过期、不是格式)", () => {
|
|
77
|
+
const ticket = createPeerWebTicket("someone-else", { now: 1_000_000 });
|
|
78
|
+
assert.deepEqual(inspectPeerWebTicket(SECRET, ticket, { now: 1_000_000 }), { ok: false, reason: "signature" });
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
await test("篡改有效期:报 signature", () => {
|
|
82
|
+
const ticket = createPeerWebTicket(SECRET, { now: 1_000_000, ttlMs: 1000 });
|
|
83
|
+
const forged = Buffer.from(String(Date.now() + 10 * PEER_WEB_TICKET_TTL_MS)).toString("base64url")
|
|
84
|
+
+ ticket.slice(ticket.lastIndexOf("."));
|
|
85
|
+
assert.deepEqual(inspectPeerWebTicket(SECRET, forged, { now: 1_000_000 }), { ok: false, reason: "signature" });
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
await test("空/畸形票据:报 malformed", () => {
|
|
89
|
+
assert.deepEqual(inspectPeerWebTicket(SECRET, ""), { ok: false, reason: "malformed" });
|
|
90
|
+
assert.deepEqual(inspectPeerWebTicket(SECRET, "nodot"), { ok: false, reason: "malformed" });
|
|
91
|
+
assert.deepEqual(inspectPeerWebTicket(SECRET, "a."), { ok: false, reason: "malformed" });
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
console.log("── 路径还原 ──");
|
|
95
|
+
await test("剥前缀 + 抹掉票据参数", () => {
|
|
96
|
+
assert.equal(peerWebRemainder(`${PEER_WEB_PREFIX}/api/state`), "/api/state");
|
|
97
|
+
assert.equal(peerWebRemainder(`${PEER_WEB_PREFIX}/api/x?a=1&t=zzz`), "/api/x?a=1");
|
|
98
|
+
assert.equal(peerWebRemainder(`${PEER_WEB_PREFIX}/plugins/p.js?t=zzz`), "/plugins/p.js");
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
await test("DSH 的 /plugins/??a,b&rev=… 逐字节保留(回归:编码坏会让模块脚本吃到 index.html)", () => {
|
|
102
|
+
const raw = `${PEER_WEB_PREFIX}/plugins/??@deepseek-ai/dsh-client-modules/client.js,@x/y/client.js&rev=cddf5581d5d5`;
|
|
103
|
+
assert.equal(
|
|
104
|
+
peerWebRemainder(raw),
|
|
105
|
+
"/plugins/??@deepseek-ai/dsh-client-modules/client.js,@x/y/client.js&rev=cddf5581d5d5",
|
|
106
|
+
);
|
|
107
|
+
assert.equal(
|
|
108
|
+
peerWebRemainder(`${raw}&t=ticket`),
|
|
109
|
+
"/plugins/??@deepseek-ai/dsh-client-modules/client.js,@x/y/client.js&rev=cddf5581d5d5",
|
|
110
|
+
);
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
await test("只摘 t 参数:&t=、?t= 都不误伤邻居参数", () => {
|
|
114
|
+
assert.equal(peerWebRemainder(`${PEER_WEB_PREFIX}/a?x=1&t=zz&y=2`), "/a?x=1&y=2");
|
|
115
|
+
assert.equal(peerWebRemainder(`${PEER_WEB_PREFIX}/a?t=zz`), "/a");
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
await test("前缀本身 → /", () => {
|
|
119
|
+
assert.equal(peerWebRemainder(PEER_WEB_PREFIX), "/");
|
|
120
|
+
assert.equal(peerWebRemainder(`${PEER_WEB_PREFIX}/`), "/");
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
await test("前缀外 → undefined", () => {
|
|
124
|
+
assert.equal(peerWebRemainder("/mesh/v1/health"), undefined);
|
|
125
|
+
assert.equal(peerWebRemainder("/mesh/peer-webx/a"), undefined);
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
console.log("── HTTP 转发 ──");
|
|
129
|
+
{
|
|
130
|
+
const seen = [];
|
|
131
|
+
const upgraded = [];
|
|
132
|
+
const upstream = createServer((req, res) => {
|
|
133
|
+
seen.push({ url: req.url, headers: req.headers });
|
|
134
|
+
res.writeHead(200, { "content-type": "application/json", "set-cookie": "upstream=forbidden-to-leak" });
|
|
135
|
+
res.end(JSON.stringify({ ok: true, url: req.url }));
|
|
136
|
+
});
|
|
137
|
+
// 上游的流式载波:只回 101,稍后关掉(这里不需要真的说 WS 帧)
|
|
138
|
+
upstream.on("upgrade", (req, socket) => {
|
|
139
|
+
upgraded.push({ url: req.url, headers: req.headers });
|
|
140
|
+
socket.write("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n");
|
|
141
|
+
setTimeout(() => socket.destroy(), 150);
|
|
142
|
+
});
|
|
143
|
+
const upstreamInfo = await listen(upstream);
|
|
144
|
+
const forwarder = createPeerWebForwarder({
|
|
145
|
+
portOf: () => upstreamInfo.port,
|
|
146
|
+
secretOf: () => WEB_SECRET,
|
|
147
|
+
});
|
|
148
|
+
const mesh = createServer((req, res) => forwarder.handle(req, res));
|
|
149
|
+
mesh.on("upgrade", (req, socket, head) => forwarder.upgrade(req, socket, head));
|
|
150
|
+
const meshInfo = await listen(mesh);
|
|
151
|
+
|
|
152
|
+
await test("转发到上游:路径正确、票据被抹掉", async () => {
|
|
153
|
+
const res = await fetch(`http://127.0.0.1:${meshInfo.port}${PEER_WEB_PREFIX}/api/state?a=1&t=secret-ticket`, {
|
|
154
|
+
headers: { [PEER_WEB_TICKET_HEADER]: "secret-ticket", "x-dsh-mesh-token": "mesh-secret" },
|
|
155
|
+
});
|
|
156
|
+
assert.equal(res.status, 200);
|
|
157
|
+
const body = await res.json();
|
|
158
|
+
assert.equal(body.url, "/api/state?a=1");
|
|
159
|
+
assert.equal(seen.length, 1);
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
await test("Host / Origin / Referer 都改写成上游自己的 authority", () => {
|
|
163
|
+
const { headers } = seen[0];
|
|
164
|
+
const authority = `127.0.0.1:${upstreamInfo.port}`;
|
|
165
|
+
assert.equal(headers.host, authority);
|
|
166
|
+
assert.equal(headers.origin, `http://${authority}`);
|
|
167
|
+
assert.equal(headers.origin, `http://${headers.host}`, "Origin 必须与 Host 同源,否则对端围栏 403");
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
await test("会话 cookie 由转发器按上游 authority 自己签", () => {
|
|
171
|
+
const { headers } = seen[0];
|
|
172
|
+
const authority = `127.0.0.1:${upstreamInfo.port}`;
|
|
173
|
+
const expected = signSessionCookie(WEB_SECRET, authority);
|
|
174
|
+
const cookie = String(headers.cookie ?? "");
|
|
175
|
+
const name = cookie.slice(0, cookie.indexOf("="));
|
|
176
|
+
// cookie 名绑定 authority;payload 里也必须写的就是上游 authority。
|
|
177
|
+
// (签名含 issuedAt,所以不能拿两次签名做字符串比较 —— 只验结构。
|
|
178
|
+
assert.equal(name, expected.name);
|
|
179
|
+
const payload = JSON.parse(Buffer.from(cookie.split(".")[1], "base64url").toString("utf8"));
|
|
180
|
+
assert.equal(payload.authority, authority);
|
|
181
|
+
assert.equal(payload.version, 1);
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
await test("票据头与 mesh 密钥头都不会带给上游", () => {
|
|
185
|
+
assert.equal(seen[0].headers[PEER_WEB_TICKET_HEADER], undefined);
|
|
186
|
+
assert.equal(seen[0].headers["x-dsh-mesh-token"], undefined);
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
await test("上游的 Set-Cookie 不会泄进隧道", async () => {
|
|
190
|
+
const res = await fetch(`http://127.0.0.1:${meshInfo.port}${PEER_WEB_PREFIX}/api/state`);
|
|
191
|
+
assert.equal(res.headers.get("set-cookie"), null);
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
await test("没有 Web 端口时如实 503,不装作转发成功", async () => {
|
|
195
|
+
const noGui = createServer((req, res) => {
|
|
196
|
+
createPeerWebForwarder({ portOf: () => 0, secretOf: () => WEB_SECRET }).handle(req, res);
|
|
197
|
+
});
|
|
198
|
+
const noGuiInfo = await listen(noGui);
|
|
199
|
+
const res = await fetch(`http://127.0.0.1:${noGuiInfo.port}${PEER_WEB_PREFIX}/`);
|
|
200
|
+
assert.equal(res.status, 503);
|
|
201
|
+
const text = await res.text();
|
|
202
|
+
assert.match(text, /Web GUI/);
|
|
203
|
+
await noGuiInfo.close();
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
console.log("── WebSocket 升级 ──");
|
|
207
|
+
await test("升级请求被搬到上游并回 101", async () => {
|
|
208
|
+
const reply = await new Promise((resolvePromise, reject) => {
|
|
209
|
+
const socket = netConnect(meshInfo.port, "127.0.0.1", () => {
|
|
210
|
+
socket.write(
|
|
211
|
+
[
|
|
212
|
+
`GET ${PEER_WEB_PREFIX}/api/remote.mux HTTP/1.1`,
|
|
213
|
+
`host: 127.0.0.1:${meshInfo.port}`,
|
|
214
|
+
"connection: Upgrade",
|
|
215
|
+
"upgrade: websocket",
|
|
216
|
+
"sec-websocket-version: 13",
|
|
217
|
+
"sec-websocket-key: dGhlIHNhbXBsZSBub25jZQ==",
|
|
218
|
+
`${PEER_WEB_TICKET_HEADER}: t`,
|
|
219
|
+
"",
|
|
220
|
+
"",
|
|
221
|
+
].join("\r\n"),
|
|
222
|
+
);
|
|
223
|
+
});
|
|
224
|
+
let buffer = "";
|
|
225
|
+
socket.setTimeout(4000);
|
|
226
|
+
socket.on("data", (chunk) => {
|
|
227
|
+
buffer += chunk.toString("utf8");
|
|
228
|
+
if (buffer.includes("\r\n")) {
|
|
229
|
+
socket.destroy();
|
|
230
|
+
resolvePromise(buffer.split("\r\n")[0]);
|
|
231
|
+
}
|
|
232
|
+
});
|
|
233
|
+
socket.on("timeout", () => { socket.destroy(); reject(new Error("升级超时")); });
|
|
234
|
+
socket.on("error", reject);
|
|
235
|
+
});
|
|
236
|
+
assert.match(reply, /101/);
|
|
237
|
+
});
|
|
238
|
+
|
|
239
|
+
await upstreamInfo.close();
|
|
240
|
+
await meshInfo.close();
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
console.log("── 端到端:本机反代 → mesh 隧道 → GUI(含同源围栏)──");
|
|
245
|
+
{
|
|
246
|
+
const SESSION = Buffer.from("e2e-browser-session-secret", "utf8");
|
|
247
|
+
const fenceSeen = [];
|
|
248
|
+
/**
|
|
249
|
+
* 按真实服务端的**验证**语义校验 cookie(而不是重新签一次做字符串比较 ——
|
|
250
|
+
* 签名里含 issuedAt,两次签名天然不同,比字符串会假失败)。
|
|
251
|
+
*/
|
|
252
|
+
const cookieValid = (cookie, host) => {
|
|
253
|
+
const eq = String(cookie).indexOf("=");
|
|
254
|
+
if (eq === -1) return false;
|
|
255
|
+
const [head, value] = [String(cookie).slice(0, eq), String(cookie).slice(eq + 1)];
|
|
256
|
+
if (head !== signSessionCookie(SESSION, host).name) return false;
|
|
257
|
+
const parts = value.split(".");
|
|
258
|
+
if (parts.length !== 3 || parts[0] !== "v1") return false;
|
|
259
|
+
if (parts[2] !== createHmac("sha256", SESSION).update(parts[1]).digest("base64url")) return false;
|
|
260
|
+
try {
|
|
261
|
+
const payload = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
|
|
262
|
+
return payload.authority === host && payload.expiresAt > Date.now();
|
|
263
|
+
} catch {
|
|
264
|
+
return false;
|
|
265
|
+
}
|
|
266
|
+
};
|
|
267
|
+
// 模拟真实 GUI 的围栏:Host 必须是回环,Origin 必须与 Host 同源,cookie 必须验得过
|
|
268
|
+
const gui = createServer((req, res) => {
|
|
269
|
+
const host = String(req.headers.host ?? "");
|
|
270
|
+
const origin = req.headers.origin;
|
|
271
|
+
const cookie = String(req.headers.cookie ?? "");
|
|
272
|
+
fenceSeen.push({ url: req.url, host, origin, cookie });
|
|
273
|
+
const originOk = origin === undefined || new URL(String(origin)).host === host;
|
|
274
|
+
if (!/^127\.0\.0\.1:\d+$/.test(host) || !originOk) { res.writeHead(403); res.end("forbidden"); return; }
|
|
275
|
+
if (!cookieValid(cookie, host)) { res.writeHead(401); res.end("unauthorized"); return; }
|
|
276
|
+
res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
|
|
277
|
+
res.end("<title>peer gui</title>");
|
|
278
|
+
});
|
|
279
|
+
const guiInfo = await listen(gui);
|
|
280
|
+
const forwarder = createPeerWebForwarder({ portOf: () => guiInfo.port, secretOf: () => SESSION });
|
|
281
|
+
const mesh = createServer((req, res) => forwarder.handle(req, res));
|
|
282
|
+
mesh.on("upgrade", (req, socket, head) => forwarder.upgrade(req, socket, head));
|
|
283
|
+
const meshInfo = await listen(mesh);
|
|
284
|
+
|
|
285
|
+
const proxy = await createWebProxy({
|
|
286
|
+
remoteBase: `http://127.0.0.1:${meshInfo.port}/`,
|
|
287
|
+
nonce: "e2e-nonce",
|
|
288
|
+
pathPrefix: PEER_WEB_PREFIX,
|
|
289
|
+
passthrough: true,
|
|
290
|
+
upstreamHeaders: { [PEER_WEB_TICKET_HEADER]: "e2e-ticket" },
|
|
291
|
+
});
|
|
292
|
+
|
|
293
|
+
await test("浏览器的 Origin(回环代理端口)不会让对端 403", async () => {
|
|
294
|
+
const res = await fetch(`${proxy.url}`);
|
|
295
|
+
assert.equal(res.status, 200);
|
|
296
|
+
assert.match(await res.text(), /peer gui/);
|
|
297
|
+
const last = fenceSeen.at(-1);
|
|
298
|
+
assert.equal(last.origin, `http://${last.host}`, "隧道必须把 Origin 改写成上游同源,否则 403");
|
|
299
|
+
assert.equal(last.url, "/", "根路径要落到上游 /");
|
|
300
|
+
});
|
|
301
|
+
|
|
302
|
+
await test("带门禁 cookie 打一个围栏接口:200(不是 403/401)", async () => {
|
|
303
|
+
const first = await fetch(`${proxy.url}`);
|
|
304
|
+
const gate = String(first.headers.get("set-cookie") ?? "").split(";")[0];
|
|
305
|
+
first.body?.cancel?.();
|
|
306
|
+
const res = await fetch(`http://127.0.0.1:${proxy.port}/api/state`, { headers: { cookie: gate } });
|
|
307
|
+
assert.equal(res.status, 200);
|
|
308
|
+
assert.equal(fenceSeen.at(-1).url, "/api/state");
|
|
309
|
+
});
|
|
310
|
+
|
|
311
|
+
await proxy.close();
|
|
312
|
+
await guiInfo.close();
|
|
313
|
+
await meshInfo.close();
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
console.log(`\n${failed === 0 ? "全部通过" : "有失败"}:${passed} 通过 / ${failed} 失败`);
|
|
317
|
+
process.exitCode = failed === 0 ? 0 : 1;
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 「这次 SSH 连哪儿」的决策自测。
|
|
3
|
+
*
|
|
4
|
+
* 这段守着一个具体事故:宿主没有 100.x 路由,用 tailnet 地址去连 22 端口
|
|
5
|
+
* 必然卡到 `timed out waiting for handshake`。所以:
|
|
6
|
+
* · 有实测可连的候选 → 直连(局域网优先,不占 sidecar 端口)
|
|
7
|
+
* · 一个都连不上但对端有 tailnet 端点 → 走本机回环 + tailnet 字节流
|
|
8
|
+
* · 两条都不成立 → 报清楚原因,不编地址
|
|
9
|
+
*
|
|
10
|
+
* node lib/_selftest-ssh-target.mjs
|
|
11
|
+
*/
|
|
12
|
+
import { strict as assert } from "node:assert";
|
|
13
|
+
import { planSshTarget, sshDirectCandidates } from "./ssh-target.js";
|
|
14
|
+
|
|
15
|
+
let passed = 0;
|
|
16
|
+
let failed = 0;
|
|
17
|
+
function test(name, fn) {
|
|
18
|
+
try {
|
|
19
|
+
fn();
|
|
20
|
+
passed += 1;
|
|
21
|
+
console.log(` ✓ ${name}`);
|
|
22
|
+
} catch (err) {
|
|
23
|
+
failed += 1;
|
|
24
|
+
console.log(` ✗ ${name}`);
|
|
25
|
+
console.log(` ${err?.message ?? err}`);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
console.log("\n── 直连优先 ──");
|
|
30
|
+
|
|
31
|
+
test("探测证明能连 → 直连,端口保留", () => {
|
|
32
|
+
const plan = planSshTarget({ reachableHost: "192.168.1.8", port: 22, tsnetHost: "100.81.214.118" });
|
|
33
|
+
assert.equal(plan.mode, "direct");
|
|
34
|
+
assert.equal(plan.host, "192.168.1.8");
|
|
35
|
+
assert.equal(plan.port, 22);
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
test("自定义端口不被吃掉", () => {
|
|
39
|
+
const plan = planSshTarget({ reachableHost: "192.168.1.8", port: 8022, tsnetHost: "100.81.214.118" });
|
|
40
|
+
assert.equal(plan.port, 8022);
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
console.log("\n── 直连不通 → 走 tailnet 字节流 ──");
|
|
44
|
+
|
|
45
|
+
test("有 tailnet 端点 → stream 到 <tailnet>:<port>", () => {
|
|
46
|
+
const plan = planSshTarget({ port: 22, tsnetHost: "100.81.214.118" });
|
|
47
|
+
assert.equal(plan.mode, "stream");
|
|
48
|
+
assert.equal(plan.address, "100.81.214.118:22");
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
test("stream 模式也带自定义端口", () => {
|
|
52
|
+
const plan = planSshTarget({ port: 8022, tsnetHost: "100.81.214.118" });
|
|
53
|
+
assert.equal(plan.address, "100.81.214.118:8022");
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
console.log("\n── 两条都不成立:报原因,不编地址 ──");
|
|
57
|
+
|
|
58
|
+
test("没有 tailnet 端点 → none,且带上候选说明", () => {
|
|
59
|
+
const plan = planSshTarget({
|
|
60
|
+
endpoints: [{ host: "192.168.1.8", transport: "lan" }],
|
|
61
|
+
port: 22,
|
|
62
|
+
requestedHost: "192.168.1.8",
|
|
63
|
+
});
|
|
64
|
+
assert.equal(plan.mode, "none");
|
|
65
|
+
assert.match(plan.note, /192\.168\.1\.8|局域网可达/);
|
|
66
|
+
assert.doesNotMatch(plan.note, /^直连|^经本机/);
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
test("端口非法时退回 22(不产生 :0)", () => {
|
|
70
|
+
const plan = planSshTarget({ port: 0, tsnetHost: "100.64.0.9" });
|
|
71
|
+
assert.equal(plan.address, "100.64.0.9:22");
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
console.log("\n── 候选顺序:局域网优先,tailnet 不进直连候选 ──");
|
|
75
|
+
|
|
76
|
+
test("私有地址排在前面,重复项去掉", () => {
|
|
77
|
+
const list = sshDirectCandidates(
|
|
78
|
+
[
|
|
79
|
+
{ host: "100.81.214.118", transport: "tsnet" },
|
|
80
|
+
{ host: "192.168.1.8", transport: "lan" },
|
|
81
|
+
{ host: "192.168.1.8", transport: "ws" },
|
|
82
|
+
{ host: "120.244.161.183", transport: "lan" },
|
|
83
|
+
],
|
|
84
|
+
"192.168.1.8",
|
|
85
|
+
);
|
|
86
|
+
assert.deepEqual(list, ["192.168.1.8", "120.244.161.183"]);
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
test("客户端给的私有地址即使不在端点表里也参与直连", () => {
|
|
90
|
+
const list = sshDirectCandidates([{ host: "100.81.214.118", transport: "tsnet" }], "10.0.0.9");
|
|
91
|
+
assert.deepEqual(list, ["10.0.0.9"]);
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
test("tailnet 地址绝不进直连候选(宿主没有路由)", () => {
|
|
95
|
+
const list = sshDirectCandidates(
|
|
96
|
+
[
|
|
97
|
+
{ host: "100.81.214.118", transport: "tsnet" },
|
|
98
|
+
{ host: "100.74.219.116", transport: "tsnet" },
|
|
99
|
+
],
|
|
100
|
+
"",
|
|
101
|
+
);
|
|
102
|
+
assert.deepEqual(list, []);
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
console.log(`\n${failed === 0 ? "全部通过" : "有失败"}:${passed} 通过 / ${failed} 失败\n`);
|
|
106
|
+
process.exit(failed === 0 ? 0 : 1);
|