dsh-mobile-plugin 0.5.144 → 0.5.145

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,3 +1,4 @@
1
+ // 2026-11-30:局域网 Bonjour 广播单独开关进 schema,老状态缺项按开。
1
2
  // 2026-11-27:零讯客户端身份两格进 schema(连上时落盘,复用本机客户端前比对,手机配置口不开放)。
2
3
  // 2026-11-25:专属回环入口端口进 schema(worker 绑定后落盘、手机配置口不开放),兜底期间的手填地址备份同属运行时字段。
3
4
  // 固定端口设置随远程连接配置一并保存和投影。
@@ -44,6 +45,8 @@ const RemoteControlSettingsSchema = z.object({
44
45
  // 宿主从列表选择并注册一条线路,中选地址写回首项;手机只跟随当前注册线路。
45
46
  relayUrls: z.array(z.string()).default([]),
46
47
  lanEnabled: z.boolean().default(true),
48
+ // Bonjour 广播的单独开关,默认开;关掉只停发布,不动局域网监听与配对。
49
+ lanDiscoveryEnabled: z.boolean().default(true),
47
50
  lanPort: z.number().step(1).min(1024).max(65535).default(51887),
48
51
  // 外部穿透软件的固定目标由用户声明;插件内配置的穿透另外自动锁定。
49
52
  lanPortFixed: z.boolean().default(false),
@@ -134,6 +137,8 @@ function configOf(state) {
134
137
  relayUrl: relay.relayUrl,
135
138
  relayUrls: relay.relayUrls,
136
139
  lanEnabled: Boolean(state.lanEnabled),
140
+ // 只有显式 false 才算关;老状态文件没这一格、坏值都按开(与历史行为一致)。
141
+ lanDiscoveryEnabled: state.lanDiscoveryEnabled !== false,
137
142
  lanPort: Number.isInteger(state.lanPort) ? state.lanPort : 51887,
138
143
  lanPortFixed: state.lanPortFixed === true,
139
144
  // 专属入口还没分配时按 0(worker 绑好之后才有值),坏值不能冒充已就绪。
package/lib/relay/core.js CHANGED
@@ -1,3 +1,4 @@
1
+ // 2026-11-30:局域网 Bonjour 广播单独开关进默认状态,老配置缺项按开。
1
2
  // 2026-11-27:零讯客户端身份两格进默认状态(连上时落盘,复用本机客户端前比对)。
2
3
  // 2026-11-25:专属回环入口端口与兜底期手填地址备份进默认状态(运行时字段,手机配置口不开放)。
3
4
  // 配置收敛保持两格自洽;不再按域名清理废弃内置中转地址(2026-11-29:退役清单清完,自建同名域名照常保留)。
@@ -61,6 +62,9 @@ function defaultState() {
61
62
  // 老状态文件没这一格时靠这里兜底,别在别处再判一次「没有就拒绝」。
62
63
  pairingTier: 'full',
63
64
  lanEnabled: true, lanPort: 51887, lanSecret: crypto.randomBytes(32).toString('hex'), enabled: false,
65
+ // Bonjour 广播单独开关:关掉只停发布,局域网监听 / 地址候选 / 配对 / 二维码都不变。
66
+ // 老状态文件没这一格时按开,与历史行为一致。
67
+ lanDiscoveryEnabled: true,
64
68
  // 专属回环入口端口(默认 0 = 还没分配):worker 启动时绑定、宿主写回,手机配置口不开放。
65
69
  // 局域网默认 51887 与 0.0.0.0 绑定都不动,它是另外一条只听 127.0.0.1 的入口。
66
70
  tunnelIngressPort: 0,
@@ -1,3 +1,4 @@
1
+ // 2026-11-30:需求变为不接老配对——/__lan_pair 的六位码入口直接拒掉,带票据的二维码照常配。
1
2
  // 2026-11-29:配对口不再按来源拒公网 IPv6,与公网 IPv4 同走全局令牌桶。
2
3
  // 2026-11-28:回环来源的通道标注从 lan 改记 tunnel,第三方穿透不再显示成「局域网」。
3
4
  // 2026-11-25:多开一条只听 127.0.0.1 的专属入口,与主入口共用 handleRequest;被占则内核另分一次并报上去。
@@ -27,7 +28,6 @@ const http = require('node:http');
27
28
  const { WebSocketServer, WebSocket } = require('ws');
28
29
  const core = require('./core.js');
29
30
  const { advertisedCandidates, ipv6Candidates, isGlobalUnicastV6 } = require('./lan-network.cjs');
30
- const { safeEqual } = require('../shared/dshtoken');
31
31
  const { isFreshRequest } = require('../shared/fresh-request');
32
32
  const { encodeJsonBody } = require('../shared/http-util');
33
33
  const { withViaHeader } = require('../shared/via-header');
@@ -866,7 +866,8 @@ function createLanProxy(opts) {
866
866
  const input = JSON.parse(b || '{}')
867
867
  // 校验用的码 / 票据 / 实例号以主进程为准(旁车缓存那份可能和二维码错开)。
868
868
  const pairing = await resolvePairing();
869
- // 两种形状(§8.3(2)):带 `sealed` 是协议 v2,带 `code` 是旧 App。
869
+ // 协议 v2 的形状:带 `sealed`。没有 sealed 的六位码入口不再受理
870
+ //(需求变为不接老配对),带 `proto` 的过期旧图在上面按重扫当前二维码收口。
870
871
  const sealed = typeof input?.sealed === 'string' ? input.sealed.trim() : '';
871
872
  // 与 `/pair` 同一条收口(§10.4(d)):认得协议(请求里带 `proto`)却还带
872
873
  // 六位码,只可能是过期的旧二维码 —— 那条形状逐位可试,不值得继续开门。
@@ -903,34 +904,19 @@ function createLanProxy(opts) {
903
904
  issuedExtra = { deviceKey: opened.deviceKey, keyId: opened.keyId };
904
905
  pairKey = opened.pairKey;
905
906
  } else {
906
- const code = typeof input?.code === 'string' ? input.code.trim() : '';
907
- // 长度不符直接判错(timingSafeEqual 长度不同会抛异常,曾导致整个 dsh web 崩溃)
908
- if (!/^\d{6}$/.test(code)) {
909
- res.writeHead(400, { 'content-type': 'application/json' });
910
- res.end(JSON.stringify({ ok: false, error: '配对码需为 6 位数字' }));
911
- return;
912
- }
913
- if (!safeEqual(code, String(pairing.code || ''))) {
914
- log('lan pair: pairing code mismatch')
915
- pairThrottle.noteFail();
916
- pairDenied(res);
917
- return;
918
- }
919
- suppliedDevice = input && typeof input.device === 'object' && input.device !== null
920
- ? input.device
921
- : {
922
- name: input?.name,
923
- platform: input?.platform,
924
- osVersion: input?.osVersion,
925
- version: input?.version,
926
- appVersion: input?.appVersion,
927
- id: input?.id,
928
- deviceId: input?.deviceId,
929
- }
907
+ // 需求变为不接老配对:无 proto 的六位码入口会新产生明文会话,官方二维码
908
+ // 都带票据,这个入口直接拒掉,提示用当前二维码重新扫。码的真假不再校验。
909
+ res.writeHead(400, { 'content-type': 'application/json' });
910
+ res.end(JSON.stringify({
911
+ ok: false,
912
+ code: 'pairing-code-retired',
913
+ error: '六位配对码已停用,请用电脑面板上当前的二维码重新扫',
914
+ }));
915
+ return;
930
916
  }
931
- // 配对码正确 / 票据解得开 → 桌面端授权(TeamViewer 模型)。透传手机端完整设备元数据。
917
+ // 票据解得开 → 桌面端授权(TeamViewer 模型)。透传手机端完整设备元数据。
932
918
  // 注意:这里**不**清限流计数——被拒绝的尝试同样要计数,否则
933
- // 猜对配对码但被拒的一方可以无限次重试。
919
+ // 拿得到票据但被拒的一方可以无限次重试。
934
920
  const device = {
935
921
  ...Object.fromEntries(Object.entries(suppliedDevice || {}).filter(([, value]) => value !== undefined)),
936
922
  ip: (suppliedDevice && suppliedDevice.ip) || ip,
@@ -939,8 +925,8 @@ function createLanProxy(opts) {
939
925
  .then(({ approved, token, platform }) => {
940
926
  if (!approved) {
941
927
  // 走到这里才是「电脑真的放行策略拒绝了它」;内部没答上那条已在
942
- // onApprove 里抛成 5xx,不会冒充这句。与「配对码错误」返回同一响应,
943
- // 配对码不再可通过状态码探测。
928
+ // onApprove 里抛成 5xx,不会冒充这句。与「解不开票据」返回同一响应,
929
+ // 授权结果不再可通过状态码探测。
944
930
  log('lan pair: approval denied by host policy')
945
931
  pairDenied(res);
946
932
  return;
@@ -1,3 +1,4 @@
1
+ // 2026-11-30:放大弹窗的勾选预览走 `pairingPayload.filterInclude`——按 query 只换码内容,不落盘、不动票据。
1
2
  // 2026-11-29:公网 IPv6 也能单独撑起一张配对码——宿主侧拒 IPv6 的限制已删,出码判据跟上。
2
3
  // 2026-11-27:进二维码的服务商线路名字截到 40 字——名字只是显示用,长名字能把码撑到扫不出来。
3
4
  // 2026-11-24:服务商的 http(s) 地址同时进 lanUrls,让不认 routes 的老包也能扫码走服务商直连;
@@ -27,6 +28,7 @@ const {
27
28
  advertisedCandidates,
28
29
  phoneCandidates,
29
30
  manualCandidate,
31
+ manualIpv4Candidate,
30
32
  ipv6Candidates,
31
33
  withManualIpv4Candidate,
32
34
  withManualIpv6Candidate,
@@ -183,6 +185,72 @@ function pairingPayload(state, lanPort) {
183
185
  return { payload, text: pairingText(payload) };
184
186
  }
185
187
 
188
+ /**
189
+ * 放大弹窗里那五类勾选的预览过滤(`/api/relay/pairing?include=`)。
190
+ *
191
+ * 只在调用方明确带了 `?include=` 时才起作用;参数缺失,或者五类全在集合里,都原样返回——
192
+ * 默认那张码必须与没有这个功能时逐字一致。过滤是**就地把这次生成的 payload 削一削**,
193
+ * 不碰 state、不换票据、不写配置;调用方随后还会照常做 pairingHasAddress 判定,空集合自然出不了码。
194
+ *
195
+ * `lanUrls` 里混着三类地址:网卡扫出来的、用户手填的(含手填 IPv4),以及 TCP 桥那条
196
+ * `http://host:port`。这里按来源把它们分开:手填的认设置项,TCP 认 `tcpDirectTarget`,
197
+ * 剩下的才算「局域网自动发现」。服务商线路与 Cloudflare 是独立那一栏,不在这五类里,
198
+ * 仍按原样留在 `routes` 与 `lanUrls`。
199
+ *
200
+ * 挂在 `pairingPayload` 上而不是在控制面顶部加一条 import:出码那两行取样代码是票据复核的
201
+ * 基准(见 test/control-plane-routes.test.cjs 的变异用例),保持它原样最省事。
202
+ */
203
+ const PAIRING_INCLUDE_KEYS = ['relay', 'lan', 'direct', 'ipv6', 'tcp'];
204
+
205
+ /** query 值 → 勾选集合;参数缺失(`null`)表示全选。未知 token 忽略,全选等价于不过滤。 */
206
+ function parsePairingInclude(raw) {
207
+ if (raw === null || raw === undefined) return null;
208
+ const set = new Set(String(raw).split(',').map((part) => part.trim().toLowerCase())
209
+ .filter((part) => PAIRING_INCLUDE_KEYS.includes(part)));
210
+ if (PAIRING_INCLUDE_KEYS.every((key) => set.has(key))) return null;
211
+ return set;
212
+ }
213
+
214
+ function filterPairingInclude(payload, raw, state) {
215
+ const include = parsePairingInclude(raw);
216
+ if (!include || !payload || typeof payload !== 'object') return payload;
217
+ const keep = (key) => include.has(key);
218
+
219
+ if (!keep('relay')) {
220
+ delete payload.relayUrl;
221
+ delete payload.relayUrls;
222
+ }
223
+ if (!keep('ipv6')) delete payload.ipv6Candidates;
224
+ if (!keep('tcp')) delete payload.tcpUrl;
225
+ if (!keep('direct')) delete payload.directUrl;
226
+
227
+ const manual = new Set();
228
+ if (state && state.lanEnabled) {
229
+ const direct = manualCandidate(state.manualLanUrl);
230
+ if (direct) manual.add(direct.url);
231
+ const ipv4 = manualIpv4Candidate(state.manualIpv4Url);
232
+ if (ipv4) manual.add(ipv4.url);
233
+ }
234
+ const tcpTarget = tcpDirectTarget(state && state.manualTcpUrl);
235
+ const tcpLanUrl = tcpTarget ? `http://${tcpTarget}` : '';
236
+ // 服务商线路不在这五类里:routes 整栏照旧,写进 lanUrls 的那份兼容副本也照旧。
237
+ const routeUrls = new Set((Array.isArray(payload.routes) ? payload.routes : [])
238
+ .filter((row) => row && row.transport === 'http' && typeof row.url === 'string')
239
+ .map((row) => row.url));
240
+ if (Array.isArray(payload.lanUrls)) {
241
+ payload.lanUrls = payload.lanUrls.filter((url) => {
242
+ if (routeUrls.has(url)) return true;
243
+ if (manual.has(url)) return keep('direct');
244
+ if (tcpLanUrl && url === tcpLanUrl) return keep('tcp');
245
+ return keep('lan');
246
+ });
247
+ }
248
+ return payload;
249
+ }
250
+
251
+ pairingPayload.parseInclude = parsePairingInclude;
252
+ pairingPayload.filterInclude = filterPairingInclude;
253
+
186
254
  /**
187
255
  * 载荷 → 二维码里那一串 `dshpair://`。
188
256
  *
@@ -220,4 +288,4 @@ function pairingHasAddress(payload) {
220
288
  );
221
289
  }
222
290
 
223
- module.exports = { pairingPayload, pairingText, pairingHasAddress };
291
+ module.exports = { pairingPayload, pairingText, pairingHasAddress, parsePairingInclude, filterPairingInclude, PAIRING_INCLUDE_KEYS };
@@ -1,3 +1,4 @@
1
+ // 2026-11-30:出码路由支持 ?include= 勾选预览:只换二维码内容,不落盘、不作废票据。
1
2
  // 2026-11-28:新增语音面板配置口(/api/relay/voice/config),纳入网页访问窗口。
2
3
  // 2026-11-27:面板中转检测与 APP 同判据——不跟跳、回包必须 ok 且服务名正确,别再给假绿灯。
3
4
  // 2026-11-27:二维码回归一次性门票——隧道段只在唯一通路时进码,点对点只带身份不带候选清单。
@@ -1213,7 +1214,14 @@ function registerControlPlaneRoutes(deps) {
1213
1214
  * 配置」,等于拿一条还没验过的地址覆盖正在用的设置;现在预览走这里,真写入只在用户
1214
1215
  * 明确按下「连接中转」时发生。
1215
1216
  */
1216
- const preview = typeof req.url === 'string' ? new URL(req.url, 'http://local').searchParams.get('relayUrl') : null
1217
+ const query = typeof req.url === 'string' ? new URL(req.url, 'http://local').searchParams : null
1218
+ const preview = query ? query.get('relayUrl') : null
1219
+ /**
1220
+ * `?include=` 是放大弹窗那五类勾选的**预览参数**:relay / lan / direct / ipv6 / tcp 的逗号集合。
1221
+ * 与上面的 `?relayUrl=` 同一条规矩——只换这一张码的内容,不写配置、不作废票据;参数缺失
1222
+ * (以及五类全选)由 `filterInclude` 原样放过,生成的码与没有这个功能时逐字一致。
1223
+ */
1224
+ const include = query ? query.get('include') : null
1217
1225
  // 预览那一份要**两格一起换**:只改 `relayUrl` 的话,state 上原来那组 `relayUrls` 会
1218
1226
  // 按「列表优先」把预览地址盖回去,面板上填了新域名却还是旧的那张码。
1219
1227
  const previewUrl = preview && /^https?:\/\/[^\s]+$/i.test(preview.trim())
@@ -1233,6 +1241,8 @@ function registerControlPlaneRoutes(deps) {
1233
1241
  }
1234
1242
  const source = previewUrl ? { ...state, relayUrl: previewUrl, relayUrls: [previewUrl] } : state
1235
1243
  const { payload } = pairingPayload(source, lanPortInUse())
1244
+ // 勾选预览:就在这一份 payload 上剔字段,下面验票 / 地址判定 / SVG 全用剔过的那份。
1245
+ if (include !== null) pairingPayload.filterInclude(payload, include, source)
1236
1246
  // 隧道这一整段又长又敏感(地址、钥匙、证明),而它是**配好之后**才需要的数据通道:
1237
1247
  // 手机配完凭已经通着的那条连接报名就能换到入口地址。所以只有它本身就是唯一通路
1238
1248
  // (没中转、没局域网/服务商线路)时才写进码里;有别的路可走就不重复投递。
@@ -1,3 +1,4 @@
1
+ // 2026-11-30:五类真实动作的成功回包记账,按设备时间经 activity 的状态出口带出去。
1
2
  // 2026-11-29:挂语音自动学习词库接口 /voice/lexicon/learn。
2
3
  // 2026-11-28:语音流升级路由改由装配层显式交 ctx(取值器),不再只靠运行时记下的那一个。
3
4
  // 2026-11-28:挂语音网关三条移动路由(能力表 / 整段 / 流式升级),实现在 mobile/voice/。
@@ -115,6 +116,8 @@ const sync = require('../mobile/sync.js');
115
116
  const { createTransferTickets } = require('../mobile/transfer-tickets.js');
116
117
  const { createSyncInboxStore } = require('../mobile/sync-inbox-store.js');
117
118
  const { credentialsEntry } = require('../shared/credentials-entry.js');
119
+ // 五类真实操作的记账:包装层只看这五条路径的成功回包,其它一律不碰。
120
+ const activity = require('../mobile/activity.cjs');
118
121
  const { handleCredentialUpgrade } = require('../mobile/credential-upgrade.js');
119
122
  const { handleSyncIdentity } = require('../mobile/claim-identity.js');
120
123
  const extensions = require('../mobile/extensions.js');
@@ -295,7 +298,7 @@ function registerMobileRoutes(deps) {
295
298
  const tunnel = getSidecarSnapshot?.()?.tunnel
296
299
  return state.enabled && tunnel?.state === 'connected' ? tunnel.relayUrl || tunnel.route?.url || null : null
297
300
  }
298
- const route = (path, handler) => registerRoute({ kind: 'exact', path, handler: guarded(handler) })
301
+ const route = (path, handler) => registerRoute({ kind: 'exact', path, handler: guarded(activity.withInteractionNote(path, handler)) })
299
302
  // 只能 POST 的写路由:路由注册器不分方法,若不挡,GET 带查询串也能进写 handler
300
303
  // (Forge 的读体会回落到查询串),等于给了个可被链接/预取误触的写入口。
301
304
  const postOnly = (handler) => (ctx, req, res) => (req.method === 'POST'
@@ -1,3 +1,4 @@
1
+ // 2026-11-30:Bonjour 广播单独开关;关掉只停发布,局域网监听与配对照旧。
1
2
  // 2026-11-29:绑定局域网入口不再传凭据库;换号只看固定端口开关。
2
3
  // 2026-11-26:控制台退出事件不再带走 worker,信号处理器抢在依赖加载之前注册。
3
4
  // 2026-11-25:专属回环入口随局域网代理一起启动,实绑端口上报宿主落盘;sidecar 白名单放行该运行时字段。
@@ -366,6 +367,13 @@ function snapshotRead(info) {
366
367
  }
367
368
  return body
368
369
  }
370
+ /**
371
+ * Bonjour 广播要不要发布。入口关着当然不发布;发现开关只有显式 false 才算关,
372
+ * 老配置没这一格、坏值都按开(老行为)。这一位只管发布,不管局域网监听与地址候选。
373
+ */
374
+ function discoveryPublishingOf(c) {
375
+ return Boolean(c.lanEnabled) && c.lanDiscoveryEnabled !== false
376
+ }
369
377
  /**
370
378
  * 「这份配置里哪几项决定隧道要重建」。
371
379
  *
@@ -392,7 +400,7 @@ function tunnelSignature(c) {
392
400
  function lanSignature(c) {
393
401
  // **配对码与票据不在其中**:它们由 `currentPairing` 现读,改它们不该重建监听 ——
394
402
  // 配对成功就要换一次(§5.1),跟着重建会把刚握上的连接掐掉。
395
- return JSON.stringify([Boolean(c.enabled), Boolean(c.lanEnabled), c.lanPort || 0, c.tunnelIngressPort || 0, c.upstreamPort || 0, c.upstreamHost || '', c.instanceId || '', c.previousInstanceId || '', c.lanSecret || '', c.pairingTier || 'full'])
403
+ return JSON.stringify([Boolean(c.enabled), Boolean(c.lanEnabled), c.lanDiscoveryEnabled !== false, c.lanPort || 0, c.tunnelIngressPort || 0, c.upstreamPort || 0, c.upstreamHost || '', c.instanceId || '', c.previousInstanceId || '', c.lanSecret || '', c.pairingTier || 'full'])
396
404
  }
397
405
  /** 「这份配置里哪几项决定网络监视器要不要重排」。 */
398
406
  function monitorSignature(c) {
@@ -763,7 +771,7 @@ async function startLan() {
763
771
  const own = lanGeneration
764
772
  lanRequestedPort = config.lanPort
765
773
  lanState = 'connecting'
766
- const discovery = config.lanEnabled
774
+ const discovery = discoveryPublishingOf(config)
767
775
  ? createLanDiscovery({ instanceId: config.instanceId, onChange: publishState })
768
776
  : { publish: async () => false, stop: async () => {}, snapshot: () => ({ state: 'off', error: null }) }
769
777
  lanDiscovery = discovery
@@ -851,7 +859,7 @@ async function configure(next) {
851
859
  // `relayUrls` 在白名单里,而且从这一轮起**进签名**(见 tunnelSignature):地址组或它的
852
860
  // 顺序变了就要重新择路。白名单缺了它,宿主下发这一格会直接抛 unknown configuration
853
861
  // field,整次配置下发失败。
854
- const allowed = ['enabled', 'relayUrl', 'relayUrls', 'instanceId', 'previousInstanceId', 'pairingCode', 'pairingTicket', 'pairingTier', 'name', 'upstreamPort', 'upstreamHost', 'lanPort', 'lanPortLockReason', 'lanEnabled', 'lanSecret', 'registerSecret', 'tunnelIngressPort', 'ipVersionPolicy']
862
+ const allowed = ['enabled', 'relayUrl', 'relayUrls', 'instanceId', 'previousInstanceId', 'pairingCode', 'pairingTicket', 'pairingTier', 'name', 'upstreamPort', 'upstreamHost', 'lanPort', 'lanPortLockReason', 'lanEnabled', 'lanDiscoveryEnabled', 'lanSecret', 'registerSecret', 'tunnelIngressPort', 'ipVersionPolicy']
855
863
  if (Object.keys(next).some(key => !allowed.includes(key))) throw new Error('unknown configuration field')
856
864
  if (next.ipVersionPolicy !== undefined && !['auto', 'ipv4-first', 'ipv4-only'].includes(next.ipVersionPolicy)) throw new Error('invalid ipVersionPolicy')
857
865
  if (typeof next.instanceId !== 'string' || next.instanceId.length > 128) throw new Error('invalid instanceId')
@@ -862,6 +870,8 @@ async function configure(next) {
862
870
  if (typeof next.upstreamPort !== 'number' || !Number.isInteger(next.upstreamPort) || next.upstreamPort < 1 || next.upstreamPort > 65535) throw new Error('invalid upstreamPort')
863
871
  if (next.upstreamHost !== undefined && (typeof next.upstreamHost !== 'string' || !next.upstreamHost || next.upstreamHost.length > 64)) throw new Error('invalid upstreamHost')
864
872
  if (next.lanPort !== undefined && (!Number.isInteger(next.lanPort) || next.lanPort < 1024 || next.lanPort > 65535)) throw new Error('invalid lanPort')
873
+ // 广播开关只认布尔;缺字段与坏值都按开,但下发的坏形状当场挡住,别让半截配置进监听。
874
+ if (next.lanDiscoveryEnabled !== undefined && typeof next.lanDiscoveryEnabled !== 'boolean') throw new Error('invalid lanDiscoveryEnabled')
865
875
  // 专属入口端口是运行时字段(默认 0 = 内核分配);坏值宁可退回分配,也不拿它去听一个死端口。
866
876
  if (next.tunnelIngressPort !== undefined && (!Number.isInteger(next.tunnelIngressPort) || next.tunnelIngressPort < 0 || next.tunnelIngressPort > 65535)) throw new Error('invalid tunnelIngressPort')
867
877
  if (next.registerSecret !== undefined && (typeof next.registerSecret !== 'string' || next.registerSecret.length > 512)) throw new Error('invalid registerSecret')
@@ -1,3 +1,4 @@
1
+ // 2026-11-30:需求变为不接外部组件老形状——助手事件缺 peerKey 直接丢,密码学材料不齐直接抛错。
1
2
  // 助手重启读取当前已持久身份与白名单,按 peer 保留 IPC 生命周期;平台表含 Windows ARM64。
2
3
  'use strict';
3
4
 
@@ -40,9 +41,9 @@ const BACKOFF_MS = [1_000, 2_000, 5_000, 10_000, 30_000];
40
41
  /** 事件里允许出现的键,多一个少一个都当脏数据丢掉(stdout 是私有 IPC)。 */
41
42
  const EVENT_KEYS = {
42
43
  ready: ['address'],
43
- p2pReady: ['url', 'candidates'],
44
- p2pStopped: [],
45
- p2pStatus: ['running', 'url', 'path', 'active', 'detail', 'candidates'],
44
+ p2pReady: ['url', 'candidates', 'peerKey'],
45
+ p2pStopped: ['peerKey'],
46
+ p2pStatus: ['running', 'url', 'path', 'active', 'detail', 'candidates', 'peerKey'],
46
47
  p2pKeys: ['private', 'public', 'port'],
47
48
  pairing: ['address', 'port', 'key', 'proof', 'expiresAt'],
48
49
  paired: ['address', 'client'],
@@ -51,19 +52,6 @@ const EVENT_KEYS = {
51
52
  error: ['code'],
52
53
  };
53
54
 
54
- /**
55
- * 这些事件**允许**多带一个 `peerKey`(手机公钥),其余键一个不多。
56
- *
57
- * 一台电脑同时接多台手机之后,助手报的 `p2pReady` / `p2pStatus` 是「哪一台的」必须能分开,
58
- * 否则插件没法把状态路由到对应那台。但这条 IPC 的严格白名单照旧:只给这两个事件开这一个
59
- * 可选键,其余键、其余事件多一个字节都还是脏数据。老助手不发这一格,所以是可选而不是必填。
60
- */
61
- const OPTIONAL_EVENT_KEYS = {
62
- p2pReady: ['peerKey'],
63
- p2pStatus: ['peerKey'],
64
- p2pStopped: ['peerKey'],
65
- };
66
-
67
55
  const ADDRESS = /^tc[\x21-\x7e]{0,4095}$/;
68
56
  const PRIVATE_KEY = /^privkey:[0-9a-f]{64}$/;
69
57
  const CLIENT_KEY = /^nodekey:[0-9a-f]{64}$/;
@@ -161,14 +149,12 @@ function createTailcatHost(options) {
161
149
  if (typeof kind !== 'string' || !EVENT_KEYS[kind]) return;
162
150
  const keys = Object.keys(value);
163
151
  const fields = EVENT_KEYS[kind];
164
- // 已发布的旧助手只回 running:false;仅这一个空形态补齐,运行态仍须完整。
165
- if (kind === 'p2pStatus' && value.running === false) {
166
- value = { url: '', path: 'unknown', active: false, detail: '', candidates: [], ...value };
167
- }
168
152
  if (fields.some(field => !(field in value))) return;
169
- const optional = OPTIONAL_EVENT_KEYS[kind] || [];
170
- const extra = keys.filter(key => key !== 'event' && !fields.includes(key) && !optional.includes(key));
153
+ const extra = keys.filter(key => key !== 'event' && !fields.includes(key));
171
154
  if (extra.length > 0) return;
155
+ // 需求变为不接外部组件老形状:peerKey 现在是必填标识,缺了就丢,不猜是哪台手机。
156
+ if ((kind === 'p2pReady' || kind === 'p2pStatus' || kind === 'p2pStopped')
157
+ && (typeof value.peerKey !== 'string' || !value.peerKey.trim())) return;
172
158
 
173
159
  if (kind === 'ready' && typeof value.address === 'string' && (value.address === '' || ADDRESS.test(value.address))) {
174
160
  ready = true;
@@ -292,11 +278,15 @@ function createTailcatHost(options) {
292
278
  * 三个动作。
293
279
  */
294
280
  startP2P(options) {
281
+ // 密码学桥缺私钥 / 对端公钥必须抛错,不能写空串给助手装作拉起了隧道。
282
+ const privateKey = typeof options.privateKey === 'string' ? options.privateKey.trim() : '';
283
+ const peerKey = typeof options.peerKey === 'string' ? options.peerKey.trim() : '';
284
+ if (!privateKey || !peerKey) throw new Error('P2P 公钥或私钥缺失,拒绝拉起隧道');
295
285
  const list = (value) => (Array.isArray(value) ? value.filter(item => typeof item === 'string') : []);
296
286
  write({
297
287
  command: 'p2pStart',
298
- p2pPrivateKey: String(options.privateKey || ''),
299
- p2pPeerKey: String(options.peerKey || ''),
288
+ p2pPrivateKey: privateKey,
289
+ p2pPeerKey: peerKey,
300
290
  p2pPeerLocal: list(options.peerLocal),
301
291
  p2pPeerPublic: list(options.peerPublic),
302
292
  p2pListenPort: Number(options.listenPort) || 0,
@@ -304,7 +294,9 @@ function createTailcatHost(options) {
304
294
  });
305
295
  },
306
296
  stopP2P(peerKey) {
307
- write({ command: 'p2pStop', ...(peerKey ? { p2pPeerKey: String(peerKey) } : {}) });
297
+ const key = typeof peerKey === 'string' ? peerKey.trim() : '';
298
+ if (!key) throw new Error('停止 P2P 缺少对端公钥,拒绝猜落点');
299
+ write({ command: 'p2pStop', p2pPeerKey: key });
308
300
  },
309
301
  statusP2P() {
310
302
  write({ command: 'p2pStatus' });
@@ -1,3 +1,4 @@
1
+ // 2026-11-30:需求变为不接外部组件老形状,老客户端的流量输出不再当「没有」,改报升级提示。
1
2
  // 2026-11-29:所有 CLI 调用显式带 --workdir,普通用户读账号快照不再落到 /etc/zeronews。
2
3
  // 只读账号快照:把 CLI 的 status / show 三张清单归一成面板能直接画的结构,不写配置、不建隧道。
3
4
  'use strict';
@@ -293,8 +294,7 @@ function createZeroNewsAccountReader(options = {}) {
293
294
  });
294
295
  }
295
296
  // 几张清单彼此独立,一起拉;某一张读失败就空着,不把整页带崩。
296
- // 流量是 4.1.1 才有的命令,老客户端执行它只会打帮助文本、照样退 0;
297
- // 读不出就 traffic 为空,面板不显示这一行,别让它把「清单读失败」的提示带出来。
297
+ // 流量是 4.1.1 才有的命令,老客户端执行它只会打帮助文本、照样退 0。
298
298
  const [devicesRes, tunnelsRes, domainsRes, trafficRes] = await Promise.all([
299
299
  runJson(binary, ['show', 'devices', '--json']),
300
300
  runJson(binary, ['show', 'tunnels', '--json']),
@@ -304,13 +304,17 @@ function createZeroNewsAccountReader(options = {}) {
304
304
  const deviceItems = itemsOf(devicesRes.parsed);
305
305
  const tunnelItems = itemsOf(tunnelsRes.parsed);
306
306
  const domainItems = itemsOf(domainsRes.parsed);
307
+ // 需求变为不接外部组件老形状:流量读不出不再当「这一格没有」,明确报升级提示。
308
+ const traffic = normalizeTraffic(trafficRes.parsed);
309
+ const legacyTraffic = traffic === null;
307
310
  const failed = [devicesRes, tunnelsRes, domainsRes].some((r) => !r.parsed);
308
311
  return {
309
312
  ok: true,
310
313
  available: true,
311
314
  login: true,
312
315
  resourcesLoaded: !failed,
313
- error: failed ? 'part of account data could not be loaded' : '',
316
+ error: failed ? 'part of account data could not be loaded'
317
+ : (legacyTraffic ? '本机 ZeroNews 客户端版本过旧,请升级到 4.1.1 后才能读取流量用量' : ''),
314
318
  client,
315
319
  account,
316
320
  counts: {
@@ -318,7 +322,7 @@ function createZeroNewsAccountReader(options = {}) {
318
322
  tunnels: totalOf(tunnelsRes.parsed, tunnelItems),
319
323
  domains: totalOf(domainsRes.parsed, domainItems),
320
324
  },
321
- traffic: normalizeTraffic(trafficRes.parsed),
325
+ traffic,
322
326
  devices: compact(deviceItems.map(normalizeDevice)),
323
327
  tunnels: compact(tunnelItems.map(normalizeTunnel)),
324
328
  domains: compact(domainItems.map(normalizeDomain)),
@@ -1,3 +1,4 @@
1
+ // 2026-11-30:需求变为不接外部组件老形状,本地 API 只认新版 endpoints 响应字段。
1
2
  // 从本机 ZeroNews 客户端读取「已建好的隧道公网地址」,给面板的「一键填入直连地址」用。
2
3
  'use strict';
3
4
 
@@ -38,29 +39,29 @@ function httpsUrlOf(value) {
38
39
  return url;
39
40
  }
40
41
 
42
+ function legacyShapeError() {
43
+ return new Error('本机 ZeroNews 客户端输出的是老格式,请升级客户端到支持新版 endpoints 响应的版本');
44
+ }
45
+
41
46
  /**
42
- * 从 ZeroNews 本地 API 的响应体里挑出可用的 HTTPS 公网地址。
43
- * 兼容两种形状:官方文档的 `{ code:200, data:{ items:[...] } }`,以及某些版本回的裸数组 / `{ endpoints:[...] }`。
44
- * 每条 endpoint 的域名可能在 `domain` 或 `public_url`;端口由 ZeroNews 自己管,域名不带端口。
47
+ * 从 ZeroNews 本地 API 的新版响应 `{ code:200, data:{ items:[...] } }` 里挑 HTTPS 公网地址。
48
+ * 域名只认 `domain`。需求变为不接外部组件老形状:裸数组 / `endpoints` 别名 / `public_url`
49
+ * 别名一律拒绝,报「升级客户端」,不再替老工具归一。
45
50
  */
46
51
  function extractEndpoints(payload) {
47
- const data = payload && typeof payload === 'object' && 'data' in payload ? payload.data : payload;
48
- let items = [];
49
- if (Array.isArray(data)) items = data;
50
- else if (data && Array.isArray(data.items)) items = data.items;
51
- else if (data && Array.isArray(data.endpoints)) items = data.endpoints;
52
+ const obj = payload && typeof payload === 'object' && !Array.isArray(payload) ? payload : {};
53
+ const data = obj.data;
54
+ if (obj.code !== 200 || !data || typeof data !== 'object' || Array.isArray(data) || !Array.isArray(data.items)) throw legacyShapeError();
52
55
  const out = [];
53
56
  const seen = new Set();
54
- for (const item of items) {
57
+ for (const item of data.items) {
55
58
  if (!item || typeof item !== 'object') continue;
56
59
  const status = String(item.status || '').toLowerCase();
57
60
  if (status && status !== 'active') continue;
58
61
  const type = String(item.type || '').toUpperCase();
59
62
  if (type && type !== 'HTTPS') continue;
60
- const domain = typeof item.domain === 'string' && item.domain
61
- ? item.domain
62
- : typeof item.public_url === 'string' ? item.public_url : '';
63
- const url = httpsUrlOf(domain.includes('://') ? domain : `https://${domain}`);
63
+ if (typeof item.domain !== 'string' || !item.domain) throw legacyShapeError();
64
+ const url = httpsUrlOf(`https://${item.domain}`);
64
65
  if (!url || seen.has(url)) continue;
65
66
  seen.add(url);
66
67
  out.push(url);
@@ -105,7 +106,14 @@ async function readZeroNewsEndpoints(options = {}) {
105
106
  if (payload && typeof payload === 'object' && 'code' in payload && payload.code !== 200) {
106
107
  return { ok: false, urls: [], available: true, error: 'ZeroNews 客户端返回了错误' };
107
108
  }
108
- return { ok: true, urls: extractEndpoints(payload), available: true, error: '' };
109
+ // 只认官方新版响应;老形状直接报「升级客户端」,不替老工具归一。
110
+ let urls;
111
+ try {
112
+ urls = extractEndpoints(payload);
113
+ } catch (error) {
114
+ return { ok: false, urls: [], available: true, error: error && error.message ? error.message : 'ZeroNews 客户端输出老格式,请升级' };
115
+ }
116
+ return { ok: true, urls, available: true, error: '' };
109
117
  } catch (error) {
110
118
  if (controller && controller.signal.aborted) {
111
119
  return { ok: false, urls: [], available: false, error: '读取本机 ZeroNews 超时,请确认客户端正在运行' };
@@ -1,3 +1,4 @@
1
+ // 2026-11-30:需求变为不接外部组件老形状,CLI status 只认新版字段,老工具报错提示升级。
1
2
  // 2026-11-29:所有 CLI 调用显式带 --workdir(可执行文件所在目录,普通用户可写),不再落到 /etc/zeronews。
2
3
  // 2026-11-29:本地判活走本机 healthz,不跑官方 CLI,重载窗口里 attach 的客户端静默退出也能发现。
3
4
  // 2026-11-29:体检不再自己跑官方 CLI 查状态;面板读账号快照带来的 status 直接传进来判活。
@@ -5,7 +6,7 @@
5
6
  // 2026-11-27:复用本机已在跑的客户端前比对 client_id / cloud_server_addr,另一个身份占位就明确报错不 attach。
6
7
  // 2026-11-27:外部把隧道重建到新端口时,先用 endpoints 的落点刷新本次比对值,第一次 connect 就认下新端口。
7
8
  // 2026-11-26:体检发现旧隧道落点端口没人监听就判失效(只改本机状态,不删不建云端隧道),交接线层清地址让兜底顶上。
8
- // 2026-11-25:CLI status 的 connected 也认作在跑,兼容新版客户端字段,别把活线路抖成掉线重连。
9
+ // 2026-11-25:running 认新版 CLI 的 connected,老客户端只报 running 的按老形状拒绝并提示升级。
9
10
  // 2026-11-25:端口失配带上可识别的 reason,让接线层清掉旧地址(配对码不再带失效线路)。
10
11
  // 2026-11-25:running 认守护进程而非早退出的启动进程;连上后可由接线层定时体检判活。
11
12
  // 2026-11-25:复用隧道前比对 local_port,旧端口隧道不再静默复用。
@@ -148,12 +149,16 @@ function pickEndpoint(payload, expectedPort) {
148
149
  */
149
150
  function parseStatusPayload(raw) {
150
151
  const obj = raw && typeof raw === 'object' ? raw : {};
152
+ // 需求变为不接外部组件老形状:running 是老字段,新版只报 connected。
153
+ if ('running' in obj && !('connected' in obj)) {
154
+ throw legacyShapeError('本机 ZeroNews 客户端输出的是老版 status 字段(running),请升级客户端到新版后再接入');
155
+ }
151
156
  const truthy = (value) => value === true || value === 'true';
152
157
  return {
153
158
  login: truthy(obj.login),
154
159
  loginPending: truthy(obj.login_pending),
155
160
  loginError: typeof obj.login_error === 'string' ? obj.login_error.trim() : '',
156
- running: truthy(obj.running) || truthy(obj.connected),
161
+ running: truthy(obj.connected),
157
162
  configured: truthy(obj.configured),
158
163
  clientId: typeof obj.client_id === 'string' ? obj.client_id.trim() : '',
159
164
  node: typeof obj.cloud_server_addr === 'string' ? obj.cloud_server_addr.trim() : '',
@@ -184,6 +189,13 @@ function terminalError(message, reason) {
184
189
  return error;
185
190
  }
186
191
 
192
+ /** 老工具字段形状:报「升级客户端」,标 terminal 让接线层别无限重试。 */
193
+ function legacyShapeError(message) {
194
+ const error = new Error(message);
195
+ error.code = 'zeronews-legacy';
196
+ return error;
197
+ }
198
+
187
199
  /**
188
200
  * @param {object} options
189
201
  * @param {() => Promise<{ok:boolean,path:string,code?:string}>} options.ensure 取二进制(provision)
@@ -288,11 +300,16 @@ function createZeroNewsRunner(options = {}) {
288
300
  const start = text.indexOf('{');
289
301
  const end = text.lastIndexOf('}');
290
302
  if (start >= 0 && end > start) {
303
+ let parsed = null;
291
304
  try {
292
- const parsed = parseStatusPayload(JSON.parse(text.slice(start, end + 1)));
305
+ parsed = parseStatusPayload(JSON.parse(text.slice(start, end + 1)));
306
+ } catch (error) {
307
+ if (error && error.code === 'zeronews-legacy') throw terminalError(error.message);
308
+ }
309
+ if (parsed) {
293
310
  parsed.exitCode = result && typeof result.code === 'number' ? result.code : 0;
294
311
  return parsed;
295
- } catch { /* 落到下面按报错原文兜底 */ }
312
+ }
296
313
  }
297
314
  // 有些失败只把原因打在 stderr(比如 `auth client failed: client count limit ...`),没有 JSON。
298
315
  // 认得出就把原文挂到 loginError,走上层统一翻译,别当成「没登录」去空等。
@@ -634,7 +651,11 @@ function createZeroNewsRunner(options = {}) {
634
651
  if (phase !== 'connected' || aliveCheckPromise) return status();
635
652
  const gen = generation;
636
653
  aliveCheckPromise = (async () => {
637
- const st = stGiven !== undefined ? stGiven : await cliStatus();
654
+ let st = stGiven;
655
+ if (st === undefined) {
656
+ // CLI 读不到(含老格式报升级)当「不知道」,不动状态 —— 别因为一次读取失败抖掉还能用的线路。
657
+ try { st = await cliStatus(); } catch { return; }
658
+ }
638
659
  if (gen !== generation || phase !== 'connected' || !st) return;
639
660
  daemonRunning = st.running === true;
640
661
  await applyLiveness(gen);