dsh-mobile-plugin 0.5.66 → 0.5.67

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.
@@ -218,7 +218,9 @@ libs/… 你自己的库、样式、字体,相对路径引用
218
218
 
219
219
  **导航是自动认的,不需要登记任何东西。** 声明了 `pageOrigin` 之后,App 会把「指向你这个
220
220
  本源、以及它下面任何站内路径」的跳转都留在页面里(`/canvas/abc`、`?x=1`、`#hash` 都算),
221
- **只有真的往外走的外链才交给系统浏览器**(官网、GitHub 这类照常能点开)。
221
+ **只有真的往外走的外链才交给 App 的内置浏览器打开**(官网、GitHub 这类照常能点开)。
222
+ 页面里直接写 `<a href="https://…">` 就行,不用加任何声明、也不用调接口 —— 外链会在内置
223
+ 浏览器里显示,既不跳去系统浏览器,也不会把扩展页本身带走。
222
224
 
223
225
  这条判据是按「这个地址是不是你自己的」算的,不认识具体哪个扩展 —— 所以你不用申请、不用
224
226
  等我们加白名单,声明了就自动生效。反过来说,**别指望它当成外链跳板**:到了别的域名就是
package/lib/client.js CHANGED
@@ -10,6 +10,9 @@
10
10
  * 页面里切过去、不重新加载。方向是单向的(桌面 → 宿主 → 手机),手机上的折叠只存在 App
11
11
  * 本地,不写回。
12
12
  *
13
+ * 设置卡上另有两颗侧边栏图标(手机 / 电脑)的显示开关:默认全开、至少留一颗,选择写进
14
+ * 插件配置;同一页里两颗图标当场收起或回来,不必等下一次状态轮询。
15
+ *
13
16
  * 本文件不经任何构建(package.json 直接收录 lib 下的 .js),所以不能写 JSX,统一用
14
17
  * `React.createElement` 的别名 `h`;客户端插件按约定写成惰性工厂,定时器与页签在物化时才起。
15
18
  */
@@ -90,6 +93,10 @@ window.__ModuleLoader__.load({
90
93
  .dshm_btn:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover)}
91
94
  .dshm_btn:disabled{cursor:default;opacity:.45}
92
95
  .dshm_btnPrimary{background:var(--dsw-alias-state-business-primary);border-color:transparent;color:var(--dsw-alias-bg-layer-1)}
96
+ /* 侧边栏图标开关:沿用卡片里的字号与描边,不开第二种控件语言。 */
97
+ .dshm_iconRow{display:flex;align-items:center;justify-content:space-between;gap:12px;font-size:13px;line-height:20px}
98
+ .dshm_iconSwitch{border:.5px solid var(--dsw-alias-border-l3);border-radius:var(--dsw-radius-sm);background:transparent;color:var(--dsw-alias-label-secondary);cursor:pointer;font:inherit;font-size:12px;line-height:18px;min-width:48px;padding:3px 10px}
99
+ .dshm_iconSwitch[aria-checked="true"]{background:var(--dsw-alias-state-business-primary);border-color:transparent;color:var(--dsw-alias-bg-layer-1)}
93
100
  `;
94
101
  if (typeof document !== 'undefined' && document.querySelector(`style[data-plugin-css="${STYLE_ID}"]`) === null) {
95
102
  const tag = document.createElement('style');
@@ -450,6 +457,14 @@ window.__ModuleLoader__.load({
450
457
  cardPanel: '配置页面',
451
458
  openPanel: '打开配置页面',
452
459
  openHint: '配对、网络配置与插件更新都在这个页面里。',
460
+ iconsTitle: '侧边栏图标',
461
+ iconsHint: '选择桌面侧边栏底部显示哪颗入口;至少保留一颗。',
462
+ iconPhone: '手机图标',
463
+ iconComputer: '电脑图标',
464
+ iconShown: '显示',
465
+ iconHidden: '隐藏',
466
+ iconKeepOne: '至少要保留一颗图标',
467
+ iconSaveFailed: '保存图标设置失败',
453
468
  panelPending: '正在读取页面地址…',
454
469
  panelMissing: '宿主还没给出页面地址,稍后再打开这一页试试。',
455
470
  loadFailed: '读取宿主状态失败',
@@ -527,6 +542,14 @@ window.__ModuleLoader__.load({
527
542
  cardPanel: 'Configuration page',
528
543
  openPanel: 'Open the configuration page',
529
544
  openHint: 'Pairing, network settings and plugin updates all live on this page.',
545
+ iconsTitle: 'Sidebar icons',
546
+ iconsHint: 'Choose which shortcut sits at the bottom of the desktop sidebar; keep at least one.',
547
+ iconPhone: 'Phone icon',
548
+ iconComputer: 'Computer icon',
549
+ iconShown: 'Shown',
550
+ iconHidden: 'Hidden',
551
+ iconKeepOne: 'Keep at least one icon',
552
+ iconSaveFailed: 'Could not save icon settings',
530
553
  panelPending: 'Reading the page address…',
531
554
  panelMissing: 'The host has not reported a page address yet — reopen this item in a moment.',
532
555
  loadFailed: 'Failed to read host status',
@@ -596,6 +619,33 @@ window.__ModuleLoader__.load({
596
619
  },
597
620
  };
598
621
 
622
+ /* ── 侧边栏图标选择(同一页共享) ────────────────────────────────────────
623
+ * 设置卡和两颗图标各自物化,谁先谁后不定;选择放在这一份闭包里,开关一拨当场生效,
624
+ * 不必等下一轮 20 秒的 /status。状态先到者写入;用户拨过之后,在途的旧状态不再覆盖
625
+ * 他的选择(否则图标会先消失、再自己回来)。写盘失败时回滚并通知同一页的订阅者。
626
+ */
627
+ let footerIcons = { phone: true, computer: true };
628
+ let footerIconsTouched = false;
629
+ const footerIconWatchers = new Set();
630
+ function setFooterIcons(next) {
631
+ footerIcons = next;
632
+ for (const watch of footerIconWatchers) watch(next);
633
+ }
634
+ function adoptFooterIcons(view) {
635
+ if (footerIconsTouched || !view) return;
636
+ const next = {
637
+ phone: view.desktopPhoneIcon !== false,
638
+ computer: view.desktopComputerIcon !== false,
639
+ };
640
+ if (footerIcons.phone === next.phone && footerIcons.computer === next.computer) return;
641
+ setFooterIcons(next);
642
+ }
643
+ function watchFooterIcons(watch) {
644
+ watch(footerIcons);
645
+ footerIconWatchers.add(watch);
646
+ return () => { footerIconWatchers.delete(watch); };
647
+ }
648
+
599
649
  /* ── 诊断弹窗 ──────────────────────────────────────────────────────────
600
650
  * 点这颗图标打不开配置页、或者开窗口失败时,不能只让用户「点了没反应」。
601
651
  *
@@ -745,8 +795,8 @@ window.__ModuleLoader__.load({
745
795
  if (spec.summary) card.appendChild(make('p', 'dshm_dialogLead', spec.summary));
746
796
  // 自定义内容区(入口那两块就挂在这儿):节点由调用方造,这里只负责挂上。
747
797
  if (spec.body) card.appendChild(spec.body);
748
- // 内嵌一整页(调试那一窗):外壳里 `window.open` 不可靠,所以把页面嵌进来。
749
- // `src` 已经由调用方按同源地址算好(壳里是 `dsh-app://app/api/relay/panel/debug`,
798
+ // 内嵌一整页(控制台 / 远程电脑那一窗):外壳里 `window.open` 不可靠,所以把页面嵌进来。
799
+ // `src` 已经由调用方按同源地址算好(壳里是 `dsh-app://app/api/relay/panel/console`,
750
800
  // 网页里是同源 http),远程浏览器的那两小时窗口也在拨号那一步开好了。
751
801
  //
752
802
  // load 只说明文档结束导航;空页、错误响应、脚本启动失败都不能算控制台就绪。
@@ -1365,6 +1415,9 @@ window.__ModuleLoader__.load({
1365
1415
  const [hint, setHint] = useState('');
1366
1416
  /** 展开态是否已经插进设置那一行。插不上就自己占一行。 */
1367
1417
  const [anchored, setAnchored] = useState(true);
1418
+ /** 用户在设置卡上有没有把这颗收起来;收起来时连插入的 DOM 一起撤掉。 */
1419
+ const [visible, setVisible] = useState(footerIcons.phone);
1420
+ useEffect(() => watchFooterIcons((next) => setVisible(next.phone)), []);
1368
1421
  const nodeRef = useRef(null);
1369
1422
  const dialogRef = useRef(null);
1370
1423
  useEffect(() => () => {
@@ -1406,6 +1459,7 @@ window.__ModuleLoader__.load({
1406
1459
  try {
1407
1460
  const next = await call('/status');
1408
1461
  const view = next && typeof next === 'object' ? next : {};
1462
+ adoptFooterIcons(view);
1409
1463
  const summary = readStatusView(view);
1410
1464
  setUrl(summary.panelUrl);
1411
1465
  setWebAccess(summary.webAccess);
@@ -1494,7 +1548,7 @@ window.__ModuleLoader__.load({
1494
1548
  * 跳过去,而是「它现在到底哪一环断了」——启动、装载、隧道、旁挂进程、自检全都在那一屏
1495
1549
  * 里,比一个打不开的页面有用。跳转本身没取消,挪进了那一屏里的一颗按钮。
1496
1550
  *
1497
- * 那一屏的内容是网页版的 `/api/relay/panel/debug`(React 写的,改完刷新就见效),
1551
+ * 那一屏的内容是网页版的 `/api/relay/panel/console`(React 写的,改完刷新就见效),
1498
1552
  * 这里只把同源地址算出来嵌进去。**必须先保证控制面认这个浏览器**,否则嵌进来的是一屏
1499
1553
  * 423 JSON:所以公网入口先按 `panelScope` 开好两小时窗口,本机和局域网直接进入。
1500
1554
  *
@@ -1584,9 +1638,8 @@ window.__ModuleLoader__.load({
1584
1638
  };
1585
1639
 
1586
1640
  /**
1587
- * 点一下手机图标,**直接就是这一屏控制台**:不再有「进入控制台 / 报错调试」那一层
1588
- * 中间入口。调试页没删,退到页面自己顶栏里那颗按钮;这一窗的外壳只留「在浏览器打开」
1589
- * 与「关闭」两颗图标,剩下的操作都在页面里,不占嵌页的地方。
1641
+ * 点一下手机图标,**直接就是这一屏控制台**:没有中间入口。调试页 2026-11-17 删了,
1642
+ * 窗口操作那两颗按钮也搬进了页面顶栏;这一窗的外壳只剩一圈薄边,不占嵌页的地方。
1590
1643
  */
1591
1644
  dialog.open({
1592
1645
  title: t('consoleTitle'),
@@ -1824,8 +1877,9 @@ window.__ModuleLoader__.load({
1824
1877
  useEffect(() => {
1825
1878
  if (typeof document === 'undefined') return undefined;
1826
1879
  const doc = document;
1827
- // 窄条那一行塞不下第二颗:不插,自己占一行。
1828
- if (!wide) {
1880
+ // 窄条那一行塞不下第二颗:不插,自己占一行。用户在设置卡上收起来时同样不插,
1881
+ // 走下面的清理把已插的那颗摘掉;观察器也不能再把它捡回来。
1882
+ if (!wide || !visible) {
1829
1883
  setAnchored(false);
1830
1884
  return undefined;
1831
1885
  }
@@ -1873,7 +1927,7 @@ window.__ModuleLoader__.load({
1873
1927
  frame = 0;
1874
1928
  try {
1875
1929
  sync();
1876
- setAnchored(ensureFooterIcon(doc, node));
1930
+ setAnchored(visible ? ensureFooterIcon(doc, node) : false);
1877
1931
  } catch {
1878
1932
  setAnchored(false);
1879
1933
  }
@@ -1886,9 +1940,11 @@ window.__ModuleLoader__.load({
1886
1940
  if (frame !== 0 && typeof cancelAnimationFrame === 'function') cancelAnimationFrame(frame);
1887
1941
  if (typeof node.remove === 'function' && node.parentElement) node.remove();
1888
1942
  };
1889
- }, [wide, url, openLabel, loadMissingLabel, pendingLabel, problem, panelScope, webAccess, hint, fault]);
1943
+ }, [wide, visible, url, openLabel, loadMissingLabel, pendingLabel, problem, panelScope, webAccess, hint, fault]);
1890
1944
 
1891
1945
  // 窄条,或者这一版外壳里认不出那一行:自己占一行,入口不能因为认不出位置就消失。
1946
+ // 收起来的那一颗例外:它这一页里根本不该再有入口。
1947
+ if (!visible) return null;
1892
1948
  if (!wide || !anchored) {
1893
1949
  const state = footerState();
1894
1950
  return h('a', {
@@ -1943,6 +1999,8 @@ window.__ModuleLoader__.load({
1943
1999
  const [panelScope, setPanelScope] = useState('');
1944
2000
  const [problem, setProblem] = useState(null);
1945
2001
  const [anchored, setAnchored] = useState(true);
2002
+ const [visible, setVisible] = useState(footerIcons.computer);
2003
+ useEffect(() => watchFooterIcons((next) => setVisible(next.computer)), []);
1946
2004
  const nodeRef = useRef(null);
1947
2005
  const dialogRef = useRef(null);
1948
2006
  useEffect(() => () => {
@@ -1958,6 +2016,7 @@ window.__ModuleLoader__.load({
1958
2016
  try {
1959
2017
  const next = await call('/status');
1960
2018
  const view = readStatusView(next);
2019
+ adoptFooterIcons(next);
1961
2020
  setUrl(view.panelUrl);
1962
2021
  setWebAccess(view.webAccess);
1963
2022
  setPanelScope(view.panelScope);
@@ -2108,10 +2167,11 @@ window.__ModuleLoader__.load({
2108
2167
  }, []);
2109
2168
 
2110
2169
  // 展开态:纯 DOM 插进设置那一行,紧跟手机图标;认不出位置就退回自己一行。
2170
+ // 收起来时不插,也不让观察器把它捡回来(已插的那颗在 effect 清理里摘掉)。
2111
2171
  useEffect(() => {
2112
2172
  if (typeof document === 'undefined') return undefined;
2113
2173
  const doc = document;
2114
- if (!wide) {
2174
+ if (!wide || !visible) {
2115
2175
  setAnchored(false);
2116
2176
  return undefined;
2117
2177
  }
@@ -2158,7 +2218,7 @@ window.__ModuleLoader__.load({
2158
2218
  frame = 0;
2159
2219
  try {
2160
2220
  sync();
2161
- setAnchored(ensureRemoteFooterIcon(doc, node));
2221
+ setAnchored(visible ? ensureRemoteFooterIcon(doc, node) : false);
2162
2222
  } catch {
2163
2223
  setAnchored(false);
2164
2224
  }
@@ -2171,9 +2231,10 @@ window.__ModuleLoader__.load({
2171
2231
  if (frame !== 0 && typeof cancelAnimationFrame === 'function') cancelAnimationFrame(frame);
2172
2232
  if (typeof node.remove === 'function' && node.parentElement) node.remove();
2173
2233
  };
2174
- }, [wide, url, openLabel, problem, panelScope, webAccess]);
2234
+ }, [wide, visible, url, openLabel, problem, panelScope, webAccess]);
2175
2235
 
2176
2236
  // 窄条,或认不出那一行:自己占一行,入口不能因为认不出位置就消失。
2237
+ if (!visible) return null;
2177
2238
  if (!wide || !anchored) {
2178
2239
  return h('a', {
2179
2240
  className: 'dshm_footAction dshm_footActionRail',
@@ -2379,8 +2440,9 @@ window.__ModuleLoader__.load({
2379
2440
  * 这一张是设置里的正规入口):介绍产品时说的入口就是「设置 → 移动端」,只留图标会让从
2380
2441
  * 网页版进来的人不知道配置在哪。
2381
2442
  *
2382
- * 刻意只有一张薄卡:界面本体全在网页版里(A3-37),在这里再画一套等于长期维护第二套 UI,
2383
- * 而两套迟早会打架。卡片只做两件事——说清配置在哪、把那一页开出来;开不出来就在卡上写原因。
2443
+ * 刻意只放轻量的设置:界面本体全在网页版里(A3-37),在这里再画一套等于长期维护第二套 UI,
2444
+ * 而两套迟早会打架。配置页卡只做两件事——说清配置在哪、把那一页开出来;开不出来就在卡上写
2445
+ * 原因。2026-11-17 用户要在这一页选侧边栏那两颗图标,才添了第二张小卡。
2384
2446
  */
2385
2447
  function MobileSettingsSection({ t }) {
2386
2448
  /** null = 还在问宿主;'' = 问到了但宿主没给地址(老版本或还没起来)。 */
@@ -2389,6 +2451,10 @@ window.__ModuleLoader__.load({
2389
2451
  const [access, setAccess] = useState(null);
2390
2452
  /** `null` = 这一次没出错;否则 `{ kind: 'load' | 'open', message }`。 */
2391
2453
  const [failure, setFailure] = useState(null);
2454
+ /** 侧边栏两颗图标的选择,与那两颗图标共享同一份状态。 */
2455
+ const [icons, setIcons] = useState(footerIcons);
2456
+ const [iconError, setIconError] = useState('');
2457
+ useEffect(() => watchFooterIcons(setIcons), []);
2392
2458
 
2393
2459
  useEffect(() => {
2394
2460
  let alive = true;
@@ -2397,6 +2463,7 @@ window.__ModuleLoader__.load({
2397
2463
  const next = await call('/status');
2398
2464
  if (!alive) return;
2399
2465
  const view = next && typeof next === 'object' ? next : {};
2466
+ adoptFooterIcons(view);
2400
2467
  setUrl(typeof view.panelUrl === 'string' ? view.panelUrl : '');
2401
2468
  setScope(typeof view.panelScope === 'string' ? view.panelScope : '');
2402
2469
  setAccess(view.webAccess && typeof view.webAccess.enabled === 'boolean' ? view.webAccess : null);
@@ -2449,6 +2516,33 @@ window.__ModuleLoader__.load({
2449
2516
  })();
2450
2517
  }
2451
2518
 
2519
+ /**
2520
+ * 拨一颗图标的开关。至少留一颗:两颗都收起来,侧边栏就没有桌面入口了,用户回到这一页
2521
+ * 才能改回来——这不是「都关掉也行」的偏好,是别把人锁在门外。
2522
+ * 先改共享状态让图标当场跟着变,再落盘;写失败就把两颗都还原,并说清原因。
2523
+ */
2524
+ async function toggleIcon(key) {
2525
+ const before = { ...icons };
2526
+ const other = key === 'phone' ? 'computer' : 'phone';
2527
+ if (before[key] && !before[other]) {
2528
+ setIconError(t('iconKeepOne'));
2529
+ return;
2530
+ }
2531
+ const next = { ...before, [key]: !before[key] };
2532
+ footerIconsTouched = true;
2533
+ setFooterIcons(next);
2534
+ setIconError('');
2535
+ try {
2536
+ await postJson('/config', {
2537
+ desktopPhoneIcon: next.phone,
2538
+ desktopComputerIcon: next.computer,
2539
+ });
2540
+ } catch (error) {
2541
+ setFooterIcons(before);
2542
+ setIconError(`${t('iconSaveFailed')}:${String((error && error.message) || error)}`);
2543
+ }
2544
+ }
2545
+
2452
2546
  const hint = url === null ? t('panelPending') : url === '' ? t('panelMissing') : t('openHint');
2453
2547
  return h('div', { className: 'dshm_root' },
2454
2548
  h('h2', { className: 'dshm_heading' }, t('heading')),
@@ -2467,7 +2561,24 @@ window.__ModuleLoader__.load({
2467
2561
  failure
2468
2562
  ? h('p', { className: 'dshm_error' },
2469
2563
  `${failure.kind === 'load' ? t('loadFailed') : t('openFailed')}:${failure.message}`)
2470
- : null));
2564
+ : null),
2565
+ h('div', { className: 'dshm_card' },
2566
+ h('h3', { className: 'dshm_cardTitle' }, t('iconsTitle')),
2567
+ h('p', { className: 'dshm_note' }, t('iconsHint')),
2568
+ [['phone', 'iconPhone'], ['computer', 'iconComputer']].map(([key, label]) => h('div', {
2569
+ key,
2570
+ className: 'dshm_iconRow',
2571
+ },
2572
+ h('span', {}, t(label)),
2573
+ h('button', {
2574
+ type: 'button',
2575
+ className: 'dshm_iconSwitch',
2576
+ role: 'switch',
2577
+ 'aria-checked': icons[key] ? 'true' : 'false',
2578
+ 'aria-label': t(label),
2579
+ onClick: () => void toggleIcon(key),
2580
+ }, t(icons[key] ? 'iconShown' : 'iconHidden')))),
2581
+ iconError ? h('p', { className: 'dshm_error' }, iconError) : null));
2471
2582
  }
2472
2583
 
2473
2584
  /* ── 聊天嵌入页:把网页定位到顶栏那条会话 ───────────────────────────────
package/lib/impl.js CHANGED
@@ -6,6 +6,7 @@
6
6
  * (`test/assembly-layer.test.cjs` 钉着)。
7
7
  */
8
8
  // 远程电脑入口独立装配,手机端路由与权限保持原有边界。
9
+ // 桌面侧边栏两颗图标的显示偏好也落在这份 relay.json 里(默认全开)。
9
10
  import { createRequire } from 'node:module'
10
11
  import os from 'node:os'
11
12
  import path from 'node:path'
@@ -42,6 +43,7 @@ const { mountP2P } = require('./p2p/wiring.cjs') // 点对点隧道:助手会
42
43
  // FRP 直连:用面板导入的配置拉起本地 frpc(见 lib/frpc/runner.cjs)。
43
44
  const { createFrpcRunner } = require('./frpc/runner.cjs')
44
45
  const { createPreviewService } = require('./relay/preview.js')
46
+ const { createMuxService } = require('./mobile/mux.js')
45
47
  const { mountRemoteComputers } = require('./remote/runtime.cjs')
46
48
  // 手机打开「电脑上的网页版」时用的那枚一次性登录令牌(见 mobile/host-web.js)。
47
49
  const hostWeb = require('./mobile/host-web.js')
@@ -121,6 +123,10 @@ export const RemoteControlSettingsSchema = z.object({
121
123
  // 新配对设备的权限档位(只读 / 可答审批 / 全权)。配对时在电脑侧选定,展开成 permissions
122
124
  // 写进凭据记录(见 lib/mobile/permissions.js)。缺省 full = 与今天单 token 全给等价。
123
125
  pairingTier: z.union(permissions.TIER_NAMES.map(t => z.const(t))).default(permissions.DEFAULT_TIER), approvalAutoReview: z.boolean().default(false), // 审批自动审阅档(默认关,见 mobile/auto-review.js)
126
+ // 桌面设置页那两颗侧边栏图标(手机 / 电脑)的可见性。默认全开;老 relay.json 没这两格时
127
+ // 由 configOf 收成 true,界面不会在升级后突然少一颗。只给桌面控制面写,手机端配置口不收。
128
+ desktopPhoneIcon: z.boolean().default(true),
129
+ desktopComputerIcon: z.boolean().default(true),
124
130
  // 中转注册密钥(对偶于中转的 TUNNEL_REGISTER_SECRET)。桌面版拿不到 shell
125
131
  // 环境变量,所以它和其他配置一样存在 relay.json(0600),由 /api/relay/config
126
132
  // 在回环上写入;status / pairing / 二维码都不回显它。
@@ -155,6 +161,9 @@ function configOf(state) {
155
161
  pairingPolicy: pairingApproval.normalize(state.pairingPolicy),
156
162
  pairingTier: permissions.isKnownTier(state.pairingTier) ? state.pairingTier : permissions.DEFAULT_TIER, // 未知值收敛回 full
157
163
  approvalAutoReview: state.approvalAutoReview === true, // 非 true 一律当关
164
+ // 没写过的老配置按显示处理:这两颗是入口,不因为升级就凭空消失。
165
+ desktopPhoneIcon: state.desktopPhoneIcon !== false,
166
+ desktopComputerIcon: state.desktopComputerIcon !== false,
158
167
  // 密钥只往 sidecar 和状态文件走:status() / pairingPayload() 都单独取字段,
159
168
  // 不会把它回显给手机、二维码或日志。
160
169
  registerSecret: typeof state.registerSecret === 'string' ? state.registerSecret : '',
@@ -544,6 +553,16 @@ function apply(ctx) {
544
553
  })
545
554
  ctx.effect(() => () => preview.close(), `${name}: preview pipes`)
546
555
 
556
+ // 对话页长连接(mux):一条手机 WS 上按 id 多路复用,逐条转成本地回环请求打到移动 API。
557
+ // 鉴权口径与预览升级路由同一套(设备凭据有效即可);逐路由权限仍由回环 HTTP 的 guarded 判,
558
+ // mux 只是搬运工,不另立权限面。帧契约见 `docs/mux-long-connection-design.md` §11。
559
+ const muxPermission = permissions.createUpgradePermission({ credentials, instanceId: state.instanceId, presentedCredential })
560
+ const mux = createMuxService({
561
+ upstream: { host: '127.0.0.1', port: ctx.webServer.port },
562
+ authorize: (req) => { try { return Boolean(muxPermission.recordOf(req)) } catch { return false } },
563
+ onLog: (message) => ctx.logger?.info?.(`${name}: %s`, message),
564
+ })
565
+
547
566
  const remoteComputers = mount('远程电脑', () => mountRemoteComputers({ ctx, state, credentials, registerRoute, lanPortInUse: advertisedLanPort, tailcat, p2p, log: warn }))
548
567
 
549
568
  // 移动端路由表在 lib/routes/mobile-api.js:那里是一张可以对着 App 侧 apiPaths.ts
@@ -559,6 +578,7 @@ function apply(ctx) {
559
578
  // 一样必须包在 ctx.effect 里,否则插件重载时重复注册会直接抛错。
560
579
  registerUpgradeRoute: (route) => mountRoute(route, true),
561
580
  preview,
581
+ mux,
562
582
  // 网页版登录令牌那条:handler 在这里造好、按依赖交给路由表,理由与 preview 一样——
563
583
  // 它要读的是本进程的 `ctx.webServer` 与 `ctx.get('connection')`。
564
584
  hostWeb: hostWeb.handleHostWeb,
@@ -0,0 +1,231 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * 对话页长连接(mux):一条 WebSocket 上的双向多路复用服务(宿主侧)。
5
+ *
6
+ * 背景见 `docs/mux-long-connection-design.md`。要点:App 侧握住一条持久 WS,把「发送」「实时事件」
7
+ * 以及其它**文本类**请求都变成这条 WS 上的逻辑流(按 id 并行);宿主在这里按 id 把它们逐条转成
8
+ * 本地回环 HTTP(`127.0.0.1:<webPort>`)打到既有的移动 API 上。于是:
9
+ *
10
+ * - 业务处理器、鉴权、E2EE、按路由权限统统**一行不动**——mux 只是搬运工,逐路由权限仍由回环
11
+ * HTTP 那一层(`guarded`)判;本服务只负责「这条 WS 是否一台已配对设备」和按 id 拆装。
12
+ * - 中转零改动:手机 WS 经中转原样代理到宿主这个升级路由(与内置浏览器预览同一条现成管道)。
13
+ * - 兜底永远在:mux 连不上/不支持时 App 走原来的 HTTPS+SSE,最坏不比今天差。
14
+ *
15
+ * 载体口径:**文本帧**(JSON 直接放 UTF-8 文本)。mux 只承载文本类移动 API(发送 / 事件订阅 /
16
+ * JSON 读),二进制下载(文件、附件字节)仍走 HTTP,不进 mux。宿主用 `StringDecoder` 切响应体,
17
+ * 保证分块边界不会劈开一个多字节字符。
18
+ *
19
+ * 帧契约见设计文档 §11:一条 WS 消息 = 一帧 JSON。
20
+ */
21
+
22
+ const http = require('node:http');
23
+ const { StringDecoder } = require('node:string_decoder');
24
+ const { WebSocketServer } = require('ws');
25
+
26
+ /** 单帧上限:与中转 `MAX_WS_MESSAGE_BYTES` / 宿主预览管道对齐(8 MiB)。 */
27
+ const MAX_MESSAGE_BYTES = 8 * 1024 * 1024;
28
+
29
+ /** 单连接并行逻辑流上限:够用且挡住失控。 */
30
+ const MAX_STREAMS_PER_CONNECTION = 64;
31
+ /** 宿主侧同时存在的 mux 连接上限。 */
32
+ const MAX_CONNECTIONS = 32;
33
+
34
+ /** 往手机方向的水位:缓冲超过高水位就把上游按住,落到低水位再放开。 */
35
+ const SEND_HIGH_WATER_BYTES = 4 * 1024 * 1024;
36
+ const SEND_LOW_WATER_BYTES = 1 * 1024 * 1024;
37
+ const SEND_RESUME_POLL_MS = 20;
38
+
39
+ /** 上游拨号超时:只覆盖「还没拿到响应头」这一段,之后是长连接,不能有读超时。 */
40
+ const UPSTREAM_HEADER_TIMEOUT_MS = 30_000;
41
+
42
+ /** 不往上游转发的逐跳头(与隧道/预览同一口径)。 */
43
+ const HOP_BY_HOP = new Set([
44
+ 'connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization',
45
+ 'te', 'trailer', 'transfer-encoding', 'upgrade', 'host',
46
+ ]);
47
+
48
+ function safeJson(text) {
49
+ try { return JSON.parse(text); } catch { return null; }
50
+ }
51
+
52
+ /**
53
+ * 建一个 mux 服务。
54
+ *
55
+ * @param {object} opts
56
+ * @param {{host?:string, port:number}} opts.upstream 本地移动 API 地址(一般 `127.0.0.1:<webPort>`)。
57
+ * @param {(req: import('node:http').IncomingMessage) => boolean} opts.authorize 握手鉴权。
58
+ * @param {(msg: string) => void} [opts.onLog]
59
+ */
60
+ function createMuxService(opts = {}) {
61
+ const upstreamHost = opts.upstream && opts.upstream.host ? opts.upstream.host : '127.0.0.1';
62
+ const upstreamPort = opts.upstream ? Number(opts.upstream.port) : 0;
63
+ const authorize = typeof opts.authorize === 'function' ? opts.authorize : () => false;
64
+ const onLog = typeof opts.onLog === 'function' ? opts.onLog : () => {};
65
+
66
+ const wss = new WebSocketServer({ noServer: true, maxPayload: MAX_MESSAGE_BYTES });
67
+ let connectionCount = 0;
68
+
69
+ /**
70
+ * 宿主 webServer 的升级处理器(`ctx.webServer.registerUpgrade`)。
71
+ *
72
+ * 鉴权与拒绝必须发生在 `handleUpgrade` **之前**:那时 socket 还是普通 HTTP 连接,能干净地回
73
+ * 一个 401 关掉;握手之后再拒就只是给对端一条立断的 WS。
74
+ */
75
+ function handleUpgrade(req, socket, head) {
76
+ let allowed = false;
77
+ try { allowed = authorize(req) === true; } catch { allowed = false; }
78
+ if (!allowed) {
79
+ try { socket.write('HTTP/1.1 401 Unauthorized\r\nconnection: close\r\ncontent-length: 0\r\n\r\n'); } catch { /* 已断 */ }
80
+ try { socket.destroy(); } catch { /* ignore */ }
81
+ return;
82
+ }
83
+ if (connectionCount >= MAX_CONNECTIONS) {
84
+ try { socket.write('HTTP/1.1 503 Service Unavailable\r\nconnection: close\r\ncontent-length: 0\r\n\r\n'); } catch { /* ignore */ }
85
+ try { socket.destroy(); } catch { /* ignore */ }
86
+ return;
87
+ }
88
+ wss.handleUpgrade(req, socket, head, (ws) => openConnection(ws));
89
+ }
90
+
91
+ function openConnection(ws) {
92
+ connectionCount += 1;
93
+ /** id → 一条在飞的本地请求。 */
94
+ const streams = new Map();
95
+ let closed = false;
96
+
97
+ const send = (obj) => {
98
+ if (closed || ws.readyState !== 1 /* OPEN */) return;
99
+ try { ws.send(JSON.stringify(obj)); } catch { /* 断了,close 会收尾 */ }
100
+ };
101
+ const fail = (id, message) => send({ t: 'err', id, message: String(message || 'error') });
102
+
103
+ /** 收掉一条逻辑流:销毁上游请求、释放槽位。 */
104
+ const dropStream = (id, reason) => {
105
+ const entry = streams.get(id);
106
+ if (!entry) return;
107
+ streams.delete(id);
108
+ if (entry.resumeTimer) clearTimeout(entry.resumeTimer);
109
+ try { entry.req && entry.req.destroy(); } catch { /* ignore */ }
110
+ if (reason) fail(id, reason);
111
+ };
112
+
113
+ const scheduleResume = (entry, res, id) => {
114
+ if (entry.resumeTimer) return;
115
+ entry.resumeTimer = setTimeout(() => {
116
+ entry.resumeTimer = null;
117
+ if (closed || streams.get(id) !== entry) return;
118
+ if (ws.bufferedAmount > SEND_LOW_WATER_BYTES) { scheduleResume(entry, res, id); return; }
119
+ entry.paused = false;
120
+ try { res.resume(); } catch { /* ignore */ }
121
+ }, SEND_RESUME_POLL_MS);
122
+ };
123
+
124
+ const startRequest = (frame) => {
125
+ const id = frame.id;
126
+ if (typeof id !== 'number') return;
127
+ if (streams.has(id)) { fail(id, 'duplicate id'); return; }
128
+ if (streams.size >= MAX_STREAMS_PER_CONNECTION) { fail(id, 'too many streams'); return; }
129
+ const method = String(frame.method || 'GET').toUpperCase();
130
+ const path = typeof frame.path === 'string' && frame.path ? frame.path : '/';
131
+ const headers = {};
132
+ if (frame.headers && typeof frame.headers === 'object') {
133
+ for (const [k, v] of Object.entries(frame.headers)) {
134
+ if (!k || HOP_BY_HOP.has(k.toLowerCase())) continue;
135
+ headers[k] = v;
136
+ }
137
+ }
138
+ const entry = { req: null, res: null, paused: false, resumeTimer: null, decoder: new StringDecoder('utf8') };
139
+ streams.set(id, entry);
140
+
141
+ let req;
142
+ try {
143
+ req = http.request({ host: upstreamHost, port: upstreamPort, method, path, headers }, (res) => {
144
+ if (closed || streams.get(id) !== entry) { res.destroy(); return; }
145
+ entry.res = res;
146
+ const respHeaders = {};
147
+ for (const [k, v] of Object.entries(res.headers)) {
148
+ if (!k || HOP_BY_HOP.has(k.toLowerCase()) || k.toLowerCase() === 'content-length') continue;
149
+ respHeaders[k] = v;
150
+ }
151
+ send({ t: 'resp', id, status: res.statusCode || 200, headers: respHeaders });
152
+ res.on('data', (buf) => {
153
+ if (closed || streams.get(id) !== entry) return;
154
+ // dec.write 只吐出完整字符,残缺的多字节尾巴自己留着,等下一块补上。
155
+ const text = entry.decoder.write(buf);
156
+ if (text) send({ t: 'chunk', id, text });
157
+ if (!entry.paused && ws.bufferedAmount > SEND_HIGH_WATER_BYTES) {
158
+ entry.paused = true;
159
+ res.pause();
160
+ scheduleResume(entry, res, id);
161
+ }
162
+ });
163
+ res.on('end', () => {
164
+ if (streams.get(id) !== entry) return;
165
+ streams.delete(id);
166
+ const rest = entry.decoder.end();
167
+ if (rest) send({ t: 'chunk', id, text: rest });
168
+ send({ t: 'end', id });
169
+ });
170
+ res.on('error', () => { if (streams.get(id) === entry) dropStream(id, 'upstream response error'); });
171
+ });
172
+ } catch (error) {
173
+ dropStream(id, error && error.message ? error.message : 'upstream request failed');
174
+ return;
175
+ }
176
+ entry.req = req;
177
+ req.setTimeout(UPSTREAM_HEADER_TIMEOUT_MS, () => dropStream(id, 'upstream header timeout'));
178
+ req.on('error', (error) => { if (streams.get(id) === entry) dropStream(id, error && error.message ? error.message : 'upstream error'); });
179
+ if (frame.body !== undefined && frame.body !== null) {
180
+ if (typeof frame.body !== 'string') { dropStream(id, 'bad body'); return; }
181
+ try { req.write(Buffer.from(frame.body, 'utf8')); } catch { /* error 会收 */ }
182
+ }
183
+ };
184
+
185
+ const onFrame = (frame) => {
186
+ if (!frame || typeof frame !== 'object') return;
187
+ switch (frame.t) {
188
+ case 'req': startRequest(frame); break;
189
+ case 'body': {
190
+ const entry = streams.get(frame.id);
191
+ if (!entry || !entry.req) return;
192
+ if (typeof frame.text !== 'string') { fail(frame.id, 'bad body'); return; }
193
+ try { entry.req.write(Buffer.from(frame.text, 'utf8')); } catch { /* ignore */ }
194
+ break;
195
+ }
196
+ case 'bodyEnd': {
197
+ const entry = streams.get(frame.id);
198
+ if (entry && entry.req) { try { entry.req.end(); } catch { /* ignore */ } }
199
+ break;
200
+ }
201
+ case 'cancel': dropStream(frame.id); break;
202
+ case 'ping': send({ t: 'pong' }); break;
203
+ default: break; // 未知帧忽略(前向兼容)
204
+ }
205
+ };
206
+
207
+ const cleanup = () => {
208
+ if (closed) return;
209
+ closed = true;
210
+ connectionCount -= 1;
211
+ for (const entry of streams.values()) {
212
+ if (entry.resumeTimer) clearTimeout(entry.resumeTimer);
213
+ try { entry.req && entry.req.destroy(); } catch { /* ignore */ }
214
+ }
215
+ streams.clear();
216
+ };
217
+
218
+ ws.on('message', (data, isBinary) => {
219
+ if (isBinary) return; // 契约只走 JSON 文本帧
220
+ const frame = safeJson(data.toString('utf8'));
221
+ if (!frame) { onLog('mux: bad json frame'); return; }
222
+ onFrame(frame);
223
+ });
224
+ ws.on('close', cleanup);
225
+ ws.on('error', cleanup);
226
+ }
227
+
228
+ return { handleUpgrade, MAX_MESSAGE_BYTES };
229
+ }
230
+
231
+ module.exports = { createMuxService, MAX_MESSAGE_BYTES, MAX_STREAMS_PER_CONNECTION, MAX_CONNECTIONS };
@@ -293,6 +293,9 @@ const MAP = Object.freeze({
293
293
  // 这条关掉的是 `permissions: []` 那种「明确什么都不给」的设备 —— 它们原来也能连上来。
294
294
  // 它能拨到哪儿另有独立的边界(protectedPorts / webapp 那一档,见 relay/preview.js)。
295
295
  '/api/mobile/v1/preview': V.VIEW,
296
+ // 对话页长连接(WebSocket 升级路由):与 preview 同档,归只读;逐路由权限仍由 mux 转发的
297
+ // 本地回环 HTTP 自己判(mux 只是搬运,不另立权限面)。
298
+ '/api/mobile/v1/mux': V.VIEW,
296
299
 
297
300
  // ── files.write:写文件 / 工作区 / git 写 / 技能写 / 画布写 ─────
298
301
  '/api/mobile/v1/file/create': V.FILES_WRITE,