dsh-mobile-plugin 0.5.70 → 0.5.72
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.md +2 -0
- package/docs/extension-authoring.md +14 -8
- package/lib/impl.js +29 -3
- package/lib/mobile/plugin-market.js +13 -6
- package/lib/panel/index.html +2 -2
- package/lib/remote/controller.cjs +12 -1
- package/lib/remote/crypto.cjs +24 -6
- package/lib/remote/host-control.cjs +6 -6
- package/lib/remote/host.cjs +24 -5
- package/lib/remote/local-upstream.cjs +81 -33
- package/lib/remote/local.cjs +1 -0
- package/lib/remote/router.cjs +29 -2
- package/lib/remote/routes.cjs +24 -3
- package/lib/remote/runtime.cjs +4 -4
- package/lib/remote/transport.cjs +24 -3
- package/lib/routes/control-plane.js +20 -1
- package/package.json +6 -6
|
@@ -6,7 +6,7 @@ const { createRemoteRouter } = require('./router.cjs');
|
|
|
6
6
|
const { createNetworkMonitor } = require('./network.cjs');
|
|
7
7
|
const { safeRoutes } = require('./local-headers.cjs');
|
|
8
8
|
|
|
9
|
-
function createRemoteController({ store, transport, name, tunnels }) {
|
|
9
|
+
function createRemoteController({ store, transport, name, tunnels, onBindingsChanged }) {
|
|
10
10
|
const devices = new Map();
|
|
11
11
|
let closed = false;
|
|
12
12
|
let heartbeatAt = 0;
|
|
@@ -17,12 +17,16 @@ function createRemoteController({ store, transport, name, tunnels }) {
|
|
|
17
17
|
REMOTE_REVOKED: '这台电脑已解除本机的绑定,请重新绑定。',
|
|
18
18
|
REMOTE_EXPIRED: '远程授权已到期,请重新绑定。',
|
|
19
19
|
REMOTE_AUTH: '远程电脑身份验证失败。',
|
|
20
|
+
REMOTE_VERSION: '对方插件版本不兼容,请升级到支持远程电脑的版本。',
|
|
20
21
|
REMOTE_TIMEOUT: '远程连接超时。',
|
|
21
22
|
REMOTE_CONNECT: '远程电脑暂时离线。',
|
|
22
23
|
};
|
|
23
24
|
return messages[error?.code] || '远程连接暂时不可用。';
|
|
24
25
|
}
|
|
25
26
|
|
|
27
|
+
// 绑定增减后通知装配层:有远程电脑时要用局域网候选,联动失败不能反过来让管理动作失败。
|
|
28
|
+
async function bindingsChanged() { try { await onBindingsChanged?.(); } catch { /* ignore */ } }
|
|
29
|
+
|
|
26
30
|
function routerFor(item) {
|
|
27
31
|
const router = createRemoteRouter({ binding: item.binding, transport, tunnels,
|
|
28
32
|
onError: (error) => { if (!closed && item.router === router) fault(item, error); },
|
|
@@ -170,6 +174,7 @@ function createRemoteController({ store, transport, name, tunnels }) {
|
|
|
170
174
|
const existing = devices.get(binding.id);
|
|
171
175
|
if (existing) { await stopItem(existing); devices.delete(binding.id); }
|
|
172
176
|
await store.put(binding);
|
|
177
|
+
await bindingsChanged();
|
|
173
178
|
return row(ensure(binding));
|
|
174
179
|
},
|
|
175
180
|
open,
|
|
@@ -194,6 +199,7 @@ function createRemoteController({ store, transport, name, tunnels }) {
|
|
|
194
199
|
const item = await find(id);
|
|
195
200
|
await stopItem(item); item.router.close();
|
|
196
201
|
await store.delete(item.binding.id); devices.delete(item.binding.id);
|
|
202
|
+
await bindingsChanged();
|
|
197
203
|
},
|
|
198
204
|
async setMode(id, mode) {
|
|
199
205
|
const item = await find(id);
|
|
@@ -215,6 +221,11 @@ function createRemoteController({ store, transport, name, tunnels }) {
|
|
|
215
221
|
catch (error) { fault(item, error); }
|
|
216
222
|
return row(item);
|
|
217
223
|
},
|
|
224
|
+
/** 逐线路探活:只读诊断,不改已选线路与状态。 */
|
|
225
|
+
async diagnose(id) {
|
|
226
|
+
const item = await find(id);
|
|
227
|
+
return item.router.diagnose();
|
|
228
|
+
},
|
|
218
229
|
async close() {
|
|
219
230
|
if (closed) return;
|
|
220
231
|
closed = true; network.close();
|
package/lib/remote/crypto.cjs
CHANGED
|
@@ -102,6 +102,13 @@ function secureStream(ws, pair, options = {}) {
|
|
|
102
102
|
let renewalId = 0;
|
|
103
103
|
const renewals = new Map();
|
|
104
104
|
const closeIfEnded = () => { if (readEnded && writeEnded) ws.close(); };
|
|
105
|
+
// 心跳只在真正空闲时发,长时间收不到任何入站帧就认为链路已死;定时器不拖住进程。
|
|
106
|
+
const idleMs = options.heartbeatIdleMs ?? 25_000;
|
|
107
|
+
const deadMs = options.heartbeatTimeoutMs ?? 75_000;
|
|
108
|
+
let lastOut = Date.now();
|
|
109
|
+
let lastIn = Date.now();
|
|
110
|
+
let heartbeat = null;
|
|
111
|
+
const send = (kind, data, callback) => { lastOut = Date.now(); sendFrame(ws, pair.send, kind, data, callback); };
|
|
105
112
|
const stream = new Duplex({
|
|
106
113
|
allowHalfOpen: true,
|
|
107
114
|
read() { ws.resume(); },
|
|
@@ -112,12 +119,12 @@ function secureStream(ws, pair, options = {}) {
|
|
|
112
119
|
if (offset >= chunk.length) { done(); return; }
|
|
113
120
|
const part = chunk.subarray(offset, offset + MAX_FRAME);
|
|
114
121
|
offset += part.length;
|
|
115
|
-
|
|
122
|
+
send(0, part, next);
|
|
116
123
|
};
|
|
117
124
|
next();
|
|
118
125
|
},
|
|
119
126
|
final(done) {
|
|
120
|
-
|
|
127
|
+
send(1, undefined, (err) => {
|
|
121
128
|
writeEnded = !err;
|
|
122
129
|
done(err);
|
|
123
130
|
closeIfEnded();
|
|
@@ -125,6 +132,7 @@ function secureStream(ws, pair, options = {}) {
|
|
|
125
132
|
},
|
|
126
133
|
destroy(err, done) {
|
|
127
134
|
finished = true;
|
|
135
|
+
clearInterval(heartbeat);
|
|
128
136
|
for (const pending of renewals.values()) { clearTimeout(pending.timer); pending.reject(err || error('REMOTE_CONNECT', 'Remote connection closed')); }
|
|
129
137
|
renewals.clear();
|
|
130
138
|
ws.off('message', onMessage);
|
|
@@ -136,7 +144,10 @@ function secureStream(ws, pair, options = {}) {
|
|
|
136
144
|
try {
|
|
137
145
|
if (!binary) throw error('REMOTE_AUTH', 'Expected encrypted bytes');
|
|
138
146
|
const frame = pair.receive.open(data);
|
|
139
|
-
|
|
147
|
+
lastIn = Date.now();
|
|
148
|
+
if (frame.kind === 5) {
|
|
149
|
+
// 对端心跳:只用来证明链路还活着,不参与数据与续期语义。
|
|
150
|
+
} else if (frame.kind === 0 && !readEnded) {
|
|
140
151
|
if (!stream.push(frame.data)) ws.pause();
|
|
141
152
|
} else if (frame.kind === 1 && !readEnded && frame.data.length === 0) {
|
|
142
153
|
readEnded = true;
|
|
@@ -145,7 +156,7 @@ function secureStream(ws, pair, options = {}) {
|
|
|
145
156
|
} else if (frame.kind === 2 && typeof options.onRenew === 'function') {
|
|
146
157
|
const request = JSON.parse(frame.data.toString());
|
|
147
158
|
const remainingMs = options.onRenew(request.leaseMs);
|
|
148
|
-
|
|
159
|
+
send(3, json({ id: request.id, remainingMs }));
|
|
149
160
|
} else if (frame.kind === 3 && typeof options.onRenewed === 'function') {
|
|
150
161
|
const response = JSON.parse(frame.data.toString());
|
|
151
162
|
const pending = renewals.get(response.id);
|
|
@@ -162,6 +173,13 @@ function secureStream(ws, pair, options = {}) {
|
|
|
162
173
|
} catch (err) { stream.destroy(err.code?.startsWith('REMOTE_') ? err : error('REMOTE_AUTH', 'Invalid encrypted bytes')); }
|
|
163
174
|
};
|
|
164
175
|
ws.on('message', onMessage);
|
|
176
|
+
heartbeat = setInterval(() => {
|
|
177
|
+
if (finished || stream.destroyed) return;
|
|
178
|
+
const now = Date.now();
|
|
179
|
+
if (now - lastIn > deadMs) { stream.destroy(error('REMOTE_TIMEOUT', 'Remote heartbeat timeout')); return; }
|
|
180
|
+
if (!writeEnded && now - lastOut >= idleMs) send(5);
|
|
181
|
+
}, Math.max(10, Math.min(idleMs, 5000)));
|
|
182
|
+
heartbeat.unref?.();
|
|
165
183
|
ws.on('error', () => stream.destroy(error('REMOTE_CONNECT', 'Remote connection failed')));
|
|
166
184
|
ws.on('close', () => {
|
|
167
185
|
if (!finished) stream.destroy(readEnded && writeEnded ? undefined : error('REMOTE_CONNECT', 'Remote connection closed'));
|
|
@@ -173,12 +191,12 @@ function secureStream(ws, pair, options = {}) {
|
|
|
173
191
|
const timer = setTimeout(() => { renewals.delete(id); reject(error('REMOTE_TIMEOUT', 'Lease renewal timed out')); }, 10_000);
|
|
174
192
|
timer.unref?.();
|
|
175
193
|
renewals.set(id, { resolve, reject, timer, expiresAt });
|
|
176
|
-
|
|
194
|
+
send(2, json({ id, leaseMs }), (err) => {
|
|
177
195
|
if (!err) return;
|
|
178
196
|
clearTimeout(timer); renewals.delete(id); reject(err);
|
|
179
197
|
});
|
|
180
198
|
});
|
|
181
|
-
stream.endAccess = (code) =>
|
|
199
|
+
stream.endAccess = (code) => send(4, json({ code }));
|
|
182
200
|
// 关闭可先于调用方接管,错误仍通过 close/destroyed 体现。
|
|
183
201
|
stream.on('error', () => {});
|
|
184
202
|
return stream;
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
const { relayAddressesOf } = require('../relay/core.js');
|
|
4
4
|
const { advertisedCandidates, phoneCandidates, ipv6Candidates, withManualIpv6Candidate } = require('../relay/lan-network.cjs');
|
|
5
5
|
|
|
6
|
-
function routesOf({ state, lanPortInUse }) {
|
|
6
|
+
function routesOf({ state, lanPortInUse, lanAvailable = () => state.lanEnabled, interfaces }) {
|
|
7
7
|
const routes = [];
|
|
8
8
|
const push = (url, channel) => {
|
|
9
9
|
if (typeof url !== 'string' || !url || routes.some(row => row.url === url)) return;
|
|
@@ -11,10 +11,10 @@ function routesOf({ state, lanPortInUse }) {
|
|
|
11
11
|
if (!['http:', 'https:'].includes(parsed.protocol) || parsed.username || parsed.password || parsed.search || parsed.hash) return;
|
|
12
12
|
routes.push({ url: parsed.href.replace(/\/$/, ''), channel });
|
|
13
13
|
};
|
|
14
|
-
if (
|
|
14
|
+
if (lanAvailable()) {
|
|
15
15
|
const port = lanPortInUse();
|
|
16
|
-
for (const item of phoneCandidates(advertisedCandidates(port), { manual: state.manualLanUrl })) push(item.url, 'lan');
|
|
17
|
-
for (const item of withManualIpv6Candidate(ipv6Candidates(port), state.manualIpv6Url)) push(item.url, 'ipv6');
|
|
16
|
+
for (const item of phoneCandidates(advertisedCandidates(port, interfaces), { manual: state.manualLanUrl })) push(item.url, 'lan');
|
|
17
|
+
for (const item of withManualIpv6Candidate(ipv6Candidates(port, interfaces), state.manualIpv6Url)) push(item.url, 'ipv6');
|
|
18
18
|
}
|
|
19
19
|
for (const url of relayAddressesOf(state).relayUrls) push(url, 'relay');
|
|
20
20
|
return routes;
|
|
@@ -23,9 +23,9 @@ function candidates(value) {
|
|
|
23
23
|
if (!Array.isArray(value)) return [];
|
|
24
24
|
return value.filter(item => typeof item === 'string' && item.length > 0 && item.length <= 96).slice(0, 16);
|
|
25
25
|
}
|
|
26
|
-
function createHostControl({ state, tailcat, p2p, lanPortInUse }) {
|
|
26
|
+
function createHostControl({ state, tailcat, p2p, lanPortInUse, lanAvailable }) {
|
|
27
27
|
const pending = new Map();
|
|
28
|
-
const currentRoutes = () => routesOf({ state, lanPortInUse });
|
|
28
|
+
const currentRoutes = () => routesOf({ state, lanPortInUse, lanAvailable });
|
|
29
29
|
return {
|
|
30
30
|
routesOf: currentRoutes,
|
|
31
31
|
connectionInfo: () => ({ routes: currentRoutes() }),
|
package/lib/remote/host.cjs
CHANGED
|
@@ -16,8 +16,23 @@ const HANDSHAKE_MS = 10_000;
|
|
|
16
16
|
const KEY_ID = /^[0-9a-f]{16}$/;
|
|
17
17
|
const CONTROL_OPS = new Set(['tunnels', 'tunnels.refresh']);
|
|
18
18
|
|
|
19
|
+
// 版本号是数字但不等于 1 说明对端插件协议代不同,报 REMOTE_VERSION 好让它提示升级,
|
|
20
|
+
// 不要混进普通身份认证失败。
|
|
21
|
+
function parseHandshake(data, binary) {
|
|
22
|
+
try {
|
|
23
|
+
return c.parseMessage(data, binary);
|
|
24
|
+
} catch (error) {
|
|
25
|
+
if (error?.code === 'REMOTE_AUTH' && !binary) {
|
|
26
|
+
let value;
|
|
27
|
+
try { value = JSON.parse(Buffer.from(data).toString('utf8')); } catch { value = null; }
|
|
28
|
+
if (value && typeof value.v === 'number' && value.v !== 1) throw c.error('REMOTE_VERSION', 'Unsupported remote protocol version');
|
|
29
|
+
}
|
|
30
|
+
throw error;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
19
34
|
|
|
20
|
-
function createRemoteHost({ state, credentials, routesOf, getUpstreamPort, getWebPort, getLaunchToken, getConnectionInfo, onControl, now = Date.now, log = () => {} }) {
|
|
35
|
+
function createRemoteHost({ state, credentials, routesOf, getUpstreamPort, getWebPort, getLaunchToken, getConnectionInfo, onControl, onInvite, now = Date.now, log = () => {} }) {
|
|
21
36
|
const tickets = new Map();
|
|
22
37
|
const sessions = new Set();
|
|
23
38
|
const throttle = createPairThrottle({ now });
|
|
@@ -62,6 +77,9 @@ function createRemoteHost({ state, credentials, routesOf, getUpstreamPort, getWe
|
|
|
62
77
|
|
|
63
78
|
async function mintInvite() {
|
|
64
79
|
if (closed) throw c.error('REMOTE_CONNECT', 'Remote host is closed');
|
|
80
|
+
// 先把局域网口打开,再算邀请里的线路:第一台电脑绑定前还没有绑定记录,
|
|
81
|
+
// 不在这里临时开一下,邀请里就带不上内网地址。
|
|
82
|
+
if (typeof onInvite === 'function') await onInvite(INVITE_TTL);
|
|
65
83
|
for (const [id, value] of tickets) if (value.expiresAt <= now()) tickets.delete(id);
|
|
66
84
|
const payload = { type: 'dsh-computer', version: 1, instanceId: instanceId(), name: name(), ticketId: c.random(16), ticket: c.random(), expiresAt: now() + INVITE_TTL, routes: await routes() };
|
|
67
85
|
tickets.set(payload.ticketId, payload);
|
|
@@ -100,7 +118,8 @@ function createRemoteHost({ state, credentials, routesOf, getUpstreamPort, getWe
|
|
|
100
118
|
try { body = await readJsonBody(req, c.MAX_HANDSHAKE); } finally { clearTimeout(timeout); }
|
|
101
119
|
const ticket = body && tickets.get(body.ticketId);
|
|
102
120
|
try {
|
|
103
|
-
if (!ticket || ticket.expiresAt <= now() || body.instanceId !== instanceId()
|
|
121
|
+
if (!ticket || ticket.expiresAt <= now() || body.instanceId !== instanceId()) throw c.error('REMOTE_AUTH');
|
|
122
|
+
if (body.v !== 1) throw c.error(typeof body.v === 'number' ? 'REMOTE_VERSION' : 'REMOTE_AUTH');
|
|
104
123
|
const keys = c.pairKeys(ticket.ticket, instanceId(), ticket.ticketId);
|
|
105
124
|
const request = c.openJson(keys.up, body.sealed, pairAad(ticket.ticketId, 'up'));
|
|
106
125
|
c.keyBytes(request.deviceKey);
|
|
@@ -113,9 +132,9 @@ function createRemoteHost({ state, credentials, routesOf, getUpstreamPort, getWe
|
|
|
113
132
|
const binding = { instanceId: instanceId(), name: name(), deviceId: issued.deviceId, credential: issued.credential, keyId: request.keyId, routes: await routes(), createdAt: now(), nonce: request.nonce, connectionInfo: await info() };
|
|
114
133
|
throttle.noteSuccess();
|
|
115
134
|
sendJson(res, 200, { ok: true, v: 1, sealed: c.sealJson(keys.down, binding, pairAad(ticket.ticketId, 'down')) });
|
|
116
|
-
} catch {
|
|
135
|
+
} catch (error) {
|
|
117
136
|
throttle.noteFail();
|
|
118
|
-
sendJson(res, 401, { ok: false, code: 'REMOTE_AUTH' });
|
|
137
|
+
sendJson(res, 401, { ok: false, code: error?.code === 'REMOTE_VERSION' ? 'REMOTE_VERSION' : 'REMOTE_AUTH' });
|
|
119
138
|
}
|
|
120
139
|
}
|
|
121
140
|
|
|
@@ -132,7 +151,7 @@ function createRemoteHost({ state, credentials, routesOf, getUpstreamPort, getWe
|
|
|
132
151
|
session.timer.unref?.();
|
|
133
152
|
const receive = async (data, binary) => {
|
|
134
153
|
try {
|
|
135
|
-
const message =
|
|
154
|
+
const message = parseHandshake(data, binary);
|
|
136
155
|
if (stage === 'hello') {
|
|
137
156
|
stage = 'auth';
|
|
138
157
|
if (message.type !== 'hello' || message.instanceId !== instanceId() || !KEY_ID.test(message.keyId)) throw c.error('REMOTE_AUTH');
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
//
|
|
1
|
+
// 远程网页的加密上游:共享一条 keep-alive 池复用加密流,WebSocket 单独一条;仅宿主会话存内存。
|
|
2
2
|
'use strict';
|
|
3
3
|
|
|
4
4
|
const http = require('node:http');
|
|
@@ -8,17 +8,35 @@ function createUpstream({ connect, active, live, origin, expiresAt, noticeTransf
|
|
|
8
8
|
const jar = new Map();
|
|
9
9
|
let identity = '';
|
|
10
10
|
let authenticating = null;
|
|
11
|
+
let host = null; // 当前远端的 port/token;一旦变化就作废旧池重建
|
|
12
|
+
let agent = null; // 共享 keep-alive 池,底层每条 socket 就是一条加密流
|
|
13
|
+
let pending = null; // 首次连接先建好、待交给池子复用的加密流
|
|
14
|
+
let ensuring = null;
|
|
15
|
+
|
|
16
|
+
function resetPool() {
|
|
17
|
+
if (pending) { const stream = pending; pending = null; stream.destroy(); }
|
|
18
|
+
if (agent) { const pool = agent; agent = null; pool.destroy(); }
|
|
19
|
+
}
|
|
11
20
|
|
|
12
21
|
async function connection() {
|
|
13
22
|
if (!active()) throw Object.assign(new Error('访问已结束'), { code: 'REMOTE_EXPIRED' });
|
|
14
23
|
const before = expiresAt?.();
|
|
15
24
|
const result = await connect();
|
|
16
|
-
const
|
|
17
|
-
if (!result?.stream || !Number.isInteger(
|
|
25
|
+
const next = result?.host;
|
|
26
|
+
if (!result?.stream || !Number.isInteger(next?.port) || next.port < 1 || next.port > 65535 || typeof next.token !== 'string' || !next.token) {
|
|
18
27
|
result?.stream?.destroy();
|
|
19
28
|
throw new Error('远程网页握手无效');
|
|
20
29
|
}
|
|
21
30
|
if (!active()) { result.stream.destroy(); throw Object.assign(new Error('访问已结束'), { code: 'REMOTE_EXPIRED' }); }
|
|
31
|
+
// 池子保活/复用时会调这些 net.Socket 方法;加密流没有,补空实现即可照常复用。
|
|
32
|
+
const stream = result.stream;
|
|
33
|
+
if (typeof stream.setKeepAlive !== 'function') stream.setKeepAlive = () => {};
|
|
34
|
+
if (typeof stream.setTimeout !== 'function') stream.setTimeout = () => {};
|
|
35
|
+
if (typeof stream.unref !== 'function') stream.unref = () => {};
|
|
36
|
+
if (typeof stream.ref !== 'function') stream.ref = () => {};
|
|
37
|
+
// 目标变了就不复用旧池,避免把上一台电脑的连接交给新会话。
|
|
38
|
+
if (host && (host.port !== next.port || host.token !== next.token)) resetPool();
|
|
39
|
+
host = next;
|
|
22
40
|
live.add(result.stream);
|
|
23
41
|
result.stream.once('close', () => live.delete(result.stream));
|
|
24
42
|
result.stream.on('error', () => {});
|
|
@@ -29,26 +47,53 @@ function createUpstream({ connect, active, live, origin, expiresAt, noticeTransf
|
|
|
29
47
|
return result;
|
|
30
48
|
}
|
|
31
49
|
|
|
32
|
-
function
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
50
|
+
function ensureAgent() {
|
|
51
|
+
if (agent) return agent;
|
|
52
|
+
const pool = new http.Agent({ keepAlive: true, maxSockets: 6, maxFreeSockets: 2 });
|
|
53
|
+
pool.createConnection = (_options, callback) => {
|
|
54
|
+
if (pending) { const stream = pending; pending = null; callback(null, stream); return; }
|
|
55
|
+
connection().then(({ stream }) => callback(null, stream), callback);
|
|
56
|
+
};
|
|
57
|
+
agent = pool;
|
|
58
|
+
return agent;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// 首次请求前先建一条连接探出真实 host,并把它留作池里第一条流。
|
|
62
|
+
async function ensureHost() {
|
|
63
|
+
if (host) return host;
|
|
64
|
+
if (!ensuring) {
|
|
65
|
+
ensuring = connection()
|
|
66
|
+
.then((result) => { pending = result.stream; return result.host; })
|
|
67
|
+
.finally(() => { ensuring = null; });
|
|
68
|
+
}
|
|
69
|
+
return ensuring;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function request(target, options, receive) {
|
|
73
|
+
return http.request({ hostname: '127.0.0.1', port: target.port, ...options, agent: ensureAgent() }, receive);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// WebSocket 升级要一条独占加密流,不能和普通请求共用 keep-alive 池。
|
|
77
|
+
function dedicated(conn, options, receive) {
|
|
78
|
+
const pool = new http.Agent({ keepAlive: false });
|
|
79
|
+
pool.createConnection = (_options, callback) => { callback(null, conn.stream); return conn.stream; };
|
|
80
|
+
const req = http.request({ hostname: '127.0.0.1', port: conn.host.port, ...options, agent: pool }, receive);
|
|
81
|
+
req.once('close', () => pool.destroy());
|
|
37
82
|
return req;
|
|
38
83
|
}
|
|
39
84
|
|
|
40
|
-
async function cookies(
|
|
41
|
-
const
|
|
42
|
-
|
|
43
|
-
if (
|
|
85
|
+
async function cookies() {
|
|
86
|
+
const target = await ensureHost();
|
|
87
|
+
const key = `${target.port}:${target.token}`;
|
|
88
|
+
if (identity === key && jar.size) return target;
|
|
89
|
+
if (authenticating) { await authenticating; if (identity === key && jar.size) return target; }
|
|
44
90
|
authenticating = (async () => {
|
|
45
91
|
jar.clear();
|
|
46
|
-
const upstream = await connection();
|
|
47
|
-
if (upstream.host.port !== host.port || upstream.host.token !== host.token) { upstream.stream.destroy(); throw new Error('远程网页会话已改变'); }
|
|
48
92
|
await new Promise((resolve, reject) => {
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
93
|
+
// 认证也走共享池,成功后的这条流直接留给后续页面请求复用。
|
|
94
|
+
const req = request(target, {
|
|
95
|
+
method: 'GET', path: `/?token=${encodeURIComponent(target.token)}`,
|
|
96
|
+
headers: { host: `127.0.0.1:${target.port}`, accept: 'text/html' },
|
|
52
97
|
}, (res) => {
|
|
53
98
|
rememberCookies(jar, res.headers['set-cookie']);
|
|
54
99
|
res.resume();
|
|
@@ -62,28 +107,31 @@ function createUpstream({ connect, active, live, origin, expiresAt, noticeTransf
|
|
|
62
107
|
req.end();
|
|
63
108
|
});
|
|
64
109
|
})();
|
|
65
|
-
try { await authenticating; }
|
|
110
|
+
try { await authenticating; } catch (error) {
|
|
111
|
+
// 认证失败往往意味着会话或连接已坏:整池作废,下次请求重新握手。
|
|
112
|
+
resetPool(); host = null; identity = '';
|
|
113
|
+
throw error;
|
|
114
|
+
} finally { authenticating = null; }
|
|
115
|
+
return target;
|
|
66
116
|
}
|
|
67
117
|
|
|
68
118
|
async function forward(req, res) {
|
|
69
|
-
let
|
|
70
|
-
let up;
|
|
119
|
+
let target;
|
|
71
120
|
try {
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
const outgoing = upstreamHeaders(req.headers, conn.host, jar);
|
|
121
|
+
target = await cookies();
|
|
122
|
+
if (res.destroyed || !active()) return;
|
|
123
|
+
const outgoing = upstreamHeaders(req.headers, target, jar);
|
|
76
124
|
outgoing['accept-encoding'] = 'identity';
|
|
77
|
-
up = request(
|
|
125
|
+
const up = request(target, {
|
|
78
126
|
method: req.method, path: req.url, headers: outgoing,
|
|
79
127
|
}, (remote) => {
|
|
80
128
|
rememberCookies(jar, remote.headers['set-cookie']);
|
|
81
129
|
if (remote.statusCode === 401) { jar.clear(); identity = ''; }
|
|
82
|
-
const output = responseHeaders(remote.headers, origin(),
|
|
130
|
+
const output = responseHeaders(remote.headers, origin(), target);
|
|
83
131
|
const main = req.method === 'GET' && (req.headers['sec-fetch-dest'] === 'document' || (!req.headers['sec-fetch-dest'] && String(req.headers.accept || '').includes('text/html')));
|
|
84
132
|
const html = String(remote.headers['content-type'] || '').toLowerCase().startsWith('text/html');
|
|
85
|
-
const
|
|
86
|
-
const notice = noticeTransform && main && html &&
|
|
133
|
+
const plain = !remote.headers['content-encoding'] || remote.headers['content-encoding'] === 'identity';
|
|
134
|
+
const notice = noticeTransform && main && html && plain ? noticeTransform() : null;
|
|
87
135
|
if (notice) { delete output['content-length']; delete output.etag; }
|
|
88
136
|
output['referrer-policy'] = 'no-referrer';
|
|
89
137
|
output['x-frame-options'] = 'SAMEORIGIN';
|
|
@@ -97,7 +145,7 @@ function createUpstream({ connect, active, live, origin, expiresAt, noticeTransf
|
|
|
97
145
|
req.once('aborted', () => up.destroy());
|
|
98
146
|
res.once('close', () => { if (!res.writableEnded) up.destroy(); });
|
|
99
147
|
req.pipe(up);
|
|
100
|
-
} catch (error) {
|
|
148
|
+
} catch (error) { fail(error); }
|
|
101
149
|
function fail(error) {
|
|
102
150
|
onError(error);
|
|
103
151
|
if (res.destroyed) return;
|
|
@@ -110,16 +158,16 @@ function createUpstream({ connect, active, live, origin, expiresAt, noticeTransf
|
|
|
110
158
|
async function upgrade(req, socket, head) {
|
|
111
159
|
let conn;
|
|
112
160
|
try {
|
|
161
|
+
const target = await cookies();
|
|
113
162
|
conn = await connection();
|
|
114
|
-
await cookies(conn.host);
|
|
115
163
|
if (socket.destroyed || !active()) { conn.stream.destroy(); return; }
|
|
116
|
-
const up =
|
|
164
|
+
const up = dedicated(conn, { method: req.method, path: req.url, headers: upstreamHeaders(req.headers, target, jar, true) });
|
|
117
165
|
const drop = () => { socket.destroy(); conn.stream.destroy(); };
|
|
118
166
|
up.once('error', (error) => { onError(error); drop(); });
|
|
119
167
|
up.once('response', (remote) => { remote.resume(); drop(); });
|
|
120
168
|
up.once('upgrade', (remote, stream, upstreamHead) => {
|
|
121
169
|
rememberCookies(jar, remote.headers['set-cookie']);
|
|
122
|
-
const headers = responseHeaders(remote.headers, origin(),
|
|
170
|
+
const headers = responseHeaders(remote.headers, origin(), target, true);
|
|
123
171
|
const lines = [`HTTP/1.1 ${remote.statusCode} ${remote.statusMessage || 'Switching Protocols'}`];
|
|
124
172
|
for (const [key, value] of Object.entries(headers)) {
|
|
125
173
|
for (const item of Array.isArray(value) ? value : [value]) lines.push(`${key}: ${item}`);
|
|
@@ -138,7 +186,7 @@ function createUpstream({ connect, active, live, origin, expiresAt, noticeTransf
|
|
|
138
186
|
} catch (error) { onError(error); conn?.stream.destroy(); socket.destroy(); }
|
|
139
187
|
}
|
|
140
188
|
|
|
141
|
-
return { forward, upgrade, close() { jar.clear(); identity = ''; } };
|
|
189
|
+
return { forward, upgrade, close() { jar.clear(); identity = ''; host = null; resetPool(); } };
|
|
142
190
|
}
|
|
143
191
|
|
|
144
192
|
module.exports = { createUpstream };
|
package/lib/remote/local.cjs
CHANGED
|
@@ -35,6 +35,7 @@ function createLocalGateway({ connect, expiresAt, now = Date.now, onExpire = ()
|
|
|
35
35
|
const origin = () => `http://127.0.0.1:${port}`;
|
|
36
36
|
const active = () => !closed && now() < deadline;
|
|
37
37
|
const inUse = (time = now()) => !closed && (live.size > 0 || time - lastActivity < ACTIVE_MS);
|
|
38
|
+
// 共享池里的加密流同样进 live,续期与到期销毁都统一走这里。
|
|
38
39
|
const upstream = createUpstream({ connect, active, live, origin, expiresAt: () => deadline, onError, noticeTransform: createNoticeTransform });
|
|
39
40
|
const server = http.createServer(handle);
|
|
40
41
|
server.requestTimeout = 0;
|
package/lib/remote/router.cjs
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
const { createRoutePolicy } = require('../shared/route-order.cjs');
|
|
7
7
|
const { safeRoutes } = require('./local-headers.cjs');
|
|
8
8
|
|
|
9
|
-
const PRIORITY = ['lan', '
|
|
9
|
+
const PRIORITY = ['lan', 'ipv6', 'relay', 'tunnel', 'p2p'];
|
|
10
10
|
const keyOf = (route) => `${route.channel}|${route.url}`;
|
|
11
11
|
const terminal = (error) => ['REMOTE_REVOKED', 'REMOTE_EXPIRED'].includes(error?.code);
|
|
12
12
|
|
|
@@ -195,12 +195,39 @@ function createRemoteRouter({ binding, transport, tunnels, now = Date.now, onErr
|
|
|
195
195
|
return probing;
|
|
196
196
|
}
|
|
197
197
|
|
|
198
|
+
// 逐条探活当前所有安全候选:只读探测,既不选中也不改 state,单条失败不影响其它。
|
|
199
|
+
// 不传 onConnectionInfo,避免探测顺手把地址写回绑定。
|
|
200
|
+
async function diagnose() {
|
|
201
|
+
const probeOne = async (route) => {
|
|
202
|
+
const connectTimeoutMs = Math.min(8_000, connectBudget(route));
|
|
203
|
+
const idleTimeoutMs = Math.min(8_000, idleBudget(route));
|
|
204
|
+
let timer;
|
|
205
|
+
try {
|
|
206
|
+
const ms = await timed((signal) => {
|
|
207
|
+
const probe = transport.probeRemote(binding, route, { connectTimeoutMs, idleTimeoutMs, signal });
|
|
208
|
+
const cap = new Promise((_resolve, reject) => {
|
|
209
|
+
timer = setTimeout(() => reject(Object.assign(new Error('探测超时'), { code: 'REMOTE_TIMEOUT' })), connectTimeoutMs);
|
|
210
|
+
timer.unref?.();
|
|
211
|
+
});
|
|
212
|
+
return Promise.race([probe, cap]);
|
|
213
|
+
});
|
|
214
|
+
const latencyMs = typeof ms === 'number' && Number.isFinite(ms) && ms >= 0 ? Math.round(ms) : null;
|
|
215
|
+
return { channel: route.channel, url: route.url, ok: latencyMs !== null, latencyMs, errorCode: null };
|
|
216
|
+
} catch (error) {
|
|
217
|
+
return { channel: route.channel, url: route.url, ok: false, latencyMs: null, errorCode: error?.code || 'REMOTE_CONNECT' };
|
|
218
|
+
} finally {
|
|
219
|
+
clearTimeout(timer);
|
|
220
|
+
}
|
|
221
|
+
};
|
|
222
|
+
return Promise.all([...routes].map(probeOne));
|
|
223
|
+
}
|
|
224
|
+
|
|
198
225
|
function snapshot() {
|
|
199
226
|
return { route: selected, routes: [...routes], latencyMs: selected ? policy.routeLatencyOf(selected.url) : null };
|
|
200
227
|
}
|
|
201
228
|
|
|
202
229
|
return {
|
|
203
|
-
open, probe, refresh, snapshot,
|
|
230
|
+
open, probe, refresh, snapshot, diagnose,
|
|
204
231
|
setMode(value) {
|
|
205
232
|
if (value !== 'auto' && !routes.some((route) => route.channel === value)) throw new Error('这条线路当前不可用');
|
|
206
233
|
mode = value; selected = ordered()[0] || null;
|
package/lib/remote/routes.cjs
CHANGED
|
@@ -5,11 +5,26 @@ const { sendJson, readJsonBody } = require('../shared/http-util.js');
|
|
|
5
5
|
const { trustedLocalUi, crossSiteRequest } = require('../http/routing.js');
|
|
6
6
|
const { launchShell } = require('./shell.cjs');
|
|
7
7
|
const PREFIX = '/api/relay/remote-computers';
|
|
8
|
+
// 壳拉起后先观察一小会儿:刚起来就退(缺运行库 / 无图形会话 / 闪退)就当没打开,让前端退回浏览器。
|
|
9
|
+
const SHELL_GRACE_MS = 900;
|
|
10
|
+
function shellSurvived(child, waitMs = SHELL_GRACE_MS) {
|
|
11
|
+
if (!child || typeof child.once !== 'function') return Promise.resolve(true);
|
|
12
|
+
if (child.exitCode !== null && child.exitCode !== undefined) return Promise.resolve(false);
|
|
13
|
+
return new Promise((resolve) => {
|
|
14
|
+
let settled = false;
|
|
15
|
+
const finish = (alive) => { if (settled) return; settled = true; clearTimeout(timer); child.removeListener?.('exit', onExit); resolve(alive); };
|
|
16
|
+
const onExit = () => finish(false);
|
|
17
|
+
const timer = setTimeout(() => finish(true), waitMs);
|
|
18
|
+
timer.unref?.();
|
|
19
|
+
child.once('exit', onExit);
|
|
20
|
+
});
|
|
21
|
+
}
|
|
8
22
|
const METHODS = { '': 'GET', '/invite': 'POST', '/add': 'POST', '/open': 'POST', '/open-shell': 'POST',
|
|
9
|
-
'/renew': 'POST', '/stop': 'POST', '/remove': 'POST', '/mode': 'POST', '/probe': 'POST', '/revoke': 'POST' };
|
|
23
|
+
'/renew': 'POST', '/stop': 'POST', '/remove': 'POST', '/mode': 'POST', '/probe': 'POST', '/diagnose': 'POST', '/revoke': 'POST' };
|
|
10
24
|
const PUBLIC_ERRORS = {
|
|
11
25
|
'credentials-unavailable': '宿主凭据存储暂不可用,请稍后重试',
|
|
12
26
|
REMOTE_AUTH: '远程电脑认证失败,请重新绑定', REMOTE_REVOKED: '这台电脑的授权已被撤销,请重新绑定',
|
|
27
|
+
REMOTE_VERSION: '对方插件版本不兼容,请升级到支持远程电脑的版本',
|
|
13
28
|
REMOTE_EXPIRED: '授权已到期,请重新打开', REMOTE_TIMEOUT: '连接远程电脑超时,请重试或检测线路',
|
|
14
29
|
REMOTE_CONNECT: '暂时无法连接远程电脑,请检查网络和对方是否在线',
|
|
15
30
|
SHELL_UNAVAILABLE: '本机未安装远程电脑桌面端,请改用默认方式打开',
|
|
@@ -61,17 +76,23 @@ function createRemoteRoutes({ controller, host, credentials, instanceId, now = D
|
|
|
61
76
|
shellUrl.searchParams.set('shell', '1');
|
|
62
77
|
// 记下这次拉起的桌面进程:它一退出就当窗口关掉,面板据此回到未打开。
|
|
63
78
|
const child = launch({ url: shellUrl.href, deviceName });
|
|
79
|
+
// 壳没挺过起手那一小会儿就说明本机起不来它(缺运行库、无图形会话或直接闪退):
|
|
80
|
+
// 回 shellOpened:false,让前端退回浏览器打开,而不是让用户点了像什么都没发生。
|
|
81
|
+
if (!await shellSurvived(child)) {
|
|
82
|
+
return sendJson(res, 200, { ok: true, ...result, shellOpened: false });
|
|
83
|
+
}
|
|
64
84
|
controller.watchWindow(body.id, child);
|
|
65
|
-
return sendJson(res, 200, { ok: true, ...result });
|
|
85
|
+
return sendJson(res, 200, { ok: true, ...result, shellOpened: true });
|
|
66
86
|
}
|
|
67
87
|
if (suffix === '/renew') return sendJson(res, 200, { ok: true, ...await controller.renew(body.id) });
|
|
68
88
|
if (suffix === '/stop') await controller.stop(body.id);
|
|
69
89
|
if (suffix === '/remove') await controller.remove(body.id);
|
|
70
90
|
if (suffix === '/mode') {
|
|
71
|
-
if (typeof body.mode !== 'string' || !['auto', 'lan', '
|
|
91
|
+
if (typeof body.mode !== 'string' || !['auto', 'lan', 'ipv6', 'relay', 'tunnel', 'p2p'].includes(body.mode)) throw new Error('bad-mode');
|
|
72
92
|
await controller.setMode(body.id, body.mode);
|
|
73
93
|
}
|
|
74
94
|
if (suffix === '/probe') await controller.probe(body.id);
|
|
95
|
+
if (suffix === '/diagnose') return sendJson(res, 200, { ok: true, routes: await controller.diagnose(body.id) });
|
|
75
96
|
return sendJson(res, 200, { ok: true });
|
|
76
97
|
} catch (error) {
|
|
77
98
|
const code = typeof error?.code === 'string' ? error.code : 'remote-operation-failed';
|
package/lib/remote/runtime.cjs
CHANGED
|
@@ -9,21 +9,21 @@ const { createRemoteRoutes } = require('./routes.cjs');
|
|
|
9
9
|
const { createHostControl } = require('./host-control.cjs');
|
|
10
10
|
const { createTunnelForwarder } = require('../relay/tunnel-forwarder.cjs');
|
|
11
11
|
|
|
12
|
-
function mountRemoteComputers({ ctx, state, credentials, registerRoute, lanPortInUse, tailcat, p2p, log = () => {} }) {
|
|
12
|
+
function mountRemoteComputers({ ctx, state, credentials, registerRoute, lanPortInUse, tailcat, p2p, lanAvailable, onBindingsChanged, onInvite, log = () => {} }) {
|
|
13
13
|
const store = createRemoteStore({ credentials: () => ctx.get('credentials') });
|
|
14
14
|
const forwarder = createTunnelForwarder({ upstreamPort: () => ctx.webServer.port, log });
|
|
15
|
-
const control = createHostControl({ state, tailcat, p2p, lanPortInUse });
|
|
15
|
+
const control = createHostControl({ state, tailcat, p2p, lanPortInUse, lanAvailable });
|
|
16
16
|
const host = createRemoteHost({
|
|
17
17
|
state, credentials, routesOf: control.routesOf,
|
|
18
18
|
getUpstreamPort: async () => { await forwarder.start(); return forwarder.port(); },
|
|
19
19
|
getWebPort: () => ctx.webServer.port,
|
|
20
20
|
getLaunchToken: () => ctx.get('connection')?.browserAuth?.launchToken || '',
|
|
21
21
|
getConnectionInfo: control.connectionInfo,
|
|
22
|
-
onControl: control.onControl, log,
|
|
22
|
+
onControl: control.onControl, onInvite, log,
|
|
23
23
|
});
|
|
24
24
|
const { createRemoteTunnels } = require('./tunnels.cjs');
|
|
25
25
|
const tunnels = createRemoteTunnels({ store, transport });
|
|
26
|
-
const controller = createRemoteController({ store, transport, tunnels, name: state.name || os.hostname() });
|
|
26
|
+
const controller = createRemoteController({ store, transport, tunnels, name: state.name || os.hostname(), onBindingsChanged });
|
|
27
27
|
createRemoteRoutes({ controller, host, credentials, instanceId: state.instanceId }).register(registerRoute);
|
|
28
28
|
ctx.effect(() => () => {
|
|
29
29
|
const stopping = controller.close();
|
package/lib/remote/transport.cjs
CHANGED
|
@@ -11,6 +11,21 @@ const { WebSocket } = require('ws');
|
|
|
11
11
|
const c = require('./crypto.cjs');
|
|
12
12
|
const { PAIR_PATH, TUNNEL_PATH } = require('./host.cjs');
|
|
13
13
|
|
|
14
|
+
// 版本号是数字但不等于 1 说明对端协议代不同,单独报 REMOTE_VERSION 好让用户看到「去升级」,
|
|
15
|
+
// 而不是笼统的身份验证失败。
|
|
16
|
+
function parseHandshake(data, binary) {
|
|
17
|
+
try {
|
|
18
|
+
return c.parseMessage(data, binary);
|
|
19
|
+
} catch (error) {
|
|
20
|
+
if (error?.code === 'REMOTE_AUTH' && !binary) {
|
|
21
|
+
let value;
|
|
22
|
+
try { value = JSON.parse(Buffer.from(data).toString('utf8')); } catch { value = null; }
|
|
23
|
+
if (value && typeof value.v === 'number' && value.v !== 1) throw c.error('REMOTE_VERSION', 'Unsupported remote protocol version');
|
|
24
|
+
}
|
|
25
|
+
throw error;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
14
29
|
function parseInvitation(text) {
|
|
15
30
|
let value = text;
|
|
16
31
|
try {
|
|
@@ -20,7 +35,9 @@ function parseInvitation(text) {
|
|
|
20
35
|
if (url.protocol !== 'dshcomputer:' || url.hostname !== 'v1' || (url.pathname && url.pathname !== '/')) throw new Error();
|
|
21
36
|
value = JSON.parse(Buffer.from(url.searchParams.get('data') || '', 'base64url').toString('utf8'));
|
|
22
37
|
}
|
|
23
|
-
if (!value || value.type !== 'dsh-computer' ||
|
|
38
|
+
if (!value || value.type !== 'dsh-computer' || typeof value.instanceId !== 'string' || !value.instanceId || value.instanceId.length > 128 || typeof value.name !== 'string' || typeof value.ticketId !== 'string' || !/^[A-Za-z0-9_-]{22}$/.test(value.ticketId) || !Number.isFinite(value.expiresAt) || !Array.isArray(value.routes) || value.routes.length < 1 || value.routes.length > 32) throw new Error();
|
|
39
|
+
if (typeof value.version === 'number' && value.version !== 1) throw c.error('REMOTE_VERSION', 'Unsupported computer invitation version');
|
|
40
|
+
if (value.version !== 1) throw new Error();
|
|
24
41
|
c.keyBytes(value.ticket);
|
|
25
42
|
const routes = value.routes.map((route) => {
|
|
26
43
|
c.endpoint(route, PAIR_PATH);
|
|
@@ -28,7 +45,10 @@ function parseInvitation(text) {
|
|
|
28
45
|
return { url: route.url, channel: route.channel };
|
|
29
46
|
});
|
|
30
47
|
return { type: value.type, version: 1, instanceId: value.instanceId, name: value.name.slice(0, 128), ticketId: value.ticketId, ticket: value.ticket, expiresAt: value.expiresAt, routes };
|
|
31
|
-
} catch
|
|
48
|
+
} catch (error) {
|
|
49
|
+
if (error?.code === 'REMOTE_VERSION') throw error;
|
|
50
|
+
throw c.error('REMOTE_INVITATION', 'Invalid computer invitation');
|
|
51
|
+
}
|
|
32
52
|
}
|
|
33
53
|
|
|
34
54
|
function post(route, path, instanceId, body, timeoutMs) {
|
|
@@ -70,6 +90,7 @@ async function pairComputer(textOrObject, options = {}) {
|
|
|
70
90
|
for (const route of options.routes || invite.routes) {
|
|
71
91
|
try {
|
|
72
92
|
const response = await post(route, PAIR_PATH, invite.instanceId, request, options.timeoutMs || 10_000);
|
|
93
|
+
if (typeof response.v === 'number' && response.v !== 1) throw c.error('REMOTE_VERSION', 'Unsupported remote protocol version');
|
|
73
94
|
if (response.v !== 1 || !response.ok) throw c.error('REMOTE_AUTH');
|
|
74
95
|
const binding = c.openJson(keys.down, response.sealed, aad('down'));
|
|
75
96
|
if (binding.instanceId !== invite.instanceId || binding.deviceId !== deviceId || binding.keyId !== keyId || binding.nonce !== nonce || typeof binding.credential !== 'string' || !binding.credential || !Array.isArray(binding.routes)) throw c.error('REMOTE_AUTH', 'Unexpected computer identity');
|
|
@@ -121,7 +142,7 @@ function openRemoteStream(binding, route, options = {}) {
|
|
|
121
142
|
// 收到任何一条协议消息都算「这条线还活着」,把沉默窗口从头计时。
|
|
122
143
|
arm(idleWindow);
|
|
123
144
|
try {
|
|
124
|
-
const message =
|
|
145
|
+
const message = parseHandshake(data, binary);
|
|
125
146
|
if (stage === 'welcome' && message.type === 'welcome') {
|
|
126
147
|
stage = 'challenge';
|
|
127
148
|
ws.send(JSON.stringify({ v: 1, type: 'hello', instanceId: binding.instanceId, keyId: binding.keyId, nonce: context.clientNonce }));
|