dsh-mobile-plugin 0.5.101 → 0.5.102

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.
@@ -20,6 +20,8 @@ const { version: pluginVersion } = require('../../package.json')
20
20
 
21
21
  // 客户端半边(桌面页面里的 lib/client.js)的活体台账,只读它的计数快照。
22
22
  const desktopHalf = require('../desktop-half-stats.cjs')
23
+ // 手机↔本机这条连接的上下行累计字节(面板那张流速图的数据源)。
24
+ const traffic = require('./traffic-stats.cjs')
23
25
  // 中转地址两格的收敛:`relayUrls[0] === relayUrl` 这条不变式在任何出口都得成立。
24
26
  const core = require('./core.js')
25
27
 
@@ -169,6 +171,9 @@ function createStatusView(deps) {
169
171
  // 桌面页面里的客户端半边「有没有来敲过门」:绿点两条同步通道都是单向轮询 + 无回执,
170
172
  // 这里的三组计数是唯一的活体证据(对照关系见 lib/desktop-half-stats.cjs 的文件头)。
171
173
  desktopHalf: desktopHalf.snapshot(),
174
+ // 手机↔本机这条连接的真实字节累计:`sentBytes` 本机发出(上行/总发送),
175
+ // `receivedBytes` 本机收到(下行/总接收)。面板按相邻取样差算速率。
176
+ traffic: traffic.snapshot(),
172
177
  }
173
178
  }
174
179
  }
@@ -0,0 +1,84 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * 手机与本机之间这条连接的流量累计计数(本进程起算)。
5
+ *
6
+ * 口径从**本机**看:
7
+ * - `sentBytes`:本机发往手机(上行 / 总发送);
8
+ * - `receivedBytes`:手机发来本机(下行 / 总接收)。
9
+ *
10
+ * 计数点在移动路由(`lib/routes/mobile-api.js` 的 `withTraffic`):中转 / 局域网 / 直连隧道 /
11
+ * 点对点不管走哪条传输,最后都落到同一批移动路由,记一处口径就统一了。
12
+ *
13
+ * 生命周期:
14
+ * - 计数与历史挂在 `globalThis` 上,**同一个 DSH 进程内**插件被重载(自动更新那种)时沿用
15
+ * 同一份状态,用户无感、数字不跳回 0;
16
+ * - 整个 DSH 完全退出再启动 = 新进程 = `globalThis` 是新的,从头统计(用户主动重启应当清零)。
17
+ *
18
+ * 历史:后台每秒记一个累计快照,面板拿整段历史直接画曲线——这样刷新页面时曲线不会清空
19
+ * (历史在宿主内存里,不在页面里)。面板只负责把最新的那段画出来并做过渡动画。
20
+ */
21
+
22
+ const HISTORY_POINTS = 60
23
+ const SAMPLE_INTERVAL_MS = 1000
24
+ const GLOBAL_KEY = '__dshMobileTrafficStats'
25
+
26
+ function freshState() {
27
+ const now = Date.now()
28
+ return {
29
+ since: now,
30
+ sentBytes: 0,
31
+ receivedBytes: 0,
32
+ samples: [{ at: now, sentBytes: 0, receivedBytes: 0 }],
33
+ timer: null,
34
+ }
35
+ }
36
+
37
+ const state = globalThis[GLOBAL_KEY] || (globalThis[GLOBAL_KEY] = freshState())
38
+ if (!Array.isArray(state.samples) || state.samples.length === 0) state.samples = [{ at: state.since || Date.now(), sentBytes: 0, receivedBytes: 0 }]
39
+
40
+ function noteSent(bytes) {
41
+ const n = Number(bytes)
42
+ if (Number.isFinite(n) && n > 0) state.sentBytes += n
43
+ }
44
+
45
+ function noteReceived(bytes) {
46
+ const n = Number(bytes)
47
+ if (Number.isFinite(n) && n > 0) state.receivedBytes += n
48
+ }
49
+
50
+ function record() {
51
+ const now = Date.now()
52
+ state.samples.push({ at: now, sentBytes: state.sentBytes, receivedBytes: state.receivedBytes })
53
+ if (state.samples.length > HISTORY_POINTS) state.samples.splice(0, state.samples.length - HISTORY_POINTS)
54
+ }
55
+
56
+ /** 每秒记一拍;重载后旧定时器还在就复用它,不重复起。 */
57
+ function ensureSampler() {
58
+ if (state.timer) return
59
+ state.timer = setInterval(record, SAMPLE_INTERVAL_MS)
60
+ if (typeof state.timer.unref === 'function') state.timer.unref()
61
+ }
62
+ ensureSampler()
63
+
64
+ /** 给一条「正要被 pipe 出去」的可读流挂个旁观计数:只读不改,与 pipe 共用同一批 chunk。 */
65
+ function countReadable(stream, direction) {
66
+ if (!stream || typeof stream.on !== 'function') return stream
67
+ const note = direction === 'sent' ? noteSent : noteReceived
68
+ stream.on('data', (chunk) => {
69
+ if (chunk && typeof chunk.length === 'number') note(chunk.length)
70
+ })
71
+ return stream
72
+ }
73
+
74
+ /** 只报累计值(状态接口用,体积小)。 */
75
+ function snapshot() {
76
+ return { since: state.since, sentBytes: state.sentBytes, receivedBytes: state.receivedBytes }
77
+ }
78
+
79
+ /** 累计快照序列(面板画曲线用,最多 HISTORY_POINTS 个点)。 */
80
+ function series() {
81
+ return state.samples.map((item) => ({ at: item.at, sentBytes: item.sentBytes, receivedBytes: item.receivedBytes }))
82
+ }
83
+
84
+ module.exports = { noteSent, noteReceived, countReadable, snapshot, series, HISTORY_POINTS, SAMPLE_INTERVAL_MS }
@@ -0,0 +1,103 @@
1
+ // 远程网页的过渡页:桌面窗口先有内容,隧道建好后再跳到真实页面,不再是一段空白。
2
+ // 与租期提示同一套语言判定;只读、自带内联脚本,不依赖远端。
3
+ 'use strict';
4
+
5
+ /** 每种语言五句:连接中 / 连接失败 / 已到期 / 授权失效 / 重试。 */
6
+ const TEXT = {
7
+ 'zh-Hans': ['正在连接远程电脑…', '连接不上远程电脑,请检查网络或对方是否在线。', '本次访问已到期,请返回本机插件重新打开。', '访问授权已失效,请重新绑定这台电脑。', '重试'],
8
+ 'zh-Hant': ['正在連線遠端電腦…', '連線不上遠端電腦,請檢查網路或對方是否在線。', '本次存取已到期,請返回本機外掛重新開啟。', '存取授權已失效,請重新綁定這台電腦。', '重試'],
9
+ en: ['Connecting to the remote computer…', 'Cannot connect to the remote computer. Check your network or whether the other computer is online.', 'This visit has expired. Return to the local plugin to open it again.', 'Access is invalid or revoked. Pair this computer again.', 'Retry'],
10
+ ja: ['リモートパソコンに接続しています…', 'リモートパソコンに接続できません。ネットワークか相手のパソコンがオンラインか確認してください。', 'アクセス期限が切れました。このパソコンのローカルプラグインから開き直してください。', 'アクセス権が無効か取り消されています。再登録してください。', '再試行'],
11
+ ko: ['원격 컴퓨터에 연결하는 중…', '원격 컴퓨터에 연결할 수 없습니다. 네트워크나 상대 컴퓨터가 켜져 있는지 확인하세요.', '접속이 만료되었습니다. 이 컴퓨터의 로컬 플러그인에서 다시 열어 주세요.', '접속 권한이 유효하지 않거나 취소되었습니다. 다시 연결 등록하세요.', '다시 시도'],
12
+ de: ['Verbindung zum entfernten Computer wird hergestellt …', 'Verbindung zum entfernten Computer nicht möglich. Prüfe das Netzwerk oder ob der andere Computer online ist.', 'Dieser Zugriff ist abgelaufen. Öffne ihn im lokalen Plugin erneut.', 'Zugriff ungültig oder widerrufen. Kopple diesen Computer erneut.', 'Erneut versuchen'],
13
+ es: ['Conectando con el ordenador remoto…', 'No se puede conectar al ordenador remoto. Comprueba tu red o si el otro ordenador está en línea.', 'Este acceso ha caducado. Vuelve al complemento local para abrirlo de nuevo.', 'Acceso no válido o revocado. Vincula este ordenador de nuevo.', 'Reintentar'],
14
+ fr: ['Connexion à l’ordinateur distant…', 'Connexion à l’ordinateur distant impossible. Vérifiez votre réseau ou si l’autre ordinateur est en ligne.', 'Cet accès a expiré. Revenez au plugin local pour le rouvrir.', 'Accès invalide ou révoqué. Associez cet ordinateur à nouveau.', 'Réessayer'],
15
+ pt: ['Conectando ao computador remoto…', 'Não foi possível conectar ao computador remoto. Verifique sua rede ou se o outro computador está online.', 'Este acesso expirou. Volte ao plugin local para abrir novamente.', 'Acesso inválido ou revogado. Vincule este computador novamente.', 'Tentar novamente'],
16
+ ru: ['Подключение к удалённому компьютеру…', 'Не удаётся подключиться к удалённому компьютеру. Проверьте сеть или включён ли другой компьютер.', 'Срок доступа истёк. Откройте его заново в локальном плагине.', 'Доступ недействителен или отозван. Подключите этот компьютер заново.', 'Повторить'],
17
+ };
18
+
19
+ /** 就绪探测路径与「已就绪」跳转标记,网关两侧共用。 */
20
+ const READY_PATH = '/__dsh_remote_ready';
21
+ const READY_PARAM = '__dsh_ready';
22
+
23
+ const PAGE_CSS = `
24
+ html, body { height: 100%; margin: 0; }
25
+ body {
26
+ display: flex; align-items: center; justify-content: center;
27
+ background: Canvas; color: CanvasText;
28
+ font: 14px/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif;
29
+ }
30
+ #box { display: flex; flex-direction: column; align-items: center; gap: 14px; padding: 24px; text-align: center; max-width: 360px; }
31
+ #spinner {
32
+ width: 28px; height: 28px; box-sizing: border-box;
33
+ border: 2.5px solid rgba(128, 128, 128, .3);
34
+ border-top-color: rgba(128, 128, 128, .9); border-radius: 50%;
35
+ animation: dshm-spin .9s linear infinite;
36
+ }
37
+ #spinner[hidden] { display: none; }
38
+ #msg { margin: 0; }
39
+ #retry {
40
+ font: inherit; padding: 6px 16px; border-radius: 8px; cursor: pointer;
41
+ border: .5px solid rgba(128, 128, 128, .45);
42
+ background: transparent; color: inherit;
43
+ }
44
+ #retry[hidden] { display: none; }
45
+ @keyframes dshm-spin { to { transform: rotate(360deg); } }
46
+ @media (prefers-reduced-motion: reduce) { #spinner { animation-duration: 2.5s; } }
47
+ `;
48
+
49
+ /** 生成过渡页 HTML:先转圈,fetch 就绪探测,成功后跳到真实页面,失败则提示并给重试。 */
50
+ function loadingPageHtml() {
51
+ return `<!doctype html>
52
+ <html><head><meta charset="utf-8">
53
+ <meta name="viewport" content="width=device-width, initial-scale=1">
54
+ <title>DSH</title>
55
+ <style>${PAGE_CSS}</style>
56
+ </head><body>
57
+ <div id="box">
58
+ <div id="spinner" aria-hidden="true"></div>
59
+ <p id="msg" role="status" aria-live="polite"></p>
60
+ <button id="retry" type="button" hidden></button>
61
+ </div>
62
+ <script>
63
+ (function () {
64
+ var TEXT = ${JSON.stringify(TEXT)};
65
+ function language() {
66
+ var tag = String(navigator.language || 'en').replace(/_/g, '-').toLowerCase();
67
+ var parts = tag.split('-');
68
+ if (parts[0] === 'zh') return parts.some(function (p) { return ['hant', 'tw', 'hk', 'mo'].indexOf(p) >= 0; }) ? 'zh-Hant' : 'zh-Hans';
69
+ return TEXT[parts[0]] ? parts[0] : 'en';
70
+ }
71
+ var T = TEXT[language()] || TEXT.en;
72
+ var msg = document.getElementById('msg');
73
+ var retry = document.getElementById('retry');
74
+ var spinner = document.getElementById('spinner');
75
+ msg.textContent = T[0];
76
+ retry.textContent = T[4];
77
+ var settled = false;
78
+ retry.addEventListener('click', function () { location.replace('/'); });
79
+ function fail(code) {
80
+ if (settled) return;
81
+ settled = true;
82
+ spinner.hidden = true;
83
+ var index = code === 'REMOTE_EXPIRED' ? 2
84
+ : (code === 'REMOTE_REVOKED' || code === 'REMOTE_AUTH' || code === 'REMOTE_VERSION') ? 3 : 1;
85
+ msg.textContent = T[index];
86
+ retry.hidden = false;
87
+ }
88
+ var controller = new AbortController();
89
+ var timer = setTimeout(function () { controller.abort(); fail('REMOTE_TIMEOUT'); }, 45000);
90
+ fetch(${JSON.stringify(READY_PATH)}, { credentials: 'same-origin', cache: 'no-store', headers: { accept: 'application/json' }, signal: controller.signal })
91
+ .then(function (res) { return res.json(); })
92
+ .then(function (data) {
93
+ clearTimeout(timer);
94
+ if (data && data.ok) { settled = true; location.replace('/?${READY_PARAM}=1'); }
95
+ else fail(data && data.code);
96
+ })
97
+ .catch(function () { clearTimeout(timer); fail('REMOTE_CONNECT'); });
98
+ })();
99
+ </script>
100
+ </body></html>`;
101
+ }
102
+
103
+ module.exports = { loadingPageHtml, READY_PATH, READY_PARAM };
@@ -1,4 +1,5 @@
1
1
  // 远程网页的加密上游:共享一条 keep-alive 池复用加密流,WebSocket 单独一条;仅宿主会话存内存。
2
+ // 2026-11-23:对外补 prime / isReady,供过渡页在真实页面之前先把首条加密流建好。
2
3
  'use strict';
3
4
 
4
5
  const http = require('node:http');
@@ -186,7 +187,13 @@ function createUpstream({ connect, active, live, origin, expiresAt, noticeTransf
186
187
  } catch (error) { onError(error); conn?.stream.destroy(); socket.destroy(); }
187
188
  }
188
189
 
189
- return { forward, upgrade, close() { jar.clear(); identity = ''; host = null; resetPool(); } };
190
+ // 是否已建立并认证好上游:过渡页据它决定要不要先出一屏内容。
191
+ function isReady() { return Boolean(host) && Boolean(identity) && identity === `${host.port}:${host.token}`; }
192
+
193
+ // 主动把首条加密流建好(认证也一并完成),供过渡页的就绪探测调用;失败原样抛出。
194
+ async function prime() { await cookies(); }
195
+
196
+ return { forward, upgrade, prime, isReady, close() { jar.clear(); identity = ''; host = null; resetPool(); } };
190
197
  }
191
198
 
192
199
  module.exports = { createUpstream };
@@ -2,6 +2,7 @@
2
2
  // 每台网关各管各的租期;续期只延长期限,不重发入口地址、不动已建立的连接。
3
3
  // 壳会话另发一枚只读标记:只给桌面窗口启用官方自带的让位与拖动排版。
4
4
  // 2026-11-19:重签入口时保留还没被用过的一次性 ticket,避免第二个窗口的入口把先开窗口的入口覆盖掉。
5
+ // 2026-11-23:主文档首次打开先回一屏过渡页,等隧道建好再跳真实页面,桌面窗口不再空等一片白。
5
6
  'use strict';
6
7
 
7
8
  const http = require('node:http');
@@ -9,6 +10,7 @@ const crypto = require('node:crypto');
9
10
  const { sameOrigin, cookieOf, requestPath } = require('./local-headers.cjs');
10
11
  const { createUpstream } = require('./local-upstream.cjs');
11
12
  const { noticeScript, createNoticeTransform } = require('./browser-notice.cjs');
13
+ const { loadingPageHtml, READY_PATH, READY_PARAM } = require('./loading-page.cjs');
12
14
 
13
15
  const LEASE_MS = 60 * 60 * 1000;
14
16
  const OPEN_MS = 60 * 1000;
@@ -19,6 +21,15 @@ const RENEW_CHECK_MS = 30 * 1000;
19
21
  const ATTACH_GRACE_MS = 4 * 1000;
20
22
  const OPEN_PATH = '/__dsh_remote_open';
21
23
 
24
+ // 顶层文档导航才出过渡页:优先看 Fetch Metadata,缺头时退回 Accept 是否要 HTML。
25
+ // 普通子资源(脚本 / 图片 / 接口)与测试里只带 cookie 的请求都不满足,照常直接转发。
26
+ function wantsDocument(req) {
27
+ if (req.method !== 'GET') return false;
28
+ const dest = req.headers['sec-fetch-dest'];
29
+ if (dest) return dest === 'document';
30
+ return String(req.headers.accept || '').includes('text/html');
31
+ }
32
+
22
33
  function createLocalGateway({ connect, expiresAt, now = Date.now, onExpire = () => {}, onError, onRenew = () => {}, platform = process.platform }) {
23
34
  const live = new Set();
24
35
  const cookieName = `dsh_remote_${crypto.randomBytes(12).toString('hex')}`;
@@ -66,7 +77,7 @@ function createLocalGateway({ connect, expiresAt, now = Date.now, onExpire = ()
66
77
  res.end(text);
67
78
  }
68
79
 
69
- function handle(req, res) {
80
+ async function handle(req, res) {
70
81
  const path = requestPath(req.url);
71
82
  if (!path || !active()) return reply(res, 410, '本次访问已到期,请在本机面板重新打开。');
72
83
  const url = new URL(path, origin());
@@ -95,7 +106,35 @@ function createLocalGateway({ connect, expiresAt, now = Date.now, onExpire = ()
95
106
  const shell = cookieOf(req.headers.cookie, shellCookie) === '1';
96
107
  res.end(noticeScript({ shell, platform })); return;
97
108
  }
98
- req.url = path;
109
+ // 过渡页的就绪探测:这里才真正建起加密流,成不成如实回给页面。
110
+ if (url.pathname === READY_PATH) {
111
+ if (req.method !== 'GET') return reply(res, 405, '只读入口。');
112
+ const type = 'application/json; charset=utf-8';
113
+ try {
114
+ await upstream.prime();
115
+ if (closed || res.destroyed) return;
116
+ res.writeHead(200, { 'content-type': type, 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' });
117
+ res.end(JSON.stringify({ ok: true, expiresAt: deadline }));
118
+ } catch (error) {
119
+ if (closed || res.destroyed) return;
120
+ res.writeHead(200, { 'content-type': type, 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' });
121
+ res.end(JSON.stringify({ ok: false, code: error?.code || 'REMOTE_CONNECT' }));
122
+ }
123
+ return;
124
+ }
125
+ // 顶层文档还没建好隧道时先给过渡页,别让桌面窗口空等一片白。
126
+ if (url.pathname === '/' && wantsDocument(req) && !url.searchParams.has(READY_PARAM) && !upstream.isReady()) {
127
+ res.writeHead(200, {
128
+ 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store',
129
+ 'referrer-policy': 'no-referrer', 'x-content-type-options': 'nosniff',
130
+ });
131
+ res.end(loadingPageHtml()); return;
132
+ }
133
+ // 过渡页跳转带来的内部标记不转给远端。
134
+ if (url.searchParams.has(READY_PARAM)) {
135
+ url.searchParams.delete(READY_PARAM);
136
+ req.url = url.pathname + url.search;
137
+ } else req.url = path;
99
138
  void upstream.forward(req, res);
100
139
  }
101
140
 
@@ -25,6 +25,7 @@ const { pairingText } = require('../relay/pairing-payload.cjs');
25
25
  const { randomBytes } = require('node:crypto');
26
26
 
27
27
  const core = require('../relay/core.js');
28
+ const traffic = require('../relay/traffic-stats.cjs');
28
29
  const pairingApproval = require('../relay/pairing-policy.js');
29
30
  // 端口自检用的是局域网代理**同一把探针**(见 `../relay/port-allocator.cjs` 的文件头):
30
31
  // 这里说「可用」,真正 listen 时就不会 EADDRINUSE,两边不会各说各话。
@@ -627,6 +628,8 @@ function registerControlPlaneRoutes(deps) {
627
628
  }
628
629
  }
629
630
  registerRoute({ kind: 'exact', path: '/api/relay/status', handler: localOnly('GET', async (req, res) => sendJson(res, 200, { ...status(), shellChanged: shellChangedNow(), tailcat: deps.tailcat && typeof deps.tailcat.status === 'function' ? deps.tailcat.status() : null, frp: deps.frp && typeof deps.frp.status === 'function' ? deps.frp.status() : null, cloudflare: deps.cloudflare && typeof deps.cloudflare.status === 'function' ? deps.cloudflare.status() : null, zeroNews: deps.zeroNews && typeof deps.zeroNews.status === 'function' ? deps.zeroNews.status() : null, panelUrl: panelUrlOf(req), panelScope: panelScopeOf(req), devices: deviceSummary(), ...mobileActivity(), selfCheck: selfCheck.snapshot() })) })
631
+ // 面板流速图的数据源:累计值 + 最近每秒快照序列(只读本机内存,重启进程即清零)。
632
+ registerRoute({ kind: 'exact', path: '/api/relay/traffic', handler: localOnly('GET', async (_req, res) => sendJson(res, 200, { ...traffic.snapshot(), samples: traffic.series() })) })
630
633
 
631
634
  // ── 手机直连隧道(Tailcat):面板查看与管理 ────────────────────────────────
632
635
  //
@@ -790,6 +793,21 @@ function registerControlPlaneRoutes(deps) {
790
793
  sendJson(res, 200, result)
791
794
  }) })
792
795
 
796
+ // ── ZeroNews 账号快照:面板那块服务商主页的「概览 / 隧道 / 设备」数据 ──────────────
797
+ // 只读:跑本机客户端的 status 与 show 三张清单,归一后交给面板。不建隧道、不碰账号、不写配置。
798
+ // 读失败也按 200 回、用 ok / available / error 三格如实说明,别把「没装客户端」伪装成接口坏了。
799
+ registerRoute({ kind: 'exact', path: '/api/relay/zeronews/account', handler: localOnly('GET', async (_req, res) => {
800
+ if (!deps.zeroNews || typeof deps.zeroNews.account !== 'function') {
801
+ return sendJson(res, 200, { ok: false, available: false, error: '这台宿主没有接入 ZeroNews 线路能力' })
802
+ }
803
+ try {
804
+ const snapshot = await deps.zeroNews.account()
805
+ sendJson(res, 200, snapshot || { ok: false, available: false, error: '' })
806
+ } catch (err) {
807
+ sendJson(res, 200, { ok: false, available: false, error: err && err.message ? err.message : String(err) })
808
+ }
809
+ }) })
810
+
793
811
  // ── 节点小宝线路:本机设备端状态、绑定链接、手填线路地址 ──────────────────────
794
812
  // 它跟我们接入的其它线路不一样:设备端是以系统服务装进机器的,插件不启动也不管理它的进程,
795
813
  // 这里只读它的本地管理口(macOS 2080 / Linux 9118),把「装没装、绑没绑」如实交给面板。
@@ -1515,6 +1533,8 @@ const WEB_ACCESS_ROUTES = new Set([
1515
1533
  '/api/relay/probe-relays',
1516
1534
  '/api/relay/probe-direct',
1517
1535
  '/api/relay/status',
1536
+ // 面板流速图:只读的上下行累计与每秒快照,跟状态同档、只在本机面板里读。
1537
+ '/api/relay/traffic',
1518
1538
  '/api/relay/panel',
1519
1539
  '/api/relay/panel/setup',
1520
1540
  '/api/relay/panel/settings',
@@ -1545,6 +1565,7 @@ const WEB_ACCESS_ROUTES = new Set([
1545
1565
  '/api/cloudflare/stop',
1546
1566
  // ZeroNews 公网地址读取:localOnly 的本机只读路由,留在清单里保持盘点完整。
1547
1567
  '/api/relay/zeronews/endpoints',
1568
+ '/api/relay/zeronews/account',
1548
1569
  '/api/relay/zeronews/prepare',
1549
1570
  // ZeroNews 线路连接 / 断开:与其它管理动作一样不按来源拦,留在清单里保持盘点完整。
1550
1571
  '/api/relay/zeronews/connect',
@@ -18,6 +18,7 @@
18
18
  */
19
19
 
20
20
  const { sendJson } = require('../http/routing.js');
21
+ const traffic = require('../relay/traffic-stats.cjs');
21
22
  const { readJsonBody } = require('../shared/http-util.js');
22
23
  const { createP2PRendezvousHandler } = require('../p2p/rendezvous.cjs');
23
24
  const { orderCandidates, withManualCandidate, manualCandidate, withManualIpv4Candidate, withManualIpv6Candidate, tcpDirectTarget } = require('../relay/lan-network.cjs');
@@ -158,6 +159,42 @@ function profileNodeModulesOf(ctx) {
158
159
  }
159
160
  }
160
161
 
162
+ /**
163
+ * 手机↔本机流量记账(见 `../relay/traffic-stats.cjs`):一条移动路由请求进来多少字节、
164
+ * 回出去多少字节,都记到这条连接上。放在这里而不是各条转发路径:中转 / 局域网 / 直连隧道 /
165
+ * 点对点最后都落到同一批移动路由,记一处口径就统一了。只读不改——给 req 挂个旁听、
166
+ * 把 res 的 write/end 包一层照样转发。
167
+ */
168
+ const countMobileTraffic = (req, res) => {
169
+ if (req && typeof req.on === 'function') {
170
+ req.on('data', (chunk) => {
171
+ if (chunk && typeof chunk.length === 'number') traffic.noteReceived(chunk.length)
172
+ })
173
+ }
174
+ if (!res || typeof res.write !== 'function' || typeof res.end !== 'function') return
175
+ const originalWrite = res.write.bind(res)
176
+ const originalEnd = res.end.bind(res)
177
+ const note = (chunk) => {
178
+ if (!chunk) return
179
+ if (typeof chunk === 'string') traffic.noteSent(Buffer.byteLength(chunk))
180
+ else if (typeof chunk.length === 'number') traffic.noteSent(chunk.length)
181
+ }
182
+ res.write = (chunk, ...rest) => { note(chunk); return originalWrite(chunk, ...rest) }
183
+ res.end = (chunk, ...rest) => { note(chunk); return originalEnd(chunk, ...rest) }
184
+ }
185
+
186
+ /** 把一条已挂好的移动路由 handler 包上流量记账。原样透传全部实参:宿主按 `(req, res, peer)` 调,
187
+ * 路由层内部约定又是 `(ctx, req, res)`,截成 `(req, res)` 会丢掉 peer,也会把内部的 res 顶掉。 */
188
+ const withTraffic = (handler) => {
189
+ const wrapped = async (...args) => {
190
+ countMobileTraffic(args[0], args[1])
191
+ return handler(...args)
192
+ }
193
+ // 测试要能透过记账层认回原 handler:路由「指向哪个实现」的引用相等契约不该被装饰器弄没。
194
+ wrapped.innerHandler = handler
195
+ return wrapped
196
+ }
197
+
161
198
  function registerMobileRoutes(deps) {
162
199
  const { registerRoute: registerRouteRaw, registerUpgradeRoute: registerUpgradeRouteRaw, tailcat, p2p, guarded, state, getControl, hostMetadata, getSidecarSnapshot, safeLanCandidates, safeIpv6Candidates, lanPortInUse, mux = { handleUpgrade: () => {} }, preview, core, pairingApproval, rotatePairing, getHistoryKey, credentials, dropDeviceStreams } = deps;
163
200
  /**
@@ -167,7 +204,7 @@ function registerMobileRoutes(deps) {
167
204
  * `/api/relay/*` 不经过本函数,仍保持要求桌面会话。
168
205
  */
169
206
  const anonymousRoute = (route) => (route && route.auth === undefined ? { ...route, auth: 'anonymous' } : route)
170
- const registerRoute = (route) => registerRouteRaw(anonymousRoute(route))
207
+ const registerRoute = (route) => registerRouteRaw(anonymousRoute(route && typeof route.handler === 'function' ? { ...route, handler: withTraffic(route.handler) } : route))
171
208
  const registerUpgradeRoute = typeof registerUpgradeRouteRaw === 'function'
172
209
  ? (route) => registerUpgradeRouteRaw(anonymousRoute(route))
173
210
  : registerUpgradeRouteRaw
@@ -961,4 +998,4 @@ function registerMobileRoutes(deps) {
961
998
 
962
999
  }
963
1000
 
964
- module.exports = { registerMobileRoutes };
1001
+ module.exports = { registerMobileRoutes, withTraffic };