dsh-mobile-plugin 0.5.80 → 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.
@@ -118,7 +118,7 @@ function controlMeta(state, connected = false) {
118
118
  * @param {(msg: string, ...rest: any[]) => void} [deps.log]
119
119
  */
120
120
  function createControlClient(options = {}) {
121
- const { persist, getPort, getHistoryKey, getAddresses, getRelayConnected, log = () => {} } = options
121
+ const { persist, getPort, getHistoryKey, getAddresses, getRelayConnected, log = () => {}, onIdentityConflict = null } = options
122
122
  // `getState` 让控制客户端读到**当前这一代**的状态(换代后状态对象会换一份):老的直接传
123
123
  // `state` 的用法保留为兜底,测试与旧调用方行为不变。
124
124
  const getState = typeof options.getState === 'function' ? options.getState : () => options.state
@@ -135,6 +135,32 @@ function createControlClient(options = {}) {
135
135
  let attempt = 0;
136
136
  let reconnectTimer = null;
137
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
+ }
138
164
 
139
165
  // `at` 是采样时刻,每次 tick 都会变;不进 canonical,否则每分钟都会白推一次 update。
140
166
  const canonical = (list, meta) => JSON.stringify([
@@ -209,7 +235,9 @@ function createControlClient(options = {}) {
209
235
  lastSent = '';
210
236
  ws.addEventListener('open', () => {
211
237
  if (sock !== ws) return;
212
- attempt = 0;
238
+ // 注意:这里**不**清零退避。连上不等于能用——服务端可能刚连上就以 unauthorized 断开;
239
+ // 若在 open 就清零,每次被拒后都按最短 1 秒重连,等于把「被拒」放大成每秒一次的热循环。
240
+ // 退避在收到 registered(真正注册成功)时再清零,见 message 处理。
213
241
  connected = true;
214
242
  send({ type: 'register', payload });
215
243
  lastSent = canonical(addresses, meta);
@@ -223,13 +251,21 @@ function createControlClient(options = {}) {
223
251
  } catch {
224
252
  return;
225
253
  }
226
- if (msg && msg.type === 'registered' && typeof msg.token === 'string') {
227
- 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) {
228
259
  token = msg.token;
229
260
  getState().controlToken = msg.token;
230
261
  try { persist?.(); } catch { /* 落盘失败下次注册还会拿到同一枚,不必打断 */ }
231
262
  }
232
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);
233
269
  try { ws.close(); } catch { /* ignore */ }
234
270
  }
235
271
  });
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' };
@@ -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) => {
@@ -52,6 +52,8 @@ export function installTransportHosts(ctx) {
52
52
  getPort: () => 0,
53
53
  getHistoryKey: () => '',
54
54
  getRelayConnected: () => sidecarHost.tunnelConnected(),
55
+ // 身份冲突时触发换身份的动作,由当前这一代注入(换代换它即可)。缺省不启用。
56
+ onIdentityConflict: null,
55
57
  }
56
58
  const controlClient = createControlClient({
57
59
  getState: () => controlProviders.getState(),
@@ -59,6 +61,10 @@ export function installTransportHosts(ctx) {
59
61
  getPort: () => controlProviders.getPort(),
60
62
  getHistoryKey: () => controlProviders.getHistoryKey(),
61
63
  getRelayConnected: () => controlProviders.getRelayConnected(),
64
+ onIdentityConflict: (...args) => {
65
+ const fn = controlProviders.onIdentityConflict
66
+ return typeof fn === 'function' ? fn(...args) : undefined
67
+ },
62
68
  })
63
69
  ctx.reflect.provide('dshMobileTransportControl', {
64
70
  client: controlClient,
@@ -44,6 +44,19 @@ const parentPort = Number(process.env.DSH_SIDECAR_PARENT_PORT)
44
44
  const token = process.env.DSH_SIDECAR_TOKEN
45
45
  const authorization = `Bearer ${token}`
46
46
  let config = {}
47
+ /**
48
+ * 按凭据查记录:先查当前号,过渡期再兜底旧号(见 core.rotateIdentity)。
49
+ * 只用于「认不认这枚凭据」,配对签发仍只用当前号。
50
+ */
51
+ function lookupAccepted(presented) {
52
+ return credentials.lookup(presented, config.instanceId)
53
+ || (config.previousInstanceId ? credentials.lookup(presented, config.previousInstanceId) : null)
54
+ }
55
+ /** 旧的无状态令牌验签:同样当前号优先、旧号兜底。 */
56
+ function verifyLanAccepted(presented) {
57
+ return core.verifyLanToken(config.lanSecret, presented, config.instanceId)
58
+ || (config.previousInstanceId ? core.verifyLanToken(config.lanSecret, presented, config.previousInstanceId) : false)
59
+ }
47
60
  const sockets = new Set()
48
61
  let tunnel = null
49
62
  let lan = null
@@ -302,15 +315,15 @@ function snapshotRead(info) {
302
315
  // (印在配对二维码上),不带任何凭据也能经中转读到会话 / 工作区列表。验不过回 null 回源,
303
316
  // 交给主进程守卫如实驳回(401);被吊销 / 已过期的凭据同样回落,吊销才不会在这条路上失效。
304
317
  if (!snapshotAuthorized(info && info.headers, {
305
- lookup: (presented) => credentials.lookup(presented, config.instanceId),
306
- verifyLanToken: (presented) => core.verifyLanToken(config.lanSecret, presented, config.instanceId),
318
+ lookup: lookupAccepted,
319
+ verifyLanToken: verifyLanAccepted,
307
320
  })) return null
308
321
  // **v2 绑定设备不能因中转删掉协议版本头就回明文快照**:这条捷径不封信封,一旦把一条
309
322
  // 绑了 `deviceKey` 的凭据当成老客户端,它要的列表 / 工作区就会以明文经中转送出去——
310
323
  // 主进程那条 `e2ee-required` 拦不到捷径这一层。认得出是设备密钥凭据就回源,交给主进程
311
324
  // 按「加密会话没带信封」如实驳回(见 lib/http/routing.js)。
312
325
  const boundRecord = snapshotAuthRecord(info && info.headers, {
313
- lookup: (presented) => credentials.lookup(presented, config.instanceId),
326
+ lookup: lookupAccepted,
314
327
  })
315
328
  if (boundRecord && boundRecord.deviceKey) return null
316
329
  let url
@@ -369,7 +382,7 @@ function tunnelSignature(c) {
369
382
  function lanSignature(c) {
370
383
  // **配对码与票据不在其中**:它们由 `currentPairing` 现读,改它们不该重建监听 ——
371
384
  // 配对成功就要换一次(§5.1),跟着重建会把刚握上的连接掐掉。
372
- return JSON.stringify([Boolean(c.enabled), Boolean(c.lanEnabled), c.lanPort || 0, c.upstreamPort || 0, c.upstreamHost || '', c.instanceId || '', c.lanSecret || '', c.pairingTier || 'full'])
385
+ return JSON.stringify([Boolean(c.enabled), Boolean(c.lanEnabled), c.lanPort || 0, c.upstreamPort || 0, c.upstreamHost || '', c.instanceId || '', c.previousInstanceId || '', c.lanSecret || '', c.pairingTier || 'full'])
373
386
  }
374
387
  /** 「这份配置里哪几项决定网络监视器要不要重排」。 */
375
388
  function monitorSignature(c) {
@@ -681,7 +694,7 @@ async function startLan() {
681
694
  requestedPort: config.lanPort, discovery, store: credentials, instanceId: config.instanceId,
682
695
  isCurrent: () => own === lanGeneration,
683
696
  createProxy: port => createLanProxy({
684
- lanPort: port, instanceId: config.instanceId, lanSecret: config.lanSecret,
697
+ lanPort: port, instanceId: config.instanceId, previousInstanceId: config.previousInstanceId || '', lanSecret: config.lanSecret,
685
698
  // 配对码与票据走取值器:配对成功之后宿主会换掉它们(§5.1),而重建局域网代理会把
686
699
  // 刚握上的连接全掐掉 —— 换值不该动监听。
687
700
  currentPairing: () => ({ code: config.pairingCode, ticket: config.pairingTicket || '' }),
@@ -732,9 +745,10 @@ async function configure(next) {
732
745
  // `relayUrls` 在白名单里,而且从这一轮起**进签名**(见 tunnelSignature):地址组或它的
733
746
  // 顺序变了就要重新择路。白名单缺了它,宿主下发这一格会直接抛 unknown configuration
734
747
  // field,整次配置下发失败。
735
- const allowed = ['enabled', 'relayUrl', 'relayUrls', 'instanceId', 'pairingCode', 'pairingTicket', 'pairingTier', 'name', 'upstreamPort', 'upstreamHost', 'lanPort', 'lanEnabled', 'lanSecret', 'registerSecret']
748
+ const allowed = ['enabled', 'relayUrl', 'relayUrls', 'instanceId', 'previousInstanceId', 'pairingCode', 'pairingTicket', 'pairingTier', 'name', 'upstreamPort', 'upstreamHost', 'lanPort', 'lanEnabled', 'lanSecret', 'registerSecret']
736
749
  if (Object.keys(next).some(key => !allowed.includes(key))) throw new Error('unknown configuration field')
737
750
  if (typeof next.instanceId !== 'string' || next.instanceId.length > 128) throw new Error('invalid instanceId')
751
+ if (next.previousInstanceId !== undefined && (typeof next.previousInstanceId !== 'string' || next.previousInstanceId.length > 128)) throw new Error('invalid previousInstanceId')
738
752
  if (typeof next.pairingCode !== 'string' || !/^\d{6}$/.test(next.pairingCode)) throw new Error('invalid pairingCode')
739
753
  if (next.pairingTicket !== undefined && (typeof next.pairingTicket !== 'string' || !/^[A-Za-z0-9_-]{0,64}$/.test(next.pairingTicket))) throw new Error('invalid pairingTicket')
740
754
  if (next.pairingTier !== undefined && !['readonly', 'approve', 'full'].includes(next.pairingTier)) throw new Error('invalid pairingTier')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-mobile-plugin",
3
- "version": "0.5.80",
3
+ "version": "0.5.81",
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",