dsh-mobile-plugin 0.5.51 → 0.5.53
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 +10 -0
- package/dsh-mobile-credentials/lib/credentials.js +34 -2
- package/lib/client.js +203 -11
- package/lib/impl.js +5 -0
- package/lib/mobile/channels.js +18 -21
- package/lib/mobile/directory-listing.js +3 -1
- package/lib/mobile/events.js +2 -0
- package/lib/mobile/host-bridge/endpoints.js +2 -1
- package/lib/mobile/host-bridge/event-synthesis.js +48 -39
- package/lib/mobile/host-web.js +2 -2
- package/lib/mobile/model-caps.js +15 -5
- package/lib/mobile/model-meta-table.cjs +5 -4
- package/lib/mobile/model-meta.js +5 -3
- package/lib/mobile/permissions.js +1 -3
- package/lib/mobile/stream.js +2 -0
- package/lib/mobile/workspaces.js +6 -5
- package/lib/panel/index.html +15 -15
- package/lib/relay/lan-proxy.js +15 -8
- package/lib/remote/browser-notice.cjs +118 -0
- package/lib/remote/controller.cjs +212 -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 +144 -0
- package/lib/remote/network.cjs +42 -0
- package/lib/remote/router.cjs +194 -0
- package/lib/remote/routes.cjs +73 -0
- package/lib/remote/runtime.cjs +36 -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/lib/tailcat/session.cjs +31 -36
- package/package.json +7 -6
- package/lib/mobile/perf-trace.js +0 -142
|
@@ -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,73 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// 远程电脑管理仅接受本机可信界面;电脑配对和加密升级由各自协议独立认证。
|
|
3
|
+
const { sendJson, readJsonBody } = require('../shared/http-util.js');
|
|
4
|
+
const { trustedLocalUi, crossSiteRequest } = require('../http/routing.js');
|
|
5
|
+
const PREFIX = '/api/relay/remote-computers';
|
|
6
|
+
const METHODS = { '': 'GET', '/invite': 'POST', '/add': 'POST', '/open': 'POST', '/renew': 'POST',
|
|
7
|
+
'/stop': 'POST', '/remove': 'POST', '/mode': 'POST', '/probe': 'POST', '/revoke': 'POST' };
|
|
8
|
+
const PUBLIC_ERRORS = {
|
|
9
|
+
'credentials-unavailable': '宿主凭据存储暂不可用,请稍后重试',
|
|
10
|
+
REMOTE_AUTH: '远程电脑认证失败,请重新绑定', REMOTE_REVOKED: '这台电脑的授权已被撤销,请重新绑定',
|
|
11
|
+
REMOTE_EXPIRED: '授权已到期,请重新打开', REMOTE_TIMEOUT: '连接远程电脑超时,请重试或检测线路',
|
|
12
|
+
REMOTE_CONNECT: '暂时无法连接远程电脑,请检查网络和对方是否在线',
|
|
13
|
+
};
|
|
14
|
+
function createRemoteRoutes({ controller, host, credentials, instanceId, now = Date.now }) {
|
|
15
|
+
function authorizedComputers() {
|
|
16
|
+
return credentials.listRemoteComputers(instanceId);
|
|
17
|
+
}
|
|
18
|
+
function handler(suffix) {
|
|
19
|
+
return async (req, res) => {
|
|
20
|
+
res.setHeader('cache-control', 'no-store');
|
|
21
|
+
if (!trustedLocalUi(req) || crossSiteRequest(req)) return sendJson(res, 403, {
|
|
22
|
+
ok: false, error: { code: 'local_only', message: '请从本机 DSH 插件打开远程电脑管理' },
|
|
23
|
+
});
|
|
24
|
+
if (req.method !== METHODS[suffix]) return sendJson(res, 405, {
|
|
25
|
+
ok: false, error: { code: 'method-not-allowed', message: '请求方法不支持' },
|
|
26
|
+
});
|
|
27
|
+
try {
|
|
28
|
+
if (!suffix) return sendJson(res, 200, { ok: true, devices: await controller.list(),
|
|
29
|
+
authorizedComputers: authorizedComputers(), serverNow: now() });
|
|
30
|
+
if (!/^application\/json(?:\s*;|$)/i.test(req.headers['content-type'] || '')) {
|
|
31
|
+
return sendJson(res, 415, { ok: false, error: { code: 'json-required', message: '请使用 JSON 请求' } });
|
|
32
|
+
}
|
|
33
|
+
const body = await readJsonBody(req, 32 * 1024);
|
|
34
|
+
if (!body || typeof body !== 'object' || Array.isArray(body)) return sendJson(res, 400, {
|
|
35
|
+
ok: false, error: { code: 'bad-request', message: '请求内容不合法' },
|
|
36
|
+
});
|
|
37
|
+
if (suffix === '/invite') return sendJson(res, 200, { ok: true, ...await host.mintInvite() });
|
|
38
|
+
if (suffix === '/add') {
|
|
39
|
+
if (typeof body.invite !== 'string' || body.invite.length > 24 * 1024) throw new Error('bad-invite');
|
|
40
|
+
return sendJson(res, 200, { ok: true, device: await controller.add(body.invite) });
|
|
41
|
+
}
|
|
42
|
+
if (suffix === '/revoke') {
|
|
43
|
+
if (typeof body.deviceId !== 'string' || !authorizedComputers().some(row => row.deviceId === body.deviceId)) {
|
|
44
|
+
return sendJson(res, 404, { ok: false, error: { code: 'not-found', message: '电脑授权不存在' } });
|
|
45
|
+
}
|
|
46
|
+
const revoked = credentials.revokeDevice(instanceId, body.deviceId);
|
|
47
|
+
host.revoke(body.deviceId);
|
|
48
|
+
return sendJson(res, 200, { ok: true, revoked });
|
|
49
|
+
}
|
|
50
|
+
if (typeof body.id !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(body.id)) throw new Error('bad-id');
|
|
51
|
+
if (suffix === '/open') return sendJson(res, 200, { ok: true, ...await controller.open(body.id) });
|
|
52
|
+
if (suffix === '/renew') return sendJson(res, 200, { ok: true, ...await controller.renew(body.id) });
|
|
53
|
+
if (suffix === '/stop') await controller.stop(body.id);
|
|
54
|
+
if (suffix === '/remove') await controller.remove(body.id);
|
|
55
|
+
if (suffix === '/mode') {
|
|
56
|
+
if (typeof body.mode !== 'string' || !['auto', 'lan', 'direct', 'ipv6', 'relay', 'tunnel', 'p2p'].includes(body.mode)) throw new Error('bad-mode');
|
|
57
|
+
await controller.setMode(body.id, body.mode);
|
|
58
|
+
}
|
|
59
|
+
if (suffix === '/probe') await controller.probe(body.id);
|
|
60
|
+
return sendJson(res, 200, { ok: true });
|
|
61
|
+
} catch (error) {
|
|
62
|
+
const code = typeof error?.code === 'string' ? error.code : 'remote-operation-failed';
|
|
63
|
+
const status = /REVOKED|AUTH/.test(code) ? 401 : /EXPIRED|expired/i.test(code) ? 410 : 400;
|
|
64
|
+
return sendJson(res, status, { ok: false, error: { code,
|
|
65
|
+
message: PUBLIC_ERRORS[code] || '远程电脑操作未完成,请确认绑定信息、网络和访问期限后重试' } });
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
return { register(registerRoute) {
|
|
70
|
+
for (const suffix of Object.keys(METHODS)) registerRoute({ kind: 'exact', path: PREFIX + suffix, handler: handler(suffix) });
|
|
71
|
+
}, handler, authorizedComputers };
|
|
72
|
+
}
|
|
73
|
+
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,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 };
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
// 远程电脑邀请客户端与经端到端身份验证的加密字节通道。
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
const http = require('node:http');
|
|
5
|
+
const https = require('node:https');
|
|
6
|
+
const os = require('node:os');
|
|
7
|
+
const crypto = require('node:crypto');
|
|
8
|
+
const { WebSocket } = require('ws');
|
|
9
|
+
const c = require('./crypto.cjs');
|
|
10
|
+
const { PAIR_PATH, TUNNEL_PATH } = require('./host.cjs');
|
|
11
|
+
|
|
12
|
+
function parseInvitation(text) {
|
|
13
|
+
let value = text;
|
|
14
|
+
try {
|
|
15
|
+
if (typeof text === 'string') {
|
|
16
|
+
if (text.length > c.MAX_HANDSHAKE * 2) throw new Error();
|
|
17
|
+
const url = new URL(text.trim());
|
|
18
|
+
if (url.protocol !== 'dshcomputer:' || url.hostname !== 'v1' || (url.pathname && url.pathname !== '/')) throw new Error();
|
|
19
|
+
value = JSON.parse(Buffer.from(url.searchParams.get('data') || '', 'base64url').toString('utf8'));
|
|
20
|
+
}
|
|
21
|
+
if (!value || value.type !== 'dsh-computer' || value.version !== 1 || 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();
|
|
22
|
+
c.keyBytes(value.ticket);
|
|
23
|
+
const routes = value.routes.map((route) => {
|
|
24
|
+
c.endpoint(route, PAIR_PATH);
|
|
25
|
+
if (typeof route.channel !== 'string' || !route.channel || route.channel.length > 32) throw new Error();
|
|
26
|
+
return { url: route.url, channel: route.channel };
|
|
27
|
+
});
|
|
28
|
+
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 };
|
|
29
|
+
} catch { throw c.error('REMOTE_INVITATION', 'Invalid computer invitation'); }
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function post(route, path, instanceId, body, timeoutMs) {
|
|
33
|
+
return new Promise((resolve, reject) => {
|
|
34
|
+
const bytes = c.json(body);
|
|
35
|
+
const url = c.endpoint(route, path);
|
|
36
|
+
const request = (url.protocol === 'https:' ? https : http).request(url, { method: 'POST', agent: false, headers: { 'content-type': 'application/json', 'content-length': bytes.length, 'x-dsh-instance': instanceId } }, (response) => {
|
|
37
|
+
const chunks = [];
|
|
38
|
+
let length = 0;
|
|
39
|
+
response.on('data', (chunk) => {
|
|
40
|
+
length += chunk.length;
|
|
41
|
+
if (length > c.MAX_HANDSHAKE * 2) { request.destroy(c.error('REMOTE_AUTH', 'Pair response too large')); return; }
|
|
42
|
+
chunks.push(chunk);
|
|
43
|
+
});
|
|
44
|
+
response.on('error', reject);
|
|
45
|
+
response.on('end', () => {
|
|
46
|
+
if (response.statusCode !== 200) { reject(c.error(response.statusCode === 401 ? 'REMOTE_AUTH' : 'REMOTE_CONNECT', 'Computer pairing was refused')); return; }
|
|
47
|
+
try { resolve(JSON.parse(Buffer.concat(chunks).toString('utf8'))); } catch { reject(c.error('REMOTE_AUTH', 'Invalid pair response')); }
|
|
48
|
+
});
|
|
49
|
+
});
|
|
50
|
+
const timer = setTimeout(() => request.destroy(c.error('REMOTE_TIMEOUT', 'Computer pairing timed out')), timeoutMs);
|
|
51
|
+
timer.unref?.();
|
|
52
|
+
request.on('close', () => clearTimeout(timer));
|
|
53
|
+
request.on('error', (err) => reject(err.code?.startsWith('REMOTE_') ? err : c.error('REMOTE_CONNECT', 'Computer pairing failed')));
|
|
54
|
+
request.end(bytes);
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
async function pairComputer(textOrObject, options = {}) {
|
|
59
|
+
const invite = parseInvitation(textOrObject);
|
|
60
|
+
const deviceKey = c.random();
|
|
61
|
+
const keyId = crypto.randomBytes(8).toString('hex');
|
|
62
|
+
const deviceId = options.deviceId || crypto.randomUUID();
|
|
63
|
+
const nonce = c.random();
|
|
64
|
+
const keys = c.pairKeys(invite.ticket, invite.instanceId, invite.ticketId);
|
|
65
|
+
const aad = (direction) => JSON.stringify(['dsh-computer-pair-v1', invite.instanceId, invite.ticketId, direction]);
|
|
66
|
+
const request = { v: 1, instanceId: invite.instanceId, ticketId: invite.ticketId, sealed: c.sealJson(keys.up, { deviceId, name: options.name || os.hostname(), deviceKey, keyId, nonce }, aad('up')) };
|
|
67
|
+
let lastError;
|
|
68
|
+
for (const route of options.routes || invite.routes) {
|
|
69
|
+
try {
|
|
70
|
+
const response = await post(route, PAIR_PATH, invite.instanceId, request, options.timeoutMs || 10_000);
|
|
71
|
+
if (response.v !== 1 || !response.ok) throw c.error('REMOTE_AUTH');
|
|
72
|
+
const binding = c.openJson(keys.down, response.sealed, aad('down'));
|
|
73
|
+
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');
|
|
74
|
+
for (const candidate of binding.routes) c.endpoint(candidate, TUNNEL_PATH, true);
|
|
75
|
+
return { instanceId: binding.instanceId, name: binding.name, deviceId, credential: binding.credential, deviceKey, keyId, routes: binding.routes, createdAt: binding.createdAt, ...(binding.connectionInfo ? { connectionInfo: binding.connectionInfo } : {}) };
|
|
76
|
+
} catch (err) {
|
|
77
|
+
lastError = err.code?.startsWith('REMOTE_') ? err : c.error('REMOTE_AUTH', 'Computer pairing authentication failed');
|
|
78
|
+
if (lastError.code !== 'REMOTE_CONNECT' && lastError.code !== 'REMOTE_TIMEOUT') throw lastError;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
throw lastError || c.error('REMOTE_CONNECT', 'No computer route is available');
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function openRemoteStream(binding, route, options = {}) {
|
|
85
|
+
return new Promise((resolve, reject) => {
|
|
86
|
+
let ws;
|
|
87
|
+
let initial;
|
|
88
|
+
let keys;
|
|
89
|
+
let stage = 'welcome';
|
|
90
|
+
let settled = false;
|
|
91
|
+
let timer;
|
|
92
|
+
const abort = () => fail(c.error('REMOTE_CONNECT', 'Computer connection cancelled'));
|
|
93
|
+
const fail = (err) => {
|
|
94
|
+
if (settled) return;
|
|
95
|
+
settled = true;
|
|
96
|
+
clearTimeout(timer);
|
|
97
|
+
options.signal?.removeEventListener('abort', abort);
|
|
98
|
+
ws?.terminate();
|
|
99
|
+
reject(err.code?.startsWith('REMOTE_') ? err : c.error('REMOTE_AUTH', 'Computer authentication failed'));
|
|
100
|
+
};
|
|
101
|
+
try {
|
|
102
|
+
if (options.signal?.aborted) { abort(); return; }
|
|
103
|
+
options.signal?.addEventListener('abort', abort, { once: true });
|
|
104
|
+
c.keyBytes(binding.deviceKey);
|
|
105
|
+
if (!binding.credential || !binding.instanceId || !/^[0-9a-f]{16}$/.test(binding.keyId)) throw c.error('REMOTE_AUTH');
|
|
106
|
+
if (options.expiresAt && options.expiresAt <= Date.now()) throw c.error('REMOTE_EXPIRED');
|
|
107
|
+
const context = { instanceId: binding.instanceId, keyId: binding.keyId, clientNonce: c.random() };
|
|
108
|
+
ws = new WebSocket(c.endpoint(route, TUNNEL_PATH, true), { perMessageDeflate: false, maxPayload: c.MAX_MESSAGE, handshakeTimeout: options.timeoutMs || 10_000, headers: { 'x-dsh-instance': binding.instanceId } });
|
|
109
|
+
timer = setTimeout(() => fail(c.error('REMOTE_TIMEOUT', 'Computer connection timed out')), options.timeoutMs || 10_000);
|
|
110
|
+
timer.unref?.();
|
|
111
|
+
const receive = (data, binary) => {
|
|
112
|
+
try {
|
|
113
|
+
const message = c.parseMessage(data, binary);
|
|
114
|
+
if (stage === 'welcome' && message.type === 'welcome') {
|
|
115
|
+
stage = 'challenge';
|
|
116
|
+
ws.send(JSON.stringify({ v: 1, type: 'hello', instanceId: binding.instanceId, keyId: binding.keyId, nonce: context.clientNonce }));
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
if (message.type === 'denied' && initial) {
|
|
120
|
+
const denied = c.openJson(initial.authDown, message.sealed, initial.transcript);
|
|
121
|
+
throw c.error(denied.code || 'REMOTE_AUTH', 'Computer access was refused');
|
|
122
|
+
}
|
|
123
|
+
if (stage === 'challenge' && message.type === 'challenge') {
|
|
124
|
+
context.serverNonce = message.nonce;
|
|
125
|
+
initial = c.connectionKeys(binding.deviceKey, context);
|
|
126
|
+
const challenge = c.openJson(initial.authDown, message.sealed, initial.transcript);
|
|
127
|
+
if (challenge.instanceId !== binding.instanceId || challenge.keyId !== binding.keyId || challenge.clientNonce !== context.clientNonce) throw c.error('REMOTE_AUTH', 'Unexpected computer identity');
|
|
128
|
+
keys = c.connectionKeys(binding.deviceKey, { ...context, credential: binding.credential });
|
|
129
|
+
stage = 'ready';
|
|
130
|
+
const leaseMs = Math.min(c.HOUR, (options.expiresAt || Date.now() + c.HOUR) - Date.now());
|
|
131
|
+
if (leaseMs <= 0) throw c.error('REMOTE_EXPIRED');
|
|
132
|
+
ws.send(JSON.stringify({ v: 1, type: 'auth', sealed: c.sealJson(initial.authUp, { credential: binding.credential, deviceId: binding.deviceId, leaseMs, probe: Boolean(options.probe), control: options.control }, initial.transcript) }));
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
if (stage !== 'ready' || message.type !== 'ready') throw c.error('REMOTE_AUTH');
|
|
136
|
+
const ready = c.openJson(keys.authDown, message.sealed, keys.transcript);
|
|
137
|
+
if (!ready.ok || ready.instanceId !== binding.instanceId || !Number.isFinite(ready.remainingMs) || ready.remainingMs <= 0 || ready.remainingMs > c.HOUR || !ready.host) throw c.error('REMOTE_AUTH');
|
|
138
|
+
if (!options.probe && !options.control && (!Number.isInteger(ready.host.port) || ready.host.port < 1 || ready.host.port > 65535 || typeof ready.host.token !== 'string' || !ready.host.token)) throw c.error('REMOTE_AUTH', 'Invalid computer web metadata');
|
|
139
|
+
if (ready.host.connectionInfo && typeof options.onConnectionInfo === 'function') {
|
|
140
|
+
try { Promise.resolve(options.onConnectionInfo(ready.host.connectionInfo)).catch(() => {}); } catch { /* 地址保存失败不使已认证连接失效。 */ }
|
|
141
|
+
}
|
|
142
|
+
settled = true;
|
|
143
|
+
clearTimeout(timer);
|
|
144
|
+
options.signal?.removeEventListener('abort', abort);
|
|
145
|
+
ws.off('message', receive);
|
|
146
|
+
if (options.probe || options.control) { ws.close(); resolve({ host: ready.host }); return; }
|
|
147
|
+
let expiresAt = Math.min(Date.now() + ready.remainingMs, options.expiresAt || Infinity, Date.now() + c.HOUR);
|
|
148
|
+
let expiry;
|
|
149
|
+
const armExpiry = () => {
|
|
150
|
+
clearTimeout(expiry);
|
|
151
|
+
expiry = setTimeout(() => stream.destroy(c.error('REMOTE_EXPIRED', 'Computer access expired')), Math.max(1, expiresAt - Date.now()));
|
|
152
|
+
expiry.unref?.();
|
|
153
|
+
};
|
|
154
|
+
const stream = c.secureStream(ws, c.codecs(keys, false), { onRenewed(remainingMs, requestedExpiry) {
|
|
155
|
+
if (expiresAt <= Date.now()) throw c.error('REMOTE_EXPIRED');
|
|
156
|
+
expiresAt = Math.min(Date.now() + remainingMs, requestedExpiry, Date.now() + c.HOUR);
|
|
157
|
+
if (expiresAt <= Date.now()) throw c.error('REMOTE_EXPIRED');
|
|
158
|
+
armExpiry();
|
|
159
|
+
return expiresAt;
|
|
160
|
+
} });
|
|
161
|
+
armExpiry();
|
|
162
|
+
stream.once('close', () => clearTimeout(expiry));
|
|
163
|
+
resolve({ stream, host: ready.host });
|
|
164
|
+
} catch (err) { fail(err); }
|
|
165
|
+
};
|
|
166
|
+
ws.on('message', receive);
|
|
167
|
+
ws.on('error', () => fail(c.error('REMOTE_CONNECT', 'Computer connection failed')));
|
|
168
|
+
ws.on('close', () => fail(c.error('REMOTE_CONNECT', 'Computer connection closed')));
|
|
169
|
+
} catch (err) { fail(err); }
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
async function probeRemote(binding, route, options = {}) {
|
|
174
|
+
const started = performance.now();
|
|
175
|
+
await openRemoteStream(binding, route, { ...options, probe: true });
|
|
176
|
+
return Math.max(0, Math.round(performance.now() - started));
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
async function callRemoteControl(binding, route, control, options = {}) {
|
|
180
|
+
const result = await openRemoteStream(binding, route, { ...options, control });
|
|
181
|
+
return result.host.controlResult;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
module.exports = { parseInvitation, pairComputer, openRemoteStream, probeRemote, callRemoteControl };
|