dsh-mobile-plugin 0.5.52 → 0.5.54
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 +12 -0
- package/dsh-mobile-credentials/lib/credentials.js +34 -2
- package/extensions/README.md +1 -2
- package/lib/client.js +32 -15
- package/lib/impl.js +5 -0
- package/lib/mobile/directory-listing.js +3 -1
- package/lib/mobile/host-bridge/endpoints.js +2 -1
- package/lib/mobile/permissions.js +1 -3
- package/lib/mobile/workspaces.js +6 -5
- package/lib/panel/index.html +10 -10
- package/lib/relay/lan-proxy.js +15 -8
- package/lib/remote/browser-notice.cjs +118 -0
- package/lib/remote/controller.cjs +230 -0
- package/lib/remote/crypto.cjs +197 -0
- package/lib/remote/host-control.cjs +59 -0
- package/lib/remote/host.cjs +226 -0
- package/lib/remote/local-headers.cjs +102 -0
- package/lib/remote/local-upstream.cjs +144 -0
- package/lib/remote/local.cjs +173 -0
- package/lib/remote/network.cjs +42 -0
- package/lib/remote/router.cjs +194 -0
- package/lib/remote/routes.cjs +84 -0
- package/lib/remote/runtime.cjs +36 -0
- package/lib/remote/shell.cjs +101 -0
- package/lib/remote/store.cjs +60 -0
- package/lib/remote/transport.cjs +184 -0
- package/lib/remote/tunnel-helper.cjs +167 -0
- package/lib/remote/tunnels.cjs +190 -0
- package/lib/routes/mobile-api.js +7 -2
- package/lib/shared/route-order.cjs +202 -0
- package/package.json +12 -6
- package/lib/mobile/perf-trace.js +0 -142
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// 桌面网络变化与系统唤醒检测,不依赖手机蜂窝网络分类。
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
const os = require('node:os');
|
|
5
|
+
|
|
6
|
+
function interfacesOf(read = os.networkInterfaces) {
|
|
7
|
+
const rows = [];
|
|
8
|
+
for (const [name, addresses] of Object.entries(read() || {})) {
|
|
9
|
+
for (const entry of addresses || []) {
|
|
10
|
+
if (entry.internal) continue;
|
|
11
|
+
rows.push([name, entry.family, entry.address, entry.netmask, entry.scopeid || 0].join('|'));
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
return rows.sort();
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function createNetworkMonitor({ onChange = () => {}, onTick = () => {}, now = Date.now, interfaces = os.networkInterfaces, intervalMs = 5000 } = {}) {
|
|
18
|
+
let previous = interfacesOf(interfaces);
|
|
19
|
+
let last = now();
|
|
20
|
+
let running = false;
|
|
21
|
+
let closed = false;
|
|
22
|
+
|
|
23
|
+
async function poll() {
|
|
24
|
+
if (closed || running) return;
|
|
25
|
+
running = true;
|
|
26
|
+
try {
|
|
27
|
+
const currentTime = now();
|
|
28
|
+
const current = interfacesOf(interfaces);
|
|
29
|
+
const changed = current.length !== previous.length || current.some((value, index) => value !== previous[index]);
|
|
30
|
+
const woke = currentTime - last > intervalMs * 3 || currentTime < last;
|
|
31
|
+
previous = current; last = currentTime;
|
|
32
|
+
if (changed || woke) void Promise.resolve(onChange({ reason: changed ? 'network' : 'wake' })).catch(() => {});
|
|
33
|
+
await onTick(currentTime);
|
|
34
|
+
} finally { running = false; }
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const timer = setInterval(() => { void poll().catch(() => {}); }, intervalMs);
|
|
38
|
+
timer.unref?.();
|
|
39
|
+
return { poll, close() { closed = true; clearInterval(timer); } };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
module.exports = { createNetworkMonitor, interfacesOf };
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
// 每台电脑独立选路:实测排序、失败退避与身份验证。
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
const { createRoutePolicy } = require('../shared/route-order.cjs');
|
|
5
|
+
const { safeRoutes } = require('./local-headers.cjs');
|
|
6
|
+
|
|
7
|
+
const PRIORITY = ['lan', 'direct', 'ipv6', 'relay', 'tunnel', 'p2p'];
|
|
8
|
+
const keyOf = (route) => `${route.channel}|${route.url}`;
|
|
9
|
+
const terminal = (error) => ['REMOTE_REVOKED', 'REMOTE_EXPIRED'].includes(error?.code);
|
|
10
|
+
|
|
11
|
+
function createRemoteRouter({ binding, transport, tunnels, now = Date.now, onError = () => {}, onRoutes = async () => {} }) {
|
|
12
|
+
const policy = createRoutePolicy();
|
|
13
|
+
const accounts = new Map();
|
|
14
|
+
let routes = safeRoutes(binding.routes);
|
|
15
|
+
let selected = null;
|
|
16
|
+
let mode = binding.mode || 'auto';
|
|
17
|
+
let probing = null;
|
|
18
|
+
let refreshing = null;
|
|
19
|
+
let generation = 0;
|
|
20
|
+
let closed = false;
|
|
21
|
+
let probeCursor = 0;
|
|
22
|
+
const pending = new Set();
|
|
23
|
+
|
|
24
|
+
async function connectionInfo(info) {
|
|
25
|
+
if (closed || !Array.isArray(info?.routes)) return;
|
|
26
|
+
const next = safeRoutes(info.routes);
|
|
27
|
+
if (!next.length || JSON.stringify(next) === JSON.stringify(safeRoutes(binding.routes))) return;
|
|
28
|
+
await onRoutes(next);
|
|
29
|
+
if (closed) return;
|
|
30
|
+
binding.routes = next;
|
|
31
|
+
routes = safeRoutes([...next, ...routes.filter((route) => ['tunnel', 'p2p'].includes(route.channel))]);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function account(route) {
|
|
35
|
+
const key = keyOf(route);
|
|
36
|
+
if (!accounts.has(key)) accounts.set(key, { failures: 0, until: 0, proven: false });
|
|
37
|
+
return accounts.get(key);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function failure(route, error, penalize = true) {
|
|
41
|
+
if (!route) return;
|
|
42
|
+
const item = account(route);
|
|
43
|
+
item.failures = Math.min(64, item.failures + 1);
|
|
44
|
+
const threshold = ['tunnel', 'p2p'].includes(route.channel) ? 1 : 2;
|
|
45
|
+
if (item.failures >= threshold) item.until = now() + Math.min(30000, 1000 * 2 ** Math.min(5, item.failures - threshold));
|
|
46
|
+
if (penalize) policy.noteRouteFailure(route.url);
|
|
47
|
+
if (error?.code === 'REMOTE_AUTH') policy.noteRouteForeign(route.url);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function proven(route) { accounts.set(keyOf(route), { failures: 0, until: 0, proven: true }); }
|
|
51
|
+
|
|
52
|
+
function ordered() {
|
|
53
|
+
const candidates = routes.filter((route) => mode === 'auto' || route.channel === mode);
|
|
54
|
+
const suspended = candidates.filter((route) => account(route).until > now()).map((route) => route.url);
|
|
55
|
+
return policy.orderRouteCandidates(candidates, selected?.url || '', suspended);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function refresh(networkChanged = false) {
|
|
59
|
+
if (!['auto', 'tunnel', 'p2p'].includes(mode)) {
|
|
60
|
+
routes = safeRoutes(binding.routes).sort((a, b) => PRIORITY.indexOf(a.channel) - PRIORITY.indexOf(b.channel));
|
|
61
|
+
return Promise.resolve(routes);
|
|
62
|
+
}
|
|
63
|
+
if (refreshing && !networkChanged) return refreshing;
|
|
64
|
+
const ticket = generation;
|
|
65
|
+
const work = (async () => {
|
|
66
|
+
let extra = [];
|
|
67
|
+
try {
|
|
68
|
+
const read = networkChanged && tunnels?.refresh ? tunnels.refresh(binding) : tunnels?.routesFor?.(binding);
|
|
69
|
+
extra = await read || [];
|
|
70
|
+
} catch (error) { if (terminal(error)) { onError(error); throw error; } }
|
|
71
|
+
if (closed || ticket !== generation) return routes;
|
|
72
|
+
routes = safeRoutes([...(binding.routes || []), ...extra]).sort((a, b) => PRIORITY.indexOf(a.channel) - PRIORITY.indexOf(b.channel));
|
|
73
|
+
return routes;
|
|
74
|
+
})();
|
|
75
|
+
refreshing = work;
|
|
76
|
+
work.finally(() => { if (refreshing === work) refreshing = null; }).catch(() => {});
|
|
77
|
+
return work;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
async function timed(operation, timeoutMs, late) {
|
|
81
|
+
let timer;
|
|
82
|
+
let elapsed = false;
|
|
83
|
+
const abort = new AbortController();
|
|
84
|
+
pending.add(abort);
|
|
85
|
+
const result = Promise.resolve().then(() => operation(abort.signal));
|
|
86
|
+
result.then((value) => { if (elapsed) late?.(value); }, () => {});
|
|
87
|
+
try {
|
|
88
|
+
return await Promise.race([result, new Promise((_resolve, reject) => {
|
|
89
|
+
const cancel = () => { elapsed = true; reject(Object.assign(new Error('远程连接已取消'), { code: 'REMOTE_CONNECT' })); };
|
|
90
|
+
abort.signal.addEventListener('abort', cancel, { once: true });
|
|
91
|
+
timer = setTimeout(() => { elapsed = true; reject(Object.assign(new Error('远程连接超时'), { code: 'REMOTE_TIMEOUT' })); abort.abort(); }, timeoutMs);
|
|
92
|
+
timer.unref?.();
|
|
93
|
+
})]);
|
|
94
|
+
} finally { clearTimeout(timer); pending.delete(abort); }
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function budget(route) {
|
|
98
|
+
const item = account(route);
|
|
99
|
+
if (['tunnel', 'p2p'].includes(route.channel)) return item.failures ? 4000 : 10000;
|
|
100
|
+
return (!item.proven && route.channel !== 'relay') || item.failures ? 2500 : 7000;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
async function open({ expiresAt } = {}) {
|
|
104
|
+
if (closed) throw new Error('远程连接已停止');
|
|
105
|
+
const refreshing = refresh();
|
|
106
|
+
if (!routes.length) await refreshing;
|
|
107
|
+
else void refreshing.catch(() => {});
|
|
108
|
+
let last;
|
|
109
|
+
for (const route of ordered()) {
|
|
110
|
+
if (closed) throw Object.assign(new Error('远程连接已停止'), { code: 'REMOTE_CONNECT' });
|
|
111
|
+
if (expiresAt && now() >= expiresAt) throw Object.assign(new Error('访问已到期'), { code: 'REMOTE_EXPIRED' });
|
|
112
|
+
const timeoutMs = Math.max(1, Math.min(budget(route), expiresAt ? expiresAt - now() : Infinity));
|
|
113
|
+
try {
|
|
114
|
+
const result = await timed((signal) => transport.openRemoteStream(binding, route, { timeoutMs, expiresAt, signal, onConnectionInfo: connectionInfo }), timeoutMs, (value) => value?.stream?.destroy());
|
|
115
|
+
if (closed || (expiresAt && now() >= expiresAt)) { result.stream.destroy(); throw Object.assign(new Error('访问已到期'), { code: 'REMOTE_EXPIRED' }); }
|
|
116
|
+
selected = route; proven(route);
|
|
117
|
+
await connectionInfo(result.host?.connectionInfo).catch(() => {});
|
|
118
|
+
return result;
|
|
119
|
+
} catch (error) {
|
|
120
|
+
failure(route, error); last = error;
|
|
121
|
+
if (terminal(error)) { onError(error); throw error; }
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
throw last || Object.assign(new Error('没有可用的远程线路'), { code: 'REMOTE_CONNECT' });
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function probe() {
|
|
128
|
+
if (probing) return probing;
|
|
129
|
+
const ticket = generation;
|
|
130
|
+
probing = (async () => {
|
|
131
|
+
const warming = refresh();
|
|
132
|
+
if (!routes.length) await warming;
|
|
133
|
+
else void warming.catch(() => {});
|
|
134
|
+
const candidates = ordered();
|
|
135
|
+
const current = candidates.find((route) => route.url === selected?.url);
|
|
136
|
+
const challengers = candidates.filter((route) => route !== current);
|
|
137
|
+
const rotated = challengers.length ? [...challengers.slice(probeCursor % challengers.length), ...challengers.slice(0, probeCursor % challengers.length)] : [];
|
|
138
|
+
const queue = [...(current ? [current] : []), ...rotated.slice(0, 3)];
|
|
139
|
+
probeCursor += Math.min(3, challengers.length);
|
|
140
|
+
let index = 0;
|
|
141
|
+
let fatal;
|
|
142
|
+
let lastError;
|
|
143
|
+
let successes = 0;
|
|
144
|
+
const worker = async () => {
|
|
145
|
+
while (!closed && ticket === generation && index < queue.length && !fatal) {
|
|
146
|
+
const route = queue[index++];
|
|
147
|
+
const timeoutMs = budget(route);
|
|
148
|
+
try {
|
|
149
|
+
const ms = await timed((signal) => transport.probeRemote(binding, route, { timeoutMs, signal, onConnectionInfo: connectionInfo }), timeoutMs);
|
|
150
|
+
if (closed || ticket !== generation) return;
|
|
151
|
+
if (typeof ms !== 'number' || !Number.isFinite(ms) || ms < 0) throw new Error('远程探测没有返回延迟');
|
|
152
|
+
policy.noteRouteLatency(route.url, ms); proven(route); successes += 1;
|
|
153
|
+
} catch (error) {
|
|
154
|
+
if (ticket !== generation || closed) return;
|
|
155
|
+
policy.noteRouteLatency(route.url, null); failure(route, error, false); lastError = error;
|
|
156
|
+
if (terminal(error)) { fatal = error; onError(error); }
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
};
|
|
160
|
+
await Promise.all(Array.from({ length: Math.min(2, queue.length) }, worker));
|
|
161
|
+
if (fatal) throw fatal;
|
|
162
|
+
if (!successes && ticket === generation && !closed) throw lastError || Object.assign(new Error('没有可用的远程线路'), { code: 'REMOTE_CONNECT' });
|
|
163
|
+
if (ticket === generation && !closed) selected = ordered()[0] || selected;
|
|
164
|
+
return snapshot();
|
|
165
|
+
})();
|
|
166
|
+
probing.finally(() => { probing = null; }).catch(() => {});
|
|
167
|
+
return probing;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function snapshot() {
|
|
171
|
+
return { route: selected, routes: [...routes], latencyMs: selected ? policy.routeLatencyOf(selected.url) : null };
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
return {
|
|
175
|
+
open, probe, refresh, snapshot,
|
|
176
|
+
setMode(value) {
|
|
177
|
+
if (value !== 'auto' && !routes.some((route) => route.channel === value)) throw new Error('这条线路当前不可用');
|
|
178
|
+
mode = value; selected = ordered()[0] || null;
|
|
179
|
+
},
|
|
180
|
+
failure(error) { failure(selected, error); },
|
|
181
|
+
async networkChanged() {
|
|
182
|
+
generation += 1; policy.forgetRouteFacts(); accounts.clear(); selected = null;
|
|
183
|
+
for (const abort of pending) abort.abort();
|
|
184
|
+
const previous = probing;
|
|
185
|
+
void refresh(true).catch((error) => onError(error));
|
|
186
|
+
if (previous) await previous.catch(() => {});
|
|
187
|
+
if (!closed) return probe();
|
|
188
|
+
return snapshot();
|
|
189
|
+
},
|
|
190
|
+
close() { closed = true; generation += 1; for (const abort of pending) abort.abort(); policy.forgetRouteFacts(); accounts.clear(); },
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
module.exports = { createRemoteRouter };
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// 远程电脑管理仅接受本机可信界面;电脑配对和加密升级由各自协议独立认证。
|
|
3
|
+
const { sendJson, readJsonBody } = require('../shared/http-util.js');
|
|
4
|
+
const { trustedLocalUi, crossSiteRequest } = require('../http/routing.js');
|
|
5
|
+
const { launchShell } = require('./shell.cjs');
|
|
6
|
+
const PREFIX = '/api/relay/remote-computers';
|
|
7
|
+
const METHODS = { '': 'GET', '/invite': 'POST', '/add': 'POST', '/open': 'POST', '/open-shell': 'POST',
|
|
8
|
+
'/renew': 'POST', '/stop': 'POST', '/remove': 'POST', '/mode': 'POST', '/probe': 'POST', '/revoke': 'POST' };
|
|
9
|
+
const PUBLIC_ERRORS = {
|
|
10
|
+
'credentials-unavailable': '宿主凭据存储暂不可用,请稍后重试',
|
|
11
|
+
REMOTE_AUTH: '远程电脑认证失败,请重新绑定', REMOTE_REVOKED: '这台电脑的授权已被撤销,请重新绑定',
|
|
12
|
+
REMOTE_EXPIRED: '授权已到期,请重新打开', REMOTE_TIMEOUT: '连接远程电脑超时,请重试或检测线路',
|
|
13
|
+
REMOTE_CONNECT: '暂时无法连接远程电脑,请检查网络和对方是否在线',
|
|
14
|
+
SHELL_UNAVAILABLE: '本机未安装远程电脑桌面端,请改用默认方式打开',
|
|
15
|
+
};
|
|
16
|
+
function createRemoteRoutes({ controller, host, credentials, instanceId, now = Date.now }) {
|
|
17
|
+
function authorizedComputers() {
|
|
18
|
+
return credentials.listRemoteComputers(instanceId);
|
|
19
|
+
}
|
|
20
|
+
function handler(suffix) {
|
|
21
|
+
return async (req, res) => {
|
|
22
|
+
res.setHeader('cache-control', 'no-store');
|
|
23
|
+
if (!trustedLocalUi(req) || crossSiteRequest(req)) return sendJson(res, 403, {
|
|
24
|
+
ok: false, error: { code: 'local_only', message: '请从本机 DSH 插件打开远程电脑管理' },
|
|
25
|
+
});
|
|
26
|
+
if (req.method !== METHODS[suffix]) return sendJson(res, 405, {
|
|
27
|
+
ok: false, error: { code: 'method-not-allowed', message: '请求方法不支持' },
|
|
28
|
+
});
|
|
29
|
+
try {
|
|
30
|
+
if (!suffix) return sendJson(res, 200, { ok: true, devices: await controller.list(),
|
|
31
|
+
authorizedComputers: authorizedComputers(), serverNow: now() });
|
|
32
|
+
if (!/^application\/json(?:\s*;|$)/i.test(req.headers['content-type'] || '')) {
|
|
33
|
+
return sendJson(res, 415, { ok: false, error: { code: 'json-required', message: '请使用 JSON 请求' } });
|
|
34
|
+
}
|
|
35
|
+
const body = await readJsonBody(req, 32 * 1024);
|
|
36
|
+
if (!body || typeof body !== 'object' || Array.isArray(body)) return sendJson(res, 400, {
|
|
37
|
+
ok: false, error: { code: 'bad-request', message: '请求内容不合法' },
|
|
38
|
+
});
|
|
39
|
+
if (suffix === '/invite') return sendJson(res, 200, { ok: true, ...await host.mintInvite() });
|
|
40
|
+
if (suffix === '/add') {
|
|
41
|
+
if (typeof body.invite !== 'string' || body.invite.length > 24 * 1024) throw new Error('bad-invite');
|
|
42
|
+
return sendJson(res, 200, { ok: true, device: await controller.add(body.invite) });
|
|
43
|
+
}
|
|
44
|
+
if (suffix === '/revoke') {
|
|
45
|
+
if (typeof body.deviceId !== 'string' || !authorizedComputers().some(row => row.deviceId === body.deviceId)) {
|
|
46
|
+
return sendJson(res, 404, { ok: false, error: { code: 'not-found', message: '电脑授权不存在' } });
|
|
47
|
+
}
|
|
48
|
+
const revoked = credentials.revokeDevice(instanceId, body.deviceId);
|
|
49
|
+
host.revoke(body.deviceId);
|
|
50
|
+
return sendJson(res, 200, { ok: true, revoked });
|
|
51
|
+
}
|
|
52
|
+
if (typeof body.id !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(body.id)) throw new Error('bad-id');
|
|
53
|
+
if (suffix === '/open') return sendJson(res, 200, { ok: true, ...await controller.open(body.id) });
|
|
54
|
+
if (suffix === '/open-shell') {
|
|
55
|
+
const result = await controller.open(body.id);
|
|
56
|
+
const devices = await controller.list();
|
|
57
|
+
const deviceName = devices.find(row => row.id === body.id)?.name || '';
|
|
58
|
+
// 记下这次拉起的桌面进程:它一退出就当窗口关掉,面板据此回到未打开。
|
|
59
|
+
const child = launchShell({ url: result.url, deviceName });
|
|
60
|
+
controller.watchWindow(body.id, child);
|
|
61
|
+
return sendJson(res, 200, { ok: true, ...result });
|
|
62
|
+
}
|
|
63
|
+
if (suffix === '/renew') return sendJson(res, 200, { ok: true, ...await controller.renew(body.id) });
|
|
64
|
+
if (suffix === '/stop') await controller.stop(body.id);
|
|
65
|
+
if (suffix === '/remove') await controller.remove(body.id);
|
|
66
|
+
if (suffix === '/mode') {
|
|
67
|
+
if (typeof body.mode !== 'string' || !['auto', 'lan', 'direct', 'ipv6', 'relay', 'tunnel', 'p2p'].includes(body.mode)) throw new Error('bad-mode');
|
|
68
|
+
await controller.setMode(body.id, body.mode);
|
|
69
|
+
}
|
|
70
|
+
if (suffix === '/probe') await controller.probe(body.id);
|
|
71
|
+
return sendJson(res, 200, { ok: true });
|
|
72
|
+
} catch (error) {
|
|
73
|
+
const code = typeof error?.code === 'string' ? error.code : 'remote-operation-failed';
|
|
74
|
+
const status = /REVOKED|AUTH/.test(code) ? 401 : /EXPIRED|expired/i.test(code) ? 410 : 400;
|
|
75
|
+
return sendJson(res, status, { ok: false, error: { code,
|
|
76
|
+
message: PUBLIC_ERRORS[code] || '远程电脑操作未完成,请确认绑定信息、网络和访问期限后重试' } });
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
return { register(registerRoute) {
|
|
81
|
+
for (const suffix of Object.keys(METHODS)) registerRoute({ kind: 'exact', path: PREFIX + suffix, handler: handler(suffix) });
|
|
82
|
+
}, handler, authorizedComputers };
|
|
83
|
+
}
|
|
84
|
+
module.exports = { createRemoteRoutes, PREFIX, METHODS };
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// 电脑间远程网页的装配与生命周期;入口只在可信本机界面签发。
|
|
3
|
+
const os = require('node:os');
|
|
4
|
+
const { createRemoteStore } = require('./store.cjs');
|
|
5
|
+
const { createRemoteHost } = require('./host.cjs');
|
|
6
|
+
const transport = require('./transport.cjs');
|
|
7
|
+
const { createRemoteController } = require('./controller.cjs');
|
|
8
|
+
const { createRemoteRoutes } = require('./routes.cjs');
|
|
9
|
+
const { createHostControl } = require('./host-control.cjs');
|
|
10
|
+
const { createTunnelForwarder } = require('../relay/tunnel-forwarder.cjs');
|
|
11
|
+
|
|
12
|
+
function mountRemoteComputers({ ctx, state, credentials, registerRoute, lanPortInUse, tailcat, p2p, log = () => {} }) {
|
|
13
|
+
const store = createRemoteStore({ credentials: () => ctx.get('credentials') });
|
|
14
|
+
const forwarder = createTunnelForwarder({ upstreamPort: () => ctx.webServer.port, log });
|
|
15
|
+
const control = createHostControl({ state, tailcat, p2p, lanPortInUse });
|
|
16
|
+
const host = createRemoteHost({
|
|
17
|
+
state, credentials, routesOf: control.routesOf,
|
|
18
|
+
getUpstreamPort: async () => { await forwarder.start(); return forwarder.port(); },
|
|
19
|
+
getWebPort: () => ctx.webServer.port,
|
|
20
|
+
getLaunchToken: () => ctx.get('connection')?.browserAuth?.launchToken || '',
|
|
21
|
+
getConnectionInfo: control.connectionInfo,
|
|
22
|
+
onControl: control.onControl, log,
|
|
23
|
+
});
|
|
24
|
+
const { createRemoteTunnels } = require('./tunnels.cjs');
|
|
25
|
+
const tunnels = createRemoteTunnels({ store, transport });
|
|
26
|
+
const controller = createRemoteController({ store, transport, tunnels, name: state.name || os.hostname() });
|
|
27
|
+
createRemoteRoutes({ controller, host, credentials, instanceId: state.instanceId }).register(registerRoute);
|
|
28
|
+
ctx.effect(() => () => {
|
|
29
|
+
const stopping = controller.close();
|
|
30
|
+
host.close();
|
|
31
|
+
forwarder.close();
|
|
32
|
+
return Promise.resolve(stopping).catch(() => {}).then(() => tunnels.closeAll());
|
|
33
|
+
}, 'dsh-mobile-plugin: remote computers');
|
|
34
|
+
return host;
|
|
35
|
+
}
|
|
36
|
+
module.exports = { mountRemoteComputers };
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// 远程电脑桌面端显示壳:按平台包找到随插件分发的可执行文件,用一次性入口拉起独立窗口。
|
|
3
|
+
const { spawn } = require('node:child_process');
|
|
4
|
+
const fs = require('node:fs');
|
|
5
|
+
const path = require('node:path');
|
|
6
|
+
|
|
7
|
+
/** 五个分发平台,与平台包 dsh-mobile-shell-<id> 一一对应。 */
|
|
8
|
+
const PLATFORM_IDS = ['darwin-arm64', 'darwin-x64', 'linux-x64', 'linux-arm64', 'win32-x64'];
|
|
9
|
+
|
|
10
|
+
/** 平台包不可用时的统一错误码。 */
|
|
11
|
+
const SHELL_UNAVAILABLE = 'SHELL_UNAVAILABLE';
|
|
12
|
+
|
|
13
|
+
const DEV_ROOT = path.resolve(__dirname, '..', '..', '..');
|
|
14
|
+
|
|
15
|
+
function failure(code) {
|
|
16
|
+
const error = new Error(code);
|
|
17
|
+
error.code = code;
|
|
18
|
+
return error;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** 这台机器对应哪个平台包;没有对应包就返回 undefined。 */
|
|
22
|
+
function platformId(platform = process.platform, arch = process.arch) {
|
|
23
|
+
const os = platform === 'win32' ? 'win32' : platform;
|
|
24
|
+
const cpu = arch === 'x64' ? 'x64' : arch === 'arm64' ? 'arm64' : arch;
|
|
25
|
+
const id = `${os}-${cpu}`;
|
|
26
|
+
return PLATFORM_IDS.includes(id) ? id : undefined;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** 平台包内可执行文件的相对路径(macOS 是 .app 包里的那个二进制)。 */
|
|
30
|
+
function binaryPath(platform) {
|
|
31
|
+
if (platform === 'win32-x64') return 'dsh-mobile-shell.exe';
|
|
32
|
+
if (platform.startsWith('darwin-')) return 'dsh-mobile-shell.app/Contents/MacOS/dsh-mobile-shell';
|
|
33
|
+
return 'dsh-mobile-shell';
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** 只认本机代理给出的一次性入口:带端口的 http://127.0.0.1,不带账号密码。 */
|
|
37
|
+
function validRemoteUrl(value) {
|
|
38
|
+
if (typeof value !== 'string' || !value || /[\u0000-\u0020\u007f]/.test(value)) return false;
|
|
39
|
+
let url;
|
|
40
|
+
try { url = new URL(value); } catch { return false; }
|
|
41
|
+
return url.protocol === 'http:' && url.hostname === '127.0.0.1' && Boolean(url.port)
|
|
42
|
+
&& !url.username && !url.password;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* 找桌面端可执行文件:先按本模块所在位置解析可选依赖(npm / pnpm 的嵌套与 hoisted 布局都
|
|
47
|
+
* 命中),再退回调用方指定路径 / 当前工作目录,然后是开发产物与环境变量覆盖。找不到一律
|
|
48
|
+
* 回 null,把这条通道标成不可用,不抛错、不影响插件其余功能。
|
|
49
|
+
*/
|
|
50
|
+
function resolveShell(options = {}) {
|
|
51
|
+
const exists = options.exists || fs.existsSync;
|
|
52
|
+
const platform = options.platformId || platformId(options.platform, options.arch);
|
|
53
|
+
if (!platform) return null;
|
|
54
|
+
const relative = binaryPath(platform);
|
|
55
|
+
const pkg = `dsh-mobile-shell-${platform}`;
|
|
56
|
+
for (const paths of [undefined, options.paths || [process.cwd()]]) {
|
|
57
|
+
try {
|
|
58
|
+
const manifest = require.resolve(`${pkg}/package.json`, paths ? { paths } : undefined);
|
|
59
|
+
const candidate = path.join(path.dirname(manifest), relative);
|
|
60
|
+
if (exists(candidate)) return candidate;
|
|
61
|
+
} catch {
|
|
62
|
+
/* 这一路没有:试下一路 */
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
const override = (options.env || process.env).DSHM_MOBILE_SHELL;
|
|
66
|
+
if (typeof override === 'string' && override && exists(override)) return override;
|
|
67
|
+
// 随包分发的本机原生产物(开发机由 reload-dev 从 build/desktop-shell 拷进来)。
|
|
68
|
+
const nativeRoot = options.nativeRoot || path.join(__dirname, '..', '..', 'native', 'desktop-shell');
|
|
69
|
+
const native = path.join(nativeRoot, platform, relative);
|
|
70
|
+
if (exists(native)) return native;
|
|
71
|
+
const dev = path.join(options.devRoot || DEV_ROOT, 'build', 'desktop-shell', platform, relative);
|
|
72
|
+
if (exists(dev)) return dev;
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** 命令行参数固定两项:一次性地址与设备名,不经 shell、不拼命令。 */
|
|
77
|
+
function buildArgs({ url, deviceName } = {}) {
|
|
78
|
+
return [`--remote-url=${url}`, `--device-name=${String(deviceName || '')}`];
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* 一次点击拉起一个窗口:进程 detached、stdio 丢弃、unref,插件退出不拖着窗口。
|
|
83
|
+
* 地址只来自 controller.open,校验过后交给参数数组,不写日志、不落盘。
|
|
84
|
+
*/
|
|
85
|
+
function launchShell({ url, deviceName } = {}, options = {}) {
|
|
86
|
+
if (!validRemoteUrl(url)) throw failure('REMOTE_OPEN_URL');
|
|
87
|
+
const binary = (options.resolve || resolveShell)(options);
|
|
88
|
+
if (!binary) throw failure(SHELL_UNAVAILABLE);
|
|
89
|
+
const launch = options.spawn || spawn;
|
|
90
|
+
let child;
|
|
91
|
+
try {
|
|
92
|
+
child = launch(binary, buildArgs({ url, deviceName }), { detached: true, stdio: 'ignore', windowsHide: true });
|
|
93
|
+
} catch {
|
|
94
|
+
throw failure(SHELL_UNAVAILABLE);
|
|
95
|
+
}
|
|
96
|
+
child?.on?.('error', () => {});
|
|
97
|
+
child?.unref?.();
|
|
98
|
+
return child;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
module.exports = { PLATFORM_IDS, SHELL_UNAVAILABLE, platformId, binaryPath, resolveShell, buildArgs, launchShell };
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// 远程电脑的长期绑定仅保存于宿主凭据记录,面板只消费控制器的无密钥投影。
|
|
3
|
+
const OWNER = 'dsh-mobile-plugin';
|
|
4
|
+
const PREFIX = `${OWNER}/remote-computer-`;
|
|
5
|
+
const ID = /^[A-Za-z0-9_-]{1,128}$/;
|
|
6
|
+
|
|
7
|
+
function copy(value) { return value == null ? value : JSON.parse(JSON.stringify(value)); }
|
|
8
|
+
function createRemoteStore(options = {}) {
|
|
9
|
+
const providerOf = typeof options.credentials === 'function' ? options.credentials : () => options.credentials;
|
|
10
|
+
function provider() {
|
|
11
|
+
const value = providerOf();
|
|
12
|
+
if (!value || typeof value.readRecord !== 'function' || typeof value.modifyRecord !== 'function') {
|
|
13
|
+
const error = new Error('宿主凭据存储暂不可用,无法保存远程电脑绑定');
|
|
14
|
+
error.code = 'credentials-unavailable';
|
|
15
|
+
throw error;
|
|
16
|
+
}
|
|
17
|
+
return value;
|
|
18
|
+
}
|
|
19
|
+
function keyOf(id) {
|
|
20
|
+
if (typeof id !== 'string' || !ID.test(id)) throw new Error('远程电脑标识不合法');
|
|
21
|
+
return PREFIX + Buffer.from(id, 'utf8').toString('hex');
|
|
22
|
+
}
|
|
23
|
+
function payloadOf(record) {
|
|
24
|
+
if (!record || record.kind !== 'grant' || record.payload?.version !== 1) return null;
|
|
25
|
+
const binding = record.payload.binding;
|
|
26
|
+
if (!binding || !ID.test(binding.id || '') || typeof binding.instanceId !== 'string') return null;
|
|
27
|
+
return copy(binding);
|
|
28
|
+
}
|
|
29
|
+
return {
|
|
30
|
+
async list() {
|
|
31
|
+
const value = provider();
|
|
32
|
+
const records = await value.listRecords();
|
|
33
|
+
const keys = records.filter(item => typeof item.key === 'string' && item.key.startsWith(PREFIX));
|
|
34
|
+
const rows = await Promise.all(keys.map(async item => payloadOf(await value.readRecord(item.key))));
|
|
35
|
+
return rows.filter(Boolean);
|
|
36
|
+
},
|
|
37
|
+
async get(id) { return payloadOf(await provider().readRecord(keyOf(id))); },
|
|
38
|
+
async put(binding) {
|
|
39
|
+
const id = binding?.id || binding?.instanceId;
|
|
40
|
+
const key = keyOf(id);
|
|
41
|
+
const next = copy({ ...binding, id });
|
|
42
|
+
await provider().modifyRecord(key, current => ({
|
|
43
|
+
kind: 'grant', payload: { version: 1, binding: { ...(payloadOf(current) || {}), ...next } },
|
|
44
|
+
}));
|
|
45
|
+
return next;
|
|
46
|
+
},
|
|
47
|
+
async delete(id) { await provider().deleteRecord(keyOf(id)); },
|
|
48
|
+
async update(id, change) {
|
|
49
|
+
let result;
|
|
50
|
+
await provider().modifyRecord(keyOf(id), async current => {
|
|
51
|
+
const binding = payloadOf(current);
|
|
52
|
+
if (!binding) throw new Error('远程电脑绑定不存在');
|
|
53
|
+
result = { ...binding, ...await change(copy(binding)), id };
|
|
54
|
+
return { kind: 'grant', payload: { version: 1, binding: result } };
|
|
55
|
+
});
|
|
56
|
+
return copy(result);
|
|
57
|
+
},
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
module.exports = { createRemoteStore, PREFIX };
|