dsh-mobile-ios 0.2.18 → 0.2.19

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/README.md CHANGED
@@ -271,6 +271,9 @@ bash spike0/run-demo.sh # 自动起服务 → 造 3 帧 → 跑客户
271
271
  | `POST /mobile/v1/tunnel/provision` | 开通固定地址(幂等)。写 DNS 前先做凭据预检,见 9.1 |
272
272
  | `POST /mobile/v1/tunnel/recheck-dns` | 强制重探解析 + 强制刷新凭据预检(解开「解析异常」自锁死) |
273
273
  | `POST /mobile/v1/tunnel/reset` | 清本机固定地址状态与 ingress(不碰 cert.pem、不删云端隧道),幂等 |
274
+ | `POST /mobile/v1/tunnel/login` | 发起 Cloudflare 浏览器授权(起 `cloudflared tunnel login`,返回授权链接),幂等 |
275
+ | `GET /mobile/v1/tunnel/login` | 授权进度:`idle/waiting/ok/error/canceled` + 链接 + 失败原因 |
276
+ | `POST /mobile/v1/tunnel/login/cancel` | 取消等待中的授权并回收子进程 |
274
277
  | `POST /mobile/v1/tunnel/install-cloudflared` | 用户同意后从官方源自举安装 cloudflared 到私有目录 |
275
278
  | `GET /mobile/v1/diag/bundle` | 脱敏诊断包,含可直接粘贴的 `text` 字段 |
276
279
 
@@ -296,10 +299,32 @@ bash spike0/run-demo.sh # 自动起服务 → 造 3 帧 → 跑客户
296
299
 
297
300
  诊断矩阵(`TunnelStatus.credentials.state`):`ok` / `missing`(没有 cert) / `unreadable`(解析不了,降级)
298
301
  / `no-token`(旧版证书,降级) / `forbidden`(403) / `zone-missing`(这账号看不到域名) /
299
- `account-mismatch`(证书账号 ≠ zone 账号) / `stale-zone`(证书指向已被重建的 zone) /
300
- `zone-moved`(域名被另一账号接管) / `unknown`(网络不可达)。
302
+ `zone-scoped-other`(证书授权的是**另一个域名**) / `account-mismatch`(证书账号 ≠ zone 账号) /
303
+ `stale-zone`(证书指向已被重建/删除的 zone) / `zone-moved`(域名被另一账号接管) / `unknown`(网络不可达)。
304
+
305
+ `zone-missing` 与 `zone-scoped-other` 的区别很关键:前者是账号里真没有这个域名,后者是
306
+ **登录时在浏览器里点错了域名**(zone 范围的 token 只覆盖被授权的那一把 zone)。两种情况都要
307
+ 重新授权,但后者必须在提示里点名「上次授权的是 xxx」。预检因此额外回传
308
+ `certAccountName` / `certZoneName`——否则用户在自己的账号里明明看得到目标域名,无从判断
309
+ 「我刚跑的 login 到底生效了没有」。
310
+
311
+ ### 9.2 一键重新授权(0.2.19)
312
+
313
+ 唯一正确的修法只有一个:**用持有该域名的账号重新授权**。但它需要人在浏览器里点「允许」,
314
+ 所以插件把这一步做成了一条路,而不是一句终端命令(现场教训:用户重装、重启、点重置、
315
+ 点重新检测全都无效——这些动作**都不会换掉 cert.pem**):
316
+
317
+ | 步骤 | 谁做 | 实现 |
318
+ |---|---|---|
319
+ | 点「重新授权(浏览器)」 | 用户 | 面板 `startTunnelLogin` → `POST /tunnel/login` |
320
+ | 起 `cloudflared tunnel login`、捞授权链接 | 网关 | `cloudflared-login.mjs`(进程级单例,幂等) |
321
+ | 浏览器里选账号并授权 | 用户 | 链接来自 cloudflared 输出;面板提供「复制授权链接」 |
322
+ | 轮询结果 → 强制重检 → 继续开通 | 面板 | `pollLogin` 每 1.5 秒一次,成功后 `afterLoginOk` |
323
+
324
+ 四条不变量:幂等(等待中重复点不起第二个授权)、不静默(超时/退出码非 0/退出但没生成证书
325
+ 都有可读原因,且保留 cloudflared 最后几行而不是第一行)、不留孤儿(取消或超时 kill 子进程)、
326
+ 只覆盖 `HOME`(证书一定落在本机真正使用的 `~/.cloudflared`)。
301
327
 
302
- 唯一正确的修法只有一个:**用持有该域名的账号重跑 `cloudflared tunnel login`**。
303
328
  换账号后 `ensure()` 会自动识别账号变更、重建隧道并**沿用同一个子域**(地址不变、无需重新配对)。
304
329
 
305
330
  ## 10. 下一步
package/lib/client.js CHANGED
@@ -195,6 +195,11 @@ 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
+ /* 兜底文字链(重置本机状态之类):不抢主按钮的位置,但要能看见、能点 */
199
+ .dsh-mios-modal .modal-link { display:block; width:100%; margin:10px 0 0; padding:2px 0;
200
+ background:none; border:none; color:var(--modal-muted); font-family:inherit; font-size:11px;
201
+ text-align:left; text-decoration:underline; cursor:pointer; }
202
+ .dsh-mios-modal .modal-link:hover { color:var(--modal-fg); }
198
203
  /* 复制结果必须看得见:dsh-app:// 页面里剪贴板可能不可用,只改按钮文字容易被无视。
199
204
  .modal-toast 常驻在动作条上方,成功/失败都留痕。 */
200
205
  .dsh-mios-modal .modal-toast { margin:10px 0 0; padding:7px 10px; border-radius:8px; font-size:11px;
@@ -734,7 +739,7 @@ window.__ModuleLoader__.load({
734
739
  updateModal?.remove();
735
740
  updateModal = null;
736
741
  }
737
- function showUpdateModal({ title, banner, lines, note, steps, actions }) {
742
+ function showUpdateModal({ title, banner, lines, note, steps, actions, footLink }) {
738
743
  closeUpdateModal();
739
744
  const mask = document.createElement('div');
740
745
  mask.className = 'dsh-mios-modal-mask';
@@ -795,10 +800,35 @@ window.__ModuleLoader__.load({
795
800
  const btn = document.createElement('button');
796
801
  btn.textContent = action.label;
797
802
  if (action.primary) btn.className = 'primary';
798
- btn.addEventListener('click', () => action.onClick?.(btn));
803
+ // 异步动作一律包一层:onClick 里抛异常时,原来等价于「点了没反应」。
804
+ // 现在至少把错误摆到弹窗里(toast),用户能复制给我们。
805
+ btn.addEventListener('click', () => {
806
+ try {
807
+ const ret = action.onClick?.(btn);
808
+ if (ret && typeof ret.catch === 'function') {
809
+ ret.catch((err) => {
810
+ console.error('modal action failed', err);
811
+ showModalToast(`操作失败:${err?.message || err}`, 'error');
812
+ });
813
+ }
814
+ } catch (err) {
815
+ console.error('modal action failed', err);
816
+ showModalToast(`操作失败:${err?.message || err}`, 'error');
817
+ }
818
+ });
799
819
  bar.append(btn);
800
820
  }
801
821
  box.append(bar);
822
+ // 兜底动作(如「重置本机状态」)做成弱化的文字链,避免主按钮挤成四个
823
+ if (footLink) {
824
+ const link = document.createElement('button');
825
+ link.className = 'modal-link';
826
+ link.textContent = footLink.label;
827
+ link.addEventListener('click', () => {
828
+ try { footLink.onClick?.(); } catch (err) { console.error('modal link failed', err); }
829
+ });
830
+ box.append(link);
831
+ }
802
832
  mask.append(box);
803
833
  mask.addEventListener('click', (e) => { if (e.target === mask) closeUpdateModal(); });
804
834
  document.body.append(mask);
@@ -1298,48 +1328,258 @@ window.__ModuleLoader__.load({
1298
1328
  /** 记住最近一次触发远程动作的 banner:弹窗里的「重新检测」要能继续同一条链。 */
1299
1329
  let lastRemoteBanner = null;
1300
1330
 
1331
+ /** 授权轮询句柄(同一时刻只允许一条,重复点不会起两个计时器)。 */
1332
+ let loginPoll = null;
1333
+
1334
+ function stopLoginPoll() {
1335
+ if (loginPoll) {
1336
+ clearInterval(loginPoll);
1337
+ loginPoll = null;
1338
+ }
1339
+ }
1340
+
1341
+ /**
1342
+ * 弹窗按钮的忙碌态。
1343
+ *
1344
+ * 为什么必须有:原来「重新检测 / 重置 / 重新授权」都是 `closeUpdateModal()` 先关窗
1345
+ * 再发请求——请求最长 25 秒,这段时间**界面上什么都不发生**。用户看到的就是
1346
+ * 「点了没反应」,于是反复点、或者以为插件坏了。
1347
+ * 现在:按钮立刻变灰并换文案,同一弹窗内原地出结果,失败也一定看得见。
1348
+ */
1349
+ function setModalBusy(activeBtn, label) {
1350
+ const box = updateModal?.querySelector?.('.dsh-mios-modal');
1351
+ const btns = box?.querySelectorAll ? Array.from(box.querySelectorAll('.modal-actions button')) : [];
1352
+ const prev = new Map();
1353
+ for (const b of btns) {
1354
+ prev.set(b, b.textContent);
1355
+ b.disabled = true;
1356
+ }
1357
+ if (activeBtn && label) activeBtn.textContent = label;
1358
+ return () => {
1359
+ for (const b of btns) {
1360
+ b.disabled = false;
1361
+ if (prev.has(b)) b.textContent = prev.get(b);
1362
+ }
1363
+ };
1364
+ }
1365
+
1301
1366
  /**
1302
- * 凭据不可用(登录的账号与域名不匹配 / 证书过时)时的唯一正确出口。
1367
+ * 凭据不可用(登录的账号与域名不匹配 / 证书过时 / 授权错了域名)。
1368
+ *
1369
+ * 现场(2026-11-21,Mac mini):cert.pem 属于另一个 Cloudflare 账号,面板提示
1370
+ * 「账号不对」,用户重装、重启、点重置、点重新检测全都无效——因为这三个动作
1371
+ * 都**不会**换掉 cert.pem。唯一有效的是用持有该域名的账号重新授权。
1372
+ * 所以这里把它做成一步:点「重新授权」→ 浏览器里点允许 → 面板自动继续开通。
1303
1373
  *
1304
- * 现场(2026-11-21):新 Mac 上 cert.pem 属于另一个 Cloudflare 账号,
1305
- * 面板只报「写入 DNS 失败:Command failed: …」,用户以为插件坏了,重装、重启、
1306
- * 改 NS 全试了一遍——都无效。真正要做的只有一件:用**持有该域名**的账号重跑
1307
- * `cloudflared tunnel login`。这个弹窗把这句话说清楚,并给出两条兜底:
1308
- * · 重新检测:login 完之后不用重启插件,点一下就能继续开通;
1309
- * · 重置本机状态:状态文件被跨机拷贝时的自救入口。
1374
+ * @param {object} credentials 凭据结论(来自 summary.tunnel.credentials)
1375
+ * @param {object} [opts]
1376
+ * @param {boolean} [opts.again] 刚做过一次检测、结论没变
1377
+ * @param {boolean} [opts.afterLogin] 刚到浏览器授权回来的复检
1310
1378
  */
1311
- function showCredentialHelpModal(credentials = {}) {
1379
+ function showCredentialHelpModal(credentials = {}, opts = {}) {
1312
1380
  const stateText = credentials.hint || '当前登录的 Cloudflare 账号无法管理这个域名';
1313
- const exe = 'cloudflared';
1381
+ const certAccount = credentials.certAccountName
1382
+ || (credentials.certAccountId ? `账号 ${String(credentials.certAccountId).slice(0, 8)}…` : null);
1383
+ const scopedOther = credentials.state === 'zone-scoped-other' && credentials.certZoneName;
1314
1384
  const lines = [
1315
- ...(credentials.accountName ? [{ label: '当前证书账号', value: credentials.accountName }] : []),
1385
+ ...(certAccount ? [{ label: '当前证书账号', value: certAccount }] : []),
1316
1386
  ...(credentials.zoneName ? [{ label: '固定地址域名', value: credentials.zoneName }] : []),
1387
+ ...(scopedOther ? [{ label: '证书授权域名', value: credentials.certZoneName }] : []),
1317
1388
  ...(credentials.zoneStatus ? [{ label: '域名状态', value: credentials.zoneStatus }] : []),
1318
1389
  ];
1390
+ const bannerText = opts.afterLogin
1391
+ ? `⚠️ 授权后仍然不行:${stateText}`
1392
+ : opts.again
1393
+ ? `⚠️ 重新检测结论没变:${stateText}`
1394
+ : `⚠️ ${stateText}`;
1319
1395
  showUpdateModal({
1320
- title: '登录的 Cloudflare 账号不对',
1321
- banner: { text: `⚠️ ${stateText}`, tone: 'warn' },
1396
+ title: opts.afterLogin ? '授权完成,但这个账号不行' : '登录的 Cloudflare 账号不对',
1397
+ banner: { text: bannerText, tone: 'warn' },
1322
1398
  lines,
1323
1399
  note: '固定地址写在 Cloudflare 的域名下,只有「持有该域名的账号」才写得进去。'
1324
- + '换账号登录后,本机会自动重建隧道并沿用同一个地址,手机不需要重新配对。'
1325
- + `请在终端执行:${exe} tunnel login(面板无法代做浏览器授权)。`,
1400
+ + '重装插件、重启宿主、点重置都不会换掉证书——只有重新授权能修好。'
1401
+ + '授权后本机会自动重建隧道并沿用同一个地址,手机不需要重新配对。',
1326
1402
  steps: [
1327
- `在这台电脑打开「终端」,执行:${exe} tunnel login`,
1328
- '浏览器里选择「持有该域名」的账号,点授权(会覆盖 ~/.cloudflared/cert.pem)。',
1329
- '回到面板点「重新检测」——账号一致后会自动重建隧道、保留原地址。',
1330
- '如果这台电脑是从别的电脑拷过来的(状态文件不是本机生成的),可先点「重置本机状态」再重试。',
1403
+ '点下面的「重新授权(浏览器)」,面板会调起 Cloudflare 的授权页。',
1404
+ scopedOther
1405
+ ? `浏览器里务必选「${credentials.zoneName || '固定地址域名'}」所在的账号(上次选成了 ${credentials.certZoneName})。`
1406
+ : '浏览器里选择「持有该域名」的账号,点「允许 / Authorize」。',
1407
+ '回到面板不用做别的:授权成功后会自动继续开通固定地址。',
1331
1408
  ],
1409
+ footLink: { label: '重置本机状态(清掉本机的旧地址记录)', onClick: () => confirmResetTunnelState() },
1332
1410
  actions: [
1333
1411
  { label: '关闭', onClick: closeUpdateModal },
1334
- { label: '重置本机状态', onClick: () => confirmResetTunnelState() },
1335
- {
1336
- label: '重新检测', primary: true,
1337
- onClick: () => { closeUpdateModal(); recheckDnsAction(lastRemoteBanner); },
1338
- },
1412
+ { label: '重新检测', onClick: (btn) => recheckDnsAction(lastRemoteBanner, btn) },
1413
+ { label: '重新授权(浏览器)', primary: true, onClick: (btn) => startTunnelLogin(btn) },
1414
+ ],
1415
+ });
1416
+ }
1417
+
1418
+ /**
1419
+ * 发起浏览器授权:起 `cloudflared tunnel login`,把链接摆到弹窗里,然后轮询结果。
1420
+ *
1421
+ * 为什么要轮询而不是等 POST 返回:cloudflared 会一直挂着等浏览器回调,
1422
+ * 同步等会把 HTTP 请求挂死 5 分钟。POST 只负责「起进程 + 尽早给链接」。
1423
+ */
1424
+ async function startTunnelLogin(btn) {
1425
+ const restore = setModalBusy(btn, '启动中…');
1426
+ stopLoginPoll();
1427
+ let first = null;
1428
+ try {
1429
+ first = await fetchJson('/mobile/v1/tunnel/login', { method: 'POST' }, 20000);
1430
+ } catch (err) {
1431
+ restore();
1432
+ showUpdateModal({
1433
+ title: '无法发起授权',
1434
+ banner: { text: '❌ 没能调起 cloudflared', tone: 'error' },
1435
+ lines: [],
1436
+ note: `${err?.body?.error?.message || err?.message || String(err)}。`
1437
+ + '仍可在终端执行 cloudflared tunnel login 完成授权,然后点「重新检测」。',
1438
+ steps: [],
1439
+ actions: [
1440
+ { label: '关闭', onClick: closeUpdateModal },
1441
+ { label: '重试', primary: true, onClick: (b) => startTunnelLogin(b) },
1442
+ ],
1443
+ });
1444
+ return;
1445
+ }
1446
+ renderLoginModal(first);
1447
+ pollLogin();
1448
+ }
1449
+
1450
+ /** 授权进行中的弹窗:链接、进度、取消。链接拿不到就说明还在等 cloudflared 打印。 */
1451
+ function renderLoginModal(status = {}) {
1452
+ const url = status.url || null;
1453
+ showUpdateModal({
1454
+ title: '等待浏览器授权',
1455
+ banner: {
1456
+ text: status.state === 'ok' ? '✅ 授权完成' : '⏳ 正在等待 Cloudflare 授权…',
1457
+ tone: status.state === 'ok' ? 'success' : 'info',
1458
+ },
1459
+ lines: url ? [{ label: '授权链接', value: url }] : [],
1460
+ note: url
1461
+ ? '浏览器没自动打开的话,点「复制授权链接」用任意浏览器打开;授权完成后回到面板即可,不需要保持那个页面。'
1462
+ : '正在启动 cloudflared 并获取授权链接,通常 1–2 秒。',
1463
+ steps: [
1464
+ '在打开页面里选择持有该域名的 Cloudflare 账号。',
1465
+ '点「允许 / Authorize」,浏览器会跳回本机完成授权。',
1466
+ '面板会自动检测结果并继续开通,不需要再点别的。',
1467
+ ],
1468
+ actions: [
1469
+ { label: '取消授权', onClick: () => cancelTunnelLogin() },
1470
+ ...(url ? [{ label: '复制授权链接', onClick: (btn) => copyLoginUrl(url, btn) }] : []),
1339
1471
  ],
1340
1472
  });
1341
1473
  }
1342
1474
 
1475
+ async function copyLoginUrl(url, btn) {
1476
+ const ok = await copyToClipboard(url);
1477
+ showModalToast(ok ? '授权链接已复制' : '复制失败:请手动选中上面的链接复制', ok ? 'success' : 'error');
1478
+ if (btn) btn.textContent = ok ? '已复制' : '复制失败';
1479
+ }
1480
+
1481
+ async function cancelTunnelLogin() {
1482
+ stopLoginPoll();
1483
+ try { await fetchJson('/mobile/v1/tunnel/login/cancel', { method: 'POST' }, 8000); } catch { /* 已结束 */ }
1484
+ closeUpdateModal();
1485
+ }
1486
+
1487
+ /** 轮询授权结果;成功后自动复检并继续开通。 */
1488
+ function pollLogin() {
1489
+ stopLoginPoll();
1490
+ const startedAt = Date.now();
1491
+ let lastUrl = null;
1492
+ loginPoll = setInterval(async () => {
1493
+ // 服务端 5 分钟超时,这里多留一分钟余量,避免界面上的计时器先死掉
1494
+ if (Date.now() - startedAt > 6 * 60_000) {
1495
+ stopLoginPoll();
1496
+ closeUpdateModal();
1497
+ return;
1498
+ }
1499
+ let st = null;
1500
+ try {
1501
+ st = await fetchJson('/mobile/v1/tunnel/login', {}, 8000);
1502
+ } catch {
1503
+ return; // 网关暂时不可达:继续轮询,不要把一次网络抖动画成失败
1504
+ }
1505
+ if (!st) return;
1506
+ if (st.state === 'waiting') {
1507
+ // 链接晚到:只在第一次拿到时重绘,避免每 1.5 秒闪一次
1508
+ if (st.url && st.url !== lastUrl) {
1509
+ lastUrl = st.url;
1510
+ renderLoginModal(st);
1511
+ }
1512
+ return;
1513
+ }
1514
+ stopLoginPoll();
1515
+ if (st.state === 'ok') {
1516
+ await afterLoginOk();
1517
+ } else if (st.state === 'canceled') {
1518
+ closeUpdateModal();
1519
+ } else {
1520
+ showUpdateModal({
1521
+ title: '授权没有完成',
1522
+ banner: { text: '❌ 浏览器授权未完成', tone: 'error' },
1523
+ lines: [],
1524
+ note: `${st.error || '没有拿到新的证书'}。`
1525
+ + '可以再试一次;如果浏览器打不开,就在这台电脑的终端执行 cloudflared tunnel login。',
1526
+ steps: [],
1527
+ actions: [
1528
+ { label: '关闭', onClick: closeUpdateModal },
1529
+ { label: '重新授权', primary: true, onClick: (b) => startTunnelLogin(b) },
1530
+ ],
1531
+ });
1532
+ }
1533
+ }, 1500);
1534
+ }
1535
+
1536
+ /**
1537
+ * 授权成功之后:强制重检 → 结论变了就继续开通,没变就说清「换了账号还是不行」。
1538
+ *
1539
+ * 关键点:这里必须**强制**重检(force),否则凭据结论还挂在旧证书的 TTL 缓存上,
1540
+ * 用户刚授权完却仍看到「账号不对」,会以为授权白做了。
1541
+ */
1542
+ async function afterLoginOk() {
1543
+ showUpdateModal({
1544
+ title: '授权完成',
1545
+ banner: { text: '✅ 证书已更新,正在验证账号权限', tone: 'success' },
1546
+ lines: [],
1547
+ note: '正在用新证书检查这台电脑能不能写这个域名的 DNS。',
1548
+ steps: [],
1549
+ actions: [],
1550
+ });
1551
+ let res = null;
1552
+ try {
1553
+ res = await fetchJson('/mobile/v1/tunnel/recheck-dns', { method: 'POST' }, 30000);
1554
+ } catch (err) {
1555
+ // 重检失败也要给出下一步,不能只关窗
1556
+ showUpdateModal({
1557
+ title: '授权完成,但检测失败',
1558
+ banner: { text: '⚠️ 新证书已就位,检查没跑完', tone: 'warn' },
1559
+ lines: [],
1560
+ note: `${err?.body?.error?.message || err?.message || String(err)}。可点「重新检测」再试一次。`,
1561
+ steps: [],
1562
+ actions: [
1563
+ { label: '关闭', onClick: closeUpdateModal },
1564
+ { label: '重新检测', primary: true, onClick: (btn) => recheckDnsAction(lastRemoteBanner, btn) },
1565
+ ],
1566
+ });
1567
+ return;
1568
+ }
1569
+ await probe();
1570
+ renderSummary();
1571
+ const creds = res?.credentials || summary?.tunnel?.credentials || null;
1572
+ if (creds?.blocking) {
1573
+ showCredentialHelpModal({ ...creds, hint: creds.hint }, { afterLogin: true });
1574
+ return;
1575
+ }
1576
+ if (res && res.ok === false) {
1577
+ showDnsHelpModal(res);
1578
+ return;
1579
+ }
1580
+ await remoteMainAction(lastRemoteBanner);
1581
+ }
1582
+
1343
1583
  /** 重置是「清本机状态」,不是删云端隧道:必须讲清后果再执行。 */
1344
1584
  function confirmResetTunnelState() {
1345
1585
  showUpdateModal({
@@ -1351,41 +1591,58 @@ window.__ModuleLoader__.load({
1351
1591
  + '如果旧地址仍指向这台机器,新地址会换一个前缀。',
1352
1592
  steps: [],
1353
1593
  actions: [
1354
- { label: '取消', onClick: showCredentialHelpModal.bind(null, summary?.tunnel?.credentials || {}) },
1355
- { label: '确认重置', primary: true, onClick: () => resetTunnelStateAction() },
1594
+ { label: '取消', onClick: showCredentialHelpModal.bind(null, summary?.tunnel?.credentials || {}, {}) },
1595
+ { label: '确认重置', primary: true, onClick: (btn) => resetTunnelStateAction(btn) },
1356
1596
  ],
1357
1597
  });
1358
1598
  }
1359
1599
 
1360
- async function resetTunnelStateAction() {
1600
+
1601
+ async function resetTunnelStateAction(btn) {
1602
+ const restore = setModalBusy(btn, '重置中…');
1361
1603
  showUpdateModal({
1362
1604
  title: '正在重置',
1363
1605
  banner: { text: '⏳ 清理本机固定地址状态', tone: 'info' },
1364
1606
  lines: [],
1365
- note: '正在删除本机状态与 ingress 配置,请稍候。',
1607
+ note: '正在停止隧道并删除本机状态与 ingress 配置,请稍候(通常 1–3 秒)。',
1366
1608
  actions: [],
1367
1609
  });
1368
1610
  try {
1369
1611
  const res = await fetchJson('/mobile/v1/tunnel/reset', { method: 'POST' }, 25000);
1612
+ // 重置只清本机状态,**不会**换掉 cert.pem:如果账号问题还在,
1613
+ // 这里必须当场说清,否则用户点完「开启远程」又看到同一个弹窗,
1614
+ // 只会得出「重置也没用」的结论。所以重置后立刻复检一次。
1370
1615
  await probe();
1371
1616
  renderSummary();
1617
+ const creds = summary?.tunnel?.credentials || null;
1618
+ const stillBlocked = Boolean(creds?.blocking);
1372
1619
  showUpdateModal({
1373
- title: '已重置',
1374
- banner: { text: '✅ 本机固定地址状态已清空', tone: 'success' },
1620
+ title: stillBlocked ? '已重置,但账号问题还在' : '已重置',
1621
+ banner: stillBlocked
1622
+ ? { text: '⚠️ 本机状态已清空,但登录的 Cloudflare 账号仍管不了这个域名', tone: 'warn' }
1623
+ : { text: '✅ 本机固定地址状态已清空', tone: 'success' },
1375
1624
  lines: res?.removed?.length ? [{ label: '已删除', value: res.removed.join('、') }] : [],
1376
- note: res?.hadState
1377
- ? 'Cloudflare 上的隧道与 DNS 记录未删除。点「开启远程」会重新分配固定地址;若这台机器的证书属于别的账号,请先执行 cloudflared tunnel login。'
1378
- : '本机本来就没有固定地址状态。点「开启远程」开始分配。',
1625
+ note: stillBlocked
1626
+ ? '重置只清本机记录,不会换掉 ~/.cloudflared/cert.pem。要让固定地址生效,必须用持有该域名的账号重新授权。'
1627
+ : res?.hadState
1628
+ ? 'Cloudflare 上的隧道与 DNS 记录未删除。点「开启远程」会重新分配固定地址。'
1629
+ : '本机本来就没有固定地址状态。点「开启远程」开始分配。',
1379
1630
  steps: [],
1380
- actions: [
1381
- { label: '关闭', onClick: closeUpdateModal },
1382
- {
1383
- label: '开启远程', primary: true,
1384
- onClick: () => { closeUpdateModal(); remoteMainAction(lastRemoteBanner); },
1385
- },
1386
- ],
1631
+ actions: stillBlocked
1632
+ ? [
1633
+ { label: '关闭', onClick: closeUpdateModal },
1634
+ { label: '重新授权(浏览器)', primary: true, onClick: (b) => startTunnelLogin(b) },
1635
+ ]
1636
+ : [
1637
+ { label: '关闭', onClick: closeUpdateModal },
1638
+ {
1639
+ label: '开启远程', primary: true,
1640
+ onClick: () => { closeUpdateModal(); remoteMainAction(lastRemoteBanner); },
1641
+ },
1642
+ ],
1387
1643
  });
1388
1644
  } catch (err) {
1645
+ restore();
1389
1646
  showUpdateModal({
1390
1647
  title: '重置失败',
1391
1648
  banner: { text: '❌ 未能重置本机状态', tone: 'error' },
@@ -1394,7 +1651,7 @@ window.__ModuleLoader__.load({
1394
1651
  steps: [],
1395
1652
  actions: [
1396
1653
  { label: '关闭', onClick: closeUpdateModal },
1397
- { label: '重试', primary: true, onClick: () => resetTunnelStateAction() },
1654
+ { label: '重试', primary: true, onClick: (b) => resetTunnelStateAction(b) },
1398
1655
  ],
1399
1656
  });
1400
1657
  }
@@ -1503,7 +1760,7 @@ window.__ModuleLoader__.load({
1503
1760
  { label: '关闭', onClick: closeUpdateModal },
1504
1761
  {
1505
1762
  label: '重新检测', primary: true,
1506
- onClick: () => { closeUpdateModal(); recheckDnsAction(lastRemoteBanner); },
1763
+ onClick: (btn) => recheckDnsAction(lastRemoteBanner, btn),
1507
1764
  },
1508
1765
  ],
1509
1766
  });
@@ -1513,15 +1770,24 @@ window.__ModuleLoader__.load({
1513
1770
  * 域名解析异常时的主按钮出路:强制重探一次。
1514
1771
  * 通过 → 直接继续「开启 + 出码」,用户不用再点第二次;不通过 → 给排障步骤。
1515
1772
  */
1516
- async function recheckDnsAction(banner) {
1517
- if (tunnelBusy) return;
1773
+ async function recheckDnsAction(banner, btn) {
1774
+ // 之前这里是 `if (tunnelBusy) return` —— 定时轮询/重复点击时界面完全没反应,
1775
+ // 用户只能理解为「按钮坏了」。现在至少给一句「正在检测」。
1776
+ if (tunnelBusy) {
1777
+ showModalToast('正在检测中,请稍候…', 'error');
1778
+ return;
1779
+ }
1518
1780
  lastRemoteBanner = banner || lastRemoteBanner;
1519
1781
  tunnelBusy = true;
1782
+ const restore = setModalBusy(btn, '检测中…');
1520
1783
  const mainBtn = panelEl?.querySelector('#dsh-mios-remote-main');
1521
1784
  if (mainBtn) {
1522
1785
  mainBtn.disabled = true;
1523
1786
  mainBtn.textContent = '检测中…';
1524
1787
  }
1788
+ // 已有结论时的差异感:结论没变要写在弹窗标题上,否则「关掉又弹出一样的窗」
1789
+ // 和「点了没反应」在用户眼里是同一件事。
1790
+ const before = summary?.tunnel?.credentials?.state || null;
1525
1791
  try {
1526
1792
  const res = await fetchJson('/mobile/v1/tunnel/recheck-dns', { method: 'POST' }, 25000);
1527
1793
  await probe();
@@ -1536,7 +1802,8 @@ window.__ModuleLoader__.load({
1536
1802
  // 账号/证书问题与 NS 问题是两码事:重探一万次也不会让跨账号的证书变得可用。
1537
1803
  // 先把「换账号 login」这条唯一出口摆出来,别让人照着改 NS 白跑。
1538
1804
  if (res?.credentials?.blocking) {
1539
- showCredentialHelpModal(res.credentials);
1805
+ const again = Boolean(before && before === res.credentials.state);
1806
+ showCredentialHelpModal(res.credentials, { again });
1540
1807
  return;
1541
1808
  }
1542
1809
  showDnsHelpModal(res || {});
@@ -1546,6 +1813,7 @@ window.__ModuleLoader__.load({
1546
1813
  warning: err?.body?.error?.message || err?.message || String(err),
1547
1814
  });
1548
1815
  } finally {
1816
+ restore();
1549
1817
  tunnelBusy = false;
1550
1818
  if (mainBtn) mainBtn.disabled = false;
1551
1819
  renderSummary();
@@ -1554,7 +1822,11 @@ window.__ModuleLoader__.load({
1554
1822
 
1555
1823
  /** 远程主按钮:一条动作链走完「确保在跑 → 出码」。一次点击出码,绝不让人点两下。 */
1556
1824
  async function remoteMainAction(banner) {
1557
- if (tunnelBusy || bannerBusy.remote || installBusy) return;
1825
+ if (tunnelBusy || bannerBusy.remote || installBusy) {
1826
+ // 静默 return 是「点了没反应」的主要来源之一:告诉用户正在做什么。
1827
+ showModalToast(tunnelBusy ? '上一步还没结束,请稍候…' : '正在生成配对码,请稍候…', 'error');
1828
+ return;
1829
+ }
1558
1830
  lastRemoteBanner = banner || lastRemoteBanner;
1559
1831
  const mainBtn = panelEl?.querySelector('#dsh-mios-remote-main');
1560
1832
  // 缺依赖且平台可自动装:先走安装确认,装完再继续开启(避免点了必然失败的 start)
@@ -1614,7 +1886,7 @@ window.__ModuleLoader__.load({
1614
1886
  showCredentialHelpModal({
1615
1887
  ...(summary?.tunnel?.credentials || {}),
1616
1888
  hint: err?.body?.error?.message || summary?.tunnel?.credentials?.hint,
1617
- });
1889
+ }, { again: true });
1618
1890
  } else {
1619
1891
  const hint = panelEl?.querySelector('#dsh-mios-hint');
1620
1892
  if (hint) {
@@ -1740,6 +2012,7 @@ window.__ModuleLoader__.load({
1740
2012
  showUpdateModal, closeUpdateModal, copyToClipboard,
1741
2013
  showModalToast, offerManualCopy, showDnsHelpModal, recheckDnsAction,
1742
2014
  showCredentialHelpModal, confirmResetTunnelState, resetTunnelStateAction,
2015
+ startTunnelLogin, renderLoginModal, pollLogin, stopLoginPoll, afterLoginOk, cancelTunnelLogin,
1743
2016
  performUpdate, checkPluginUpdate, compareVersions, unwrapRemote,
1744
2017
  setPluginManager: (m) => { pluginManager = m; },
1745
2018
  probe, remoteMainAction, renderSummary,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-mobile-ios",
3
- "version": "0.2.18",
3
+ "version": "0.2.19",
4
4
  "type": "module",
5
5
  "description": "DSH iOS移动伴侣:iPhone/iPad 扫码连接 DSH 桌面端,局域网直连 + Cloudflare Tunnel 固定域名远程两种通道",
6
6
  "main": "entries/plugin.mjs",
@@ -29,7 +29,7 @@
29
29
  "scripts": {
30
30
  "start": "node entries/sidecar.mjs --host=mock --dev",
31
31
  "start:lan": "node entries/sidecar.mjs --host=mock --dev --lan=true",
32
- "test": "node test/selftest.mjs && node test/version.mjs && node test/lan-ip.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/workspace-actions.mjs && node test/workspace-index.mjs && node test/enhance.mjs && node test/tunnel-named.mjs && node test/tar.mjs && node test/cloudflared-install.mjs && node test/install-continue.mjs && node test/dns-recheck.mjs && node test/tunnel-credentials.mjs && node test/plugin-selfupdate.mjs && node test/zone-moved.mjs",
32
+ "test": "node test/selftest.mjs && node test/version.mjs && node test/lan-ip.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/workspace-actions.mjs && node test/workspace-index.mjs && node test/enhance.mjs && node test/tunnel-named.mjs && node test/tar.mjs && node test/cloudflared-install.mjs && node test/install-continue.mjs && node test/dns-recheck.mjs && node test/tunnel-credentials.mjs && node test/tunnel-login.mjs && node test/plugin-selfupdate.mjs && node test/zone-moved.mjs",
33
33
  "probe": "node spike0/probe.mjs"
34
34
  },
35
35
  "dsh": {
@@ -0,0 +1,188 @@
1
+ // cloudflared-login.mjs — 面板里一键完成 `cloudflared tunnel login`
2
+ //
3
+ // 为什么必须做在插件里:固定地址写在 Cloudflare 的域名下,只有**持有该域名的账号**
4
+ // 的证书才写得进去。而 `cloudflared tunnel login` 需要「在浏览器里点授权」——这一步
5
+ // 人必须参与,但**不该要求用户先会开终端、会敲命令、会找 HOME**。
6
+ // 现场(2026-11-21)的结论很直接:新机上插件提示「账号不对」,用户重装、重启、
7
+ // 点重置都没用,唯一能修好的动作是一条终端命令,而面板只说了一句话。
8
+ //
9
+ // 这个模块只做三件事:起进程、把授权链接捞出来给面板、等进程结束并交代结果。
10
+ // 四个硬约束:
11
+ // 1. 幂等:等待中重复调用返回同一会话,不会起第二个浏览器授权;
12
+ // 2. 不静默:超时/被杀/退出码非 0/退出但没生成证书,都要有可读原因;
13
+ // 3. 不留孤儿:网关停止或取消时 kill 掉子进程;
14
+ // 4. 不写死路径:用调用方给的 executable(发现链解析结果),只覆盖 HOME。
15
+
16
+ import fs from 'node:fs';
17
+ import os from 'node:os';
18
+ import path from 'node:path';
19
+ import { spawn as nodeSpawn } from 'node:child_process';
20
+
21
+ const DEFAULT_TIMEOUT_MS = 5 * 60_000;
22
+ const LOG_CAP = 8 * 1024;
23
+
24
+ /** 从 cloudflared 的输出里捞出浏览器授权链接。 */
25
+ const AUTH_URL = /https:\/\/dash\.cloudflare\.com\/argotunnel\?[^\s"'<>]+/i;
26
+
27
+ /** 有用的最后几行(错误信息通常就在末尾,且不能像原来那样只留第一行)。 */
28
+ function tailLines(raw, max = 400) {
29
+ const lines = String(raw || '').split(/\r?\n/).map((s) => s.trim()).filter(Boolean);
30
+ const text = lines.slice(-4).join(' / ');
31
+ return text.length > max ? `${text.slice(0, max)}…` : text;
32
+ }
33
+
34
+ export const LOGIN_HINT = {
35
+ idle: null,
36
+ waiting: '在浏览器里选择「持有该域名的账号」并点授权',
37
+ ok: '授权完成,本机证书已更新',
38
+ error: '授权没有完成',
39
+ canceled: '已取消授权',
40
+ };
41
+
42
+ /**
43
+ * @param {object} opts
44
+ * @param {Function} [opts.spawn] 注入用(测试里给假进程)
45
+ * @param {Function} [opts.now]
46
+ * @param {Function} [opts.log]
47
+ * @param {number} [opts.timeoutMs]
48
+ * @param {object} [opts.fsImpl]
49
+ */
50
+ export function createLoginManager({
51
+ spawn = nodeSpawn,
52
+ now = () => Date.now(),
53
+ log = () => {},
54
+ timeoutMs = DEFAULT_TIMEOUT_MS,
55
+ fsImpl = fs,
56
+ } = {}) {
57
+ let session = null; // { state, url, startedAt, finishedAt, pid, error, homeDir, child, certBefore }
58
+
59
+ const certFile = (homeDir) => path.join(homeDir || os.homedir(), '.cloudflared', 'cert.pem');
60
+ const certMtime = (homeDir) => {
61
+ try { return fsImpl.statSync(certFile(homeDir)).mtimeMs; } catch { return null; }
62
+ };
63
+
64
+ function snapshot() {
65
+ if (!session) {
66
+ return { state: 'idle', url: null, startedAt: null, finishedAt: null, pid: null, error: null, hint: null };
67
+ }
68
+ return {
69
+ state: session.state,
70
+ url: session.url,
71
+ startedAt: session.startedAt,
72
+ finishedAt: session.finishedAt,
73
+ pid: session.pid,
74
+ error: session.error,
75
+ hint: LOGIN_HINT[session.state] ?? null,
76
+ };
77
+ }
78
+
79
+ function finish(state, error = null) {
80
+ if (!session) return;
81
+ session.state = state;
82
+ session.error = error;
83
+ session.finishedAt = new Date(now()).toISOString();
84
+ session.child = null;
85
+ if (session.timer) {
86
+ clearTimeout(session.timer);
87
+ session.timer = null;
88
+ }
89
+ }
90
+
91
+ /**
92
+ * 开始(或复用)一次授权。
93
+ * @returns {{state:string,url:string|null,startedAt:string|null,pid:number|null,error:string|null}}
94
+ */
95
+ function start({ executable, homeDir = os.homedir() } = {}) {
96
+ if (session && session.state === 'waiting') return snapshot();
97
+ if (!executable) {
98
+ const err = new Error('这台主机还没有 cloudflared,无法发起授权');
99
+ err.code = 'NO_CLOUDFLARED';
100
+ throw err;
101
+ }
102
+ session = {
103
+ state: 'waiting',
104
+ url: null,
105
+ startedAt: new Date(now()).toISOString(),
106
+ finishedAt: null,
107
+ pid: null,
108
+ error: null,
109
+ homeDir,
110
+ child: null,
111
+ timer: null,
112
+ certBefore: certMtime(homeDir),
113
+ };
114
+ let raw = '';
115
+ let child;
116
+ try {
117
+ child = spawn(executable, ['tunnel', 'login'], {
118
+ // 只覆盖 HOME:证书一定落在本机真正使用的那份 ~/.cloudflared 里。
119
+ // (Windows 走 USERPROFILE,两者都设,避免 cloudflared 用另一套路径)
120
+ env: { ...process.env, HOME: homeDir, USERPROFILE: homeDir },
121
+ stdio: ['ignore', 'pipe', 'pipe'],
122
+ });
123
+ } catch (err) {
124
+ finish('error', `无法启动 cloudflared:${err?.message || err}`);
125
+ return snapshot();
126
+ }
127
+ session.child = child;
128
+ session.pid = child.pid ?? null;
129
+ log(`tunnel login 已启动 pid=${session.pid} exe=${executable}`);
130
+
131
+ const onChunk = (buf) => {
132
+ raw = (raw + String(buf)).slice(-LOG_CAP);
133
+ if (!session.url) {
134
+ const m = AUTH_URL.exec(raw);
135
+ if (m) {
136
+ // cloudflared 会把 & 原样打印;有些版本会加尾随标点,去掉
137
+ session.url = m[0].replace(/[.,;)]+$/, '');
138
+ log('tunnel login 已拿到授权链接');
139
+ }
140
+ }
141
+ };
142
+ child.stdout?.on?.('data', onChunk);
143
+ child.stderr?.on?.('data', onChunk);
144
+
145
+ child.on?.('error', (err) => {
146
+ finish('error', `无法启动 cloudflared:${err?.message || err}`);
147
+ });
148
+ child.on?.('close', (code, signal) => {
149
+ if (session.state !== 'waiting') return; // 已经被取消/超时收口
150
+ if (code === 0) {
151
+ const after = certMtime(session.homeDir);
152
+ const renewed = after !== null && (session.certBefore === null || after !== session.certBefore);
153
+ if (!renewed) {
154
+ finish('error', 'cloudflared 正常退出,但没有生成 ~/.cloudflared/cert.pem(授权可能未完成)');
155
+ return;
156
+ }
157
+ finish('ok');
158
+ log('tunnel login 完成,证书已更新');
159
+ return;
160
+ }
161
+ const reason = tailLines(raw);
162
+ finish('error', `cloudflared 退出(${signal ? `signal ${signal}` : `code ${code}`})`
163
+ + (reason ? `:${reason}` : ''));
164
+ log(`tunnel login 失败 code=${code} signal=${signal || '-'}`);
165
+ });
166
+
167
+ session.timer = setTimeout(() => {
168
+ if (session?.state !== 'waiting') return;
169
+ try { session.child?.kill?.('SIGTERM'); } catch { /* 已退出 */ }
170
+ finish('error', `等待浏览器授权超时(${Math.round(timeoutMs / 1000)} 秒)。`
171
+ + '可以重新发起,或在终端手动执行 cloudflared tunnel login。');
172
+ log('tunnel login 超时');
173
+ }, timeoutMs);
174
+ if (session.timer.unref) session.timer.unref();
175
+
176
+ return snapshot();
177
+ }
178
+
179
+ function cancel() {
180
+ if (!session || session.state !== 'waiting') return snapshot();
181
+ try { session.child?.kill?.('SIGTERM'); } catch { /* 已退出 */ }
182
+ finish('canceled');
183
+ log('tunnel login 已取消');
184
+ return snapshot();
185
+ }
186
+
187
+ return { start, cancel, status: snapshot };
188
+ }
@@ -177,8 +177,14 @@ export class LocalProvisioner {
177
177
  blocking: Boolean(verdict.blocking),
178
178
  hint: verdict.hint ?? null,
179
179
  accountName: verdict.accountName ?? null,
180
+ // 「证书账号」与「域名所在账号」在跨账号场景下是两个名字,面板必须都能显示:
181
+ // 只给域名账号名时,用户看不出自己刚跑的 tunnel login 到底切没切成功。
182
+ certAccountName: verdict.certAccountName ?? null,
183
+ certAccountId: verdict.certAccountId ?? null,
184
+ certZoneName: verdict.certZoneName ?? null,
180
185
  zoneName: verdict.zoneName ?? null,
181
186
  zoneStatus: verdict.zoneStatus ?? null,
187
+ detail: verdict.detail ?? null,
182
188
  checkedAt: this._auth?.at ? new Date(this._auth.at).toISOString() : null,
183
189
  };
184
190
  }
package/src/rest.mjs CHANGED
@@ -4,10 +4,13 @@
4
4
  import { fail, ERRORS, newId } from './protocol.mjs';
5
5
  import { translateRecords } from './adapter/session-history.mjs';
6
6
  import { createRequire } from 'node:module';
7
+ import os from 'node:os';
7
8
  import { PLUGIN_VERSION } from './version.mjs';
8
9
  import { ensureCloudflared, resolveAsset } from './cloudflared-install.mjs';
9
10
  import { selfUpdatePlugin } from './plugin-update.mjs';
10
11
  import { resolveNs } from './dns-probe.mjs';
12
+ import { createLoginManager } from './cloudflared-login.mjs';
13
+ import { findCloudflared } from './tunnel.mjs';
11
14
 
12
15
  // QR 编码(vendor:qrcode-generator 1.4.4,MIT,零依赖;见 lib/vendor/,
13
16
  // .cjs 后缀:包为 type:module,require 需显式 CommonJS)
@@ -102,6 +105,8 @@ const DESKTOP_CORS_PATHS = [
102
105
  /^\/mobile\/v1\/tunnel\/install-cloudflared$/,
103
106
  /^\/mobile\/v1\/tunnel\/recheck-dns$/,
104
107
  /^\/mobile\/v1\/tunnel\/reset$/,
108
+ /^\/mobile\/v1\/tunnel\/login$/,
109
+ /^\/mobile\/v1\/tunnel\/login\/cancel$/,
105
110
  /^\/mobile\/v1\/plugin\/self-update$/,
106
111
  ];
107
112
 
@@ -151,6 +156,22 @@ export function createRestRouter({ core, pairing, host, tickets, config = {}, lo
151
156
  const routes = [];
152
157
  const route = (method, pattern, handler) => routes.push({ method, pattern, handler });
153
158
 
159
+ /**
160
+ * 浏览器授权会话(`cloudflared tunnel login`)。
161
+ *
162
+ * 放在网关而不是面板:起子进程、读 HOME、等回调都只能在主机侧做;面板只负责
163
+ * 把链接摆出来并在结果出来后继续开通。会话是**进程级单例**——重复点不会开第二个
164
+ * 浏览器授权页(现场最容易踩的坑:点两次,两个 cloudflared 抢同一个 cert.pem)。
165
+ */
166
+ const loginManager = config.loginManager || createLoginManager({ log });
167
+
168
+ /** 授权用的 cloudflared 与开通用同一套发现链:能开通却找不到 login 的二进制没意义。 */
169
+ const loginExecutable = () => {
170
+ if (typeof config.loginExecutable === 'function') return config.loginExecutable();
171
+ const hint = config.tunnelProvisioner?.executable || 'auto';
172
+ return findCloudflared(hint, process.env) || findCloudflared('auto', process.env) || null;
173
+ };
174
+
154
175
  /**
155
176
  * 诊断包(GW-9)。
156
177
  *
@@ -267,6 +288,9 @@ export function createRestRouter({ core, pairing, host, tickets, config = {}, lo
267
288
  // 凭据预检结论(local 形态才有):state=障碍类型,blocking=是否**确定**不可写。
268
289
  // 面板因此能在用户点「开启远程」之前就提示「登录的账号不对」,而不是等写 DNS 才崩。
269
290
  credentials: prov?.credentials ?? null,
291
+ // 浏览器授权的进度(idle/waiting/ok/error/canceled)。面板刷新/重载后能凭它
292
+ // 恢复「正在等授权」的界面,不会让用户以为按钮点了没反应。
293
+ login: loginManager.status(),
270
294
  // 面板据此决定是否显示「自动安装 cloudflared」入口:仅在缺失且有官方构建时为 true。
271
295
  canAutoInstall: base.executable === 'missing' && !!resolveAsset({}),
272
296
  };
@@ -604,6 +628,46 @@ export function createRestRouter({ core, pairing, host, tickets, config = {}, lo
604
628
  return send(ctx.res, 200, { ...result, status: tunnelSnapshot() }, DESKTOP_CORS);
605
629
  });
606
630
 
631
+ /**
632
+ * 发起 Cloudflare 浏览器授权(面板「重新授权」按钮)。
633
+ *
634
+ * 边界与开通同一道门(回环-only):这一步会起子进程并让浏览器拿到一次账号授权,
635
+ * 公网上的任何人都不能触发。返回里带 `url`——面板即使拿不到系统浏览器,也能把
636
+ * 链接复制出去在任意设备上完成授权(回调仍是本机 localhost,所以必须同机浏览器)。
637
+ */
638
+ route('POST', /^\/mobile\/v1\/tunnel\/login$/, async (ctx) => {
639
+ loopbackOnly(ctx, 'Cloudflare 授权只允许在主机本机操作');
640
+ const executable = loginExecutable();
641
+ if (!executable) {
642
+ throw fail(4021, '这台主机还没有 cloudflared,先安装再授权', {
643
+ method: 'tunnel.login',
644
+ detail: '面板「安装 cloudflared」或在这台电脑终端执行 brew install cloudflared',
645
+ });
646
+ }
647
+ let status;
648
+ try {
649
+ status = loginManager.start({ executable, homeDir: os.homedir() });
650
+ } catch (err) {
651
+ throw fail(4500, err?.message || '无法发起 Cloudflare 授权', { method: 'tunnel.login' });
652
+ }
653
+ log(`rest tunnel login ${status.state}${status.url ? '(已给出链接)' : '(等待输出链接)'}`);
654
+ return send(ctx.res, 200, status, DESKTOP_CORS);
655
+ });
656
+
657
+ /** 查询授权进度(面板每 1.5 秒轮询一次;状态机在 cloudflared-login.mjs)。 */
658
+ route('GET', /^\/mobile\/v1\/tunnel\/login$/, async (ctx) => {
659
+ loopbackOnly(ctx, 'Cloudflare 授权状态只允许在主机本机读取');
660
+ return send(ctx.res, 200, loginManager.status(), DESKTOP_CORS);
661
+ });
662
+
663
+ /** 取消授权:kill 掉等待中的 cloudflared,避免用户关了弹窗它还在后台等。 */
664
+ route('POST', /^\/mobile\/v1\/tunnel\/login\/cancel$/, async (ctx) => {
665
+ loopbackOnly(ctx, 'Cloudflare 授权只允许在主机本机操作');
666
+ const status = loginManager.cancel();
667
+ log(`rest tunnel login cancel → ${status.state}`);
668
+ return send(ctx.res, 200, status, DESKTOP_CORS);
669
+ });
670
+
607
671
  /**
608
672
  * 插件自更新(不依赖宿主 pluginManager)。
609
673
  *
package/src/server.mjs CHANGED
@@ -85,6 +85,9 @@ export async function createGateway({
85
85
  // 隧道子进程的 spawn 实现。默认用 node:child_process;测试注入假进程,
86
86
  // 嵌入式场景也可替换(TunnelManager 本身已支持,这里只是让网关能透传)。
87
87
  tunnelSpawn = null,
88
+ // 面板「重新授权」用的 cloudflared 与会话(测试注入;生产走发现链 + 真子进程)
89
+ loginExecutable = null,
90
+ loginManager = null,
88
91
  } = {}) {
89
92
  if (!host) throw new Error('createGateway 需要 host 适配器');
90
93
 
@@ -151,6 +154,8 @@ export async function createGateway({
151
154
  tunnel,
152
155
  tunnelProvisioner,
153
156
  hostView,
157
+ ...(loginExecutable ? { loginExecutable } : {}),
158
+ ...(loginManager ? { loginManager } : {}),
154
159
  // 手机端要填的「电脑地址」(LAN IP:port);未起或无私网地址时为 null
155
160
  lanAddr: () => (listening?.lan ?? null),
156
161
  };
@@ -254,6 +254,7 @@ export const CREDENTIAL_STATE_HINT = {
254
254
  'no-token': 'cert.pem 里没有可用的 zone token(旧版证书)',
255
255
  forbidden: '登录的 Cloudflare 账号没有这个域名的权限',
256
256
  'zone-missing': '当前登录的账号里看不到这个域名',
257
+ 'zone-scoped-other': '证书授权的是另一个域名,不是当前的固定地址域名',
257
258
  'account-mismatch': '证书所属账号与域名所在账号不是同一个',
258
259
  'stale-zone': 'cert.pem 指向的 zone 已失效(域名可能被删后重新接入)',
259
260
  'zone-moved': '域名已被另一个 Cloudflare 账号接管',
@@ -261,7 +262,38 @@ export const CREDENTIAL_STATE_HINT = {
261
262
  };
262
263
 
263
264
  /** 这些状态是「确定不可用」:可以放心在写 DNS 之前拦下,并给出对应修法。 */
264
- const BLOCKING_STATES = new Set(['missing', 'forbidden', 'zone-missing', 'account-mismatch', 'stale-zone', 'zone-moved']);
265
+ const BLOCKING_STATES = new Set([
266
+ 'missing', 'forbidden', 'zone-missing', 'zone-scoped-other', 'account-mismatch', 'stale-zone', 'zone-moved',
267
+ ]);
268
+
269
+ /**
270
+ * 证书「看得到账号、却列不出这个域名」时,把证书真正授权的那把 zone 与账号名问出来。
271
+ *
272
+ * 为什么需要:`cloudflared tunnel login` 让人在浏览器里**选一个域名**,证书 token
273
+ * 只覆盖那一个 zone。如果当时点的是别的域名,`/zones?name=<目标>` 会返回空数组,
274
+ * 面板只能说「账号里看不到这个域名」——用户看着自己账号里明明有这个域名,无从下手。
275
+ * 问出「授权的是 xxx」之后,一句话就能说清下一步该做什么。
276
+ *
277
+ * 全部 best-effort:任何一步失败都不影响结论,只是少一句话。
278
+ */
279
+ async function probeCertScope(apiBase, cert, fetchImpl, timeoutMs) {
280
+ const out = { zoneName: null, zoneStatus: null, zoneGone: false, accountName: null };
281
+ if (cert.zoneId) {
282
+ const z = await cfRequest(apiBase, cert.apiToken, `/zones/${cert.zoneId}`, fetchImpl, timeoutMs);
283
+ if (z.ok && z.success) {
284
+ out.zoneName = z.result?.name || null;
285
+ out.zoneStatus = z.result?.status || null;
286
+ } else if (z.reached && (z.status === 400 || z.status === 404)) {
287
+ // 400 = Invalid zone identifier(zone 被删过),404 = 不存在
288
+ out.zoneGone = true;
289
+ }
290
+ }
291
+ if (cert.accountId) {
292
+ const a = await cfRequest(apiBase, cert.apiToken, `/accounts/${cert.accountId}`, fetchImpl, timeoutMs);
293
+ if (a.ok && a.success) out.accountName = a.result?.name || null;
294
+ }
295
+ return out;
296
+ }
265
297
 
266
298
  /**
267
299
  * 带 HTTP 状态的只读请求(cfGet 只关心 result,这里需要区分 403 与「断网」)。
@@ -327,6 +359,8 @@ export async function verifyCertAccess({
327
359
  zoneName: baseDomain || null,
328
360
  zoneStatus: null,
329
361
  certAccountId: null,
362
+ certAccountName: null,
363
+ certZoneName: null,
330
364
  zoneId: null,
331
365
  detail: null,
332
366
  };
@@ -370,17 +404,58 @@ export async function verifyCertAccess({
370
404
  }
371
405
 
372
406
  const zones = Array.isArray(list.result) ? list.result : [];
373
- const zone = zones.find((z) => z && String(z.name).toLowerCase() === baseDomain.toLowerCase()) || null;
407
+ let zone = zones.find((z) => z && String(z.name).toLowerCase() === baseDomain.toLowerCase()) || null;
374
408
  if (!zone) {
375
- // 空列表 = 这个 token 看不到该域名(zone 范围的 token 只列得出自己那把 zone)
376
- return {
409
+ // 空列表 = 这个 token 看不到该域名。但「看不到」有三种完全不同的原因,
410
+ // 用户要做的事也不同,所以必须多问一句「证书到底授权给了谁」:
411
+ // · 登录时在浏览器里选了别的域名 → zone-scoped-other(重登录并选对域名)
412
+ // · 那把 zone 已被删除(域名删掉后重新接入会换 zoneID)→ stale-zone
413
+ // · 权限/账号问题 → zone-missing
414
+ // 顺带把证书账号名带回来:面板原来在这一步什么都不显示,用户无法确认
415
+ // 「我刚跑的 tunnel login 到底生效了没有」。
416
+ const scope = await probeCertScope(apiBase, cert, fetchImpl, timeoutMs);
417
+ const ident = {
377
418
  ...base,
378
- state: 'zone-missing',
379
- blocking: true,
380
- hint: CREDENTIAL_STATE_HINT['zone-missing'],
381
419
  certAccountId: cert.accountId || null,
382
- detail: `证书指向 zone ${String(cert.zoneId || '未知').slice(0, 8)}…,但它已不在任何可访问的 ${baseDomain} 之下`,
420
+ certAccountName: scope.accountName,
421
+ certZoneName: scope.zoneName,
383
422
  };
423
+ if (scope.zoneName && scope.zoneName.toLowerCase() === baseDomain.toLowerCase()) {
424
+ // 按 ID 能读到、按名字列不出:token 权限怪,但证书本身确实指向这个域名。
425
+ // 这种情况不能拦(拦了就是误杀),继续走正常判定。
426
+ const byId = await cfRequest(apiBase, cert.apiToken, `/zones/${cert.zoneId}`, fetchImpl, timeoutMs);
427
+ zone = byId.ok && byId.success ? byId.result : null;
428
+ if (!zone) return { ...ident, detail: '按 ID 读取 zone 失败' };
429
+ } else if (scope.zoneName) {
430
+ return {
431
+ ...ident,
432
+ state: 'zone-scoped-other',
433
+ blocking: true,
434
+ hint: CREDENTIAL_STATE_HINT['zone-scoped-other'],
435
+ zoneName: scope.zoneName,
436
+ zoneStatus: scope.zoneStatus,
437
+ detail: `证书授权的是 ${scope.zoneName},不是 ${baseDomain}。`
438
+ + `重新执行 cloudflared tunnel login,并在浏览器里选择 ${baseDomain}。`,
439
+ };
440
+ } else if (scope.zoneGone) {
441
+ return {
442
+ ...ident,
443
+ state: 'stale-zone',
444
+ blocking: true,
445
+ hint: CREDENTIAL_STATE_HINT['stale-zone'],
446
+ detail: `证书里的 zone ${String(cert.zoneId || '').slice(0, 8)}… 在 Cloudflare 上已不存在`
447
+ + `(域名删掉后重新接入会换 zoneID)。重新执行 cloudflared tunnel login 即可换新证书。`,
448
+ };
449
+ } else {
450
+ return {
451
+ ...ident,
452
+ state: 'zone-missing',
453
+ blocking: true,
454
+ hint: CREDENTIAL_STATE_HINT['zone-missing'],
455
+ detail: `证书账号 ${scope.accountName || String(cert.accountId || '未知').slice(0, 8)} 下没有 ${baseDomain}。`
456
+ + '要么用持有该域名的账号重新授权,要么把域名加到当前账号再重试。',
457
+ };
458
+ }
384
459
  }
385
460
 
386
461
  const zoneAccountId = zone.account?.id || null;
@@ -397,6 +472,8 @@ export async function verifyCertAccess({
397
472
  zoneName: zone.name || baseDomain,
398
473
  zoneStatus: zone.status || null,
399
474
  certAccountId: cert.accountId || null,
475
+ certAccountName: accountName,
476
+ certZoneName: zone.name || null,
400
477
  zoneId: zone.id || null,
401
478
  };
402
479
  if (accountMismatch) {