dsh-mobile-plugin 0.5.64 → 0.5.65

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.
@@ -0,0 +1,260 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * 总控(地址目录)客户端:把本机的**全部连接地址**加密后上报给总控,拿回一枚设备令牌交给 APP。
5
+ *
6
+ * 地址(中转 / 局域网 / IPv6 / 直连,含自建中转)用**实例历史密钥 HK** 封成密文信封再上报,
7
+ * 总控只存密文、不持钥、解不开;APP 用自己那份 HK 解开。这样总控能做「宿主换了地址之后的
8
+ * 保底查询」,又看不到用户到底连了哪些地址。加密口径直接复用历史 blob 那套(`mirror/history-blob.cjs`
9
+ * 与 `app/src/services/viewmodels/history-blob.ts` 逐字节一致),AAD 用 `dsh-history-v1|control|<instanceId>`。
10
+ *
11
+ * 令牌:首次注册总控发一枚,之后重连必须带同一枚(总控据此拒绝冒充)。令牌落盘在 relay.json,
12
+ * 插件重启后照样带得上;同时经已鉴权的状态心跳交给 APP。
13
+ *
14
+ * 地址没变就不发——链路平时是静的,只在地址变化时推一次。
15
+ * 总控地址是内置常量,可用 `DSH_CONTROL_URL` 覆盖(本地联调用)。
16
+ */
17
+
18
+ const {
19
+ advertisedCandidates,
20
+ phoneCandidates,
21
+ ipv6Candidates,
22
+ withManualIpv6Candidate,
23
+ } = require('./lan-network.cjs');
24
+ const { relayAddressesOf } = require('./core.js');
25
+ const { sealHistoryBlob } = require('../mirror/history-blob.cjs');
26
+
27
+ // 内置总控入口(与 APP 侧常量一致)。末尾斜杠去掉,拼接时统一。
28
+ const CONTROL_BASE_URL = (process.env.DSH_CONTROL_URL || 'https://ai-hub.wnluo.com/findme').replace(/\/+$/, '');
29
+
30
+ /** https→wss、http→ws。总控的 WebSocket 端点挂在同一前缀下。 */
31
+ function controlWsUrl(base = CONTROL_BASE_URL) {
32
+ return String(base).replace(/^https:/i, 'wss:').replace(/^http:/i, 'ws:');
33
+ }
34
+
35
+ /**
36
+ * 折出本机要上报的全部连接地址(明文,上送前再加密)。
37
+ * 与配对二维码同源:中转取 `relayUrls`;局域网走 `phoneCandidates(advertisedCandidates)`;
38
+ * IPv6 走 `ipv6Candidates` 并缀上手填那条。`lanEnabled` 关掉或端口拿不到时不含局域网/IPv6。
39
+ */
40
+ function controlAddresses(state, port) {
41
+ const out = [];
42
+ let relay = { relayUrls: [] };
43
+ try {
44
+ relay = relayAddressesOf(state);
45
+ } catch {
46
+ relay = { relayUrls: [] };
47
+ }
48
+ for (const url of relay.relayUrls || []) {
49
+ if (typeof url === 'string' && url) out.push({ kind: 'relay', url });
50
+ }
51
+ const lanPort = Number.isInteger(port) ? port : 0;
52
+ if (state.lanEnabled && lanPort > 0) {
53
+ try {
54
+ const candidates = phoneCandidates(advertisedCandidates(lanPort), {
55
+ preferred: state.preferredLanAddress,
56
+ manual: state.manualLanUrl,
57
+ });
58
+ for (const c of candidates) if (c && c.url) out.push({ kind: 'lan', url: c.url });
59
+ } catch {
60
+ /* 网卡扫不出来只是少几条 LAN 候选,不影响上报主链路 */
61
+ }
62
+ try {
63
+ const v6 = withManualIpv6Candidate(ipv6Candidates(lanPort), state.manualIpv6Url);
64
+ for (const c of v6) if (c && c.url) out.push({ kind: 'ipv6', url: c.url });
65
+ } catch {
66
+ /* 同上 */
67
+ }
68
+ }
69
+ const seen = new Set();
70
+ const dedup = [];
71
+ for (const a of out) {
72
+ if (!a || !a.url || seen.has(a.url)) continue;
73
+ seen.add(a.url);
74
+ dedup.push(a);
75
+ }
76
+ return dedup;
77
+ }
78
+
79
+ /**
80
+ * @param {object} deps
81
+ * @param {object} deps.state 宿主状态(就地改:写入令牌)
82
+ * @param {() => void} [deps.persist] 令牌变了之后落盘(通常是 `core.saveState(state)`)
83
+ * @param {() => number} deps.getPort 当前实绑的局域网端口取值器
84
+ * @param {() => string} deps.getHistoryKey 取实例历史密钥(HK,base64url);缺失时会惰性生成
85
+ * @param {(state: object) => Array<{kind?: string, url: string}>} [deps.getAddresses] 地址来源覆盖(测试用)
86
+ * @param {(msg: string, ...rest: any[]) => void} [deps.log]
87
+ */
88
+ function createControlClient({ state, persist, getPort, getHistoryKey, getAddresses, log = () => {} }) {
89
+ const build = typeof getAddresses === 'function'
90
+ ? getAddresses
91
+ : (s) => controlAddresses(s, typeof getPort === 'function' ? getPort() : undefined);
92
+
93
+ let sock = null;
94
+ let running = false;
95
+ let connected = false;
96
+ let token = typeof state.controlToken === 'string' ? state.controlToken : '';
97
+ let lastSent = '';
98
+ let attempt = 0;
99
+ let reconnectTimer = null;
100
+ let tickTimer = null;
101
+
102
+ const canonical = (list) => JSON.stringify([...list].map((a) => [a.kind || '', a.url]).sort());
103
+
104
+ function hk() {
105
+ try {
106
+ const value = typeof getHistoryKey === 'function' ? getHistoryKey() : state.historyKey;
107
+ return typeof value === 'string' ? value : '';
108
+ } catch {
109
+ return '';
110
+ }
111
+ }
112
+
113
+ /** 明文地址 → 密文信封 JSON。HK 缺了就返回空串(不连)。 */
114
+ function seal(addresses) {
115
+ const key = hk();
116
+ if (!key) return '';
117
+ try {
118
+ return sealHistoryBlob(key, 'control', state.instanceId || '', { addresses });
119
+ } catch (error) {
120
+ log('control: seal failed', error && error.message);
121
+ return '';
122
+ }
123
+ }
124
+
125
+ function send(obj) {
126
+ if (sock && sock.readyState === 1) {
127
+ try { sock.send(JSON.stringify(obj)); } catch { /* 发送失败交给 close 事件重连 */ }
128
+ }
129
+ }
130
+
131
+ function scheduleReconnect() {
132
+ if (!running) return;
133
+ attempt += 1;
134
+ const delay = Math.min(30_000, 1_000 * 2 ** Math.min(attempt - 1, 5));
135
+ clearTimeout(reconnectTimer);
136
+ reconnectTimer = setTimeout(() => { reconnectTimer = null; connect(); }, delay);
137
+ }
138
+
139
+ function connect() {
140
+ if (!running || sock) return;
141
+ if (!state.enabled) return;
142
+ const addresses = build(state);
143
+ if (!Array.isArray(addresses) || addresses.length === 0) {
144
+ connected = false;
145
+ return;
146
+ }
147
+ const payload = seal(addresses);
148
+ if (!payload) {
149
+ connected = false;
150
+ return;
151
+ }
152
+ const tokenQuery = token ? `&token=${encodeURIComponent(token)}` : '';
153
+ const url = `${controlWsUrl()}/ws/device?instanceId=${encodeURIComponent(state.instanceId || '')}${tokenQuery}`;
154
+ let ws;
155
+ try {
156
+ ws = new WebSocket(url);
157
+ } catch (error) {
158
+ log('control: dial failed', error && error.message);
159
+ scheduleReconnect();
160
+ return;
161
+ }
162
+ sock = ws;
163
+ connected = false;
164
+ lastSent = '';
165
+ ws.addEventListener('open', () => {
166
+ if (sock !== ws) return;
167
+ attempt = 0;
168
+ connected = true;
169
+ send({ type: 'register', payload });
170
+ lastSent = canonical(addresses);
171
+ });
172
+ ws.addEventListener('message', (event) => {
173
+ if (sock !== ws) return;
174
+ let msg;
175
+ try {
176
+ const text = typeof event.data === 'string' ? event.data : Buffer.from(event.data).toString('utf8');
177
+ msg = JSON.parse(text);
178
+ } catch {
179
+ return;
180
+ }
181
+ if (msg && msg.type === 'registered' && typeof msg.token === 'string') {
182
+ if (msg.token !== token) {
183
+ token = msg.token;
184
+ state.controlToken = msg.token;
185
+ try { persist?.(); } catch { /* 落盘失败下次注册还会拿到同一枚,不必打断 */ }
186
+ }
187
+ } else if (msg && msg.type === 'error') {
188
+ try { ws.close(); } catch { /* ignore */ }
189
+ }
190
+ });
191
+ const done = () => {
192
+ if (sock !== ws) return;
193
+ connected = false;
194
+ sock = null;
195
+ scheduleReconnect();
196
+ };
197
+ ws.addEventListener('close', done);
198
+ ws.addEventListener('error', () => { try { ws.close(); } catch { /* ignore */ } });
199
+ }
200
+
201
+ /** 复核地址有没有变,变了就重新加密并 update。 */
202
+ function tick() {
203
+ if (!connected || !sock) return;
204
+ const addresses = build(state);
205
+ if (!Array.isArray(addresses) || addresses.length === 0) return;
206
+ if (canonical(addresses) !== lastSent) {
207
+ const payload = seal(addresses);
208
+ if (!payload) return;
209
+ send({ type: 'update', payload });
210
+ lastSent = canonical(addresses);
211
+ }
212
+ }
213
+
214
+ function snapshot() {
215
+ return { url: CONTROL_BASE_URL, connected: connected && !!sock, token: token || null };
216
+ }
217
+
218
+ function start() {
219
+ if (!running) {
220
+ running = true;
221
+ clearInterval(tickTimer);
222
+ tickTimer = setInterval(tick, 60_000);
223
+ if (tickTimer.unref) tickTimer.unref();
224
+ }
225
+ if (state.enabled && !sock) connect();
226
+ return snapshot();
227
+ }
228
+
229
+ function stop() {
230
+ running = false;
231
+ connected = false;
232
+ clearTimeout(reconnectTimer);
233
+ reconnectTimer = null;
234
+ clearInterval(tickTimer);
235
+ tickTimer = null;
236
+ if (sock) {
237
+ try { sock.close(); } catch { /* ignore */ }
238
+ sock = null;
239
+ }
240
+ attempt = 0;
241
+ }
242
+
243
+ /** 配置变更后调用:没开 / 没地址 / 没 HK 就停;否则起连或复核。 */
244
+ function sync() {
245
+ if (!state.enabled || build(state).length === 0 || !hk()) {
246
+ stop();
247
+ return;
248
+ }
249
+ if (!running) {
250
+ start();
251
+ return;
252
+ }
253
+ if (!sock) connect();
254
+ else tick();
255
+ }
256
+
257
+ return { start, stop, sync, snapshot };
258
+ }
259
+
260
+ module.exports = { CONTROL_BASE_URL, controlWsUrl, controlAddresses, createControlClient };
package/lib/relay/core.js CHANGED
@@ -30,7 +30,15 @@ const MOBILE_TOKEN_TTL_SEC = 30 * 24 * 3600;
30
30
  */
31
31
  const MOBILE_BEARER_TTL_SEC = 365 * 24 * 3600;
32
32
 
33
- function genInstanceId() { return crypto.randomBytes(4).toString('hex'); }
33
+ /**
34
+ * 实例 id(128 位随机、32 位十六进制)。
35
+ *
36
+ * 它同时是「总控地址目录」里的设备标识:知道它对不上令牌就改不了别人(见 relay/control.js 的
37
+ * 令牌绑定),所以**不可猜**很重要。早先是 4 字节(32 位,8 位十六进制),一个知道它的攻击者
38
+ * 有机会抢在某台新设备首次注册前把它占了;加长到 16 字节后这种枚举不现实。
39
+ * 老设备的 id 保持原样(改了等于换身份、配对全失效),只有新装/重建的才用新的长度。
40
+ */
41
+ function genInstanceId() { return crypto.randomBytes(16).toString('hex'); }
34
42
  function genPairingCode() { return String(crypto.randomInt(0, 1000000)).padStart(6, '0'); }
35
43
  /**
36
44
  * 二维码里那张一次性票据:32 字节随机数的 base64url(43 字符,无补位)。
@@ -60,6 +68,10 @@ function defaultState() {
60
68
  // 用户手填的 IPv6 直连地址(空 = 没填)。与上一条同一条口径:schema 里的一项、不进
61
69
  // sidecar 配置,只影响「报给手机的 IPv6 候选」与二维码。
62
70
  manualIpv6Url: '',
71
+ // 用户手填的「TCP 直连」目标(空 = 没填,形如 `主机:端口` 或 `http://主机:端口`,IPv6 用方括号)。
72
+ // 与上面两条并列、同样**不进 sidecar 配置**:它只决定手机经本机回环(安卓直接)用裸 TCP
73
+ // 拨哪个目标,不影响隧道怎么连。schema 里的一项,改它不该触发 sidecar 重配。
74
+ manualTcpUrl: '',
63
75
  // 首次接入引导走完没有。**刻意不进 RemoteControlSettingsSchema**:它不是一项
64
76
  // 「远程控制设置」,改它不该触发 sidecar 重配(那条链上每加一个字段都要同步改
65
77
  // schema、worker 的 allowed 数组与 buildConfig,漏一处就抛 unknown field)。
@@ -454,6 +454,31 @@ function phoneCandidates(list, options = {}) {
454
454
  return withManualCandidate(orderCandidates(list, options.preferred || ''), options.manual || '')
455
455
  }
456
456
 
457
+ /**
458
+ * 用户配置的直连地址(`manualLanUrl`)里能直接当裸 TCP 目标的那一条 → `host:port`。
459
+ *
460
+ * 「TCP 直连」这条通道由 App 用本机回环 + 原生裸 TCP 出站,只对**公网明文 http** 有意义:
461
+ * 私有 / 环回地址 iOS 本来就放行明文(不需要转发)、https 有 TLS(裸转发会把明文 http 打到
462
+ * TLS 端口上),两类都返回空。返回的这一条就是二维码 / 连接信息里那颗**唯一**的 TCP 地址
463
+ * ——不再掺任何网卡扫出来的候选,用户配哪条就是哪条。
464
+ */
465
+ function tcpDirectTarget(value) {
466
+ const raw = typeof value === 'string' ? value.trim() : ''
467
+ if (!raw) return ''
468
+ // 去掉 scheme 与尾部斜杠:用户既可填 `http://主机:端口`,也可直接填 `主机:端口`;IPv6 用方括号。
469
+ // 只认「带明确端口」的 host:port —— 裸 TCP 必须知道端口(不给 80/443 默认值:https 默认 443 是
470
+ // TLS,裸转发把明文打到 TLS 端口上必然失败,让用户显式填他能拨通的那个端口)。IPv6 原样保留
471
+ // 方括号(candidate 的 url 形态与 `parseTcpTarget` 同一口径)。不涉及 ATS(原生裸 TCP 出站),
472
+ // 所以这里不按私网/公网再拦,用户填什么就支持什么。
473
+ const url = raw.replace(/^[a-z][a-z0-9+.-]*:\/\//i, '').replace(/\/+$/, '')
474
+ const m = /^(\[[^\]]+\]|[^\s/:?#]+):(\d+)$/.exec(url)
475
+ if (!m) return ''
476
+ const host = m[1].trim()
477
+ const port = Number(m[2])
478
+ if (!host || !Number.isInteger(port) || port < 1 || port > 65535) return ''
479
+ return `${host}:${port}`
480
+ }
481
+
457
482
  module.exports = {
458
483
  ipv4Number,
459
484
  ipv6Number,
@@ -480,4 +505,5 @@ module.exports = {
480
505
  withManualIpv6Candidate,
481
506
  orderCandidates,
482
507
  phoneCandidates,
508
+ tcpDirectTarget,
483
509
  }
@@ -18,6 +18,7 @@ const {
18
18
  phoneCandidates,
19
19
  ipv6Candidates,
20
20
  withManualIpv6Candidate,
21
+ tcpDirectTarget,
21
22
  } = require('./lan-network.cjs');
22
23
 
23
24
  /**
@@ -64,6 +65,13 @@ function pairingPayload(state, lanPort) {
64
65
  ticket: state.pairingTicket || '',
65
66
  relayUrl: relay.relayUrl,
66
67
  lanUrls: urls,
68
+ // 「TCP 直连」那一条:用户配的那条直连地址(`manualLanUrl`)里能当裸 TCP 目标的,只此
69
+ // 一条、不掺网卡候选。App 用它当 `tcpTarget`(经本机回环 + 原生裸 TCP 出站,ATS 不参与)。
70
+ // 没有可用的就整格不写,老 App 读到会忽略。
71
+ ...(() => {
72
+ const tcp = tcpDirectTarget(state.manualTcpUrl);
73
+ return tcp ? { tcpUrl: tcp } : {};
74
+ })(),
67
75
  // **不再带 `lanCandidates`**:它与上面 `lanUrls` 是同一个数组,App 侧从来没读过它
68
76
  // (`parsePairingInvite` 只取 `lanUrls`)。一份地址在二维码里出现两遍,白占几十个字符、
69
77
  // 把码点压密一档 —— 而这正是「码看着清楚却扫不出来」的成本。
@@ -90,6 +90,7 @@ function createStatusView(deps) {
90
90
  getSidecarRestartedAt,
91
91
  getSidecarRestartError,
92
92
  getMirrorPush,
93
+ getControl,
93
94
  } = deps
94
95
 
95
96
  return function status() {
@@ -134,6 +135,8 @@ function createStatusView(deps) {
134
135
  tailcat: typeof deps.getTailcat === 'function' ? deps.getTailcat() : null,
135
136
  // 点对点隧道那一格:手机轮询 `/status` 时据此知道这条通道在不在、通没通。
136
137
  p2p: typeof deps.getP2P === 'function' ? deps.getP2P() : null,
138
+ // 总控目录上报的状态(内置地址 + 设备令牌 + 有没有连上)。
139
+ control: typeof getControl === 'function' ? getControl() : null,
137
140
  // 故障时端口为 0,配置端口单列,避免把未监听入口说成可用。
138
141
  lan: {
139
142
  ...(sidecarSnapshot.lan || {}),
@@ -285,6 +285,9 @@ function registerControlPlaneRoutes(deps) {
285
285
  getLanPortAdjusted,
286
286
  pairingPayload,
287
287
  tailcat,
288
+ // FRP 直连:面板导入配置后真正拉起本地 frpc 的进程管理器(见 lib/frpc/runner.cjs)。
289
+ // 缺省 null:单独挂 impl 的测试里没有它,那几条路由如实报不可用。
290
+ frp = null,
288
291
  restartSidecar,
289
292
  // 「手机上最近来过没有」。**只往本机这条状态路由上补**(和 panelUrl 一样),
290
293
  // 不动 createStatusView——那份 JSON 手机端也在读,给它加字段是另一个决定。
@@ -434,12 +437,15 @@ function registerControlPlaneRoutes(deps) {
434
437
  // `manualIpv6` 是同一件事的 IPv6 版:面板回显它,同时把它缀进 `ipv6` 候选最后
435
438
  // (只追加、不删网卡候选;排最后的取舍见 lan-network.cjs 的 `withManualIpv6Candidate`)。
436
439
  const manualIpv6 = typeof state.manualIpv6Url === 'string' ? state.manualIpv6Url : ''
440
+ // `manualTcp` 是「TCP 直连」目标(`主机:端口`):面板回显与修改它,手机拿它当裸 TCP 目标。
441
+ const manualTcp = typeof state.manualTcpUrl === 'string' ? state.manualTcpUrl : ''
437
442
  sendJson(res, 200, {
438
443
  ok: true,
439
444
  port,
440
445
  preferred,
441
446
  manual,
442
447
  manualIpv6,
448
+ manualTcp,
443
449
  lan: lanCandidates(port),
444
450
  public: publicCandidates(port),
445
451
  ipv6: withManualIpv6Candidate(ipv6Candidates(port), manualIpv6),
@@ -528,7 +534,7 @@ function registerControlPlaneRoutes(deps) {
528
534
  return null
529
535
  }
530
536
  }
531
- registerRoute({ kind: 'exact', path: '/api/relay/status', handler: localOnly('GET', async (req, res) => sendJson(res, 200, { ...status(), tailcat: deps.tailcat && typeof deps.tailcat.status === 'function' ? deps.tailcat.status() : null, panelUrl: panelUrlOf(req), panelScope: panelScopeOf(req), webAccess: webAccessWindow.status(), devices: deviceSummary(), ...mobileActivity(), selfCheck: selfCheck.snapshot() })) })
537
+ registerRoute({ kind: 'exact', path: '/api/relay/status', handler: localOnly('GET', async (req, res) => sendJson(res, 200, { ...status(), tailcat: deps.tailcat && typeof deps.tailcat.status === 'function' ? deps.tailcat.status() : null, frp: deps.frp && typeof deps.frp.status === 'function' ? deps.frp.status() : null, panelUrl: panelUrlOf(req), panelScope: panelScopeOf(req), webAccess: webAccessWindow.status(), devices: deviceSummary(), ...mobileActivity(), selfCheck: selfCheck.snapshot() })) })
532
538
 
533
539
  // ── 手机直连隧道(Tailcat):面板查看与管理 ────────────────────────────────
534
540
  //
@@ -546,6 +552,42 @@ function registerControlPlaneRoutes(deps) {
546
552
  const state = deps.p2p && typeof deps.p2p.status === 'function' ? deps.p2p.status() : null
547
553
  sendJson(res, 200, { ok: true, status: state })
548
554
  }) })
555
+
556
+ // ── FRP 直连:导入配置 → 落盘并拉起本地 frpc ───────────────────────────────
557
+ //
558
+ // 面板把用户粘贴的 frpc 配置原样送上来,这里交给进程管理器:它会把 `localPort` 对齐到插件
559
+ // 此刻真实监听的端口,再起 `frpc -c 配置`。这样「TCP 直连地址」后面才真的有个隧道在转发,
560
+ // 而不是只填了个地址、什么都没跑。运行状态随 `/api/relay/status` 的 `frp` 一起回给面板。
561
+ registerRoute({ kind: 'exact', path: '/api/relay/frp/import', handler: localOnly('POST', async (req, res) => {
562
+ const body = await readJson(req)
563
+ const config = body && typeof body.config === 'string' ? body.config : ''
564
+ if (!config.trim()) return sendJson(res, 400, { ok: false, error: { code: 'bad-request', message: '缺少 frpc 配置' } })
565
+ if (!deps.frp || typeof deps.frp.start !== 'function') {
566
+ return sendJson(res, 503, { ok: false, error: { code: 'frp-unavailable', message: '这台宿主没有接入 frpc 运行能力' } })
567
+ }
568
+ deps.frp.saveConfig(config)
569
+ const started = await deps.frp.start()
570
+ // frpc 起来后从它的管理接口读服务端实际分配的公网地址;读到就写进 TCP 直连地址。服务商配置
571
+ // 常不写 remotePort(端口由服务端分配),地址只能这样拿到——否则面板填的那个端口是猜的、拨不通。
572
+ let remoteAddress = ''
573
+ if (started && started.running && typeof deps.frp.discoverRemoteAddress === 'function') {
574
+ remoteAddress = await deps.frp.discoverRemoteAddress(8000).catch(() => '')
575
+ }
576
+ if (remoteAddress && state) {
577
+ state.manualTcpUrl = remoteAddress
578
+ try {
579
+ if (settings && typeof settings.update === 'function') await settings.update({ manualTcpUrl: remoteAddress })
580
+ } catch { /* 落盘失败也不影响这次返回的运行状态 */ }
581
+ }
582
+ sendJson(res, 200, { ok: true, status: { ...started, remoteAddress: remoteAddress || (started && started.remoteAddress) || '' } })
583
+ }) })
584
+ registerRoute({ kind: 'exact', path: '/api/relay/frp/stop', handler: localOnly('POST', async (_req, res) => {
585
+ if (!deps.frp || typeof deps.frp.clear !== 'function') {
586
+ return sendJson(res, 503, { ok: false, error: { code: 'frp-unavailable', message: '这台宿主没有接入 frpc 运行能力' } })
587
+ }
588
+ const state = await deps.frp.clear()
589
+ sendJson(res, 200, { ok: true, status: state })
590
+ }) })
549
591
  const tailcatSnapshot = () => {
550
592
  const state = deps.tailcat && typeof deps.tailcat.status === 'function' ? deps.tailcat.status() : null
551
593
  const allowed = deps.tailcat && typeof deps.tailcat.allowedClients === 'function' ? deps.tailcat.allowedClients() : []
@@ -925,6 +967,10 @@ function registerControlPlaneRoutes(deps) {
925
967
  if (typeof body?.manualIpv6Url === 'string' && body.manualIpv6Url.length <= 200) {
926
968
  patch.manualIpv6Url = body.manualIpv6Url.trim().replace(/\/+$/, '')
927
969
  }
970
+ // 用户手填的「TCP 直连」目标(`主机:端口`)。空串合法 = 清掉,口径同上一条。
971
+ if (typeof body?.manualTcpUrl === 'string' && body.manualTcpUrl.length <= 200) {
972
+ patch.manualTcpUrl = body.manualTcpUrl.trim()
973
+ }
928
974
  await settings.update(patch)
929
975
  // 换中转地址时宿主会**先在旧隧道上登记迁移、再重建**(顺序在 worker 的 configure 里,
930
976
  // 见 lib/relay/migrate.js)—— 面板与手机走的是同一条下发路径,不需要各自实现一遍。
@@ -1243,6 +1289,10 @@ const WEB_ACCESS_ROUTES = new Set([
1243
1289
  '/api/relay/tailcat',
1244
1290
  '/api/relay/tailcat/enabled',
1245
1291
  '/api/relay/tailcat/revoke',
1292
+ // FRP 直连的启停:同属管理动作(收在 LOCAL_OPERATOR_ROUTES 里只认本机/局域网),
1293
+ // 但仍留在窗口白名单里保持「路由都在白名单」这条语义统一。
1294
+ '/api/relay/frp/import',
1295
+ '/api/relay/frp/stop',
1246
1296
  // 点对点隧道的现状(只有查看,没有开关也没有白名单:能连上的前提就是密钥对得上)。
1247
1297
  '/api/relay/p2p',
1248
1298
  '/api/relay/revoke-all',
@@ -1284,6 +1334,9 @@ const LOCAL_OPERATOR_ROUTES = new Set([
1284
1334
  '/api/relay/devices/permissions',
1285
1335
  '/api/relay/tailcat/enabled',
1286
1336
  '/api/relay/tailcat/revoke',
1337
+ // FRP 直连的启停:会拉起/杀掉本机进程,属于只允许本机或局域网直连的动作。
1338
+ '/api/relay/frp/import',
1339
+ '/api/relay/frp/stop',
1287
1340
  '/api/relay/update/apply',
1288
1341
  '/api/relay/update/auto',
1289
1342
  '/api/relay/update/ota/apply',
@@ -18,7 +18,7 @@
18
18
  const { sendJson } = require('../http/routing.js');
19
19
  const { readJsonBody } = require('../shared/http-util.js');
20
20
  const { createP2PRendezvousHandler } = require('../p2p/rendezvous.cjs');
21
- const { orderCandidates, withManualCandidate, withManualIpv6Candidate } = require('../relay/lan-network.cjs');
21
+ const { orderCandidates, withManualCandidate, withManualIpv6Candidate, tcpDirectTarget } = require('../relay/lan-network.cjs');
22
22
  // 中转地址两格的收敛(`relayUrls[0] === relayUrl`)。直接 require 而不是走注入:它是纯函数,
23
23
  // 而这两条路由里少一格就是「手机看到两个矛盾的地址」,不该依赖装配层有没有把它递进来。
24
24
  const { relayAddressesOf } = require('../relay/core.js');
@@ -156,7 +156,7 @@ function profileNodeModulesOf(ctx) {
156
156
  }
157
157
 
158
158
  function registerMobileRoutes(deps) {
159
- const { registerRoute, tailcat, p2p, registerUpgradeRoute, guarded, state, hostMetadata, getSidecarSnapshot, safeLanCandidates, safeIpv6Candidates, lanPortInUse, preview, core, pairingApproval, rotatePairing, getHistoryKey, credentials, dropDeviceStreams } = deps;
159
+ const { registerRoute, tailcat, p2p, registerUpgradeRoute, guarded, state, getControl, hostMetadata, getSidecarSnapshot, safeLanCandidates, safeIpv6Candidates, lanPortInUse, preview, core, pairingApproval, rotatePairing, getHistoryKey, credentials, dropDeviceStreams } = deps;
160
160
  const route = (path, handler) => registerRoute({ kind: 'exact', path, handler: guarded(handler) })
161
161
  // 中转配置那一组要**装配期已有的实例**(config store、sidecar 生命周期),不能靠模块级
162
162
  // 单例去拿:同一进程里两份 relay.json 的真值只会打架。所以这里按装配层给的依赖建一次。
@@ -209,6 +209,9 @@ function registerMobileRoutes(deps) {
209
209
  // 没有中转」,与「地址是空的」区分开。
210
210
  relayUrl: state.enabled ? (state.relayUrl || null) : null,
211
211
  relayUrls,
212
+ // 总控目录:内置地址 + 这枚设备令牌。APP 拿它去总控查询/订阅本机地址(`null` = 还没连上
213
+ // 或没启用,此时 APP 就当它不存在、照旧走配对与心跳那条)。令牌只经这条已鉴权的心跳下发。
214
+ control: typeof getControl === 'function' ? getControl() : null,
212
215
  ...hostMetadata(),
213
216
  // 点对点隧道这一格。
214
217
  //
@@ -402,6 +405,12 @@ function registerMobileRoutes(deps) {
402
405
  lanUrls: candidates,
403
406
  lanCandidates: candidates,
404
407
  ipv6Candidates: ipv6,
408
+ // 「TCP 直连」目标:从用户配的那条直连地址(manualLanUrl)解出来,只此一条、不掺网卡候选。
409
+ // 与二维码里那颗同源,手机定期核对时据此刷新,保证「改了连接地址、TCP 跟着变」。
410
+ ...(() => {
411
+ const tcpUrl = tcpDirectTarget(state.manualTcpUrl)
412
+ return tcpUrl ? { tcpUrl } : {}
413
+ })(),
405
414
  updatedAt: lanUpdatedAt,
406
415
  lastSeen: lanUpdatedAt,
407
416
  })
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-mobile-plugin",
3
- "version": "0.5.64",
3
+ "version": "0.5.65",
4
4
  "description": "Mobile API (/api/mobile/v1) and relay client for the DSH mobile app — desktop profile build (dsh 0.2.x, peers resolved by the host)",
5
5
  "license": "MIT",
6
6
  "icon": "./icon.png",