dsh-mobile-plugin 0.5.52 → 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.
@@ -1,4 +1,5 @@
1
1
  'use strict';
2
+ // 电脑加密配对与隧道透传仅按精确路径放行,身份由上游独立协议校验。
2
3
 
3
4
  /**
4
5
  * 局域网直连代理:手机在同一个 Wi-Fi 下直接访问
@@ -424,7 +425,9 @@ function createLanProxy(opts) {
424
425
  * 永久留在闭包里,几小时后宿主整进程 OOM。
425
426
  */
426
427
  function handleUpgrade(req, socket, head) {
427
- if (!authorized(req)) {
428
+ const remoteComputer = req.method === 'GET'
429
+ && String(req.url || '').split('?')[0] === '/api/mobile/v1/remote-computers/tunnel';
430
+ if (!remoteComputer && !authorized(req)) {
428
431
  socket.write('HTTP/1.1 401 Unauthorized\r\nConnection: close\r\n\r\n');
429
432
  socket.destroy();
430
433
  return;
@@ -498,10 +501,10 @@ function createLanProxy(opts) {
498
501
  fail(status, `上游拒绝了这次升级(${status})`);
499
502
  });
500
503
 
501
- up.on('message', (data) => {
504
+ up.on('message', (data, isBinary) => {
502
505
  const chunk = Buffer.isBuffer(data) ? data : Buffer.from(data);
503
506
  if (phoneWs) {
504
- if (phoneWs.readyState === WebSocket.OPEN) phoneWs.send(chunk);
507
+ if (phoneWs.readyState === WebSocket.OPEN) phoneWs.send(chunk, { binary: isBinary });
505
508
  return;
506
509
  }
507
510
  pendingBytes += chunk.length;
@@ -509,7 +512,7 @@ function createLanProxy(opts) {
509
512
  fail(502, '上游数据积压超过上限');
510
513
  return;
511
514
  }
512
- pending.push(chunk);
515
+ pending.push({ chunk, isBinary });
513
516
  });
514
517
 
515
518
  up.on('open', () => {
@@ -525,15 +528,15 @@ function createLanProxy(opts) {
525
528
  phoneWs = ws;
526
529
  try {
527
530
  // 先补发暂存、再放行上游:暂停期间挂监听不会丢,恢复才一次性派发。
528
- for (const chunk of pending) {
531
+ for (const entry of pending) {
529
532
  if (ws.readyState !== WebSocket.OPEN) break;
530
- ws.send(chunk);
533
+ ws.send(entry.chunk, { binary: entry.isBinary });
531
534
  }
532
535
  dropPending();
533
536
  up.resume();
534
537
  } catch { /* 已断开 */ }
535
- ws.on('message', (data) => {
536
- if (up.readyState === WebSocket.OPEN) up.send(data);
538
+ ws.on('message', (data, isBinary) => {
539
+ if (up.readyState === WebSocket.OPEN) up.send(data, { binary: isBinary });
537
540
  });
538
541
  ws.on('close', () => { try { up.close(); } catch { /* ignore */ } });
539
542
  ws.on('error', () => { try { up.terminate(); } catch { /* ignore */ } });
@@ -770,6 +773,10 @@ function createLanProxy(opts) {
770
773
  proxyToUpstream(req, res);
771
774
  return;
772
775
  }
776
+ if (req.method === 'POST' && url.pathname === '/api/mobile/v1/remote-computers/pair') {
777
+ proxyToUpstream(req, res);
778
+ return;
779
+ }
773
780
  const auth = authOutcome(req);
774
781
  if (!auth.ok) {
775
782
  sendUnauthorized(res, auth.reason);
@@ -0,0 +1,118 @@
1
+ /** 远程网页的只读租期提示与主文档流式脚本注入。 */
2
+ 'use strict';
3
+
4
+ const { Transform } = require('node:stream');
5
+
6
+ const SCRIPT_TAG = Buffer.from('<script src="/__dsh_remote_notice.js" defer></script>');
7
+ const TEXT = {
8
+ 'zh-Hans': ['访问即将到期,请返回本机插件续期。', '本次访问已到期,请返回本机插件重新打开。', '无法确认访问状态,请返回本机插件检查。'],
9
+ 'zh-Hant': ['存取即將到期,請返回本機外掛續期。', '本次存取已到期,請返回本機外掛重新開啟。', '無法確認存取狀態,請返回本機外掛檢查。'],
10
+ en: ['Access expires soon. Return to the local plugin to renew it.', 'This visit has expired. Return to the local plugin to open it again.', 'Access status could not be checked. Return to the local plugin to check it.'],
11
+ ja: ['アクセスがまもなく終了します。このパソコンのプラグインで延長してください。', 'アクセス期限が切れました。このパソコンのプラグインから開き直してください。', 'アクセス状態を確認できません。このパソコンのプラグインで確認してください。'],
12
+ ko: ['접속이 곧 만료됩니다. 이 컴퓨터의 플러그인으로 돌아가 연장하세요.', '접속이 만료되었습니다. 이 컴퓨터의 플러그인에서 다시 열어 주세요.', '접속 상태를 확인할 수 없습니다. 이 컴퓨터의 플러그인에서 확인하세요.'],
13
+ de: ['Der Zugriff läuft bald ab. Verlängere ihn im lokalen Plugin.', 'Dieser Zugriff ist abgelaufen. Öffne ihn im lokalen Plugin erneut.', 'Der Zugriffsstatus konnte nicht geprüft werden. Prüfe ihn im lokalen Plugin.'],
14
+ es: ['El acceso caduca pronto. Vuelve al complemento local para renovarlo.', 'Este acceso ha caducado. Vuelve al complemento local para abrirlo de nuevo.', 'No se pudo comprobar el acceso. Revísalo en el complemento local.'],
15
+ fr: ['L’accès expire bientôt. Revenez au plugin local pour le renouveler.', 'Cet accès a expiré. Revenez au plugin local pour le rouvrir.', 'Impossible de vérifier l’accès. Vérifiez-le dans le plugin local.'],
16
+ pt: ['O acesso expira em breve. Volte ao plugin local para renovar.', 'Este acesso expirou. Volte ao plugin local para abrir novamente.', 'Não foi possível verificar o acesso. Confira no plugin local.'],
17
+ ru: ['Доступ скоро истечёт. Продлите его в локальном плагине.', 'Срок доступа истёк. Откройте его заново в локальном плагине.', 'Не удалось проверить доступ. Проверьте его в локальном плагине.'],
18
+ };
19
+
20
+ function browserNotice(text) {
21
+ if (window.top !== window || document.getElementById('dsh-remote-lease-notice')) return;
22
+ let lease = null;
23
+ let failed = false;
24
+ let pending = false;
25
+ let box = null;
26
+ let stopped = false;
27
+ let timer;
28
+ const monotonicNow = () => performance.now();
29
+
30
+ function language() {
31
+ const tag = String(document.documentElement.lang || navigator.language || 'en').replace(/_/g, '-').toLowerCase();
32
+ const parts = tag.split('-');
33
+ if (parts[0] === 'zh') return parts.some((part) => ['hant', 'tw', 'hk', 'mo'].includes(part)) ? 'zh-Hant' : 'zh-Hans';
34
+ return text[parts[0]] ? parts[0] : 'en';
35
+ }
36
+
37
+ function render() {
38
+ const remaining = lease ? lease.expiresAt - lease.serverNow - Math.max(0, monotonicNow() - lease.sampledAt) : null;
39
+ const message = remaining !== null && remaining <= 0 ? 1 : failed ? 2 : remaining !== null && remaining <= 5 * 60 * 1000 ? 0 : -1;
40
+ if (message < 0) { if (box) box.hidden = true; return; }
41
+ if (!box) {
42
+ box = document.createElement('div');
43
+ box.id = 'dsh-remote-lease-notice';
44
+ box.setAttribute('role', 'status');
45
+ box.setAttribute('aria-live', 'polite');
46
+ Object.assign(box.style, {
47
+ position: 'fixed', right: '16px', bottom: '16px', zIndex: '2147483001',
48
+ boxSizing: 'border-box', maxWidth: 'min(360px, calc(100vw - 32px))',
49
+ padding: '8px 10px', border: '.5px solid var(--dsw-alias-settings-card-stroke, GrayText)',
50
+ borderRadius: 'var(--dsw-radius-md, 8px)', background: 'var(--dsw-alias-settings-card-fill, Canvas)',
51
+ color: 'var(--dsw-alias-label-primary, CanvasText)', font: 'inherit', fontSize: '12px', lineHeight: '18px',
52
+ });
53
+ document.body.appendChild(box);
54
+ }
55
+ box.hidden = false;
56
+ box.textContent = text[language()][message];
57
+ }
58
+
59
+ async function poll() {
60
+ if (stopped || pending || document.hidden) return;
61
+ pending = true;
62
+ try {
63
+ const response = await fetch('/__dsh_remote_status', { credentials: 'same-origin', cache: 'no-store', headers: { accept: 'application/json' } });
64
+ if (!response.ok) throw new Error('status');
65
+ const status = await response.json();
66
+ if (!Number.isFinite(status.expiresAt) || !Number.isFinite(status.serverNow)) throw new Error('status');
67
+ lease = status.expiresAt > 0 ? { expiresAt: status.expiresAt, serverNow: status.serverNow, sampledAt: monotonicNow() } : null;
68
+ failed = false;
69
+ } catch {
70
+ failed = true;
71
+ } finally {
72
+ pending = false;
73
+ if (!stopped) render();
74
+ }
75
+ }
76
+
77
+ function tick() { if (!document.hidden) { render(); void poll(); } }
78
+ function stop() { stopped = true; clearInterval(timer); document.removeEventListener('visibilitychange', tick); }
79
+ window.addEventListener('pagehide', stop, { once: true });
80
+ document.addEventListener('visibilitychange', tick);
81
+ timer = setInterval(tick, 30 * 1000);
82
+ void poll();
83
+ }
84
+
85
+ function noticeScript() {
86
+ return `(${browserNotice.toString()})(${JSON.stringify(TEXT)});`;
87
+ }
88
+
89
+ /** 仅保留开头少量字节定位 head;剩余文档直接透传,保留字节与背压。 */
90
+ function createNoticeTransform() {
91
+ let prefix = Buffer.alloc(0);
92
+ let inserted = false;
93
+ const prefixLimit = 4096;
94
+ return new Transform({
95
+ transform(chunk, encoding, callback) {
96
+ if (inserted) { callback(null, chunk); return; }
97
+ const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding);
98
+ prefix = Buffer.concat([prefix, bytes]);
99
+ const match = /<head(?:\s[^>]*)?>/i.exec(prefix.toString('latin1'));
100
+ if (match) {
101
+ const end = match.index + match[0].length;
102
+ this.push(prefix.subarray(0, end));
103
+ this.push(SCRIPT_TAG);
104
+ this.push(prefix.subarray(end));
105
+ prefix = Buffer.alloc(0);
106
+ inserted = true;
107
+ } else if (prefix.length >= prefixLimit) {
108
+ this.push(prefix);
109
+ prefix = Buffer.alloc(0);
110
+ inserted = true;
111
+ }
112
+ callback();
113
+ },
114
+ flush(callback) { if (prefix.length) this.push(prefix); callback(); },
115
+ });
116
+ }
117
+
118
+ module.exports = { noticeScript, createNoticeTransform };
@@ -0,0 +1,212 @@
1
+ // 远程电脑绑定、浏览器访问租期与每设备线路状态。
2
+ 'use strict';
3
+
4
+ const { createLocalGateway, LEASE_MS } = require('./local.cjs');
5
+ const { createRemoteRouter } = require('./router.cjs');
6
+ const { createNetworkMonitor } = require('./network.cjs');
7
+ const { safeRoutes } = require('./local-headers.cjs');
8
+
9
+ function createRemoteController({ store, transport, name, tunnels }) {
10
+ const devices = new Map();
11
+ let closed = false;
12
+ let heartbeatAt = 0;
13
+
14
+ function expiredError() { return Object.assign(new Error('本次访问已到期,请重新打开'), { code: 'REMOTE_EXPIRED' }); }
15
+ function safeError(error) {
16
+ const messages = {
17
+ REMOTE_REVOKED: '这台电脑已解除本机的绑定,请重新绑定。',
18
+ REMOTE_EXPIRED: '远程授权已到期,请重新绑定。',
19
+ REMOTE_AUTH: '远程电脑身份验证失败。',
20
+ REMOTE_TIMEOUT: '远程连接超时。',
21
+ REMOTE_CONNECT: '远程电脑暂时离线。',
22
+ };
23
+ return messages[error?.code] || '远程连接暂时不可用。';
24
+ }
25
+
26
+ function routerFor(item) {
27
+ const router = createRemoteRouter({ binding: item.binding, transport, tunnels,
28
+ onError: (error) => { if (!closed && item.router === router) fault(item, error); },
29
+ async onRoutes(routes) {
30
+ if (closed || item.router !== router) return;
31
+ if (store.update) await store.update(item.binding.id, () => ({ routes }));
32
+ else await store.put({ ...await store.get(item.binding.id), routes });
33
+ if (!closed && item.router === router) item.binding.routes = routes;
34
+ },
35
+ });
36
+ return router;
37
+ }
38
+
39
+ function fault(item, error) {
40
+ item.lastError = safeError(error); item.lastErrorCode = error?.code || 'REMOTE_CONNECT';
41
+ if (error?.code === 'REMOTE_REVOKED') {
42
+ item.state = 'revoked'; item.gateway?.close(); item.gateway = null; item.router.close();
43
+ } else if (error?.code === 'REMOTE_EXPIRED') {
44
+ item.state = 'expired'; item.gateway?.close(); item.gateway = null; item.router.close();
45
+ } else if (item.state !== 'expired' && item.state !== 'revoked') item.state = 'offline';
46
+ }
47
+
48
+ function ensure(binding) {
49
+ const id = String(binding.id || binding.instanceId);
50
+ let item = devices.get(id);
51
+ if (item) return item;
52
+ item = { binding: { ...binding, id }, mode: binding.mode || 'auto', state: 'idle', expiresAt: null, lastError: '', gateway: null, opening: null };
53
+ item.router = routerFor(item);
54
+ devices.set(id, item);
55
+ return item;
56
+ }
57
+
58
+ async function find(id) {
59
+ if (closed) throw new Error('远程电脑管理已关闭');
60
+ const binding = await store.get(String(id));
61
+ if (closed) throw new Error('远程电脑管理已关闭');
62
+ if (!binding) throw Object.assign(new Error('找不到这台远程电脑'), { code: 'REMOTE_NOT_FOUND' });
63
+ return ensure(binding);
64
+ }
65
+
66
+ function expire(item) {
67
+ item.gateway?.close(); item.gateway = null;
68
+ item.state = 'expired'; item.lastError = ''; item.lastErrorCode = ''; item.router.close();
69
+ void Promise.resolve(tunnels?.close?.(item.binding.id)).catch(() => {});
70
+ }
71
+
72
+ function check(item) {
73
+ if (item.gateway && Date.now() >= item.expiresAt) { expire(item); return false; }
74
+ return Boolean(item.gateway);
75
+ }
76
+
77
+ function row(item) {
78
+ check(item);
79
+ const snapshot = item.router.snapshot();
80
+ const selected = safeRoutes(snapshot.route ? [snapshot.route] : [])[0];
81
+ return {
82
+ id: item.binding.id, name: String(item.binding.name || item.binding.instanceId), instanceId: item.binding.instanceId,
83
+ mode: item.mode, channel: selected?.channel || null, url: selected?.url || null,
84
+ latencyMs: snapshot.latencyMs, state: item.state, expiresAt: item.expiresAt,
85
+ ...(item.lastError ? { lastError: item.lastError, lastErrorCode: item.lastErrorCode || 'REMOTE_CONNECT' } : {}), routes: safeRoutes(snapshot.routes),
86
+ };
87
+ }
88
+
89
+ async function stopItem(item) {
90
+ item.gateway?.close(); item.gateway = null;
91
+ item.router.close();
92
+ item.state = 'idle'; item.expiresAt = null; item.lastError = ''; item.lastErrorCode = '';
93
+ await tunnels?.close?.(item.binding.id);
94
+ item.router = routerFor(item);
95
+ }
96
+
97
+ const network = createNetworkMonitor({
98
+ async onTick(time) {
99
+ const active = [...devices.values()].filter((item) => check(item));
100
+ if (time - heartbeatAt < 30000) return;
101
+ heartbeatAt = time;
102
+ void Promise.all(active.map(async (item) => {
103
+ try { await item.router.probe(); if (check(item)) { item.state = 'connected'; item.lastError = ''; item.lastErrorCode = ''; } } catch (error) { fault(item, error); }
104
+ })).catch(() => {});
105
+ },
106
+ async onChange() {
107
+ await Promise.all([...devices.values()].filter((item) => check(item)).map(async (item) => {
108
+ item.gateway.disconnect();
109
+ try { await item.router.networkChanged(); if (check(item)) { item.state = 'connected'; item.lastError = ''; item.lastErrorCode = ''; } } catch (error) { fault(item, error); }
110
+ }));
111
+ },
112
+ });
113
+
114
+ async function open(id) {
115
+ const item = await find(id);
116
+ if (item.opening) return item.opening;
117
+ if (check(item)) return item.gateway.openLink();
118
+ item.router.close(); item.router = routerFor(item);
119
+ const router = item.router;
120
+ let gateway;
121
+ const current = () => !closed && item.router === router && item.gateway === gateway;
122
+ item.opening = (async () => {
123
+ item.state = 'connecting'; item.lastError = ''; item.lastErrorCode = '';
124
+ item.expiresAt = Date.now() + LEASE_MS;
125
+ gateway = createLocalGateway({
126
+ expiresAt: item.expiresAt,
127
+ connect: async () => {
128
+ if (!current() || !check(item)) throw expiredError();
129
+ try {
130
+ const connection = await router.open({ expiresAt: item.expiresAt });
131
+ if (!current() || !check(item)) { connection.stream.destroy(); throw expiredError(); }
132
+ item.state = 'connected'; item.lastError = ''; item.lastErrorCode = '';
133
+ return connection;
134
+ } catch (error) { if (current()) fault(item, error); throw error; }
135
+ },
136
+ onExpire: () => { if (current()) expire(item); },
137
+ onError: (error) => { if (current()) { router.failure(error); fault(item, error); } },
138
+ });
139
+ item.gateway = gateway;
140
+ try {
141
+ const result = await gateway.start();
142
+ if (!current()) { gateway.close(); throw expiredError(); }
143
+ item.state = 'connecting';
144
+ void router.probe().then(() => { if (current() && check(item)) item.state = 'connected'; }).catch((error) => { if (current()) fault(item, error); });
145
+ return result;
146
+ } catch (error) {
147
+ gateway.close(); if (current()) { item.gateway = null; fault(item, error); } throw error;
148
+ }
149
+ })();
150
+ try { return await item.opening; } finally { item.opening = null; }
151
+ }
152
+
153
+ return {
154
+ async list() { return (await store.list()).map(ensure).map(row); },
155
+ async add(invite) {
156
+ if (closed) throw new Error('远程电脑管理已关闭');
157
+ const binding = await transport.pairComputer(invite, { name });
158
+ if (closed) throw new Error('远程电脑管理已关闭');
159
+ binding.id = binding.id || binding.instanceId;
160
+ binding.mode = 'auto';
161
+ const existing = devices.get(binding.id);
162
+ if (existing) { await stopItem(existing); devices.delete(binding.id); }
163
+ await store.put(binding);
164
+ return row(ensure(binding));
165
+ },
166
+ open,
167
+ async renew(id) {
168
+ const item = await find(id);
169
+ if (!check(item)) throw expiredError();
170
+ const result = await item.gateway.renew(Date.now() + LEASE_MS);
171
+ item.expiresAt = result.expiresAt;
172
+ return result;
173
+ },
174
+ async stop(id) { await stopItem(await find(id)); },
175
+ async remove(id) {
176
+ const item = await find(id);
177
+ await stopItem(item); item.router.close();
178
+ await store.delete(item.binding.id); devices.delete(item.binding.id);
179
+ },
180
+ async setMode(id, mode) {
181
+ const item = await find(id);
182
+ if (['auto', 'tunnel', 'p2p'].includes(mode)) await item.router.refresh();
183
+ item.router.setMode(mode);
184
+ if (store.update) await store.update(item.binding.id, () => ({ mode }));
185
+ else {
186
+ const latest = await store.get(item.binding.id);
187
+ await store.put({ ...latest, mode });
188
+ }
189
+ Object.assign(item.binding, await store.get(item.binding.id), { mode });
190
+ item.mode = mode;
191
+ return row(item);
192
+ },
193
+ async probe(id) {
194
+ const item = await find(id);
195
+ if (item.state === 'expired' || item.state === 'revoked') return row(item);
196
+ try { await item.router.probe(); item.lastError = ''; item.lastErrorCode = ''; if (check(item)) item.state = 'connected'; }
197
+ catch (error) { fault(item, error); }
198
+ return row(item);
199
+ },
200
+ async close() {
201
+ if (closed) return;
202
+ closed = true; network.close();
203
+ await Promise.all([...devices.values()].map(async (item) => {
204
+ item.gateway?.close(); item.gateway = null; item.router.close();
205
+ await tunnels?.close?.(item.binding.id);
206
+ }));
207
+ devices.clear();
208
+ },
209
+ };
210
+ }
211
+
212
+ module.exports = { createRemoteController };
@@ -0,0 +1,197 @@
1
+ // 远程电脑专用的邀请、双向挑战与逐连接加密字节流。
2
+ 'use strict';
3
+
4
+ const crypto = require('node:crypto');
5
+ const { Duplex } = require('node:stream');
6
+ const e2ee = require('../shared/e2ee.js');
7
+
8
+ const VERSION = 1;
9
+ const MAX_FRAME = 64 * 1024;
10
+ const MAX_MESSAGE = MAX_FRAME + 128;
11
+ const MAX_HANDSHAKE = 24 * 1024;
12
+ const HOUR = 60 * 60 * 1000;
13
+ const random = (bytes = 32) => crypto.randomBytes(bytes).toString('base64url');
14
+ const json = (value) => Buffer.from(JSON.stringify(value));
15
+ const error = (code, message = code) => Object.assign(new Error(message), { code });
16
+
17
+ function keyBytes(value) {
18
+ if (typeof value !== 'string' || !/^[A-Za-z0-9_-]{43}$/.test(value)) throw error('REMOTE_AUTH', 'Invalid device key');
19
+ return Buffer.from(value, 'base64url');
20
+ }
21
+
22
+ function derive(key, salt, info) {
23
+ return Buffer.from(crypto.hkdfSync('sha256', key, Buffer.from(salt), Buffer.from(`dsh-computer-v1|${info}`), 32));
24
+ }
25
+
26
+ function pairKeys(ticket, instanceId, ticketId) {
27
+ const salt = JSON.stringify([instanceId, ticketId]);
28
+ return { up: derive(keyBytes(ticket), salt, 'pair-up'), down: derive(keyBytes(ticket), salt, 'pair-down') };
29
+ }
30
+
31
+ function connectionKeys(deviceKey, context) {
32
+ const transcript = JSON.stringify([context.instanceId, context.keyId, context.clientNonce, context.serverNonce, context.credential || '']);
33
+ keyBytes(context.clientNonce);
34
+ keyBytes(context.serverNonce);
35
+ const key = keyBytes(deviceKey);
36
+ return {
37
+ transcript,
38
+ authUp: derive(key, transcript, 'auth-up'),
39
+ authDown: derive(key, transcript, 'auth-down'),
40
+ up: derive(key, transcript, 'stream-up'),
41
+ down: derive(key, transcript, 'stream-down'),
42
+ };
43
+ }
44
+
45
+ function sealJson(key, value, aad) {
46
+ return e2ee.seal(key, json(value), aad).toString('base64url');
47
+ }
48
+
49
+ function openJson(key, value, aad) {
50
+ if (typeof value !== 'string' || value.length > MAX_HANDSHAKE * 2) throw error('REMOTE_AUTH');
51
+ return JSON.parse(e2ee.open(key, e2ee.unb64url(value), aad).toString('utf8'));
52
+ }
53
+
54
+ function parseMessage(data, binary) {
55
+ if (binary || data.length > MAX_HANDSHAKE) throw error('REMOTE_AUTH', 'Invalid handshake');
56
+ const value = JSON.parse(Buffer.from(data).toString('utf8'));
57
+ if (!value || value.v !== VERSION) throw error('REMOTE_AUTH', 'Unsupported remote protocol');
58
+ return value;
59
+ }
60
+
61
+ function frameCodec(key, transcript, direction) {
62
+ let counter = 0n;
63
+ const aad = (seq) => Buffer.concat([Buffer.from(`${transcript}|${direction}|`), seq]);
64
+ return {
65
+ seal(kind, data = Buffer.alloc(0)) {
66
+ const seq = Buffer.alloc(8);
67
+ seq.writeBigUInt64BE(counter++);
68
+ const nonce = Buffer.concat([Buffer.alloc(4), seq]);
69
+ return Buffer.concat([seq, e2ee.sealWithNonce(key, nonce, Buffer.concat([Buffer.from([kind]), Buffer.from(data)]), aad(seq))]);
70
+ },
71
+ open(data) {
72
+ const bytes = Buffer.from(data);
73
+ if (bytes.length < 37 || bytes.length > MAX_MESSAGE) throw error('REMOTE_AUTH', 'Invalid encrypted frame');
74
+ const seq = bytes.subarray(0, 8);
75
+ if (seq.readBigUInt64BE() !== counter) throw error('REMOTE_AUTH', 'Replayed or reordered frame');
76
+ const nonce = Buffer.concat([Buffer.alloc(4), seq]);
77
+ if (!bytes.subarray(8, 20).equals(nonce)) throw error('REMOTE_AUTH', 'Invalid frame nonce');
78
+ const plain = e2ee.open(key, bytes.subarray(8), aad(seq));
79
+ counter++;
80
+ return { kind: plain[0], data: plain.subarray(1) };
81
+ },
82
+ };
83
+ }
84
+
85
+ function codecs(keys, server) {
86
+ return {
87
+ send: frameCodec(server ? keys.down : keys.up, keys.transcript, server ? 'down' : 'up'),
88
+ receive: frameCodec(server ? keys.up : keys.down, keys.transcript, server ? 'up' : 'down'),
89
+ };
90
+ }
91
+
92
+ function sendFrame(ws, codec, kind, data, callback = () => {}) {
93
+ if (ws.readyState !== 1) { callback(error('REMOTE_CONNECT', 'Remote connection closed')); return; }
94
+ ws.send(codec.seal(kind, data), { binary: true }, callback);
95
+ }
96
+
97
+ /** 一次 write 的回调等 ws 发完才放行;读缓冲满时暂停 WS,保留流式背压。 */
98
+ function secureStream(ws, pair, options = {}) {
99
+ let readEnded = false;
100
+ let writeEnded = false;
101
+ let finished = false;
102
+ let renewalId = 0;
103
+ const renewals = new Map();
104
+ const closeIfEnded = () => { if (readEnded && writeEnded) ws.close(); };
105
+ const stream = new Duplex({
106
+ allowHalfOpen: true,
107
+ read() { ws.resume(); },
108
+ write(chunk, _encoding, done) {
109
+ let offset = 0;
110
+ const next = (err) => {
111
+ if (err) { done(err); return; }
112
+ if (offset >= chunk.length) { done(); return; }
113
+ const part = chunk.subarray(offset, offset + MAX_FRAME);
114
+ offset += part.length;
115
+ sendFrame(ws, pair.send, 0, part, next);
116
+ };
117
+ next();
118
+ },
119
+ final(done) {
120
+ sendFrame(ws, pair.send, 1, undefined, (err) => {
121
+ writeEnded = !err;
122
+ done(err);
123
+ closeIfEnded();
124
+ });
125
+ },
126
+ destroy(err, done) {
127
+ finished = true;
128
+ for (const pending of renewals.values()) { clearTimeout(pending.timer); pending.reject(err || error('REMOTE_CONNECT', 'Remote connection closed')); }
129
+ renewals.clear();
130
+ ws.off('message', onMessage);
131
+ if (ws.readyState !== 3) ws.terminate();
132
+ done(err);
133
+ },
134
+ });
135
+ const onMessage = (data, binary) => {
136
+ try {
137
+ if (!binary) throw error('REMOTE_AUTH', 'Expected encrypted bytes');
138
+ const frame = pair.receive.open(data);
139
+ if (frame.kind === 0 && !readEnded) {
140
+ if (!stream.push(frame.data)) ws.pause();
141
+ } else if (frame.kind === 1 && !readEnded && frame.data.length === 0) {
142
+ readEnded = true;
143
+ stream.push(null);
144
+ closeIfEnded();
145
+ } else if (frame.kind === 2 && typeof options.onRenew === 'function') {
146
+ const request = JSON.parse(frame.data.toString());
147
+ const remainingMs = options.onRenew(request.leaseMs);
148
+ sendFrame(ws, pair.send, 3, json({ id: request.id, remainingMs }));
149
+ } else if (frame.kind === 3 && typeof options.onRenewed === 'function') {
150
+ const response = JSON.parse(frame.data.toString());
151
+ const pending = renewals.get(response.id);
152
+ if (!pending || !Number.isFinite(response.remainingMs) || response.remainingMs <= 0 || response.remainingMs > HOUR) throw error('REMOTE_AUTH');
153
+ const expiresAt = options.onRenewed(response.remainingMs, pending.expiresAt);
154
+ clearTimeout(pending.timer);
155
+ renewals.delete(response.id);
156
+ pending.resolve(expiresAt);
157
+ } else if (frame.kind === 4) {
158
+ const failure = JSON.parse(frame.data.toString());
159
+ if (!['REMOTE_REVOKED', 'REMOTE_EXPIRED', 'REMOTE_TIMEOUT', 'REMOTE_CONNECT'].includes(failure.code)) throw error('REMOTE_AUTH');
160
+ throw error(failure.code, 'Computer access ended');
161
+ } else throw error('REMOTE_AUTH', 'Unexpected encrypted frame');
162
+ } catch (err) { stream.destroy(err.code?.startsWith('REMOTE_') ? err : error('REMOTE_AUTH', 'Invalid encrypted bytes')); }
163
+ };
164
+ ws.on('message', onMessage);
165
+ ws.on('error', () => stream.destroy(error('REMOTE_CONNECT', 'Remote connection failed')));
166
+ ws.on('close', () => {
167
+ if (!finished) stream.destroy(readEnded && writeEnded ? undefined : error('REMOTE_CONNECT', 'Remote connection closed'));
168
+ });
169
+ if (options.onRenewed) stream.renew = (expiresAt) => new Promise((resolve, reject) => {
170
+ if (finished || stream.destroyed || !Number.isFinite(expiresAt) || expiresAt <= Date.now()) { reject(error('REMOTE_EXPIRED')); return; }
171
+ const leaseMs = Math.min(HOUR, expiresAt - Date.now());
172
+ const id = ++renewalId;
173
+ const timer = setTimeout(() => { renewals.delete(id); reject(error('REMOTE_TIMEOUT', 'Lease renewal timed out')); }, 10_000);
174
+ timer.unref?.();
175
+ renewals.set(id, { resolve, reject, timer, expiresAt });
176
+ sendFrame(ws, pair.send, 2, json({ id, leaseMs }), (err) => {
177
+ if (!err) return;
178
+ clearTimeout(timer); renewals.delete(id); reject(err);
179
+ });
180
+ });
181
+ stream.endAccess = (code) => sendFrame(ws, pair.send, 4, json({ code }));
182
+ // 关闭可先于调用方接管,错误仍通过 close/destroyed 体现。
183
+ stream.on('error', () => {});
184
+ return stream;
185
+ }
186
+
187
+ function endpoint(route, path, websocket = false) {
188
+ const url = new URL(typeof route === 'string' ? route : route?.url);
189
+ if (!['http:', 'https:', 'ws:', 'wss:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) {
190
+ throw error('REMOTE_CONNECT', 'Invalid remote route');
191
+ }
192
+ url.protocol = websocket ? (['https:', 'wss:'].includes(url.protocol) ? 'wss:' : 'ws:') : (['https:', 'wss:'].includes(url.protocol) ? 'https:' : 'http:');
193
+ url.pathname = `${url.pathname.replace(/\/$/, '')}${path}`;
194
+ return url;
195
+ }
196
+
197
+ module.exports = { VERSION, MAX_FRAME, MAX_MESSAGE, MAX_HANDSHAKE, HOUR, random, json, error, keyBytes, pairKeys, connectionKeys, sealJson, openJson, parseMessage, frameCodec, codecs, sendFrame, secureStream, endpoint };
@@ -0,0 +1,59 @@
1
+ 'use strict';
2
+ // 电脑间已认证控制信令只提供隧道会合,目标固定为本机插件入口。
3
+ const { relayAddressesOf } = require('../relay/core.js');
4
+ const { advertisedCandidates, phoneCandidates, ipv6Candidates, withManualIpv6Candidate } = require('../relay/lan-network.cjs');
5
+
6
+ function routesOf({ state, lanPortInUse }) {
7
+ const routes = [];
8
+ const push = (url, channel) => {
9
+ if (typeof url !== 'string' || !url || routes.some(row => row.url === url)) return;
10
+ const parsed = new URL(url);
11
+ if (!['http:', 'https:'].includes(parsed.protocol) || parsed.username || parsed.password || parsed.search || parsed.hash) return;
12
+ routes.push({ url: parsed.href.replace(/\/$/, ''), channel });
13
+ };
14
+ if (state.lanEnabled) {
15
+ const port = lanPortInUse();
16
+ for (const item of phoneCandidates(advertisedCandidates(port), { manual: state.manualLanUrl })) push(item.url, 'lan');
17
+ for (const item of withManualIpv6Candidate(ipv6Candidates(port), state.manualIpv6Url)) push(item.url, 'ipv6');
18
+ }
19
+ for (const url of relayAddressesOf(state).relayUrls) push(url, 'relay');
20
+ return routes;
21
+ }
22
+ function candidates(value) {
23
+ if (!Array.isArray(value)) return [];
24
+ return value.filter(item => typeof item === 'string' && item.length > 0 && item.length <= 96).slice(0, 16);
25
+ }
26
+ function createHostControl({ state, tailcat, p2p, lanPortInUse }) {
27
+ const pending = new Map();
28
+ const currentRoutes = () => routesOf({ state, lanPortInUse });
29
+ return {
30
+ routesOf: currentRoutes,
31
+ connectionInfo: () => ({ routes: currentRoutes() }),
32
+ async onControl(record, request) {
33
+ if (request?.op !== 'tunnels' && request?.op !== 'tunnels.refresh') throw new Error('unsupported-control');
34
+ if (!record || record.remoteWeb !== true) throw new Error('remote-web-denied');
35
+ const key = record.deviceId;
36
+ if (pending.has(key)) return pending.get(key);
37
+ const result = (async () => {
38
+ const tailcatKey = request.tailcatPublicKey;
39
+ const point = request.p2p;
40
+ const enroll = /^nodekey:[0-9a-f]{64}$/.test(tailcatKey || '') && tailcat?.enroll
41
+ ? tailcat.enroll(tailcatKey).catch(() => null) : Promise.resolve(null);
42
+ const punch = /^[A-Za-z0-9+/]{43}=$/.test(point?.publicKey || '') && p2p?.open
43
+ ? p2p.open({ phonePublicKey: point.publicKey, candidates: candidates(point.candidates),
44
+ localCandidates: candidates(point.localCandidates), targetPort: p2p.targetPort() }).catch(() => null)
45
+ : Promise.resolve(null);
46
+ const [tunnel, peer] = await Promise.all([enroll, punch]);
47
+ return {
48
+ routes: currentRoutes(),
49
+ ...(tunnel?.address ? { tailcat: { address: tunnel.address, port: tunnel.port } } : {}),
50
+ ...(peer?.ok && peer.publicKey ? { p2p: { publicKey: peer.publicKey, port: p2p.constants.P2P_PORT,
51
+ candidates: candidates(peer.candidates), localCandidates: candidates(peer.localCandidates) } } : {}),
52
+ };
53
+ })();
54
+ pending.set(key, result);
55
+ try { return await result; } finally { pending.delete(key); }
56
+ },
57
+ };
58
+ }
59
+ module.exports = { createHostControl, routesOf };