dsh-mobile-plugin 0.5.144 → 0.5.146

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,5 @@
1
+ // 2026-11-30:Windows 上系统服务持有首选端口时 listen 抛 EACCES/EPERM,专属回环入口同样退到内核另分端口。
2
+ // 2026-11-30:需求变为不接老配对——/__lan_pair 的六位码入口直接拒掉,带票据的二维码照常配。
1
3
  // 2026-11-29:配对口不再按来源拒公网 IPv6,与公网 IPv4 同走全局令牌桶。
2
4
  // 2026-11-28:回环来源的通道标注从 lan 改记 tunnel,第三方穿透不再显示成「局域网」。
3
5
  // 2026-11-25:多开一条只听 127.0.0.1 的专属入口,与主入口共用 handleRequest;被占则内核另分一次并报上去。
@@ -27,7 +29,6 @@ const http = require('node:http');
27
29
  const { WebSocketServer, WebSocket } = require('ws');
28
30
  const core = require('./core.js');
29
31
  const { advertisedCandidates, ipv6Candidates, isGlobalUnicastV6 } = require('./lan-network.cjs');
30
- const { safeEqual } = require('../shared/dshtoken');
31
32
  const { isFreshRequest } = require('../shared/fresh-request');
32
33
  const { encodeJsonBody } = require('../shared/http-util');
33
34
  const { withViaHeader } = require('../shared/via-header');
@@ -866,7 +867,8 @@ function createLanProxy(opts) {
866
867
  const input = JSON.parse(b || '{}')
867
868
  // 校验用的码 / 票据 / 实例号以主进程为准(旁车缓存那份可能和二维码错开)。
868
869
  const pairing = await resolvePairing();
869
- // 两种形状(§8.3(2)):带 `sealed` 是协议 v2,带 `code` 是旧 App。
870
+ // 协议 v2 的形状:带 `sealed`。没有 sealed 的六位码入口不再受理
871
+ //(需求变为不接老配对),带 `proto` 的过期旧图在上面按重扫当前二维码收口。
870
872
  const sealed = typeof input?.sealed === 'string' ? input.sealed.trim() : '';
871
873
  // 与 `/pair` 同一条收口(§10.4(d)):认得协议(请求里带 `proto`)却还带
872
874
  // 六位码,只可能是过期的旧二维码 —— 那条形状逐位可试,不值得继续开门。
@@ -903,34 +905,19 @@ function createLanProxy(opts) {
903
905
  issuedExtra = { deviceKey: opened.deviceKey, keyId: opened.keyId };
904
906
  pairKey = opened.pairKey;
905
907
  } 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
- }
908
+ // 需求变为不接老配对:无 proto 的六位码入口会新产生明文会话,官方二维码
909
+ // 都带票据,这个入口直接拒掉,提示用当前二维码重新扫。码的真假不再校验。
910
+ res.writeHead(400, { 'content-type': 'application/json' });
911
+ res.end(JSON.stringify({
912
+ ok: false,
913
+ code: 'pairing-code-retired',
914
+ error: '六位配对码已停用,请用电脑面板上当前的二维码重新扫',
915
+ }));
916
+ return;
930
917
  }
931
- // 配对码正确 / 票据解得开 → 桌面端授权(TeamViewer 模型)。透传手机端完整设备元数据。
918
+ // 票据解得开 → 桌面端授权(TeamViewer 模型)。透传手机端完整设备元数据。
932
919
  // 注意:这里**不**清限流计数——被拒绝的尝试同样要计数,否则
933
- // 猜对配对码但被拒的一方可以无限次重试。
920
+ // 拿得到票据但被拒的一方可以无限次重试。
934
921
  const device = {
935
922
  ...Object.fromEntries(Object.entries(suppliedDevice || {}).filter(([, value]) => value !== undefined)),
936
923
  ip: (suppliedDevice && suppliedDevice.ip) || ip,
@@ -939,8 +926,8 @@ function createLanProxy(opts) {
939
926
  .then(({ approved, token, platform }) => {
940
927
  if (!approved) {
941
928
  // 走到这里才是「电脑真的放行策略拒绝了它」;内部没答上那条已在
942
- // onApprove 里抛成 5xx,不会冒充这句。与「配对码错误」返回同一响应,
943
- // 配对码不再可通过状态码探测。
929
+ // onApprove 里抛成 5xx,不会冒充这句。与「解不开票据」返回同一响应,
930
+ // 授权结果不再可通过状态码探测。
944
931
  log('lan pair: approval denied by host policy')
945
932
  pairDenied(res);
946
933
  return;
@@ -1089,8 +1076,11 @@ function createLanProxy(opts) {
1089
1076
  const startIngress = async () => {
1090
1077
  const preferred = Number.isInteger(ingressPort) && ingressPort > 0 ? ingressPort : 0;
1091
1078
  let result = await bindIngress(preferred);
1092
- if (result.error && preferred > 0 && result.error.code === 'EADDRINUSE') {
1093
- log(`回环入口 ${preferred} 被占,改由内核另分一次`);
1079
+ // Windows 上端口被系统级服务(如 PID 4 services.exe)持有时,listen 抛的是 EACCES/EPERM,
1080
+ // 不是 EADDRINUSE。三者都按「首选端口不可用」处理,让内核另分一次;实绑端口照旧回写落盘。
1081
+ // 其它错误码仍只记日志、返回 0。
1082
+ if (result.error && preferred > 0 && (result.error.code === 'EADDRINUSE' || result.error.code === 'EACCES' || result.error.code === 'EPERM')) {
1083
+ log(`回环入口 ${preferred} 被占或权限不足(${result.error.code}),改由内核另分一次`);
1094
1084
  result = await bindIngress(0);
1095
1085
  }
1096
1086
  if (result.error) {
@@ -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,5 @@
1
+ // 2026-11-30:桌面 config 路由收 ipVersionPolicy(三档枚举,与手机端同一句拒绝文案),status 包装回显已存值。
2
+ // 2026-11-30:出码路由支持 ?include= 勾选预览:只换二维码内容,不落盘、不作废票据。
1
3
  // 2026-11-28:新增语音面板配置口(/api/relay/voice/config),纳入网页访问窗口。
2
4
  // 2026-11-27:面板中转检测与 APP 同判据——不跟跳、回包必须 ok 且服务名正确,别再给假绿灯。
3
5
  // 2026-11-27:二维码回归一次性门票——隧道段只在唯一通路时进码,点对点只带身份不带候选清单。
@@ -40,6 +42,8 @@ const { randomBytes } = require('node:crypto');
40
42
  const core = require('../relay/core.js');
41
43
  const traffic = require('../relay/traffic-stats.cjs');
42
44
  const pairingApproval = require('../relay/pairing-policy.js');
45
+ // 出站协议族策略的合法三档与手机端共用一份(auto / ipv4-first / ipv4-only)。
46
+ const { POLICIES: IP_VERSION_POLICIES } = require('../relay/net-family.cjs');
43
47
  // 端口自检用的是局域网代理**同一把探针**(见 `../relay/port-allocator.cjs` 的文件头):
44
48
  // 这里说「可用」,真正 listen 时就不会 EADDRINUSE,两边不会各说各话。
45
49
  const { canListen } = require('../relay/port-allocator.cjs');
@@ -391,7 +395,7 @@ function registerControlPlaneRoutes(deps) {
391
395
  * 面板读的 status 在宿主那份上补一格总控上报目的地。包在这一层而不是
392
396
  * `createStatusView` 里:那份 JSON 手机端也在读,给它加字段是另一个决定。
393
397
  */
394
- const status = () => ({ ...rawStatus(), controlReportTargetUrl: getControlTargetUrl() });
398
+ const status = () => ({ ...rawStatus(), controlReportTargetUrl: getControlTargetUrl(), ipVersionPolicy: state.ipVersionPolicy });
395
399
  /**
396
400
  * 宿主发布的包管理器调用方式(`profileContext.packageManager`)。
397
401
  *
@@ -1213,7 +1217,14 @@ function registerControlPlaneRoutes(deps) {
1213
1217
  * 配置」,等于拿一条还没验过的地址覆盖正在用的设置;现在预览走这里,真写入只在用户
1214
1218
  * 明确按下「连接中转」时发生。
1215
1219
  */
1216
- const preview = typeof req.url === 'string' ? new URL(req.url, 'http://local').searchParams.get('relayUrl') : null
1220
+ const query = typeof req.url === 'string' ? new URL(req.url, 'http://local').searchParams : null
1221
+ const preview = query ? query.get('relayUrl') : null
1222
+ /**
1223
+ * `?include=` 是放大弹窗那五类勾选的**预览参数**:relay / lan / direct / ipv6 / tcp 的逗号集合。
1224
+ * 与上面的 `?relayUrl=` 同一条规矩——只换这一张码的内容,不写配置、不作废票据;参数缺失
1225
+ * (以及五类全选)由 `filterInclude` 原样放过,生成的码与没有这个功能时逐字一致。
1226
+ */
1227
+ const include = query ? query.get('include') : null
1217
1228
  // 预览那一份要**两格一起换**:只改 `relayUrl` 的话,state 上原来那组 `relayUrls` 会
1218
1229
  // 按「列表优先」把预览地址盖回去,面板上填了新域名却还是旧的那张码。
1219
1230
  const previewUrl = preview && /^https?:\/\/[^\s]+$/i.test(preview.trim())
@@ -1233,6 +1244,8 @@ function registerControlPlaneRoutes(deps) {
1233
1244
  }
1234
1245
  const source = previewUrl ? { ...state, relayUrl: previewUrl, relayUrls: [previewUrl] } : state
1235
1246
  const { payload } = pairingPayload(source, lanPortInUse())
1247
+ // 勾选预览:就在这一份 payload 上剔字段,下面验票 / 地址判定 / SVG 全用剔过的那份。
1248
+ if (include !== null) pairingPayload.filterInclude(payload, include, source)
1236
1249
  // 隧道这一整段又长又敏感(地址、钥匙、证明),而它是**配好之后**才需要的数据通道:
1237
1250
  // 手机配完凭已经通着的那条连接报名就能换到入口地址。所以只有它本身就是唯一通路
1238
1251
  // (没中转、没局域网/服务商线路)时才写进码里;有别的路可走就不重复投递。
@@ -1453,6 +1466,14 @@ function registerControlPlaneRoutes(deps) {
1453
1466
  }
1454
1467
  if (typeof body?.name === 'string' && body.name.trim()) patch.name = body.name.trim()
1455
1468
  if (body?.pairingPolicy === 'code' || body?.pairingPolicy === 'deny') patch.pairingPolicy = body.pairingPolicy
1469
+ // 出站协议族策略:合法档位与拒绝文案都跟手机端共用一份,非法值整次拒绝(不静默落 auto,
1470
+ // 否则面板以为存进去了,下一次打开又变回默认)。错误格式沿用本路由既有的 bad-request。
1471
+ if (body?.ipVersionPolicy !== undefined) {
1472
+ if (!IP_VERSION_POLICIES.includes(body.ipVersionPolicy)) {
1473
+ return sendJson(res, 400, { ok: false, error: { code: 'bad-request', message: `ipVersionPolicy 只能是 ${IP_VERSION_POLICIES.join(' / ')}` } })
1474
+ }
1475
+ patch.ipVersionPolicy = body.ipVersionPolicy
1476
+ }
1456
1477
  // 「自动上报网络地址」(总控上报)开关。只认布尔值,别的形状当没带 —— 'false' / 0 静默
1457
1478
  // 解释成关会让用户以为是自己关的,而界面上再也没处改回来。
1458
1479
  if (typeof body?.controlReportEnabled === 'boolean') patch.controlReportEnabled = body.controlReportEnabled
@@ -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 超时,请确认客户端正在运行' };