dsh-mobile-plugin 0.5.79 → 0.5.81

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.
@@ -84,6 +84,10 @@ function controlAddresses(state, port) {
84
84
  seen.add(a.url);
85
85
  dedup.push(a);
86
86
  }
87
+ // 清单里本来就有可连地址、而 TCP 这一格是空的:再补一条**空 url 的 tcp 标记**。
88
+ // 手机据此把「电脑上清掉了 TCP 目标」落到本地;老手机读到空 url 直接忽略,行为不变。
89
+ // 一条别的地址都没有时不补:那种状态下手机也没别的路可学,补了只会白建一条总控连接。
90
+ if (!tcp && dedup.length) dedup.push({ kind: 'tcp', url: '' });
87
91
  return dedup;
88
92
  }
89
93
 
@@ -113,7 +117,11 @@ function controlMeta(state, connected = false) {
113
117
  * @param {() => boolean} [deps.getRelayConnected] 中转隧道此刻通没通(宿主侧权威状态)
114
118
  * @param {(msg: string, ...rest: any[]) => void} [deps.log]
115
119
  */
116
- function createControlClient({ state, persist, getPort, getHistoryKey, getAddresses, getRelayConnected, log = () => {} }) {
120
+ function createControlClient(options = {}) {
121
+ const { persist, getPort, getHistoryKey, getAddresses, getRelayConnected, log = () => {}, onIdentityConflict = null } = options
122
+ // `getState` 让控制客户端读到**当前这一代**的状态(换代后状态对象会换一份):老的直接传
123
+ // `state` 的用法保留为兜底,测试与旧调用方行为不变。
124
+ const getState = typeof options.getState === 'function' ? options.getState : () => options.state
117
125
  const build = typeof getAddresses === 'function'
118
126
  ? getAddresses
119
127
  : (s) => controlAddresses(s, typeof getPort === 'function' ? getPort() : undefined);
@@ -122,11 +130,37 @@ function createControlClient({ state, persist, getPort, getHistoryKey, getAddres
122
130
  let sock = null;
123
131
  let running = false;
124
132
  let connected = false;
125
- let token = typeof state.controlToken === 'string' ? state.controlToken : '';
133
+ let token = typeof getState().controlToken === 'string' ? getState().controlToken : '';
126
134
  let lastSent = '';
127
135
  let attempt = 0;
128
136
  let reconnectTimer = null;
129
137
  let tickTimer = null;
138
+ // 「身份冲突」连续计数:同一台机器被别处占了令牌时会持续收到 identity_conflict。
139
+ // 累计到阈值(且都在一个窗口内)就触发一次换身份,把本机换成新号从冲突里出来;
140
+ // 换完若还冲突,靠冷却期避免反复触发放大(换身份本身会重连,别在里头死循环)。
141
+ let identityConflictStreak = 0;
142
+ let lastIdentityConflictAt = 0;
143
+ let identityConflictCooldownUntil = 0;
144
+ const IDENTITY_CONFLICT_THRESHOLD = 3;
145
+ const IDENTITY_CONFLICT_WINDOW_MS = 60_000;
146
+ const IDENTITY_CONFLICT_COOLDOWN_MS = 10 * 60_000;
147
+
148
+ /** 记一次身份冲突;够阈值就调一次 onIdentityConflict(换身份),并进入冷却。 */
149
+ function noteIdentityConflict() {
150
+ if (typeof onIdentityConflict !== 'function') return;
151
+ const now = Date.now();
152
+ if (now < identityConflictCooldownUntil) return;
153
+ if (now - lastIdentityConflictAt > IDENTITY_CONFLICT_WINDOW_MS) identityConflictStreak = 0;
154
+ lastIdentityConflictAt = now;
155
+ identityConflictStreak += 1;
156
+ if (identityConflictStreak < IDENTITY_CONFLICT_THRESHOLD) return;
157
+ identityConflictStreak = 0;
158
+ identityConflictCooldownUntil = now + IDENTITY_CONFLICT_COOLDOWN_MS;
159
+ try {
160
+ const pending = onIdentityConflict();
161
+ if (pending && typeof pending.catch === 'function') pending.catch(() => {});
162
+ } catch { /* 换身份失败就让退避继续,不在这里抛 */ }
163
+ }
130
164
 
131
165
  // `at` 是采样时刻,每次 tick 都会变;不进 canonical,否则每分钟都会白推一次 update。
132
166
  const canonical = (list, meta) => JSON.stringify([
@@ -137,7 +171,7 @@ function createControlClient({ state, persist, getPort, getHistoryKey, getAddres
137
171
 
138
172
  function hk() {
139
173
  try {
140
- const value = typeof getHistoryKey === 'function' ? getHistoryKey() : state.historyKey;
174
+ const value = typeof getHistoryKey === 'function' ? getHistoryKey() : getState().historyKey;
141
175
  return typeof value === 'string' ? value : '';
142
176
  } catch {
143
177
  return '';
@@ -149,7 +183,7 @@ function createControlClient({ state, persist, getPort, getHistoryKey, getAddres
149
183
  const key = hk();
150
184
  if (!key) return '';
151
185
  try {
152
- return sealHistoryBlob(key, 'control', state.instanceId || '', { addresses, meta });
186
+ return sealHistoryBlob(key, 'control', getState().instanceId || '', { addresses, meta });
153
187
  } catch (error) {
154
188
  log('control: seal failed', error && error.message);
155
189
  return '';
@@ -172,22 +206,22 @@ function createControlClient({ state, persist, getPort, getHistoryKey, getAddres
172
206
 
173
207
  function connect() {
174
208
  if (!running || sock) return;
175
- if (!state.enabled) return;
209
+ if (!getState().enabled) return;
176
210
  // 用户在面板关掉了「自动上报网络地址」:立刻不连(sync/stop 会把已在连的这条也收掉)。
177
- if (state.controlReportEnabled === false) return;
178
- const addresses = build(state);
211
+ if (getState().controlReportEnabled === false) return;
212
+ const addresses = build(getState());
179
213
  if (!Array.isArray(addresses) || addresses.length === 0) {
180
214
  connected = false;
181
215
  return;
182
216
  }
183
- const meta = controlMeta(state, connectedOf());
217
+ const meta = controlMeta(getState(), connectedOf());
184
218
  const payload = seal(addresses, meta);
185
219
  if (!payload) {
186
220
  connected = false;
187
221
  return;
188
222
  }
189
223
  const tokenQuery = token ? `&token=${encodeURIComponent(token)}` : '';
190
- const url = `${controlWsUrl()}/ws/device?instanceId=${encodeURIComponent(state.instanceId || '')}${tokenQuery}`;
224
+ const url = `${controlWsUrl()}/ws/device?instanceId=${encodeURIComponent(getState().instanceId || '')}${tokenQuery}`;
191
225
  let ws;
192
226
  try {
193
227
  ws = new WebSocket(url);
@@ -201,7 +235,9 @@ function createControlClient({ state, persist, getPort, getHistoryKey, getAddres
201
235
  lastSent = '';
202
236
  ws.addEventListener('open', () => {
203
237
  if (sock !== ws) return;
204
- attempt = 0;
238
+ // 注意:这里**不**清零退避。连上不等于能用——服务端可能刚连上就以 unauthorized 断开;
239
+ // 若在 open 就清零,每次被拒后都按最短 1 秒重连,等于把「被拒」放大成每秒一次的热循环。
240
+ // 退避在收到 registered(真正注册成功)时再清零,见 message 处理。
205
241
  connected = true;
206
242
  send({ type: 'register', payload });
207
243
  lastSent = canonical(addresses, meta);
@@ -215,13 +251,21 @@ function createControlClient({ state, persist, getPort, getHistoryKey, getAddres
215
251
  } catch {
216
252
  return;
217
253
  }
218
- if (msg && msg.type === 'registered' && typeof msg.token === 'string') {
219
- if (msg.token !== token) {
254
+ if (msg && msg.type === 'registered') {
255
+ // 真正注册成功,链路可用,退避清零。
256
+ attempt = 0;
257
+ identityConflictStreak = 0;
258
+ if (typeof msg.token === 'string' && msg.token !== token) {
220
259
  token = msg.token;
221
- state.controlToken = msg.token;
260
+ getState().controlToken = msg.token;
222
261
  try { persist?.(); } catch { /* 落盘失败下次注册还会拿到同一枚,不必打断 */ }
223
262
  }
224
263
  } else if (msg && msg.type === 'error') {
264
+ // 包括 unauthorized(同一 instanceId 被别处占了令牌、或令牌对不上):断开后按指数退避重连,
265
+ // 不在 open 时清零,所以最多退到 30 秒一次,不会再每秒硬撞。
266
+ // 明确的 identity_conflict 额外累计,够次数就触发换身份(换到唯一的新号)。
267
+ if (String(msg.message || '') === 'identity_conflict') noteIdentityConflict();
268
+ log('control: server error', msg.message);
225
269
  try { ws.close(); } catch { /* ignore */ }
226
270
  }
227
271
  });
@@ -238,9 +282,9 @@ function createControlClient({ state, persist, getPort, getHistoryKey, getAddres
238
282
  /** 复核地址与健康有没有变,变了就重新加密并 update。 */
239
283
  function tick() {
240
284
  if (!connected || !sock) return;
241
- const addresses = build(state);
285
+ const addresses = build(getState());
242
286
  if (!Array.isArray(addresses) || addresses.length === 0) return;
243
- const meta = controlMeta(state, connectedOf());
287
+ const meta = controlMeta(getState(), connectedOf());
244
288
  const signature = canonical(addresses, meta);
245
289
  if (signature !== lastSent) {
246
290
  const payload = seal(addresses, meta);
@@ -261,7 +305,7 @@ function createControlClient({ state, persist, getPort, getHistoryKey, getAddres
261
305
  tickTimer = setInterval(tick, 60_000);
262
306
  if (tickTimer.unref) tickTimer.unref();
263
307
  }
264
- if (state.enabled && state.controlReportEnabled !== false && !sock) connect();
308
+ if (getState().enabled && getState().controlReportEnabled !== false && !sock) connect();
265
309
  return snapshot();
266
310
  }
267
311
 
@@ -281,7 +325,7 @@ function createControlClient({ state, persist, getPort, getHistoryKey, getAddres
281
325
 
282
326
  /** 配置变更后调用:没开 / 用户关了上报 / 没地址 / 没 HK 就停;否则起连或复核。 */
283
327
  function sync() {
284
- if (!state.enabled || state.controlReportEnabled === false || build(state).length === 0 || !hk()) {
328
+ if (!getState().enabled || getState().controlReportEnabled === false || build(getState()).length === 0 || !hk()) {
285
329
  stop();
286
330
  return;
287
331
  }
package/lib/relay/core.js CHANGED
@@ -122,6 +122,30 @@ function rotatePairing(state) {
122
122
  return { pairingCode: state.pairingCode, pairingTicket: state.pairingTicket };
123
123
  }
124
124
 
125
+ /**
126
+ * 换身份:把本机实例号换成新的一枚(32 位 hex),配对码 / 票据一并作废。
127
+ *
128
+ * **HK 不动**:控制载荷那层加密的 AAD 里带着 instanceId,但密钥(HK)本身与 id 无关;
129
+ * 换 id 后两端只要用**同一个新 id** 当 AAD,载荷照样解得开(手机从心跳 / 升级回包拿到新 id)。
130
+ *
131
+ * **旧号留在 `previousInstanceId`**:一台电脑可能配过好几台手机,不是每台都能在同一刻
132
+ * 换到新 id。过渡期内本机要同时认「新号」和「旧号」两个身份(鉴权、凭据、局域网发现),
133
+ * 让还没更新的手机照常能连;等它们都换过来再收掉旧号。这里只负责记住旧号,认不认由鉴权层决定。
134
+ *
135
+ * 改 id 只碰这些状态;凭据重签、总控重报、局域网令牌重签、mDNS、推送这些由装配层在拿到
136
+ * 返回值后按序做——它们依赖进程里的其它服务,不属于这份纯状态变更。
137
+ */
138
+ function rotateIdentity(state) {
139
+ const previous = typeof state.instanceId === 'string' ? state.instanceId : '';
140
+ state.instanceId = genInstanceId();
141
+ if (previous) state.previousInstanceId = previous;
142
+ else delete state.previousInstanceId;
143
+ state.pairingCode = genPairingCode();
144
+ state.pairingTicket = genPairingTicket();
145
+ saveState(state);
146
+ return { instanceId: state.instanceId, previousInstanceId: state.previousInstanceId || '' };
147
+ }
148
+
125
149
  function saveState(state) {
126
150
  normalizeRelayAddresses(state);
127
151
  fs.mkdirSync(path.dirname(STATE_FILE), { recursive: true });
@@ -353,7 +377,7 @@ function expandDefaultPublicRelays(state) {
353
377
  }
354
378
 
355
379
  module.exports = {
356
- STATE_FILE, MOBILE_TOKEN_TTL_SEC, MOBILE_BEARER_TTL_SEC, defaultState, loadState, saveState, rotatePairing, genInstanceId, genPairingCode, genPairingTicket, genHistoryKey, ensureHistoryKey,
380
+ STATE_FILE, MOBILE_TOKEN_TTL_SEC, MOBILE_BEARER_TTL_SEC, defaultState, loadState, saveState, rotatePairing, rotateIdentity, genInstanceId, genPairingCode, genPairingTicket, genHistoryKey, ensureHistoryKey,
357
381
  tunnelWsUrl, normalizeRelayUrl, normalizeRelayUrlList, normalizeRelayAddresses, relayAddressesOf, applyRelayAddressPatch, signLanToken, verifyLanToken,
358
382
  isPublicRelayUrl, publicRelayBlocked, stripPublicRelay, expandDefaultPublicRelays, PUBLIC_RELAY_URLS, MAX_RELAY_ADDRESSES,
359
383
  };
@@ -0,0 +1,27 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * 身份冲突时「换身份」的实装。
5
+ *
6
+ * 连续收到身份冲突(同一 instanceId 被别处占了令牌)后触发一次:生成新号 → 落盘 → 让 sidecar
7
+ * 用新号重下配置 → 总控用新号重连。新号唯一,换完就不再有冲突;重入保护避免并发触发。
8
+ *
9
+ * 放在这里而不是装配层:装配层只把它挂上,不许多长实现(见 `test/assembly-layer.test.cjs`)。
10
+ */
11
+ function createIdentityRotator({ state, rotateIdentity, saveState, syncSidecar, syncControl }) {
12
+ let rotating = false;
13
+ return async function rotateIdentityNow() {
14
+ if (rotating) return;
15
+ rotating = true;
16
+ try {
17
+ rotateIdentity(state);
18
+ saveState(state);
19
+ try { await syncSidecar(); } catch { /* 配置下发失败不影响重连,下次 sync 再补 */ }
20
+ try { syncControl(); } catch { /* ignore */ }
21
+ } finally {
22
+ rotating = false;
23
+ }
24
+ };
25
+ }
26
+
27
+ module.exports = { createIdentityRotator };
@@ -71,6 +71,8 @@ function createLanProxy(opts) {
71
71
  // 新配对权限档位(电脑侧选定);局域网这条配对入口与中转那条同一档位。
72
72
  pairingTier = 'full',
73
73
  instanceId,
74
+ // 换身份过渡期的旧实例号:本机此刻同时认新号和旧号(见 core.rotateIdentity)。
75
+ previousInstanceId = '',
74
76
  lanSecret,
75
77
  upstreamPort,
76
78
  upstreamHost = '127.0.0.1',
@@ -121,6 +123,26 @@ function createLanProxy(opts) {
121
123
  * 自己写盘只会和主进程那份互相覆盖(旁路签的吊销会被回滚、主进程签的在旁路查不到,
122
124
  * 经中转配上的手机回局域网就是 401)。装配层传进来就走它,测试里不传就用本地库。
123
125
  */
126
+ /** 本机此刻认的实例号列表(当前号在前,过渡期旧号在后,去重)。 */
127
+ const acceptedInstanceIds = (() => {
128
+ const ids = [];
129
+ if (typeof instanceId === 'string' && instanceId) ids.push(instanceId);
130
+ if (typeof previousInstanceId === 'string' && previousInstanceId && previousInstanceId !== instanceId) ids.push(previousInstanceId);
131
+ return ids;
132
+ })();
133
+
134
+ /** 按凭据原串查记录:新旧号各试一次(换身份过渡期,还没换过来的手机凭据仍挂在旧号下)。 */
135
+ const lookupKnown = (presented) => {
136
+ for (const id of acceptedInstanceIds) {
137
+ const found = credentials.lookup(presented, id);
138
+ if (found) return found;
139
+ }
140
+ return null;
141
+ };
142
+
143
+ /** 无状态令牌验签:新旧号各试一次。 */
144
+ const verifyLanAnyId = (token) => acceptedInstanceIds.some((id) => core.verifyLanToken(lanSecret, token, id));
145
+
124
146
  const issueCredential = typeof opts.issueCredential === 'function'
125
147
  ? opts.issueCredential
126
148
  : (device, extra) => credentials.issue(instanceId, device, '', undefined, extra);
@@ -179,14 +201,14 @@ function createLanProxy(opts) {
179
201
  function credential(req) {
180
202
  const presented = presentedCredential(req);
181
203
  if (presented) {
182
- const found = credentials.lookup(presented, instanceId);
204
+ const found = lookupKnown(presented);
183
205
  if (found) return { record: found, presented };
184
206
  // 本机不认识这一枚(中转签的 / 升级前的 HMAC),往下按 cookie 再找一次。
185
207
  }
186
208
  const m = /dsh_lan=([^;]+)/.exec(req.headers.cookie || '');
187
209
  const token = m ? m[1] : '';
188
210
  if (!token) return null;
189
- const byCookie = credentials.lookup(token, instanceId);
211
+ const byCookie = lookupKnown(token);
190
212
  return byCookie ? { record: byCookie, presented: token } : null;
191
213
  }
192
214
  /** 上游要带的 `Authorization` 值:新记录用出示的那一枚,旧记录用存下的宿主令牌。 */
@@ -203,11 +225,11 @@ function createLanProxy(opts) {
203
225
  */
204
226
  function cookieValid(req) {
205
227
  const m = /dsh_lan=([^;]+)/.exec(req.headers.cookie || '');
206
- return m ? core.verifyLanToken(lanSecret, m[1], instanceId) : false;
228
+ return m ? verifyLanAnyId(m[1]) : false;
207
229
  }
208
230
  function bearerValid(req) {
209
231
  const m = /^Bearer\s+([^\s]+)$/.exec(req.headers.authorization || '');
210
- return !!m && core.verifyLanToken(lanSecret, m[1], instanceId);
232
+ return !!m && verifyLanAnyId(m[1]);
211
233
  }
212
234
  /**
213
235
  * 鉴权结果,**带上被拒原因**(§3.8):被吊销 / 已过期 / 只是没有凭据。
@@ -235,7 +257,7 @@ function createLanProxy(opts) {
235
257
  // 候选里有**任何一枚**是本机签发过的,就以它为准:三种出示方式里只要有一枚能查到记录,
236
258
  // 「这台设备被吊销了」就是答案,不能靠另外两枚里更宽松的那个绕过它。
237
259
  for (const candidate of candidates) {
238
- const known = credentials.lookup(candidate, instanceId);
260
+ const known = lookupKnown(candidate);
239
261
  if (!known) continue;
240
262
  if (known.revokedAt) return { ok: false, reason: 'revoked' };
241
263
  if (known.expiresAt && known.expiresAt <= Date.now()) return { ok: false, reason: 'expired' };
@@ -65,9 +65,9 @@ function pairingPayload(state, lanPort) {
65
65
  ticket: state.pairingTicket || '',
66
66
  relayUrl: relay.relayUrl,
67
67
  lanUrls: urls,
68
- // 「TCP 直连」那一条:用户配的那条直连地址(`manualLanUrl`)里能当裸 TCP 目标的,只此
69
- // 一条、不掺网卡候选。App 用它当 `tcpTarget`(经本机回环 + 原生裸 TCP 出站,ATS 不参与)。
70
- // 没有可用的就整格不写,老 App 读到会忽略。
68
+ // 「TCP 直连」那一条:设置项 `manualTcpUrl` 里能当裸 TCP 目标的,只此一条、不掺网卡候选
69
+ // (与直连地址是两条,别混)。App 用它当 `tcpTarget`(经本机回环 + 原生裸 TCP 出站,ATS 不参与)。
70
+ // 没有可用的就整格不写 —— 二维码的字节数很贵,重配对时目标由 `/connection-info` 补。
71
71
  ...(() => {
72
72
  const tcp = tcpDirectTarget(state.manualTcpUrl);
73
73
  return tcp ? { tcpUrl: tcp } : {};
@@ -104,6 +104,7 @@ const { createTransferTickets } = require('../mobile/transfer-tickets.js');
104
104
  const { createSyncInboxStore } = require('../mobile/sync-inbox-store.js');
105
105
  const { credentialsEntry } = require('../shared/credentials-entry.js');
106
106
  const { handleCredentialUpgrade } = require('../mobile/credential-upgrade.js');
107
+ const { handleSyncIdentity } = require('../mobile/claim-identity.js');
107
108
  // 手机自助降档:只许把自己这台设备的权限往下收,提权只能在电脑侧(见该文件头)。
108
109
  const devicePermissions = require('../mobile/device-permissions.js');
109
110
  const extensions = require('../mobile/extensions.js');
@@ -375,6 +376,16 @@ function registerMobileRoutes(deps) {
375
376
  await handleCredentialUpgrade(req, res, { instanceId: String(state.instanceId || ''), store: credentialsEntry() })
376
377
  })
377
378
 
379
+ // 认领当前身份:换身份过渡期里,还没换过来的手机用旧号下仍有效的凭据换一枚当前号的新凭据。
380
+ // 鉴权由守卫完成(同时认新旧号),这里只按出示凭据反查记录、按当前号重签。见 claim-identity.js。
381
+ route('/api/mobile/v1/device-credential/sync-identity', async (_ctx, req, res) => {
382
+ await handleSyncIdentity(req, res, {
383
+ instanceId: String(state.instanceId || ''),
384
+ previousInstanceId: String(state.previousInstanceId || ''),
385
+ store: credentialsEntry(),
386
+ })
387
+ })
388
+
378
389
  // 手机自助降档:在「这台设备当前权限」里往下收,提不上去(提权只在电脑控制面)。任何
379
390
  // 已鉴权设备都能调(BASE,不受权限位约束)—— 收窄自己的权限本身不该被收窄挡住。
380
391
  route('/api/mobile/v1/device-credential/permissions', async (_ctx, req, res) => {
@@ -413,12 +424,10 @@ function registerMobileRoutes(deps) {
413
424
  lanUrls: candidates,
414
425
  lanCandidates: candidates,
415
426
  ipv6Candidates: ipv6,
416
- // 「TCP 直连」目标:从用户配的那条直连地址(manualLanUrl)解出来,只此一条、不掺网卡候选。
417
- // 与二维码里那颗同源,手机定期核对时据此刷新,保证「改了连接地址、TCP 跟着变」。
418
- ...(() => {
419
- const tcpUrl = tcpDirectTarget(state.manualTcpUrl)
420
- return tcpUrl ? { tcpUrl } : {}
421
- })(),
427
+ // 「TCP 直连」目标:从设置项 `manualTcpUrl` 解出来,只此一条、不掺网卡候选(与二维码同一来源)。
428
+ // **始终带这一格**(没配时是空串):手机据此分清「老宿主不认识这格」(整格不出现,别动它手上
429
+ // 那条)与「电脑上把目标清掉了」(空串,手机要跟着清)。只在有值时才报,会让清空永远传不下去。
430
+ tcpUrl: tcpDirectTarget(state.manualTcpUrl),
422
431
  updatedAt: lanUpdatedAt,
423
432
  lastSeen: lanUpdatedAt,
424
433
  })
@@ -857,7 +866,8 @@ function registerMobileRoutes(deps) {
857
866
 
858
867
  // 对话页长连接:一条手机 WS 上的双向多路复用(帧契约见 docs/mux-long-connection-design.md §11)。
859
868
  // 与 preview 一样是 WebSocket 升级路由,鉴权在服务自己里做(设备凭据有效即可)。
860
- registerUpgradeRoute({ path: '/api/mobile/v1/mux', handler: mux.handleUpgrade })
869
+ // mux 已归稳定外壳持有时,升级路由由外壳直接挂(换代不摘、已建立的 WS 不断),这里不再重复注册。
870
+ if (!deps.muxOwnedByShell) registerUpgradeRoute({ path: '/api/mobile/v1/mux', handler: mux.handleUpgrade })
861
871
 
862
872
  }
863
873