dsh-mobile-ios 0.2.8 → 0.2.9

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.
package/lib/client.js CHANGED
@@ -195,6 +195,20 @@ window.__ModuleLoader__.load({
195
195
  .dsh-mios-modal .modal-actions button.primary { border-color:var(--modal-accent);
196
196
  background:rgba(63,178,127,.16); color:var(--modal-accent); }
197
197
  .dsh-mios-modal .modal-actions button:disabled { opacity:.6; cursor:default; }
198
+ /* 复制结果必须看得见:dsh-app:// 页面里剪贴板可能不可用,只改按钮文字容易被无视。
199
+ .modal-toast 常驻在动作条上方,成功/失败都留痕。 */
200
+ .dsh-mios-modal .modal-toast { margin:10px 0 0; padding:7px 10px; border-radius:8px; font-size:11px;
201
+ font-weight:600; line-height:1.5; background:rgba(139,147,163,.14); color:var(--modal-muted); }
202
+ .dsh-mios-modal .modal-toast.success { background:rgba(63,178,127,.16); color:#2f9d70; }
203
+ .dsh-mios-modal .modal-toast.error { background:rgba(217,79,61,.14); color:#d94f3d; }
204
+ /* 复制全线失败时的兜底:给一个已自动全选的输入框,用户 Ctrl/⌘+C 就能拿走 */
205
+ .dsh-mios-modal .modal-pick { width:100%; box-sizing:border-box; margin:10px 0 0; padding:8px 10px;
206
+ border-radius:8px; border:1px solid var(--modal-accent); background:rgba(63,178,127,.10);
207
+ color:var(--modal-fg); font-family:ui-monospace, SFMono-Regular, Menlo, monospace; font-size:12px;
208
+ user-select:text; -webkit-user-select:text; }
209
+ .dsh-mios-modal .modal-steps { margin:10px 0 0; padding-left:18px; font-size:11px;
210
+ color:var(--modal-muted); line-height:1.7; }
211
+ .dsh-mios-modal .modal-steps li { margin:2px 0; }
198
212
  .dsh-mios-panel .row { display: flex; justify-content: space-between; gap: 8px; color: var(--muted); margin: 3px 0; }
199
213
  .dsh-mios-panel .row b { color: var(--fg); font-weight: 600; text-align: right; max-width: 170px;
200
214
  overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
@@ -455,13 +469,16 @@ window.__ModuleLoader__.load({
455
469
  // 「域名未生效」必须单列:地址开出来了但公网解析不到,显示「已开通」会误导人去扫码。
456
470
  const tunnel = ok ? summary.tunnel : null;
457
471
  const dnsBroken = tunnel && tunnel.dnsOk === false;
458
- const running = !!(tunnel && tunnel.state === 'running' && !dnsBroken);
472
+ // 「进程在跑」与「地址可用」是两件事:域名没生效时隧道进程可能已经起来了,
473
+ // 但扫码必然连不上,所以 running 仍然要求 dnsOk 不为 false。
474
+ const processUp = !!(tunnel && tunnel.state === 'running');
475
+ const running = processUp && !dnsBroken;
459
476
  const remoteState = panelEl.querySelector('#dsh-mios-remote-state');
460
477
  if (remoteState) {
461
478
  remoteState.textContent = !tunnel
462
479
  ? '—'
463
480
  : dnsBroken
464
- ? '解析异常 · 未开启'
481
+ ? (processUp ? '已开启 · 域名未生效' : '解析异常 · 未开启')
465
482
  : running
466
483
  ? '已开启'
467
484
  : tunnel.provisioned && tunnel.fixedUrl
@@ -481,12 +498,15 @@ window.__ModuleLoader__.load({
481
498
  // 出码态走绿色主按钮;开启态走灰色次按钮(悬浮变白),视觉上分清两件事
482
499
  mainBtn.className = 'pairbtn' + (running || dnsBroken ? '' : ' tunnelbtn');
483
500
  mainBtn.style.display = tunnel && tunnel.state !== 'disabled' ? '' : 'none';
484
- mainBtn.disabled = tunnelBusy || bannerBusy.remote || dnsBroken;
501
+ // 关键:dnsBroken 不再禁用按钮。
502
+ // 以前 disabled = ... || dnsBroken,而唯一的重探入口就在点击之后 ——
503
+ // 按钮永远点不到,NS 改对了也不恢复,只能删状态文件(自锁死)。
504
+ mainBtn.disabled = tunnelBusy || bannerBusy.remote;
485
505
  const needsInstall = tunnel.executable === 'missing';
486
506
  mainBtn.textContent = needsInstall && tunnel.canAutoInstall
487
507
  ? '安装 cloudflared 并开启远程'
488
508
  : dnsBroken
489
- ? '域名解析异常,暂不可开启'
509
+ ? '重新检测域名解析'
490
510
  : running
491
511
  ? (bannerBusy.remote ? '生成中…' : '生成配对码(远程)')
492
512
  : tunnel.mode === 'named'
@@ -495,8 +515,9 @@ window.__ModuleLoader__.load({
495
515
  }
496
516
  const stopBtn = panelEl.querySelector('#dsh-mios-remote-stop');
497
517
  if (stopBtn) {
498
- // 停止按钮只在该停的时候出现:没开过/没在跑都没有「停」可言
499
- stopBtn.style.display = running && !tunnelBusy ? '' : 'none';
518
+ // 停止按钮只在该停的时候出现:没开过/没在跑都没有「停」可言。
519
+ // 域名未生效但进程在跑时仍要给「停止」——否则用户无法收尾。
520
+ stopBtn.style.display = processUp && !tunnelBusy ? '' : 'none';
500
521
  stopBtn.disabled = tunnelBusy;
501
522
  }
502
523
  // 远程码跟着可用性走:不是 running 就收起(与「停止即收码」同一语义,
@@ -700,7 +721,7 @@ window.__ModuleLoader__.load({
700
721
  updateModal?.remove();
701
722
  updateModal = null;
702
723
  }
703
- function showUpdateModal({ title, banner, lines, note, actions }) {
724
+ function showUpdateModal({ title, banner, lines, note, steps, actions }) {
704
725
  closeUpdateModal();
705
726
  const mask = document.createElement('div');
706
727
  mask.className = 'dsh-mios-modal-mask';
@@ -743,6 +764,17 @@ window.__ModuleLoader__.load({
743
764
  n.textContent = note;
744
765
  box.append(n);
745
766
  }
767
+ // 排障步骤:域名/NS 这类问题光说「异常」没用,得给出下一步点哪里。
768
+ if (steps?.length) {
769
+ const ol = document.createElement('ol');
770
+ ol.className = 'modal-steps';
771
+ for (const s of steps) {
772
+ const li = document.createElement('li');
773
+ li.textContent = s;
774
+ ol.append(li);
775
+ }
776
+ box.append(ol);
777
+ }
746
778
 
747
779
  const bar = document.createElement('div');
748
780
  bar.className = 'modal-actions';
@@ -760,29 +792,93 @@ window.__ModuleLoader__.load({
760
792
  updateModal = mask;
761
793
  }
762
794
 
763
- /** 复制文本:clipboard API 不可用时回退到 textarea + execCommand。 */
795
+ /**
796
+ * 复制文本。三级降级,任一级成功即返回 true:
797
+ * 1) navigator.clipboard —— 只在安全上下文可用;dsh-app:// 这类自定义协议
798
+ * 通常不算安全上下文,所以这一级大概率直接缺失/抛错;
799
+ * 2) textarea + execCommand('copy') —— 必须真的可见可焦点、并显式框选,
800
+ * 之前用 opacity:0 且未 focus/未 setSelectionRange,在 Electron 里选不中,
801
+ * execCommand 返回 false(这正是「点了复制没反应」的直接原因);
802
+ * 3) 全选 contenteditable 兜底 —— 仍然失败就交给面板给用户可手动复制的输入框。
803
+ */
764
804
  async function copyToClipboard(text) {
805
+ const value = String(text ?? '');
806
+ if (!value) return false;
765
807
  try {
766
808
  if (navigator.clipboard?.writeText) {
767
- await navigator.clipboard.writeText(text);
809
+ await navigator.clipboard.writeText(value);
768
810
  return true;
769
811
  }
770
- } catch { /* 落到下面的回退 */ }
812
+ } catch { /* 落到下一级 */ }
771
813
  try {
772
814
  const ta = document.createElement('textarea');
773
- ta.value = text;
774
- ta.style.position = 'fixed';
775
- ta.style.opacity = '0';
815
+ ta.value = value;
816
+ ta.setAttribute('readonly', '');
817
+ ta.setAttribute('aria-hidden', 'true');
818
+ // 用屏幕外定位而不是 opacity:0:透明元素在部分引擎里无法获得选区
819
+ ta.style.cssText = 'position:fixed;top:0;left:-9999px;width:1px;height:1px;'
820
+ + 'padding:0;border:0;outline:none;box-shadow:none;background:transparent;';
776
821
  document.body.append(ta);
822
+ ta.focus();
777
823
  ta.select();
824
+ ta.setSelectionRange(0, value.length);
778
825
  const ok = document.execCommand('copy');
779
826
  ta.remove();
780
- return ok;
827
+ if (ok) return true;
828
+ } catch { /* 落到下一级 */ }
829
+ try {
830
+ const holder = document.createElement('div');
831
+ holder.contentEditable = 'true';
832
+ holder.textContent = value;
833
+ holder.style.cssText = 'position:fixed;top:0;left:-9999px;white-space:pre;';
834
+ document.body.append(holder);
835
+ const range = document.createRange();
836
+ range.selectNodeContents(holder);
837
+ const sel = window.getSelection();
838
+ sel.removeAllRanges();
839
+ sel.addRange(range);
840
+ const ok = document.execCommand('copy');
841
+ sel.removeAllRanges();
842
+ holder.remove();
843
+ return Boolean(ok);
781
844
  } catch {
782
845
  return false;
783
846
  }
784
847
  }
785
848
 
849
+ /** 弹窗内结果提示:复制/更新这类动作必须有可见反馈,不能只改按钮文字。 */
850
+ function showModalToast(text, tone = 'info') {
851
+ const box = updateModal?.querySelector?.('.dsh-mios-modal');
852
+ if (!box) return;
853
+ let el = box.querySelector('.modal-toast');
854
+ if (!el) {
855
+ el = document.createElement('div');
856
+ box.insertBefore(el, box.querySelector('.modal-actions'));
857
+ }
858
+ el.className = `modal-toast${tone ? ' ' + tone : ''}`;
859
+ el.textContent = text;
860
+ }
861
+
862
+ /**
863
+ * 复制全线失败时的兜底:在弹窗里放一个已全选的输入框。
864
+ * 用户按 Ctrl/⌘+C 就能拿到,不依赖任何剪贴板 API。
865
+ */
866
+ function offerManualCopy(text) {
867
+ const box = updateModal?.querySelector?.('.dsh-mios-modal');
868
+ if (!box) return;
869
+ if (box.querySelector('.modal-pick')) return;
870
+ const input = document.createElement('input');
871
+ input.className = 'modal-pick';
872
+ input.type = 'text';
873
+ input.readOnly = true;
874
+ input.value = text;
875
+ box.insertBefore(input, box.querySelector('.modal-actions'));
876
+ try {
877
+ input.focus();
878
+ input.select();
879
+ } catch { /* 焦点拿不到也让用户能手动点选 */ }
880
+ }
881
+
786
882
  async function checkPluginUpdate() {
787
883
  showUpdateModal({ title: '插件更新', lines: [], note: '正在检查更新…', actions: [] });
788
884
  const current = summary?.version || '未知';
@@ -812,24 +908,12 @@ window.__ModuleLoader__.load({
812
908
  return;
813
909
  }
814
910
  if (compareVersions(latest, current) > 0) {
815
- // 一步更新:宿主提供 pluginManager 时直接安装,无需复制包名手动添加。
911
+ // 一键更新有两条路,面板不再把「复制包名」当主路径:
912
+ // ① 宿主给了 pluginManager.installBundle → 交给 DSH 安装器;
913
+ // ② 没给(老宿主 / 自定义协议页面)→ 网关自己取 npm tarball 覆盖安装。
914
+ // 以前 ② 缺失就只剩复制包名,而这类页面里剪贴板本身也不可用,
915
+ // 结果就是「既不能一键更新、也复制不了」的死角。
816
916
  const canAuto = !!(pluginManager && typeof pluginManager.installBundle === 'function');
817
- const actions = [{ label: '稍后再说', onClick: closeUpdateModal }];
818
- if (canAuto) {
819
- actions.push({
820
- label: `立即更新到 v${latest}`, primary: true,
821
- onClick: () => performUpdate(latest),
822
- });
823
- } else {
824
- // 降级:拿不到宿主安装服务(老宿主 / 非 Desktop),保留复制包名手动安装。
825
- actions.push({
826
- label: `复制 ${PLUGIN_NAME}@${latest}`, primary: true,
827
- onClick: async (btn) => {
828
- const ok = await copyToClipboard(`${PLUGIN_NAME}@${latest}`);
829
- btn.textContent = ok ? '已复制,去插件页粘贴安装' : '复制失败,请手动复制包名';
830
- },
831
- });
832
- }
833
917
  showUpdateModal({
834
918
  title: '新版本更新',
835
919
  banner: { text: `⬆️ 发现新版本 v${latest},可一键更新`, tone: 'info' },
@@ -839,8 +923,14 @@ window.__ModuleLoader__.load({
839
923
  ],
840
924
  note: canAuto
841
925
  ? '点击「立即更新」将由 DSH 安装器一步完成,更新中请勿关闭窗口。是否更新由你决定。'
842
- : '当前宿主未提供一步更新能力,请复制包名到 DSH「插件 → 添加插件」粘贴安装。',
843
- actions,
926
+ : '点击「立即更新」由本机网关直接下载并安装,无需复制包名;完成后重启 DSH 生效。',
927
+ actions: [
928
+ { label: '稍后再说', onClick: closeUpdateModal },
929
+ {
930
+ label: `立即更新到 v${latest}`, primary: true,
931
+ onClick: () => performUpdate(latest),
932
+ },
933
+ ],
844
934
  });
845
935
  } else {
846
936
  showUpdateModal({
@@ -930,25 +1020,10 @@ window.__ModuleLoader__.load({
930
1020
  async function performUpdate(latest) {
931
1021
  // 重复点击保护:更新中直接忽略再次触发
932
1022
  if (updateInFlight) return;
933
- if (!pluginManager || typeof pluginManager.installBundle !== 'function') {
934
- showUpdateModal({
935
- title: '更新不可用',
936
- banner: { text: '⚠️ 宿主未提供一步更新能力', tone: 'warn' },
937
- lines: [],
938
- note: '请复制包名,到 DSH「插件 → 添加插件」粘贴安装。',
939
- actions: [
940
- { label: '知道了', onClick: closeUpdateModal },
941
- { label: `复制 ${PLUGIN_NAME}@${latest}`, primary: true, onClick: async (btn) => {
942
- const ok = await copyToClipboard(`${PLUGIN_NAME}@${latest}`);
943
- btn.textContent = ok ? '已复制' : '复制失败';
944
- } },
945
- ],
946
- });
947
- return;
948
- }
949
1023
  updateInFlight = true;
950
1024
  const current = summary?.version || '未知';
951
1025
  const spec = `${PLUGIN_NAME}@${latest}`;
1026
+ const canHost = !!(pluginManager && typeof pluginManager.installBundle === 'function');
952
1027
  // 先持久化「更新中」,确保 HMR 卸载本模块后新实例能恢复出结果反馈。
953
1028
  writeUpdateState({ status: 'updating', target: String(latest), at: Date.now() });
954
1029
  // 状态:更新中。无取消/关闭动作外的操作按钮,防重复点击。
@@ -959,30 +1034,45 @@ window.__ModuleLoader__.load({
959
1034
  { label: '当前版本', value: `v${current}` },
960
1035
  { label: '目标版本', value: `v${latest}`, highlight: true },
961
1036
  ],
962
- note: '正在通过 DSH 安装器更新,可能需要 1–3 分钟。请勿重复点击或关闭窗口。',
1037
+ note: canHost
1038
+ ? '正在通过 DSH 安装器更新,可能需要 1–3 分钟。请勿重复点击或关闭窗口。'
1039
+ : '正在经本机网关下载并安装(含完整性校验),请勿重复点击或关闭窗口。',
963
1040
  actions: [],
964
1041
  });
965
- let requestId;
966
1042
  try {
967
- requestId = globalThis.crypto?.randomUUID?.();
968
- if (typeof requestId !== 'string') throw new Error('无法生成更新请求 ID');
969
- let result;
970
- try {
971
- result = await withTimeout(
972
- pluginManager.installBundle(spec, { enabled: true, requestId }),
973
- UPDATE_TIMEOUT_MS, '安装',
974
- );
975
- } catch (err) {
976
- // 超时/结果未知:用 requestId 对账,绝不重复提交安装
977
- if (typeof pluginManager.waitForInstall === 'function') {
978
- const recovered = await withTimeout(pluginManager.waitForInstall(requestId), 60000, '结果对账');
979
- if (!recovered) throw err;
980
- result = recovered;
981
- } else throw err;
1043
+ let restart = false;
1044
+ if (canHost) {
1045
+ // ① 宿主安装器:最常见的 Desktop 路径
1046
+ let requestId;
1047
+ requestId = globalThis.crypto?.randomUUID?.();
1048
+ if (typeof requestId !== 'string') throw new Error('无法生成更新请求 ID');
1049
+ let result;
1050
+ try {
1051
+ result = await withTimeout(
1052
+ pluginManager.installBundle(spec, { enabled: true, requestId }),
1053
+ UPDATE_TIMEOUT_MS, '安装',
1054
+ );
1055
+ } catch (err) {
1056
+ // 超时/结果未知:用 requestId 对账,绝不重复提交安装
1057
+ if (typeof pluginManager.waitForInstall === 'function') {
1058
+ const recovered = await withTimeout(pluginManager.waitForInstall(requestId), 60000, '结果对账');
1059
+ if (!recovered) throw err;
1060
+ result = recovered;
1061
+ } else throw err;
1062
+ }
1063
+ const value = unwrapRemote(result);
1064
+ restart = !!(value && (value.restartRequired || value.restart));
1065
+ } else {
1066
+ // ② 网关自更新:宿主没给 installBundle 时的等效能力。
1067
+ // 网关从 npm 取 tarball、按 dist.shasum 校验、备份旧目录后覆盖安装。
1068
+ const res = await fetchJson('/mobile/v1/plugin/self-update', {
1069
+ method: 'POST',
1070
+ headers: { 'content-type': 'application/json' },
1071
+ body: JSON.stringify({ target: latest }),
1072
+ }, 180000);
1073
+ restart = res?.restartRequired !== false;
982
1074
  }
983
- const value = unwrapRemote(result);
984
- const restart = !!(value && (value.restartRequired || value.restart));
985
- clearUpdateState(); // 安装器已返回结果,交由本弹窗反馈,无需跨重载恢复
1075
+ clearUpdateState(); // 安装已返回结果,交由本弹窗反馈,无需跨重载恢复
986
1076
  // 状态:成功
987
1077
  showUpdateModal({
988
1078
  title: '更新完成',
@@ -991,7 +1081,7 @@ window.__ModuleLoader__.load({
991
1081
  { label: '目标版本', value: `v${latest}` },
992
1082
  ],
993
1083
  note: restart
994
- ? '插件已更新,重启 DSH 桌面端后生效。'
1084
+ ? '插件已更新,重启 DSH 桌面端后生效(面板版本号会在重启后变成新版本)。'
995
1085
  : '插件已更新。若面板未刷新,重开面板或重启 DSH 即可。',
996
1086
  actions: [{ label: '知道了', primary: true, onClick: closeUpdateModal }],
997
1087
  });
@@ -1002,10 +1092,24 @@ window.__ModuleLoader__.load({
1002
1092
  title: '更新失败',
1003
1093
  banner: { text: '❌ 更新未成功', tone: 'error' },
1004
1094
  lines: [{ label: '目标版本', value: `v${latest}` }],
1005
- note: `安装失败:${err?.message || String(err)}。可重试,或复制包名到「插件 → 添加插件」手动安装。`,
1095
+ note: `安装失败:${err?.body?.error?.message || err?.message || String(err)}。可重试,也可以复制包名到「插件 → 添加插件」手动安装。`,
1006
1096
  actions: [
1007
1097
  { label: '关闭', onClick: closeUpdateModal },
1008
1098
  { label: '重试更新', primary: true, onClick: () => performUpdate(latest) },
1099
+ {
1100
+ label: '复制包名',
1101
+ onClick: async (btn) => {
1102
+ const ok = await copyToClipboard(spec);
1103
+ if (ok) {
1104
+ btn.textContent = '已复制';
1105
+ showModalToast(`已复制 ${spec},去「插件 → 添加插件」粘贴安装`, 'success');
1106
+ } else {
1107
+ btn.textContent = '请手动复制';
1108
+ showModalToast('本机剪贴板不可用,请在下方框内全选复制', 'error');
1109
+ offerManualCopy(spec);
1110
+ }
1111
+ },
1112
+ },
1009
1113
  ],
1010
1114
  });
1011
1115
  } finally {
@@ -1125,15 +1229,105 @@ window.__ModuleLoader__.load({
1125
1229
  }
1126
1230
  }
1127
1231
 
1232
+ /** 记住最近一次触发远程动作的 banner:弹窗里的「重新检测」要能继续同一条链。 */
1233
+ let lastRemoteBanner = null;
1234
+
1235
+ /**
1236
+ * 域名未生效时的排障弹窗。
1237
+ *
1238
+ * 关键是把「异常」翻译成用户能做的三件事,并带上公网当前 NS 让他去注册商对照:
1239
+ * 用户不需要理解 zone/pending,只要看名字对不对得上。
1240
+ */
1241
+ function showDnsHelpModal(res = {}) {
1242
+ const ns = Array.isArray(res.publicNs) ? res.publicNs : [];
1243
+ const host = stripUrl(summary?.tunnel?.fixedUrl || summary?.tunnel?.hostname || '');
1244
+ const tampered = Boolean(res.tampered);
1245
+ showUpdateModal({
1246
+ title: tampered ? '固定域名被改指' : '域名暂未生效',
1247
+ banner: {
1248
+ text: tampered ? '⚠️ CNAME 已不指向本机隧道' : '⚠️ 公网解析不到这个地址',
1249
+ tone: 'warn',
1250
+ },
1251
+ lines: [
1252
+ { label: '固定域名', value: host || '—' },
1253
+ ...(ns.length ? [{ label: '公网 NS', value: ns.join(' / ') }] : []),
1254
+ ],
1255
+ note: tampered
1256
+ ? '这条 CNAME 现在指向别处,扫码会把指令发给未知服务器,网关已拒绝下发该地址。'
1257
+ : '记录已经写进 Cloudflare,但公网解析不到它。通常是这个域名在当前登录的账号里还没生效:zone 处于 pending,公网 NS 指向另一份 zone。',
1258
+ steps: tampered
1259
+ ? [
1260
+ '到 Cloudflare 该域名的 DNS 页面,检查上面这条 CNAME 指向哪里。',
1261
+ '把它改回本机隧道(或直接删除这条记录)。',
1262
+ '回到面板点「重新检测」,通过后重新生成配对码。',
1263
+ ]
1264
+ : [
1265
+ '到 Cloudflare 后台看该域名:若状态是「待激活 / Pending」,说明公网 NS 还没指向这个账号。',
1266
+ `把域名注册商处的 NS 改成该账号分配的 nameserver${ns.length ? `(当前公网是 ${ns.join('、')})` : ''}。`,
1267
+ 'NS 生效通常几分钟到几小时;生效后回到面板点「重新检测」即可,无需重装插件。',
1268
+ ],
1269
+ actions: [
1270
+ { label: '关闭', onClick: closeUpdateModal },
1271
+ {
1272
+ label: '重新检测', primary: true,
1273
+ onClick: () => { closeUpdateModal(); recheckDnsAction(lastRemoteBanner); },
1274
+ },
1275
+ ],
1276
+ });
1277
+ }
1278
+
1279
+ /**
1280
+ * 域名解析异常时的主按钮出路:强制重探一次。
1281
+ * 通过 → 直接继续「开启 + 出码」,用户不用再点第二次;不通过 → 给排障步骤。
1282
+ */
1283
+ async function recheckDnsAction(banner) {
1284
+ if (tunnelBusy) return;
1285
+ lastRemoteBanner = banner || lastRemoteBanner;
1286
+ tunnelBusy = true;
1287
+ const mainBtn = panelEl?.querySelector('#dsh-mios-remote-main');
1288
+ if (mainBtn) {
1289
+ mainBtn.disabled = true;
1290
+ mainBtn.textContent = '检测中…';
1291
+ }
1292
+ try {
1293
+ const res = await fetchJson('/mobile/v1/tunnel/recheck-dns', { method: 'POST' }, 25000);
1294
+ await probe();
1295
+ renderSummary();
1296
+ if (res?.ok) {
1297
+ // 解析恢复:把动作链接回去(此时 tunnelBusy 必须释放,否则 remoteMainAction 会直接返回)
1298
+ tunnelBusy = false;
1299
+ if (mainBtn) mainBtn.disabled = false;
1300
+ await remoteMainAction(lastRemoteBanner);
1301
+ return;
1302
+ }
1303
+ showDnsHelpModal(res || {});
1304
+ } catch (err) {
1305
+ showDnsHelpModal({
1306
+ ok: false,
1307
+ warning: err?.body?.error?.message || err?.message || String(err),
1308
+ });
1309
+ } finally {
1310
+ tunnelBusy = false;
1311
+ if (mainBtn) mainBtn.disabled = false;
1312
+ renderSummary();
1313
+ }
1314
+ }
1315
+
1128
1316
  /** 远程主按钮:一条动作链走完「确保在跑 → 出码」。一次点击出码,绝不让人点两下。 */
1129
1317
  async function remoteMainAction(banner) {
1130
1318
  if (tunnelBusy || bannerBusy.remote || installBusy) return;
1319
+ lastRemoteBanner = banner || lastRemoteBanner;
1131
1320
  const mainBtn = panelEl?.querySelector('#dsh-mios-remote-main');
1132
1321
  // 缺依赖且平台可自动装:先走安装确认,装完再继续开启(避免点了必然失败的 start)
1133
1322
  if (summary?.tunnel?.executable === 'missing' && summary?.tunnel?.canAutoInstall) {
1134
1323
  installCloudflaredAction(banner);
1135
1324
  return;
1136
1325
  }
1326
+ // 域名解析异常:先重检,别把人堵在「暂不可开启」上(那就是原来的死锁)
1327
+ if (summary?.tunnel?.dnsOk === false) {
1328
+ await recheckDnsAction(banner);
1329
+ return;
1330
+ }
1137
1331
  const running = summary?.tunnel?.state === 'running' && summary?.tunnel?.dnsOk !== false;
1138
1332
  try {
1139
1333
  if (!running) {
@@ -1282,8 +1476,11 @@ window.__ModuleLoader__.load({
1282
1476
  exports.__test = {
1283
1477
  PORT_CANDIDATES, STATUS_OK, STATUS_DOWN,
1284
1478
  showUpdateModal, closeUpdateModal, copyToClipboard,
1479
+ showModalToast, offerManualCopy, showDnsHelpModal, recheckDnsAction,
1285
1480
  performUpdate, checkPluginUpdate, compareVersions, unwrapRemote,
1286
1481
  setPluginManager: (m) => { pluginManager = m; },
1482
+ probe, remoteMainAction, renderSummary,
1483
+ getSummary: () => summary,
1287
1484
  setUpdateTimeout: (ms) => { UPDATE_TIMEOUT_MS = ms; },
1288
1485
  isUpdateInFlight: () => updateInFlight,
1289
1486
  restorePendingUpdate, readUpdateState, writeUpdateState, clearUpdateState,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-mobile-ios",
3
- "version": "0.2.8",
3
+ "version": "0.2.9",
4
4
  "type": "module",
5
5
  "description": "DSH iOS移动伴侣:iPhone/iPad 扫码连接 DSH 桌面端,局域网直连 + Cloudflare Tunnel 固定域名远程两种通道",
6
6
  "main": "entries/plugin.mjs",
@@ -30,7 +30,7 @@
30
30
  "start": "node entries/sidecar.mjs --host=mock --dev",
31
31
  "start:lan": "node entries/sidecar.mjs --host=mock --dev --lan=true",
32
32
  "probe": "node spike0/probe.mjs",
33
- "test": "node test/selftest.mjs && node test/version.mjs && node test/update-dialog.mjs && node test/ops.mjs && node test/resilience.mjs && node test/borrowed.mjs && node test/mux-table.mjs && node test/live-frames.mjs && node test/artifacts.mjs && node test/attachments.mjs && node test/session-actions.mjs && node test/enhance.mjs && node test/tunnel-named.mjs && node test/cloudflared-install.mjs && node test/install-continue.mjs"
33
+ "test": "node test/selftest.mjs && node test/version.mjs && node test/update-dialog.mjs && node test/ops.mjs && node test/resilience.mjs && node test/borrowed.mjs && node test/mux-table.mjs && node test/live-frames.mjs && node test/artifacts.mjs && node test/attachments.mjs && node test/session-actions.mjs && node test/enhance.mjs && node test/tunnel-named.mjs && node test/cloudflared-install.mjs && node test/install-continue.mjs && node test/dns-recheck.mjs && node test/plugin-selfupdate.mjs"
34
34
  },
35
35
  "dsh": {
36
36
  "bundle": {
@@ -109,6 +109,27 @@ class BaseProvisioner {
109
109
  return verdict;
110
110
  }
111
111
 
112
+ /**
113
+ * 面板「重新检测解析」:强制重探一次并写回状态,不做缓存短路。
114
+ * 与 LocalProvisioner.recheckDns 同一契约,面板对两种开通形态一视同仁。
115
+ */
116
+ async recheckDns() {
117
+ const s = this.state;
118
+ if (!s?.hostname) return { provisioned: false, ok: false, tampered: false, warning: null };
119
+ const verdict = await this.verifyDns(s.hostname);
120
+ const now = this.state;
121
+ return {
122
+ provisioned: true,
123
+ hostname: now.hostname,
124
+ ok: Boolean(verdict.ok),
125
+ tampered: Boolean(verdict.tampered),
126
+ expected: verdict.expected ?? null,
127
+ target: verdict.target ?? null,
128
+ warning: dnsWarningFor(now),
129
+ checkedAt: now.dnsCheckedAt ?? null,
130
+ };
131
+ }
132
+
112
133
  /** 状态文件里的缓存(读一次后常驻;写穿时同步更新)。 */
113
134
  get state() {
114
135
  if (this._state === undefined) this._state = loadState(this.stateFile, this.log);
@@ -143,6 +164,7 @@ class BaseProvisioner {
143
164
  port: s.port ?? null,
144
165
  // null = 还没验过;true/false = 验过且结论明确
145
166
  dnsOk: s.dnsOk ?? null,
167
+ dnsCheckedAt: s.dnsCheckedAt ?? null,
146
168
  warning: dnsWarningFor(s),
147
169
  createdAt: s.createdAt ?? null,
148
170
  updatedAt: s.updatedAt ?? null,
@@ -0,0 +1,148 @@
1
+ // plugin-update.mjs — 插件自更新(不依赖宿主插件管理器)
2
+ //
3
+ // 为什么需要它:宿主是否暴露 `remote.pluginManager.installBundle` 取决于版本与平台,
4
+ // 拿不到时面板只能让用户「复制包名 → 去插件页粘贴」,而 dsh-app:// 这类自定义协议
5
+ // 页面里 navigator.clipboard 与 document.execCommand('copy') 都可能不可用,
6
+ // 于是「一键更新」在最需要它的机器上恰恰用不了。
7
+ //
8
+ // 这里走的是网关进程自己动手:从 npm registry 取 tarball → 按 dist.shasum 校验 →
9
+ // 解包到临时目录 → 备份旧目录 → 覆盖安装目录。全程不依赖宿主 API、不依赖 shell 别名,
10
+ // 只用 Node 内置能力 + 系统 tar(Win10 1803+ 自带的 bsdtar 命名为 tar.exe)。
11
+ //
12
+ // 边界与克制:
13
+ // · 只装本插件自己的 npm 包,不接受任意包名/任意 URL(避免变成通用下载执行器);
14
+ // · 校验 shasum 不通过一律中止,绝不落盘;
15
+ // · 覆盖前先整目录备份,失败可回滚(返回 backup 路径);
16
+ // · 不做「静默后台更新」,只由面板弹窗里的明确点击触发。
17
+
18
+ import { createHash } from 'node:crypto';
19
+ import { execFile as nodeExecFile } from 'node:child_process';
20
+ import fs from 'node:fs';
21
+ import os from 'node:os';
22
+ import path from 'node:path';
23
+ import { promisify } from 'node:util';
24
+ import { fileURLToPath } from 'node:url';
25
+
26
+ const execFileAsync = promisify(nodeExecFile);
27
+
28
+ export const PLUGIN_NAME = 'dsh-mobile-ios';
29
+
30
+ /** 官方源优先,镜像作备用(国内网络下官方源偶发超时)。 */
31
+ export const PLUGIN_REGISTRIES = [
32
+ 'https://registry.npmjs.org',
33
+ 'https://registry.npmmirror.com',
34
+ ];
35
+
36
+ /**
37
+ * 本模块所在包根目录(`<...>/node_modules/dsh-mobile-ios`)。
38
+ * `src/plugin-update.mjs` 的上一级目录就是包根。
39
+ */
40
+ export function pluginRootFrom(url = import.meta.url) {
41
+ return path.dirname(path.dirname(fileURLToPath(url)));
42
+ }
43
+
44
+ function readVersion(root) {
45
+ try {
46
+ return JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')).version || null;
47
+ } catch {
48
+ return null;
49
+ }
50
+ }
51
+
52
+ function sha1(buf) {
53
+ return createHash('sha1').update(buf).digest('hex');
54
+ }
55
+
56
+ /** 取 registry 元数据:目标版本(缺省 latest)的 tarball 地址与 shasum。 */
57
+ async function loadMetadata(registry, { name = PLUGIN_NAME, target = null, fetchImpl }) {
58
+ const res = await fetchImpl(`${registry}/${name}`, {
59
+ headers: { accept: 'application/vnd.npm.install-v1+json, application/json' },
60
+ });
61
+ if (!res.ok) throw new Error(`registry ${registry} 返回 ${res.status}`);
62
+ const body = await res.json();
63
+ const version = target || body?.['dist-tags']?.latest;
64
+ if (!version) throw new Error('registry 元数据里没有可安装版本');
65
+ const entry = body?.versions?.[version];
66
+ if (!entry?.dist?.tarball) throw new Error(`registry 缺少 ${version} 的 tarball 信息`);
67
+ return { version, tarball: entry.dist.tarball, shasum: entry.dist.shasum || null };
68
+ }
69
+
70
+ /**
71
+ * 下载并安装指定版本到 `pluginRoot`。
72
+ *
73
+ * @param {object} opts
74
+ * @param {string|null} opts.target 目标版本;null = 跟随 registry latest
75
+ * @param {string|null} opts.registry 指定源;null = 官方源优先、镜像备用
76
+ * @param {string} opts.pluginRoot 安装目录(默认本包根)
77
+ * @param {Function} opts.fetchImpl 可注入(测试不联网)
78
+ * @param {Function} opts.execImpl 可注入(测试不解包)
79
+ * @returns {Promise<{ok:boolean, from:string|null, to:string, changed:boolean, root:string, backup:string|null, restartRequired:boolean}>}
80
+ */
81
+ export async function selfUpdatePlugin({
82
+ target = null,
83
+ registry = null,
84
+ pluginRoot = pluginRootFrom(),
85
+ fetchImpl = globalThis.fetch,
86
+ execImpl = execFileAsync,
87
+ log = () => {},
88
+ } = {}) {
89
+ const registries = registry ? [registry] : PLUGIN_REGISTRIES;
90
+ let meta = null;
91
+ let lastError = null;
92
+ for (const reg of registries) {
93
+ try {
94
+ meta = await loadMetadata(reg, { target, fetchImpl });
95
+ break;
96
+ } catch (err) {
97
+ lastError = err;
98
+ }
99
+ }
100
+ if (!meta) throw new Error(`无法获取版本信息:${lastError?.message || '未知错误'}`);
101
+
102
+ const from = readVersion(pluginRoot);
103
+ if (from === meta.version) {
104
+ log(`plugin 已是 ${from},无需更新`);
105
+ return { ok: true, from, to: meta.version, changed: false, root: pluginRoot, backup: null, restartRequired: false };
106
+ }
107
+
108
+ const tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-plugin-update-'));
109
+ const tgz = path.join(tmpRoot, 'pkg.tgz');
110
+ const outDir = path.join(tmpRoot, 'unpacked');
111
+ try {
112
+ log(`plugin 下载 ${meta.tarball}`);
113
+ const res = await fetchImpl(meta.tarball);
114
+ if (!res.ok) throw new Error(`下载 tarball 失败:HTTP ${res.status}`);
115
+ const buf = Buffer.from(await res.arrayBuffer());
116
+ if (buf.length < 1024) throw new Error(`下载内容异常(${buf.length} 字节)`);
117
+ if (meta.shasum) {
118
+ const actual = sha1(buf);
119
+ if (actual !== String(meta.shasum).toLowerCase()) {
120
+ throw new Error(`完整性校验失败(期望 ${meta.shasum},实际 ${actual})`);
121
+ }
122
+ }
123
+ fs.writeFileSync(tgz, buf);
124
+
125
+ fs.mkdirSync(outDir, { recursive: true });
126
+ await execImpl('tar', ['-xzf', tgz, '-C', outDir], { timeout: 120_000 });
127
+
128
+ const unpacked = path.join(outDir, 'package');
129
+ if (!fs.existsSync(path.join(unpacked, 'package.json'))) throw new Error('解包后缺少 package.json');
130
+ const got = readVersion(unpacked);
131
+ if (got !== meta.version) throw new Error(`解包版本不符(期望 ${meta.version},实际 ${got})`);
132
+
133
+ // 备份:整目录复制到同级,命名为 .<name>.backup-<from>-<ts>
134
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-');
135
+ const backup = path.join(path.dirname(pluginRoot), `.${path.basename(pluginRoot)}.backup-${from || 'unknown'}-${stamp}`);
136
+ fs.cpSync(pluginRoot, backup, { recursive: true, force: true });
137
+ log(`plugin 已备份到 ${backup}`);
138
+
139
+ fs.cpSync(unpacked, pluginRoot, { recursive: true, force: true });
140
+ const now = readVersion(pluginRoot);
141
+ if (now !== meta.version) throw new Error(`覆盖后版本仍为 ${now},更新未生效`);
142
+
143
+ log(`plugin 已更新 ${from || '?'} → ${meta.version}`);
144
+ return { ok: true, from, to: meta.version, changed: true, root: pluginRoot, backup, restartRequired: true };
145
+ } finally {
146
+ try { fs.rmSync(tmpRoot, { recursive: true, force: true }); } catch { /* 临时目录清理失败不影响结果 */ }
147
+ }
148
+ }
@@ -129,12 +129,44 @@ export class LocalProvisioner {
129
129
  port: s.port ?? null,
130
130
  // null = 还没验过(老状态文件);false = 验过但公网没有——面板必须提示,别让人扫码扫到空气
131
131
  dnsOk: s.dnsOk ?? null,
132
+ dnsCheckedAt: s.dnsCheckedAt ?? null,
132
133
  warning: dnsWarningFor(s),
133
134
  createdAt: s.createdAt ?? null,
134
135
  updatedAt: s.updatedAt ?? null,
135
136
  };
136
137
  }
137
138
 
139
+ /**
140
+ * 面板「重新检测解析」:强制重探一次并写回状态,不做任何缓存短路。
141
+ *
142
+ * 为什么必须有这条路:dnsOk=false 是持久化结论,而面板在 false 时禁用了
143
+ * 「开启远程」按钮——原来唯一的重探入口就在 ensure() 里,按钮一点就点不到,
144
+ * 于是 NS 改好了也永远停在「解析异常」,只能删状态文件才恢复(自锁死)。
145
+ */
146
+ async recheckDns() {
147
+ const s = this.state;
148
+ if (!s?.hostname) return { provisioned: false, ok: false, tampered: false, warning: null, publicNs: [] };
149
+ const verdict = evaluateDnsAnswer(await this.probe(s.hostname), s.tunnelId);
150
+ const next = {
151
+ ...s,
152
+ dnsOk: verdict.ok,
153
+ dnsTampered: verdict.tampered,
154
+ dnsCheckedAt: new Date().toISOString(),
155
+ };
156
+ this._state = next;
157
+ writeState(this.stateFile, next);
158
+ return {
159
+ provisioned: true,
160
+ hostname: next.hostname,
161
+ ok: Boolean(verdict.ok),
162
+ tampered: Boolean(verdict.tampered),
163
+ expected: verdict.expected ?? null,
164
+ target: verdict.target ?? null,
165
+ warning: dnsWarningFor(next),
166
+ checkedAt: next.dnsCheckedAt,
167
+ };
168
+ }
169
+
138
170
  async #exec(args) {
139
171
  const { stdout, stderr } = await execFileAsync(this.executable, args, {
140
172
  timeout: CLI_TIMEOUT_MS,
package/src/rest.mjs CHANGED
@@ -6,6 +6,8 @@ import { translateRecords } from './adapter/session-history.mjs';
6
6
  import { createRequire } from 'node:module';
7
7
  import { PLUGIN_VERSION } from './version.mjs';
8
8
  import { ensureCloudflared, resolveAsset } from './cloudflared-install.mjs';
9
+ import { selfUpdatePlugin } from './plugin-update.mjs';
10
+ import { resolveNs } from './dns-probe.mjs';
9
11
 
10
12
  // QR 编码(vendor:qrcode-generator 1.4.4,MIT,零依赖;见 lib/vendor/,
11
13
  // .cjs 后缀:包为 type:module,require 需显式 CommonJS)
@@ -98,6 +100,8 @@ const DESKTOP_CORS_PATHS = [
98
100
  /^\/mobile\/v1\/tunnel\/stop$/,
99
101
  /^\/mobile\/v1\/tunnel\/provision$/,
100
102
  /^\/mobile\/v1\/tunnel\/install-cloudflared$/,
103
+ /^\/mobile\/v1\/tunnel\/recheck-dns$/,
104
+ /^\/mobile\/v1\/plugin\/self-update$/,
101
105
  ];
102
106
 
103
107
  // 面板「插件版本」与更新检查的「当前版本」都取这里;必须与 npm 包版本同源。
@@ -220,9 +224,29 @@ export function createRestRouter({ core, pairing, host, tickets, config = {}, lo
220
224
  * · 进程 running 但没开通 → 只可能是 Quick Tunnel;
221
225
  * · 已开通但进程 stopped → 地址是固定的,但此刻连不上,二维码不能写它。
222
226
  */
227
+ // 「解析异常」曾经是死锁:dnsOk=false 被写进状态文件,面板据此禁用开启按钮,
228
+ // 而唯一的重探入口就在开启流程里——按钮点不到 → 永远不重探 → NS 改好了也不恢复。
229
+ // 这里补一层节流自愈:面板轮询 summary 时,若仍是 false 且距上次检查超过 60 秒,
230
+ // 后台重探一次(不阻塞响应)。用户改完 NS 最多等一分钟就会自己变好。
231
+ let dnsAutoRecheckAt = 0;
232
+ let dnsAutoRechecking = false;
233
+ const maybeAutoRecheckDns = (prov) => {
234
+ if (!prov || prov.dnsOk !== false) return;
235
+ if (typeof config.tunnelProvisioner?.recheckDns !== 'function') return;
236
+ const now = Date.now();
237
+ if (dnsAutoRechecking || now - dnsAutoRecheckAt < 60_000) return;
238
+ dnsAutoRecheckAt = now;
239
+ dnsAutoRechecking = true;
240
+ Promise.resolve()
241
+ .then(() => config.tunnelProvisioner.recheckDns())
242
+ .catch(() => { /* 探测失败保持原状态,不打扰用户 */ })
243
+ .finally(() => { dnsAutoRechecking = false; });
244
+ };
245
+
223
246
  const tunnelSnapshot = () => {
224
247
  const base = config.tunnel?.status?.() ?? { state: 'disabled', url: null, mode: 'disabled' };
225
248
  const prov = config.tunnelProvisioner?.status?.() ?? null;
249
+ maybeAutoRecheckDns(prov);
226
250
  return {
227
251
  ...base,
228
252
  mode: prov ? 'named' : (base.mode || 'quick'),
@@ -234,6 +258,7 @@ export function createRestRouter({ core, pairing, host, tickets, config = {}, lo
234
258
  // 域名在公网上解析得到吗。false 时地址虽在、扫码却连不上(zone pending / NS 没指过来),
235
259
  // 面板与二维码都要据此避开它,而不是让用户拿一个必然失败的地址去扫。
236
260
  dnsOk: prov?.dnsOk ?? null,
261
+ dnsCheckedAt: prov?.dnsCheckedAt ?? null,
237
262
  warning: prov?.warning ?? null,
238
263
  // 面板据此决定是否显示「自动安装 cloudflared」入口:仅在缺失且有官方构建时为 true。
239
264
  canAutoInstall: base.executable === 'missing' && !!resolveAsset({}),
@@ -515,6 +540,57 @@ export function createRestRouter({ core, pairing, host, tickets, config = {}, lo
515
540
  return send(ctx.res, 200, { ...result, status: tunnelSnapshot() }, DESKTOP_CORS);
516
541
  });
517
542
 
543
+ /**
544
+ * 重新检测固定域名的公网解析(面板「重新检测解析」按钮)。
545
+ *
546
+ * 存在的唯一理由:dnsOk=false 会持久化,而面板在 false 时曾禁用开启按钮——
547
+ * 用户把 NS 改对之后没有任何可点的入口让它再验一次。这条路把「自锁死」解开。
548
+ * 回环-only:探测会真发 DNS 查询,不该让外部触发。
549
+ */
550
+ route('POST', /^\/mobile\/v1\/tunnel\/recheck-dns$/, async (ctx) => {
551
+ loopbackOnly(ctx, '重新检测解析只允许在主机本机操作');
552
+ const prov = config.tunnelProvisioner;
553
+ if (!prov) throw fail(4021, '这台主机没有固定地址可检测', { method: 'tunnel.recheckDns' });
554
+ if (typeof prov.recheckDns !== 'function') throw fail(4021, '当前开通方式不支持重新检测', { method: 'tunnel.recheckDns' });
555
+ const started = Date.now();
556
+ const result = await prov.recheckDns();
557
+ log(`rest tunnel recheck-dns ok=${result.ok} tampered=${result.tampered} ${Date.now() - started}ms`);
558
+ // 把公网当前 NS 一并带回去:用户不需要理解 zone/pending,只要拿这串名字去注册商对照。
559
+ const baseDomain = prov.baseDomain
560
+ || String(result.hostname || '').split('.').slice(-2).join('.');
561
+ const publicNs = result.provisioned && baseDomain ? await resolveNs(baseDomain) : [];
562
+ return send(ctx.res, 200, {
563
+ ...result,
564
+ publicNs,
565
+ status: tunnelSnapshot(),
566
+ }, DESKTOP_CORS);
567
+ });
568
+
569
+ /**
570
+ * 插件自更新(不依赖宿主 pluginManager)。
571
+ *
572
+ * 为什么放在网关:dsh-app:// 页面里的复制/剪贴板能力不可靠,而「一键更新」缺了宿主
573
+ * API 就只剩复制包名一条路。这里由 Node 侧直接取 npm tarball、校验 shasum、
574
+ * 备份后覆盖安装目录,返回 restartRequired 让面板明确告知需要重启。
575
+ * 只允许装本插件自己(写死包名),不接受任意包/任意 URL。
576
+ */
577
+ route('POST', /^\/mobile\/v1\/plugin\/self-update$/, async (ctx) => {
578
+ loopbackOnly(ctx, '插件更新只允许在主机本机操作');
579
+ const body = await readJson(ctx.req);
580
+ const target = typeof body?.target === 'string' && /^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/.test(body.target)
581
+ ? body.target
582
+ : null;
583
+ let result;
584
+ try {
585
+ result = await selfUpdatePlugin({ target, log });
586
+ } catch (err) {
587
+ log(`rest plugin self-update 失败 ${err?.message || err}`);
588
+ throw fail(4500, err?.message || '插件更新失败', { code: 'SELF_UPDATE_FAILED' });
589
+ }
590
+ log(`rest plugin self-update ${result.from || '?'} → ${result.to} changed=${result.changed}`);
591
+ return send(ctx.res, 200, result, DESKTOP_CORS);
592
+ });
593
+
518
594
  // 诊断包(GW-9):一次拿到可直接粘贴给支持人员的东西。
519
595
  route('GET', /^\/mobile\/v1\/diag\/bundle$/, async (ctx) => {
520
596
  auth(ctx.req);