dsh-mobile-plugin 0.5.81 → 0.5.83

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.
Files changed (67) hide show
  1. package/README.md +4 -0
  2. package/dsh-mobile-credentials/lib/credentials.js +5 -0
  3. package/lib/client.js +171 -5
  4. package/lib/frpc/provision.cjs +21 -17
  5. package/lib/frpc/runner.cjs +231 -168
  6. package/lib/impl.js +77 -107
  7. package/lib/index.js +1 -1
  8. package/lib/mirror/pusher.cjs +60 -10
  9. package/lib/mobile/approval-memory.js +2 -55
  10. package/lib/mobile/approvals.js +6 -82
  11. package/lib/mobile/events.js +2 -1
  12. package/lib/mobile/feedback.js +6 -5
  13. package/lib/mobile/file-read.js +4 -2
  14. package/lib/mobile/host-bridge.js +12 -1
  15. package/lib/mobile/mux.js +148 -21
  16. package/lib/mobile/paired-devices.js +2 -1
  17. package/lib/mobile/pairing.js +8 -7
  18. package/lib/mobile/relay-control.js +33 -38
  19. package/lib/mobile/session-changes.js +8 -2
  20. package/lib/mobile/session-delivery.js +5 -1
  21. package/lib/mobile/session-file.js +46 -25
  22. package/lib/mobile/session-head.js +7 -3
  23. package/lib/mobile/session-snapshot.js +5 -1
  24. package/lib/mobile/session-step.js +13 -7
  25. package/lib/mobile/session-stop-summary.js +6 -1
  26. package/lib/mobile/stream-registry.js +48 -53
  27. package/lib/mobile/stream.js +17 -2
  28. package/lib/mobile/uploads.js +190 -163
  29. package/lib/p2p/session.cjs +169 -70
  30. package/lib/p2p/wiring.cjs +4 -2
  31. package/lib/panel/index.html +44 -24
  32. package/lib/relay/blob-upload.cjs +103 -0
  33. package/lib/relay/config-store.js +79 -0
  34. package/lib/relay/control.js +131 -52
  35. package/lib/relay/core.js +55 -17
  36. package/lib/relay/lan-discovery.cjs +22 -14
  37. package/lib/relay/lan-port-policy.cjs +8 -2
  38. package/lib/relay/lan-proxy.js +47 -12
  39. package/lib/relay/pairing-payload.cjs +14 -5
  40. package/lib/relay/preview-webapp.cjs +150 -0
  41. package/lib/relay/preview.js +35 -8
  42. package/lib/relay/protocol.js +6 -4
  43. package/lib/relay/relay-probe.js +112 -21
  44. package/lib/relay/status.js +4 -7
  45. package/lib/relay/tunnel-forwarder.cjs +4 -2
  46. package/lib/relay/tunnel.js +39 -8
  47. package/lib/remote/controller.cjs +33 -3
  48. package/lib/remote/host-control.cjs +11 -2
  49. package/lib/remote/router.cjs +83 -33
  50. package/lib/remote/transport.cjs +32 -5
  51. package/lib/remote/tunnel-helper.cjs +51 -25
  52. package/lib/remote/tunnels.cjs +27 -3
  53. package/lib/routes/control-plane.js +41 -53
  54. package/lib/routes/mobile-api.js +21 -31
  55. package/lib/shared/fresh-request.js +32 -1
  56. package/lib/shared/route-order.cjs +118 -132
  57. package/lib/shared/sse-write.js +29 -10
  58. package/lib/shared/via-header.js +5 -12
  59. package/lib/shell/transport-host.js +9 -1
  60. package/lib/shell/updater.js +18 -6
  61. package/lib/sidecar-facade-worker.cjs +165 -118
  62. package/lib/sidecar-facade.cjs +6 -1
  63. package/lib/sidecar-lifecycle.cjs +6 -2
  64. package/lib/tailcat/host-process.cjs +32 -8
  65. package/lib/tailcat/session.cjs +27 -10
  66. package/package.json +6 -6
  67. package/lib/mobile/auto-review.js +0 -178
@@ -4,8 +4,11 @@ function createRoutePolicy() {
4
4
  const exports = {};
5
5
  "use strict";
6
6
  Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.advanceRouteEvidenceRound = advanceRouteEvidenceRound;
7
8
  exports.noteRouteLatency = noteRouteLatency;
8
9
  exports.noteRouteFailure = noteRouteFailure;
10
+ exports.noteRouteProven = noteRouteProven;
11
+ exports.noteRouteVerified = noteRouteVerified;
9
12
  exports.noteRouteForeign = noteRouteForeign;
10
13
  exports.isRouteForeign = isRouteForeign;
11
14
  exports.routeLatencyOf = routeLatencyOf;
@@ -15,6 +18,26 @@ function createRoutePolicy() {
15
18
  const LOSS_PENALTY_MAX = 4;
16
19
  const FAILURE_PENALTY_STEP = 1.5;
17
20
  const FAILURE_PENALTY_MAX = 4;
21
+ const SAMPLE_WINDOW = 5;
22
+ const MIN_NOISE_SAMPLES = 2;
23
+ const ROUTE_SWITCH_SHARE = 1 / 3;
24
+ const SWITCH_GAIN_FLOOR_MS = 10;
25
+ const SETTLE_ROUNDS = 4;
26
+ const factsByScope = new Map();
27
+ function factsOf(scope) {
28
+ let facts = factsByScope.get(scope);
29
+ if (!facts) {
30
+ facts = {
31
+ latency: new Map(), samples: new Map(), lossPenalty: new Map(), failurePenalty: new Map(),
32
+ foreign: new Set(), evidenceAtRound: new Map(), evidenceRound: 0, staleRounds: 2, lastSwitch: null,
33
+ };
34
+ factsByScope.set(scope, facts);
35
+ }
36
+ return facts;
37
+ }
38
+ function norm(url) {
39
+ return String(url || '').trim().replace(/\/+$/, '');
40
+ }
18
41
  function penaltyOf(attempts) {
19
42
  if (!attempts)
20
43
  return null;
@@ -24,172 +47,135 @@ function createRoutePolicy() {
24
47
  return null;
25
48
  if (!Number.isFinite(ok) || ok <= 0)
26
49
  return LOSS_PENALTY_MAX;
27
- return Math.min(LOSS_PENALTY_MAX, total / ok);
50
+ return Math.max(1, Math.min(LOSS_PENALTY_MAX, total / ok));
51
+ }
52
+ function advanceRouteEvidenceRound(candidateCount, probeLimit, scope = '') {
53
+ const facts = factsOf(scope);
54
+ const count = Number.isFinite(candidateCount) ? Math.max(1, Math.ceil(candidateCount)) : 1;
55
+ const limit = Number.isFinite(probeLimit) ? Math.max(1, Math.floor(probeLimit)) : 1;
56
+ facts.staleRounds = 2 * Math.ceil(count / limit);
57
+ facts.evidenceRound += 1;
58
+ for (const [key, at] of facts.evidenceAtRound) {
59
+ if (facts.evidenceRound - at <= facts.staleRounds)
60
+ continue;
61
+ facts.evidenceAtRound.delete(key);
62
+ facts.samples.delete(key);
63
+ }
64
+ if (facts.lastSwitch && facts.evidenceRound - facts.lastSwitch.round > SETTLE_ROUNDS)
65
+ facts.lastSwitch = null;
28
66
  }
29
- const ROUTE_SWITCH_SHARE = 1 / 3;
30
- const SWITCH_GAIN_FLOOR_MS = 10;
31
- const STALE_EVIDENCE_ROUNDS = 12;
32
- const latency = new Map();
33
- const samples = new Map();
34
- const SAMPLE_WINDOW = 5;
35
- let evidenceRound = 0;
36
- const evidenceAtRound = new Map();
37
- const lossPenalty = new Map();
38
- const failurePenalty = new Map();
39
- const foreign = new Set();
40
- function norm(url) {
41
- return String(url || '').trim().replace(/\/+$/, '');
67
+ function isFresh(facts, key) {
68
+ const at = facts.evidenceAtRound.get(key);
69
+ return at !== undefined && facts.evidenceRound - at <= facts.staleRounds;
42
70
  }
43
- function noteRouteLatency(url, ms, attempts) {
71
+ function noteRouteLatency(url, ms, attempts, scope = '') {
44
72
  const key = norm(url);
45
- if (!key)
73
+ if (!key || typeof ms !== 'number' || !Number.isFinite(ms) || ms < 0)
46
74
  return;
47
- evidenceRound += 1;
48
- if (typeof ms === 'number' && Number.isFinite(ms) && ms >= 0) {
49
- latency.set(key, ms);
50
- evidenceAtRound.set(key, evidenceRound);
51
- const window = samples.get(key) ?? [];
52
- window.push(ms);
53
- samples.set(key, window.length > SAMPLE_WINDOW ? window.slice(window.length - SAMPLE_WINDOW) : window);
54
- const penalty = penaltyOf(attempts);
55
- if (penalty === null)
56
- lossPenalty.delete(key);
57
- else
58
- lossPenalty.set(key, penalty);
59
- failurePenalty.delete(key);
75
+ const facts = factsOf(scope);
76
+ const window = facts.samples.get(key) ?? [];
77
+ window.push(ms);
78
+ facts.samples.set(key, window.slice(-SAMPLE_WINDOW));
79
+ facts.latency.set(key, ms);
80
+ facts.evidenceAtRound.set(key, facts.evidenceRound);
81
+ const penalty = penaltyOf(attempts);
82
+ if (penalty !== null)
83
+ facts.lossPenalty.set(key, penalty);
84
+ }
85
+ function noteRouteFailure(url, scope = '') {
86
+ const key = norm(url);
87
+ if (!key)
60
88
  return;
61
- }
62
- samples.delete(key);
63
- lossPenalty.delete(key);
64
- noteRouteFailure(key);
65
- }
66
- function settledOf(key) {
67
- const window = samples.get(key);
68
- const ms = latency.get(key);
69
- if (!window || window.length === 0)
70
- return ms;
71
- if (window.length === 1)
72
- return window[0];
73
- const sorted = [...window].sort((a, b) => a - b);
74
- const mid = sorted.length >> 1;
75
- return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
76
- }
77
- const MIN_NOISE_SAMPLES = 2;
78
- function sampleCountOf(key) {
79
- return samples.get(key)?.length ?? 0;
89
+ const facts = factsOf(scope);
90
+ const prev = facts.failurePenalty.get(key) ?? 1;
91
+ facts.failurePenalty.set(key, Math.min(FAILURE_PENALTY_MAX, prev * FAILURE_PENALTY_STEP));
80
92
  }
81
- function noiseBandOf(key) {
82
- const window = samples.get(key);
83
- if (!window || window.length < 2)
84
- return 0;
85
- let min = window[0];
86
- let max = window[0];
87
- for (const value of window) {
88
- if (value < min)
89
- min = value;
90
- if (value > max)
91
- max = value;
92
- }
93
- return (max - min) / 2;
94
- }
95
- function noteRouteFailure(url) {
93
+ function noteRouteProven(url, scope = '') {
96
94
  const key = norm(url);
97
95
  if (!key)
98
96
  return;
99
- const prev = failurePenalty.get(key) ?? 1;
100
- failurePenalty.set(key, Math.min(FAILURE_PENALTY_MAX, prev * FAILURE_PENALTY_STEP));
97
+ const facts = factsByScope.get(scope);
98
+ facts?.failurePenalty.delete(key);
99
+ facts?.foreign.delete(key);
101
100
  }
102
- function isFresh(key, threshold = STALE_EVIDENCE_ROUNDS) {
103
- const at = evidenceAtRound.get(key);
104
- return typeof at === 'number' && evidenceRound - at <= threshold;
101
+ function noteRouteVerified(url, scope = '') {
102
+ factsByScope.get(scope)?.foreign.delete(norm(url));
105
103
  }
106
- function staleThresholdFor(routeCount) {
107
- const perRound = Math.max(6, routeCount);
108
- return STALE_EVIDENCE_ROUNDS * Math.max(1, Math.ceil(perRound / 6));
104
+ function noteRouteForeign(url, scope = '') {
105
+ const key = norm(url);
106
+ if (key)
107
+ factsOf(scope).foreign.add(key);
109
108
  }
110
- function settledCostOf(key) {
111
- const ms = settledOf(key);
112
- if (ms === undefined)
113
- return undefined;
114
- return ms * (lossPenalty.get(key) ?? 1) * (failurePenalty.get(key) ?? 1);
109
+ function isRouteForeign(url, scope = '') {
110
+ return factsByScope.get(scope)?.foreign.has(norm(url)) ?? false;
115
111
  }
116
- function noiseCostOf(key) {
117
- return noiseBandOf(key) * (lossPenalty.get(key) ?? 1) * (failurePenalty.get(key) ?? 1);
112
+ function routeLatencyOf(url, scope = '') {
113
+ return factsByScope.get(scope)?.latency.get(norm(url)) ?? null;
118
114
  }
119
- const SETTLE_ROUNDS = 4;
120
- let lastSwitch = null;
121
- function costOf(url) {
122
- const key = norm(url);
123
- const ms = latency.get(key);
124
- if (ms === undefined)
125
- return undefined;
126
- return ms * (lossPenalty.get(key) ?? 1) * (failurePenalty.get(key) ?? 1);
115
+ function penaltyFor(facts, key) {
116
+ return (facts.lossPenalty.get(key) ?? 1) * (facts.failurePenalty.get(key) ?? 1);
127
117
  }
128
- function noteRouteForeign(url) {
118
+ function routeCostOf(url, scope = '') {
119
+ const facts = factsByScope.get(scope);
129
120
  const key = norm(url);
130
- if (key)
131
- foreign.add(key);
121
+ const ms = facts?.latency.get(key);
122
+ return facts && ms !== undefined ? ms * penaltyFor(facts, key) : null;
132
123
  }
133
- function isRouteForeign(url) {
134
- return foreign.has(norm(url));
124
+ function forgetRouteFacts(scope = '') {
125
+ factsByScope.delete(scope);
135
126
  }
136
- function routeLatencyOf(url) {
137
- const value = latency.get(norm(url));
138
- return typeof value === 'number' ? value : null;
127
+ function median(values) {
128
+ const sorted = [...values].sort((a, b) => a - b);
129
+ const mid = sorted.length >> 1;
130
+ return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
139
131
  }
140
- function routeCostOf(url) {
141
- const value = costOf(url);
142
- return typeof value === 'number' ? value : null;
132
+ function settledCostOf(facts, key) {
133
+ const window = facts.samples.get(key);
134
+ const ms = window?.length ? median(window) : facts.latency.get(key);
135
+ return ms === undefined ? undefined : ms * penaltyFor(facts, key);
143
136
  }
144
- function forgetRouteFacts() {
145
- latency.clear();
146
- samples.clear();
147
- lossPenalty.clear();
148
- failurePenalty.clear();
149
- evidenceAtRound.clear();
150
- foreign.clear();
151
- lastSwitch = null;
137
+ function noiseCostOf(facts, key) {
138
+ const sorted = [...(facts.samples.get(key) ?? [])].sort((a, b) => a - b);
139
+ if (sorted.length < MIN_NOISE_SAMPLES)
140
+ return 0;
141
+ const stable = sorted.length >= 4 ? sorted.slice(1, -1) : sorted;
142
+ return (stable[stable.length - 1] - stable[0]) / 2 * penaltyFor(facts, key);
152
143
  }
153
- function orderRouteCandidates(routes, currentUrl = '', suspended = []) {
144
+ function orderRouteCandidates(routes, currentUrl = '', suspended = [], scope = '') {
145
+ const facts = factsOf(scope);
154
146
  const current = norm(currentUrl);
155
- const foreignFree = routes.filter((route) => !foreign.has(norm(route.url)));
147
+ const foreignFree = routes.filter((route) => !facts.foreign.has(norm(route.url)));
156
148
  const cooling = new Set((suspended || []).map(norm).filter(Boolean));
157
149
  const allCooling = foreignFree.length > 0 && foreignFree.every((route) => cooling.has(norm(route.url)));
158
150
  const cool = allCooling ? new Set() : cooling;
159
151
  const warm = foreignFree.filter((route) => !cool.has(norm(route.url)));
160
152
  const cold = foreignFree.filter((route) => cool.has(norm(route.url)));
161
- const staleThreshold = staleThresholdFor(warm.length);
162
- const known = warm
163
- .filter((route) => latency.has(norm(route.url)) && isFresh(norm(route.url), staleThreshold))
164
- .sort((a, b) => settledCostOf(norm(a.url)) - settledCostOf(norm(b.url)));
165
- const unknown = warm.filter((route) => !(latency.has(norm(route.url)) && isFresh(norm(route.url), staleThreshold)));
153
+ const known = warm.filter((route) => isFresh(facts, norm(route.url)))
154
+ .sort((a, b) => settledCostOf(facts, norm(a.url)) - settledCostOf(facts, norm(b.url)));
155
+ const unknown = warm.filter((route) => !isFresh(facts, norm(route.url)));
166
156
  const ordered = [...known, ...unknown, ...cold];
167
157
  const at = ordered.findIndex((route) => norm(route.url) === current);
168
- if (at < 0)
169
- return ordered;
170
- if (at === 0)
171
- return ordered;
172
- if (cool.has(current))
158
+ if (at <= 0 || cool.has(current) || !isFresh(facts, current))
173
159
  return ordered;
174
- const currentCost = isFresh(current, staleThreshold) ? settledCostOf(current) : undefined;
160
+ const currentCost = settledCostOf(facts, current);
175
161
  if (currentCost === undefined)
176
162
  return ordered;
177
- const headUrl = norm(ordered[0].url);
178
- const headCost = settledCostOf(headUrl);
179
- const settleRounds = SETTLE_ROUNDS * Math.max(1, Math.ceil(warm.length / 6));
180
- if (lastSwitch && evidenceRound - lastSwitch.round > settleRounds)
181
- lastSwitch = null;
182
- const bouncingBack = Boolean(lastSwitch && lastSwitch.to === current && lastSwitch.from === headUrl);
183
- const enoughEvidence = sampleCountOf(current) >= MIN_NOISE_SAMPLES
184
- && sampleCountOf(headUrl) >= MIN_NOISE_SAMPLES;
163
+ const challenger = known.find((route) => norm(route.url) !== current
164
+ && (facts.samples.get(norm(route.url))?.length ?? 0) >= MIN_NOISE_SAMPLES);
165
+ const headUrl = challenger ? norm(challenger.url) : '';
166
+ const headCost = challenger ? settledCostOf(facts, headUrl) : undefined;
185
167
  const gain = headCost !== undefined ? currentCost - headCost : 0;
186
- const noise = enoughEvidence ? noiseCostOf(current) + noiseCostOf(headUrl) : 0;
187
- const required = Math.max(noise, currentCost * ROUTE_SWITCH_SHARE, SWITCH_GAIN_FLOOR_MS);
168
+ const noise = noiseCostOf(facts, current) + noiseCostOf(facts, headUrl);
169
+ const clean = penaltyFor(facts, current) === 1 && penaltyFor(facts, headUrl) === 1;
170
+ const required = Math.max(noise, currentCost * ROUTE_SWITCH_SHARE, clean ? SWITCH_GAIN_FLOOR_MS : 0);
171
+ const bouncingBack = facts.lastSwitch?.to === current && facts.lastSwitch.from === headUrl;
188
172
  const worthwhile = headCost !== undefined && gain > required;
189
- const decisive = gain > required * 2;
190
- const settled = !bouncingBack || decisive;
191
- if (settled && worthwhile) {
192
- lastSwitch = { from: current, to: headUrl, round: evidenceRound };
173
+ const settled = !bouncingBack || gain > required * 2;
174
+ if (challenger && settled && worthwhile) {
175
+ facts.lastSwitch = { from: current, to: headUrl, round: facts.evidenceRound };
176
+ const headAt = ordered.indexOf(challenger);
177
+ ordered.splice(headAt, 1);
178
+ ordered.unshift(challenger);
193
179
  return ordered;
194
180
  }
195
181
  const [item] = ordered.splice(at, 1);
@@ -1,3 +1,4 @@
1
+ // 统一 SSE 记录、合帧计费与延迟写入的背压反馈。
1
2
  'use strict';
2
3
 
3
4
  /**
@@ -162,8 +163,14 @@ function isBatchablePayload(payload) {
162
163
  function batchStateOf(res) {
163
164
  let state = BATCH_STATES.get(res);
164
165
  if (!state) {
165
- state = { items: [], timer: null, options: null };
166
+ state = { items: [], bytes: 0, timer: null, options: null };
166
167
  BATCH_STATES.set(res, state);
168
+ res.once?.('close', () => {
169
+ if (state.timer) clearTimeout(state.timer);
170
+ state.timer = null;
171
+ state.items.length = 0;
172
+ state.bytes = 0;
173
+ });
167
174
  }
168
175
  return state;
169
176
  }
@@ -178,6 +185,7 @@ function flushFrameBatch(res) {
178
185
  }
179
186
  if (state.items.length === 0) return { ok: true };
180
187
  const events = state.items.splice(0);
188
+ state.bytes = 0;
181
189
  const options = state.options || {};
182
190
  // 合帧只做一次:`{batch:false}` 保证不会再被攒回去。
183
191
  return writeSse(res, { type: 'batch', events }, { ...options, batch: false });
@@ -223,26 +231,37 @@ function writeSse(res, payload, options = {}) {
223
231
  */
224
232
  batch = false,
225
233
  } = options;
234
+ const state = batch ? batchStateOf(res) : null;
235
+ const buffered = bufferedBytesOf(res) + (state?.bytes || 0);
236
+ if (res.destroyed || res.writableEnded || buffered > SSE_CLOSE_BUFFERED_BYTES) return { ok: false };
237
+ if (buffered > SSE_SHED_BUFFERED_BYTES && shedWhenBuffered(payload)) return { ok: true, shed: true };
238
+ let flushed = null;
226
239
  if (batch) {
227
- const state = batchStateOf(res);
228
240
  state.options = options;
229
241
  if (!isBatchablePayload(payload)) {
230
242
  // 控制帧 / 心跳 / 收尾:先把攒着的增量按原顺序发完,自己再立刻发。
231
- const flushed = flushFrameBatch(res);
243
+ flushed = flushFrameBatch(res);
232
244
  if (!flushed.ok) return flushed;
233
245
  } else {
246
+ // 密文按 base64 上界计费,回放在延迟写出之前也受同一字节预算约束。
247
+ const bytes = Math.ceil(Buffer.byteLength(JSON.stringify(payload), 'utf8') * (sealFrame ? 4 / 3 : 1)) + 256 + paddingBytes + Buffer.byteLength(padding);
248
+ if (buffered + bytes > SSE_CLOSE_BUFFERED_BYTES) return { ok: false };
234
249
  state.items.push(payload);
235
- if (state.items.length >= BATCH_MAX_EVENTS) return flushFrameBatch(res);
250
+ state.bytes += bytes;
251
+ if (state.items.length >= BATCH_MAX_EVENTS) return { ...flushFrameBatch(res), bytes };
236
252
  if (!state.timer) {
237
- state.timer = setTimeout(() => { state.timer = null; flushFrameBatch(res); }, BATCH_WINDOW_MS);
253
+ state.timer = setTimeout(() => {
254
+ state.timer = null;
255
+ const result = flushFrameBatch(res);
256
+ if (typeof state.options?.onBatchResult === 'function') state.options.onBatchResult(result);
257
+ else if (!result.ok) res.destroy?.();
258
+ }, BATCH_WINDOW_MS);
238
259
  if (typeof state.timer.unref === 'function') state.timer.unref();
239
260
  }
240
- return { ok: true, deferred: true };
261
+ return { ok: true, deferred: true, needDrain: buffered > SSE_SHED_BUFFERED_BYTES, bytes };
241
262
  }
242
263
  }
243
- const buffered = bufferedBytesOf(res);
244
- if (buffered > SSE_CLOSE_BUFFERED_BYTES) return { ok: false };
245
- if (buffered > SSE_SHED_BUFFERED_BYTES && shedWhenBuffered(payload)) return { ok: true, shed: true }; const id = stableEventId(payload, frame, namespace);
264
+ const id = stableEventId(payload, frame, namespace);
246
265
  const fields = [`retry: ${retryMs}`];
247
266
  if (id) fields.push(`id: ${id}`);
248
267
  // 每帧一条独立密文(自己的 nonce):整条流套一个信封就得等流结束才能解,那等于把
@@ -261,7 +280,7 @@ function writeSse(res, payload, options = {}) {
261
280
  const frameText = `${fields.join('\n')}\n`;
262
281
  const accepted = res.write(frameText);
263
282
  // 字节数回给调用方:断线重放要按字节封顶(事件条数封不住「每帧都很大」的会话)。
264
- return { ok: true, needDrain: accepted === false, bytes: Buffer.byteLength(frameText, 'utf8') };
283
+ return { ok: true, needDrain: accepted === false || flushed?.needDrain === true, bytes: Buffer.byteLength(frameText, 'utf8') };
265
284
  } catch { return { ok: false }; }
266
285
  }
267
286
 
@@ -1,3 +1,4 @@
1
+ // 由可信转发入口覆盖来源标记,并统一解析设备通道归属。
1
2
  'use strict';
2
3
 
3
4
  /**
@@ -24,16 +25,8 @@ const VIA_HEADER = 'x-dsh-via';
24
25
  */
25
26
  const VIA_TUNNEL = 'tunnel';
26
27
 
27
- /**
28
- * 这条请求是从哪条路转发进来的(`relay` / `lan`),本机直连返回空串。
29
- *
30
- * 设备列表要显示「最近一次走的是哪条路」,而这两条路最后都进到自己的代理里、
31
- * 各自注入了标记 —— 所以宿主不用问中转,也不用等别的版本。
32
- *
33
- * `tunnel`(隧道落点代理)**不在这里露面**:那一格只有中转 / 局域网两套文案,硬塞进去
34
- * 要么显示成谎话、要么得新增一种可见文案。控制面判据只认「有没有标记」,所以这里返回
35
- * 空串,设备列表照旧显示「—」。
36
- */
28
+ /** 返回转发入口已经覆盖的通道码;无标记时不猜测物理线路。 */
29
+ const VIA_CHANNELS = new Set(['relay', 'lan', 'tunnel', 'p2p', 'direct', 'ipv6', 'tcp', 'mux']);
37
30
  function viaChannel(req) {
38
31
  const headers = req?.headers;
39
32
  if (!headers || typeof headers !== 'object') return '';
@@ -41,7 +34,7 @@ function viaChannel(req) {
41
34
  if (name.toLowerCase() !== VIA_HEADER) continue;
42
35
  const value = Array.isArray(raw) ? raw[0] : raw;
43
36
  const text = typeof value === 'string' ? value.trim().toLowerCase() : '';
44
- return text === 'relay' || text === 'lan' ? text : '';
37
+ return VIA_CHANNELS.has(text) ? text : '';
45
38
  }
46
39
  return '';
47
40
  }
@@ -62,7 +55,7 @@ function stripHeader(headers, name) {
62
55
  * 复制一份转发用头:原头不动,去掉客户端自带的来源标记,写入代理自己的值。
63
56
  *
64
57
  * @param {Record<string, unknown>} incoming 客户端原始请求头
65
- * @param {'relay'|'lan'|'tunnel'} via 转发方
58
+ * @param {'relay'|'lan'|'tunnel'|'p2p'|'direct'|'ipv6'|'tcp'|'mux'} via 转发方
66
59
  * @param {string} fallbackHost 客户端没给 host 时用哪个
67
60
  * @returns {Record<string, unknown>}
68
61
  */
@@ -1,3 +1,4 @@
1
+ // 稳定持有传输服务,并从当前实现读取地址与中转注册真值。
1
2
  /**
2
3
  * 稳定外壳持有的传输进程:sidecar(中转隧道 + 局域网监听)、FRP 直连、总控上报。
3
4
  *
@@ -26,6 +27,11 @@ const { mountP2P } = p2pWiringCjs
26
27
  const { createMuxService } = muxCjs
27
28
 
28
29
  export function installTransportHosts(ctx) {
30
+ /** 外壳自己的告警出口:拿不到 logger 也照常往下走,不打日志不算失败。 */
31
+ const warn = (message, detail) => {
32
+ try { ctx.logger?.warn?.(`dsh-mobile-plugin: ${message}${detail ? ` ${detail}` : ''}`) } catch { /* 日志不许反噬 */ }
33
+ }
34
+
29
35
  // ── sidecar:中转隧道 + 局域网监听 ──────────────────────────────────
30
36
  // 由代首次 sync 时惰性 start(幂等);换代只换配置来源,隧道跨代存活。外壳卸载才 stop。
31
37
  const sidecarHost = createSidecarLifecycle({ ctx })
@@ -52,6 +58,7 @@ export function installTransportHosts(ctx) {
52
58
  getPort: () => 0,
53
59
  getHistoryKey: () => '',
54
60
  getRelayConnected: () => sidecarHost.tunnelConnected(),
61
+ getConnectedRelay: () => { const tunnel = sidecarHost.getSnapshot()?.tunnel; return tunnel?.state === 'connected' ? tunnel.relayUrl || tunnel.route?.url || '' : '' },
55
62
  // 身份冲突时触发换身份的动作,由当前这一代注入(换代换它即可)。缺省不启用。
56
63
  onIdentityConflict: null,
57
64
  }
@@ -61,6 +68,8 @@ export function installTransportHosts(ctx) {
61
68
  getPort: () => controlProviders.getPort(),
62
69
  getHistoryKey: () => controlProviders.getHistoryKey(),
63
70
  getRelayConnected: () => controlProviders.getRelayConnected(),
71
+ getConnectedRelay: () => controlProviders.getConnectedRelay(),
72
+ log: warn,
64
73
  onIdentityConflict: (...args) => {
65
74
  const fn = controlProviders.onIdentityConflict
66
75
  return typeof fn === 'function' ? fn(...args) : undefined
@@ -100,7 +109,6 @@ export function installTransportHosts(ctx) {
100
109
  // 惰性 ensure:只有认识这个服务的一代第一次用到时才真正创建入口/落点/助手会话并起监听,
101
110
  // 测试里的假代不碰它就完全不起端口/进程。创建用外壳的 ctx,effect 挂在外壳上,跨代存活;
102
111
  // 换代只更新状态/端口来源(`ensure` 传进来的 providers),助手会话本身照跑。
103
- const warn = message => { try { ctx.logger?.warn?.(`dsh-mobile-plugin: ${message}`) } catch { /* 日志不许反噬 */ } }
104
112
  const looseMount = (label, fn) => { try { return fn() } catch (error) { warn(`${label} 没挂上:${error && error.message ? error.message : error}`); return undefined } }
105
113
  let tailcatDoor = null
106
114
  let tailcatProviders = {}
@@ -333,7 +333,7 @@ export function performUpdate(options = {}) {
333
333
  return applying
334
334
  }
335
335
 
336
- async function runUpdate({ runtime, base, hostService = () => null, updateState, beforeInstall = null, log = () => {}, force = false, auto = false } = {}) {
336
+ async function runUpdate({ runtime, base, hostService = () => null, updateState, beforeInstall = null, log = () => {}, force = false, auto = false, runningShellHash = null } = {}) {
337
337
  const status = () => {
338
338
  try { return runtime.status() ?? {} } catch { return {} }
339
339
  }
@@ -385,8 +385,14 @@ async function runUpdate({ runtime, base, hostService = () => null, updateState,
385
385
  * 任何东西 —— 它只用这条记录在**下一次连上之后**如实显示「上次装失败了,已退回 X」。
386
386
  */
387
387
  let rollback = null
388
+ // 这次更新有没有连外壳一起改:跑着的外壳指纹(启动时算好传来)与盘上那份不一样,就说明
389
+ // 外壳变了。外壳不热更,就地换的只是实现;外壳那部分要重启一次 DSH 才生效。以前这里不
390
+ // 管外壳改没改,一律报「无需重启」,结果用户以为万事大吉、不重启,就停在了「实现换了、
391
+ // 外壳还是旧的」那种半套状态(反馈 #24)。
392
+ const installedShellHash = shellFingerprint(installedPackageDirSafe())
393
+ const shellChanged = Boolean(installedShellHash && runningShellHash && installedShellHash !== runningShellHash)
388
394
  if (!outcome.failure && (outcome.installed === true || newerOnDisk)) {
389
- const attempt = await swapTo(runtime, disk ?? runningBefore, { auto, log })
395
+ const attempt = await swapTo(runtime, disk ?? runningBefore, { auto, log, shellChanged })
390
396
  swapped = attempt.swapped
391
397
  swapFailure = attempt.failure
392
398
  deferred = attempt.deferred === true
@@ -408,8 +414,10 @@ async function runUpdate({ runtime, base, hostService = () => null, updateState,
408
414
  rolledBack,
409
415
  /** 恢复之后实际运行的版本。 */
410
416
  runningAfterRollback: rolledBack ? (rollback?.toVersion ?? runningBefore) : null,
411
- // 换代由外壳就地做,市场那套「装完要重启」在本项目一律不照做。只为如实上报。
412
- restartRequired: false,
417
+ // 实现已经就地换好、功能可用;但若这次更新连外壳一起改了,外壳那部分必须重启一次 DSH
418
+ // 才生效 —— 如实报出来,让面板和手机提示「重启一次」,而不是骗人「无需重启」。
419
+ restartRequired: shellChanged,
420
+ shellChanged,
413
421
  refreshRequired: false,
414
422
  }
415
423
  updateState.lastApply = lastApply
@@ -430,7 +438,7 @@ async function runUpdate({ runtime, base, hostService = () => null, updateState,
430
438
  * 失败只回错误、不抛:调用方要先落账再决定要不要抛。`auto` 为真时同一版本只试一次
431
439
  * (见 `swapAttempts`),手动调用不受限制。
432
440
  */
433
- async function swapTo(runtime, target, { auto = false, log = () => {} } = {}) {
441
+ async function swapTo(runtime, target, { auto = false, log = () => {}, shellChanged = false } = {}) {
434
442
  const key = String(target ?? '')
435
443
  const tried = swapAttempts.get(key) ?? 0
436
444
  if (auto && tried >= 1) {
@@ -459,7 +467,11 @@ async function swapTo(runtime, target, { auto = false, log = () => {} } = {}) {
459
467
  failure: { code: 'self_check_failed', message: rollback.reason },
460
468
  }
461
469
  }
462
- log('info', 'dsh-mobile-plugin: 已就地换到 %s(无需重启 DSH)', status?.version ?? key)
470
+ if (shellChanged) {
471
+ log('info', 'dsh-mobile-plugin: 已就地换到 %s;这次更新也改了外壳,实现已生效,外壳那部分要重启一次 DSH 才生效', status?.version ?? key)
472
+ } else {
473
+ log('info', 'dsh-mobile-plugin: 已就地换到 %s(无需重启 DSH)', status?.version ?? key)
474
+ }
463
475
  return { swapped: true, status }
464
476
  } catch (error) {
465
477
  // 新版装载直接抛错:runtime 已经按老规矩回滚过一代了,那条回滚也记在 `lastRollback`。