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,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 };
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
// 桌面出站隧道的独立助手 RPC;私钥只在本机 IPC 中传递,响应按请求编号关联。
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
const { spawn } = require('node:child_process');
|
|
5
|
+
const { randomUUID } = require('node:crypto');
|
|
6
|
+
const fs = require('node:fs');
|
|
7
|
+
const path = require('node:path');
|
|
8
|
+
const { resolveBinary, platformId, IPC_VERSION } = require('../tailcat/host-process.cjs');
|
|
9
|
+
const MAX_LINE = 64 * 1024;
|
|
10
|
+
|
|
11
|
+
function failure(code) {
|
|
12
|
+
const error = new Error(code);
|
|
13
|
+
error.code = code;
|
|
14
|
+
return error;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function resolveRemoteBinary(options = {}) {
|
|
18
|
+
const exists = options.exists || fs.existsSync;
|
|
19
|
+
const override = (options.env || process.env).DSHM_REMOTE_TUNNEL_HELPER;
|
|
20
|
+
if (typeof override === 'string' && override && exists(override)) return override;
|
|
21
|
+
const root = options.root || path.resolve(__dirname, '../../..');
|
|
22
|
+
const packageRoot = options.packageRoot || path.resolve(__dirname, '../..');
|
|
23
|
+
const platform = options.platformId || platformId();
|
|
24
|
+
if (platform) {
|
|
25
|
+
const name = platform === 'win32-x64' ? 'dsh-tailcat-host.exe' : 'dsh-tailcat-host';
|
|
26
|
+
const bundled = path.join(packageRoot, 'native', platform, name);
|
|
27
|
+
if (exists(bundled)) return bundled;
|
|
28
|
+
if (exists(path.join(root, 'tailcat-host', 'runtime-version.json'))) {
|
|
29
|
+
const development = path.join(root, 'build', 'tailcat-runtime', platform, name);
|
|
30
|
+
if (exists(development)) return development;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return (options.fallback || resolveBinary)();
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function createRemoteTunnelHelper(options = {}) {
|
|
37
|
+
const binary = (options.resolve || resolveRemoteBinary)();
|
|
38
|
+
const launch = options.spawn || spawn;
|
|
39
|
+
const pending = new Map();
|
|
40
|
+
let child;
|
|
41
|
+
let ready;
|
|
42
|
+
let closed = false;
|
|
43
|
+
let unsupported = false;
|
|
44
|
+
let generation = 0;
|
|
45
|
+
|
|
46
|
+
function rejectPending(code) {
|
|
47
|
+
for (const item of pending.values()) {
|
|
48
|
+
clearTimeout(item.timer);
|
|
49
|
+
item.reject(failure(code));
|
|
50
|
+
}
|
|
51
|
+
pending.clear();
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function disable(code) {
|
|
55
|
+
unsupported = code === 'remote-helper-unsupported';
|
|
56
|
+
rejectPending(code);
|
|
57
|
+
const proc = child;
|
|
58
|
+
child = undefined;
|
|
59
|
+
ready = undefined;
|
|
60
|
+
proc?.stdin?.end();
|
|
61
|
+
proc?.kill();
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function handleLine(line) {
|
|
65
|
+
if (Buffer.byteLength(line) > MAX_LINE) return disable('remote-helper-protocol');
|
|
66
|
+
let value;
|
|
67
|
+
try { value = JSON.parse(line); } catch { return; }
|
|
68
|
+
if (!value || typeof value !== 'object') return;
|
|
69
|
+
if (value.event === 'error' && value.code === 'invalid-command') {
|
|
70
|
+
if ([...pending.values()].some(item => item.command === 'remoteCapabilities')) disable('remote-helper-unsupported');
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
if (value.event !== 'remoteResult' || typeof value.requestId !== 'string') return;
|
|
74
|
+
const item = pending.get(value.requestId);
|
|
75
|
+
if (!item) return;
|
|
76
|
+
pending.delete(value.requestId);
|
|
77
|
+
clearTimeout(item.timer);
|
|
78
|
+
if (value.ok === true && value.result && typeof value.result === 'object') item.resolve(value.result);
|
|
79
|
+
else item.reject(failure('remote-helper-request'));
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function send(command, fields = {}, timeoutMs = options.timeoutMs || 15000) {
|
|
83
|
+
if (!child?.stdin?.writable) return Promise.reject(failure('remote-helper-closed'));
|
|
84
|
+
const requestId = randomUUID();
|
|
85
|
+
return new Promise((resolve, reject) => {
|
|
86
|
+
const timer = setTimeout(() => {
|
|
87
|
+
pending.delete(requestId);
|
|
88
|
+
const code = command === 'remoteCapabilities' ? 'remote-helper-unsupported' : 'remote-helper-timeout';
|
|
89
|
+
reject(failure(code));
|
|
90
|
+
// start 可能稍后才返回,排在它后面的单设备清理会收回句柄,不影响其他电脑。
|
|
91
|
+
if (fields.deviceId && child?.stdin?.writable) {
|
|
92
|
+
child.stdin.write(`${JSON.stringify({ command: 'remoteClose', requestId: randomUUID(), deviceId: fields.deviceId })}\n`);
|
|
93
|
+
} else disable(code);
|
|
94
|
+
}, timeoutMs);
|
|
95
|
+
pending.set(requestId, { command, resolve, reject, timer });
|
|
96
|
+
const text = JSON.stringify({ ...fields, command, requestId });
|
|
97
|
+
if (Buffer.byteLength(text) > MAX_LINE) {
|
|
98
|
+
clearTimeout(timer);
|
|
99
|
+
pending.delete(requestId);
|
|
100
|
+
reject(failure('remote-helper-request'));
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
child.stdin.write(`${text}\n`, error => {
|
|
104
|
+
if (error && pending.has(requestId)) disable('remote-helper-closed');
|
|
105
|
+
});
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function start() {
|
|
110
|
+
if (closed) return Promise.reject(failure('remote-helper-closed'));
|
|
111
|
+
if (!binary) return Promise.reject(failure('remote-helper-unavailable'));
|
|
112
|
+
if (unsupported) return Promise.reject(failure('remote-helper-unsupported'));
|
|
113
|
+
if (ready) return ready;
|
|
114
|
+
let proc;
|
|
115
|
+
try { proc = launch(binary, [], { stdio: ['pipe', 'pipe', 'ignore'], windowsHide: true }); }
|
|
116
|
+
catch { return Promise.reject(failure('remote-helper-unavailable')); }
|
|
117
|
+
child = proc;
|
|
118
|
+
generation += 1;
|
|
119
|
+
let buffer = '';
|
|
120
|
+
proc.on('error', () => { if (child === proc) disable('remote-helper-unavailable'); });
|
|
121
|
+
proc.stdin.on('error', () => { if (child === proc) disable('remote-helper-closed'); });
|
|
122
|
+
proc.stdout.setEncoding('utf8');
|
|
123
|
+
proc.stdout.on('data', chunk => {
|
|
124
|
+
if (child !== proc) return;
|
|
125
|
+
buffer += chunk;
|
|
126
|
+
for (let at = buffer.indexOf('\n'); at >= 0; at = buffer.indexOf('\n')) {
|
|
127
|
+
const line = buffer.slice(0, at);
|
|
128
|
+
buffer = buffer.slice(at + 1);
|
|
129
|
+
handleLine(line);
|
|
130
|
+
}
|
|
131
|
+
if (Buffer.byteLength(buffer) > MAX_LINE) disable('remote-helper-protocol');
|
|
132
|
+
});
|
|
133
|
+
proc.on('exit', () => { if (child === proc) disable('remote-helper-closed'); });
|
|
134
|
+
proc.stdin.write(`${JSON.stringify({ version: IPC_VERSION, localPort: 19449, name: 'remote-computer-client', state: null, allowedClients: [] })}\n`);
|
|
135
|
+
ready = send('remoteCapabilities', {}, options.capabilityTimeoutMs || 3000).then(result => {
|
|
136
|
+
if (result.version !== 1 || !result.tailcat || !result.p2p) {
|
|
137
|
+
disable('remote-helper-unsupported');
|
|
138
|
+
throw failure('remote-helper-unsupported');
|
|
139
|
+
}
|
|
140
|
+
return result;
|
|
141
|
+
});
|
|
142
|
+
return ready;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
return {
|
|
146
|
+
status: () => ({ available: Boolean(binary) && !unsupported && !closed, running: Boolean(child), generation }),
|
|
147
|
+
async request(command, fields = {}) { await start(); return send(command, fields); },
|
|
148
|
+
async closeDevice(deviceId) {
|
|
149
|
+
if (child && !closed && !unsupported) await send('remoteClose', { deviceId });
|
|
150
|
+
},
|
|
151
|
+
async close() {
|
|
152
|
+
if (closed) return;
|
|
153
|
+
closed = true;
|
|
154
|
+
rejectPending('remote-helper-closed');
|
|
155
|
+
const proc = child;
|
|
156
|
+
child = undefined;
|
|
157
|
+
if (!proc || proc.exitCode !== null) return;
|
|
158
|
+
await new Promise(resolve => {
|
|
159
|
+
const timer = setTimeout(() => { proc.kill(); resolve(); }, 3000);
|
|
160
|
+
proc.once('exit', () => { clearTimeout(timer); resolve(); });
|
|
161
|
+
proc.stdin.end();
|
|
162
|
+
});
|
|
163
|
+
},
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
module.exports = { createRemoteTunnelHelper, resolveRemoteBinary };
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
// 远程电脑的 Tailcat/P2P 候选:通过已认证控制通道会合,每台绑定独立持有私钥与句柄。
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
const { createRemoteTunnelHelper } = require('./tunnel-helper.cjs');
|
|
5
|
+
const TERMINAL_ERRORS = new Set(['REMOTE_REVOKED', 'REMOTE_EXPIRED']);
|
|
6
|
+
const list = value => [...new Set((Array.isArray(value) ? value : []).filter(item => typeof item === 'string' && item.length <= 256))].sort();
|
|
7
|
+
const same = (a, b) => JSON.stringify(list(a)) === JSON.stringify(list(b));
|
|
8
|
+
const idOf = binding => binding.id || binding.instanceId;
|
|
9
|
+
|
|
10
|
+
function localRoute(url, channel) {
|
|
11
|
+
try {
|
|
12
|
+
const parsed = new URL(url);
|
|
13
|
+
if (parsed.protocol !== 'http:' || parsed.hostname !== '127.0.0.1' || !parsed.port || parsed.username || parsed.password
|
|
14
|
+
|| parsed.pathname !== '/' || parsed.search || parsed.hash) return null;
|
|
15
|
+
return { url: parsed.origin, channel };
|
|
16
|
+
} catch { return null; }
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function createRemoteTunnels({ store, transport, helper = createRemoteTunnelHelper() }) {
|
|
20
|
+
const sessions = new Map();
|
|
21
|
+
const jobs = new Map();
|
|
22
|
+
const versions = new Map();
|
|
23
|
+
let closed = false;
|
|
24
|
+
const generation = () => helper.status?.().generation || 0;
|
|
25
|
+
|
|
26
|
+
function serialized(id, action) {
|
|
27
|
+
const previous = jobs.get(id) || Promise.resolve();
|
|
28
|
+
const next = previous.catch(() => {}).then(action);
|
|
29
|
+
jobs.set(id, next);
|
|
30
|
+
void next.finally(() => { if (jobs.get(id) === next) jobs.delete(id); }).catch(() => {});
|
|
31
|
+
return next;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async function keysFor(binding) {
|
|
35
|
+
const id = idOf(binding);
|
|
36
|
+
const stored = await store.get(id) || binding;
|
|
37
|
+
const keys = { ...(stored.tunnelKeys || {}) };
|
|
38
|
+
const tailcat = await helper.request('remoteTailcatKey', { deviceId: id, privateKey: keys.tailcatPrivateKey || '' });
|
|
39
|
+
keys.tailcatPrivateKey = tailcat.privateKey;
|
|
40
|
+
if (!keys.p2pPrivateKey || !keys.p2pPublicKey) {
|
|
41
|
+
const pair = await helper.request('remoteP2PKeys', { deviceId: id, p2pPrivateKey: keys.p2pPrivateKey || '' });
|
|
42
|
+
keys.p2pPrivateKey = pair.private;
|
|
43
|
+
keys.p2pPublicKey = pair.public;
|
|
44
|
+
}
|
|
45
|
+
if (!keys.tailcatPrivateKey || !keys.p2pPrivateKey || !keys.p2pPublicKey || !tailcat.publicKey) throw new Error('remote-helper-keys');
|
|
46
|
+
if (JSON.stringify(keys) !== JSON.stringify(stored.tunnelKeys || {})) {
|
|
47
|
+
if (typeof store.update === 'function') await store.update(id, () => ({ tunnelKeys: keys }));
|
|
48
|
+
else await store.put({ ...stored, id, tunnelKeys: keys });
|
|
49
|
+
}
|
|
50
|
+
return { keys, tailcatPublicKey: tailcat.publicKey };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async function control(binding, route, payload) {
|
|
54
|
+
const all = (binding.routes || []).filter(candidate => candidate && typeof candidate.url === 'string');
|
|
55
|
+
const choices = route ? [route] : [...all.slice(0, 1), ...all.filter(item => item.channel === 'relay'), ...all.slice(1)]
|
|
56
|
+
.filter((item, index, rows) => rows.findIndex(other => other.url === item.url) === index);
|
|
57
|
+
for (let index = 0; index < choices.length; index += 2) {
|
|
58
|
+
const batch = choices.slice(index, index + 2).map(async candidate => {
|
|
59
|
+
const result = await transport.callRemoteControl(binding, candidate, payload, { timeoutMs: 15000 });
|
|
60
|
+
return { result, route: candidate };
|
|
61
|
+
});
|
|
62
|
+
const results = await Promise.allSettled(batch);
|
|
63
|
+
const terminal = results.find(item => item.status === 'rejected' && TERMINAL_ERRORS.has(item.reason?.code));
|
|
64
|
+
if (terminal) throw terminal.reason;
|
|
65
|
+
const success = results.find(item => item.status === 'fulfilled');
|
|
66
|
+
if (success) return success.value;
|
|
67
|
+
}
|
|
68
|
+
throw new Error('remote-control-unavailable');
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
async function stopDevice(id) {
|
|
72
|
+
sessions.delete(id);
|
|
73
|
+
try { await helper.closeDevice(id); } catch { /* 已退出的助手没有遗留句柄。 */ }
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async function initialize(binding, route, version) {
|
|
77
|
+
const id = idOf(binding);
|
|
78
|
+
let entry;
|
|
79
|
+
try {
|
|
80
|
+
const { keys, tailcatPublicKey } = await keysFor(binding);
|
|
81
|
+
if (closed || versions.get(id) !== version) return [];
|
|
82
|
+
const payload = { op: 'tunnels', tailcatPublicKey, p2p: { publicKey: keys.p2pPublicKey, candidates: [], localCandidates: [] } };
|
|
83
|
+
const first = await control(binding, route, payload);
|
|
84
|
+
entry = { routes: [], generation: generation(), controlRoute: first.route, publicKey: keys.p2pPublicKey,
|
|
85
|
+
tailcatPublicKey, candidates: [], localCandidates: [] };
|
|
86
|
+
const tailcat = first.result?.tailcat;
|
|
87
|
+
if (tailcat?.address && Number.isInteger(tailcat.port)) {
|
|
88
|
+
try {
|
|
89
|
+
const started = await helper.request('remoteTailcatStart', { deviceId: id, privateKey: keys.tailcatPrivateKey,
|
|
90
|
+
address: tailcat.address, remotePort: tailcat.port });
|
|
91
|
+
const candidate = localRoute(`http://127.0.0.1:${started.port}`, 'tunnel');
|
|
92
|
+
if (candidate) entry.routes.push(candidate);
|
|
93
|
+
} catch { /* P2P 与基础线路仍可独立使用。 */ }
|
|
94
|
+
}
|
|
95
|
+
const peer = first.result?.p2p;
|
|
96
|
+
if (peer?.publicKey && Number.isInteger(peer.port)) {
|
|
97
|
+
try {
|
|
98
|
+
const started = await helper.request('remoteP2PStart', { deviceId: id, p2pPrivateKey: keys.p2pPrivateKey,
|
|
99
|
+
p2pPeerKey: peer.publicKey, p2pPeerPublic: list(peer.candidates), p2pPeerLocal: list(peer.localCandidates), p2pListenPort: peer.port });
|
|
100
|
+
const candidate = localRoute(started.url, 'p2p');
|
|
101
|
+
if (candidate) {
|
|
102
|
+
const local = await helper.request('remoteP2PCandidates', { deviceId: id });
|
|
103
|
+
entry.candidates = list(local.candidates || started.candidates);
|
|
104
|
+
entry.localCandidates = list(local.localCandidates);
|
|
105
|
+
const second = await control(binding, first.route, { op: 'tunnels.refresh', tailcatPublicKey,
|
|
106
|
+
p2p: { publicKey: keys.p2pPublicKey, candidates: entry.candidates, localCandidates: entry.localCandidates } });
|
|
107
|
+
if (second.result?.p2p?.publicKey !== peer.publicKey) throw new Error('remote-p2p-identity-changed');
|
|
108
|
+
// A 更新接收端后会主动打向这块 B socket;保留 B 句柄,让数据面学习 A 的当前地址。
|
|
109
|
+
entry.routes.push(candidate);
|
|
110
|
+
}
|
|
111
|
+
} catch (error) {
|
|
112
|
+
try { await helper.request('remoteP2PStop', { deviceId: id }); } catch { /* 助手退出即清理。 */ }
|
|
113
|
+
if (TERMINAL_ERRORS.has(error?.code)) throw error;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
if (closed || versions.get(id) !== version || entry.generation !== generation()) {
|
|
117
|
+
await stopDevice(id);
|
|
118
|
+
return [];
|
|
119
|
+
}
|
|
120
|
+
sessions.set(id, entry);
|
|
121
|
+
return entry.routes.map(item => ({ ...item }));
|
|
122
|
+
} catch (error) {
|
|
123
|
+
await stopDevice(id);
|
|
124
|
+
if (TERMINAL_ERRORS.has(error?.code)) throw error;
|
|
125
|
+
return [];
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
async function routesFor(binding) {
|
|
130
|
+
const id = idOf(binding);
|
|
131
|
+
return serialized(id, async () => {
|
|
132
|
+
if (closed) return [];
|
|
133
|
+
const current = sessions.get(id);
|
|
134
|
+
if (current && current.generation === generation() && helper.status?.().running !== false) {
|
|
135
|
+
if (current.routes.some(item => item.channel === 'p2p')) {
|
|
136
|
+
try {
|
|
137
|
+
const local = await helper.request('remoteP2PCandidates', { deviceId: id });
|
|
138
|
+
if (!same(local.candidates, current.candidates) || !same(local.localCandidates, current.localCandidates)) {
|
|
139
|
+
const candidates = list(local.candidates);
|
|
140
|
+
const localCandidates = list(local.localCandidates);
|
|
141
|
+
await control(binding, current.controlRoute, { op: 'tunnels.refresh', tailcatPublicKey: current.tailcatPublicKey,
|
|
142
|
+
p2p: { publicKey: current.publicKey, candidates, localCandidates } });
|
|
143
|
+
current.candidates = candidates;
|
|
144
|
+
current.localCandidates = localCandidates;
|
|
145
|
+
}
|
|
146
|
+
} catch (error) {
|
|
147
|
+
if (TERMINAL_ERRORS.has(error?.code)) {
|
|
148
|
+
await stopDevice(id);
|
|
149
|
+
throw error;
|
|
150
|
+
}
|
|
151
|
+
current.routes = current.routes.filter(item => item.channel !== 'p2p');
|
|
152
|
+
try { await helper.request('remoteP2PStop', { deviceId: id }); } catch { /* 已退出。 */ }
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
return current.routes.map(item => ({ ...item }));
|
|
156
|
+
}
|
|
157
|
+
await stopDevice(id);
|
|
158
|
+
const version = versions.get(id) || 0;
|
|
159
|
+
versions.set(id, version);
|
|
160
|
+
return initialize(binding, undefined, version);
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
return {
|
|
165
|
+
routesFor,
|
|
166
|
+
refresh(binding, { route } = {}) {
|
|
167
|
+
const id = idOf(binding);
|
|
168
|
+
const version = (versions.get(id) || 0) + 1;
|
|
169
|
+
versions.set(id, version);
|
|
170
|
+
return serialized(id, async () => {
|
|
171
|
+
await stopDevice(id);
|
|
172
|
+
if (closed || versions.get(id) !== version) return [];
|
|
173
|
+
return initialize(binding, route, version);
|
|
174
|
+
});
|
|
175
|
+
},
|
|
176
|
+
close(id) {
|
|
177
|
+
versions.set(id, (versions.get(id) || 0) + 1);
|
|
178
|
+
return serialized(id, () => stopDevice(id));
|
|
179
|
+
},
|
|
180
|
+
async closeAll() {
|
|
181
|
+
closed = true;
|
|
182
|
+
for (const id of new Set([...sessions.keys(), ...jobs.keys()])) versions.set(id, (versions.get(id) || 0) + 1);
|
|
183
|
+
await Promise.all([...jobs.values()].map(job => job.catch(() => {})));
|
|
184
|
+
sessions.clear();
|
|
185
|
+
await helper.close();
|
|
186
|
+
},
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
module.exports = { createRemoteTunnels };
|
package/lib/routes/mobile-api.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
'use strict';
|
|
2
|
+
// 电脑间配对和网页隧道使用独立加密认证,不复用手机的全权凭据。
|
|
2
3
|
|
|
3
4
|
/**
|
|
5
|
+
* 调试操作记录仅在手机复制,不挂载回传路由。
|
|
4
6
|
* 移动端 API 路由表(`/api/mobile/v1/*`)。
|
|
5
7
|
*
|
|
6
8
|
* 它本身没有逻辑,绝大部分是「路径 → 已写好的 handler」的纯映射,只有 status /
|
|
@@ -88,7 +90,6 @@ const pluginCatalog = require('../mobile/plugin-catalog.js');
|
|
|
88
90
|
const { createRelayControlHandlers } = require('../mobile/relay-control.js');
|
|
89
91
|
const uploads = require('../mobile/uploads.js');
|
|
90
92
|
const inboxClean = require('../mobile/inbox-clean.js');
|
|
91
|
-
const perfTrace = require('../mobile/perf-trace.js');
|
|
92
93
|
// 过程播报开关(读 / 写同一条路径,由 req.method 分派)。默认关,见那个文件头。
|
|
93
94
|
const narration = require('../mobile/narration.js');
|
|
94
95
|
// 通知按事件类型分级(GET 读 / PUT 整表替换,按设备分桶)。见那个文件头。
|
|
@@ -413,7 +414,6 @@ function registerMobileRoutes(deps) {
|
|
|
413
414
|
// 密钥时那头静默忽略——这条路由照常回 ok,「推没推成」不是 App 要操心的事。
|
|
414
415
|
// 判据(要不要收这个令牌)与配对同一把锁:guarded 已核过设备身份。
|
|
415
416
|
route('/api/mobile/v1/push-token', pushNotifyRoute.createPushTokenHandler({ pushNotify: deps.pushNotify }))
|
|
416
|
-
route('/api/mobile/v1/perf-trace', perfTrace.handlePerfTrace)
|
|
417
417
|
route('/api/mobile/v1/session', sessions.handleSession)
|
|
418
418
|
route('/api/mobile/v1/session/messages', sessions.handleMessages)
|
|
419
419
|
// 一步的过程详情:清单只带一行摘要,点开某一步才来这里取参数 / 输出 / diff / 思考全文。
|
|
@@ -805,6 +805,11 @@ function registerMobileRoutes(deps) {
|
|
|
805
805
|
// (`mode=webapp` 那一档才允许拨回宿主自己的 web 端口)。
|
|
806
806
|
route('/api/mobile/v1/host-web', deps.hostWeb)
|
|
807
807
|
|
|
808
|
+
if (deps.remoteComputers) {
|
|
809
|
+
registerRoute({ kind: 'exact', path: '/api/mobile/v1/remote-computers/pair', handler: deps.remoteComputers.handlePair })
|
|
810
|
+
registerUpgradeRoute({ path: '/api/mobile/v1/remote-computers/tunnel', handler: deps.remoteComputers.handleUpgrade })
|
|
811
|
+
}
|
|
812
|
+
|
|
808
813
|
// 内置浏览器预览(App 侧「点 localhost 链接在内置浏览器里打开」的宿主端一半)。
|
|
809
814
|
//
|
|
810
815
|
// 这是一条 **WebSocket 升级**路由,不是普通 HTTP 路由:手机原生模块按端口在环回监听、
|