dsh-mobile-plugin 0.5.47 → 0.5.49

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.
@@ -47,6 +47,10 @@ const WS_UPSTREAM_PENDING_MAX_BYTES = 32 * 1024 * 1024;
47
47
  // 不该碰到它。
48
48
  const MAX_UPSTREAM_SSE_CONNECTIONS = 64;
49
49
 
50
+ // 局域网配对请求体的线上上限:配对体只有码 + 设备元信息(与宿主那条 `/pair` 同档),
51
+ // 24KB 已经很宽。这条入口未认证,超限立即断开,不能先攒满整个 body 再谈限流。
52
+ const LAN_PAIR_MAX_BODY = 24 * 1024;
53
+
50
54
  function createLanProxy(opts) {
51
55
  const {
52
56
  lanPort,
@@ -581,8 +585,24 @@ function createLanProxy(opts) {
581
585
  return;
582
586
  }
583
587
  let b = '';
584
- req.on('data', (c) => (b += c));
588
+ let tooLarge = false;
589
+ req.on('data', (c) => {
590
+ if (tooLarge) return;
591
+ b += c;
592
+ if (b.length > LAN_PAIR_MAX_BODY) {
593
+ // 未认证入口:body 无上限的话,任何人先灌满内存才轮到限流与解析。
594
+ // 超限当场回 413 并断开,不再进限流与 JSON 解析。
595
+ tooLarge = true;
596
+ try {
597
+ res.writeHead(413, { 'content-type': 'application/json', connection: 'close' });
598
+ res.end(JSON.stringify({ ok: false, error: '请求体过大' }), () => req.destroy());
599
+ } catch {
600
+ req.destroy();
601
+ }
602
+ }
603
+ });
585
604
  req.on('end', () => {
605
+ if (tooLarge) return;
586
606
  try {
587
607
  const gate = pairThrottle.take();
588
608
  if (!gate.allowed) {
@@ -668,7 +688,10 @@ function createLanProxy(opts) {
668
688
  // 权限位按电脑侧档位展开,与中转那条配对入口同一口径。
669
689
  return Promise.resolve(issueCredential(device, { ...(issuedExtra || {}), permissions: permissions.permissionsForTier(pairingTier) })).then((issued) => {
670
690
  const credentialValue = issued.credential;
671
- setCookie(res, credentialValue);
691
+ // 只有明文老路才用 Set-Cookie 下发凭据;协议 v2 的加密回包已经把
692
+ // token / cookie 放进密文 body,再加一条明文 Set-Cookie 等于把一枚
693
+ // 一年期凭据从响应头漏出去。
694
+ if (!pairKey) setCookie(res, credentialValue);
672
695
  // 配对成功即换码 + 换票据(§5.1)。谁截了二维码,那张图从这一刻起就作废。
673
696
  if (typeof onPaired === 'function') {
674
697
  try { onPaired(); } catch (error) { log('rotate pair failed:', error && error.message); }
@@ -123,6 +123,8 @@ function generationVersion() {
123
123
 
124
124
  /** 按 mtime 缓存:文件被换掉之后内容变了,缓存自然失效,不必手工清。 */
125
125
  let panelCache = { file: '', mtime: -1, html: '' };
126
+ /** 上面那一份产物的 ETag,与 `panelCache` 同一份身份(同样是 mtime)。 */
127
+ let panelEtag = { file: '', mtime: -1, value: '' };
126
128
 
127
129
  function panelHtml() {
128
130
  try {
@@ -235,6 +237,30 @@ function panelScopeOf(req) {
235
237
  return 'public';
236
238
  }
237
239
 
240
+ /**
241
+ * 开 / 关网页管理窗口这条只认「Host 是地址字面量」的来源。
242
+ *
243
+ * 2026-11-02 把这条放宽到只要求 `localOnly`(同源、无中转凭据),好让公网 / 局域网部署的人
244
+ * 在自己的浏览器里点图标也能开窗口;但那把 DNS 重绑定这个口子留了下来:重绑定页面用的
245
+ * origin 与 Host 都是攻击者那个域名(浏览器把 Host 填成域名、连接却落到本机),`localOnly`
246
+ * 的同源判断认不出,任意网页就能自己把两小时管理窗口打开。
247
+ *
248
+ * 判据收窄成「Host 必须是 IP 字面量或 localhost」:重绑定页面**必然**带一个域名 Host,直接被
249
+ * 挡;正常直连——回环、局域网 IP、公网 IP、localhost——照旧能开。经域名反代访问的机器后端分
250
+ * 不出原始客户端(与 `trustedLocalUi` 对代理的取舍一致),这种部署不再支持用它开窗口。
251
+ */
252
+ function webAccessHostTrusted(req) {
253
+ const host = typeof req?.headers?.host === 'string' ? req.headers.host : '';
254
+ if (!host) return false;
255
+ let hostname = '';
256
+ try {
257
+ hostname = new URL(`http://${host}`).hostname.toLowerCase().replace(/^\[|\]$/g, '');
258
+ } catch {
259
+ return false;
260
+ }
261
+ return hostname === 'localhost' || net.isIP(hostname) !== 0;
262
+ }
263
+
238
264
  /**
239
265
  * @param {object} deps 见 `lib/impl.js` 里 registerControlPlaneRoutes({...}) 的调用点
240
266
  */
@@ -246,6 +272,7 @@ function registerControlPlaneRoutes(deps) {
246
272
  readJson,
247
273
  sendJson,
248
274
  sendHtml,
275
+ htmlEtag,
249
276
  state,
250
277
  sidecarToken,
251
278
  status,
@@ -463,13 +490,13 @@ function registerControlPlaneRoutes(deps) {
463
490
  }) })
464
491
  // 只有可信本机设置入口可以开 / 关窗口;窗口状态仅驻留进程内,DSH 重启后必定关闭。
465
492
  registerRoute({ kind: 'exact', path: '/api/relay/web-access', handler: localOnly('POST', async (req, res) => {
466
- // 谁来按这个开关(2026-11-02 用户拍板放宽,取代原先「只认可信本机设置页」)。
467
- //
468
- // 侧边栏那颗手机图标成为进网页的唯一入口之后,公网 / 局域网部署的人就是在自己的浏览器里
469
- // 点它 —— 那时 socket 对端与 Host 都不是回环,按老判据会 403,于是谁也没法把窗口打开,
470
- // 面板永远回 423。现在只要求 `localOnly` 已经保证的那一层:同源、不带中转凭据、不经本机
471
- // 代理转发。能发出这条请求的只有 DSH 自己页面里的代码,而「人在 DSH 界面里按下了这个
472
- // 按钮」正是这个窗口存在的理由。跨站页面、中转与局域网代理转进来的请求仍在 localOnly 挡掉。
493
+ // 谁来按这个开关:只认「Host 是地址字面量」的本机直连,理由见 `webAccessHostTrusted`。
494
+ // 2026-11-02 一度只要求 `localOnly` 那一层,结果任意网页能靠 DNS 重绑定自己把窗口打开;
495
+ // 现在把 Host 收窄到 IP 字面量 / localhost —— 回环、局域网、公网 IP 直连照旧能开,重绑定
496
+ // 必带的域名 Host 被挡。跨站页面、带中转凭据、经本机代理转发的仍在 localOnly 挡掉。
497
+ if (!webAccessHostTrusted(req)) {
498
+ return sendJson(res, 403, { ok: false, error: { code: 'local_only', message: '开启网页管理窗口仅允许从本机地址访问' } });
499
+ }
473
500
  const body = await readJson(req);
474
501
  if (typeof body?.enabled !== 'boolean') {
475
502
  return sendJson(res, 400, { ok: false, error: { code: 'bad-request', message: 'enabled 必须是布尔值' } });
@@ -555,9 +582,16 @@ function registerControlPlaneRoutes(deps) {
555
582
  // /api/relay/panel/console 强制进控制台那一窗(桌面端那颗手机图标的第一屏,见 React/src/Console.tsx)
556
583
  // 整页 HTML 不需要 token,但这几条仍然走 localOnly —— 它读的是本机运维界面,
557
584
  // 而局域网与中转那两条链路本来就不该看到它(它们带 dsh_pair/dsh_lan 凭据,会被挡掉)。
558
- const servePanel = (res) => {
585
+ const servePanel = (req, res) => {
559
586
  const html = panelHtml();
560
- if (html) return sendHtml(res, 200, html);
587
+ // 校验符按「这一份产物」算一次就够(1.4MB 的 sha1 约 0.5ms):拿 mtime 当身份,
588
+ // 与上面那份缓存同一口径 —— 文件被换掉才重算,不是每个请求都白算一遍。
589
+ if (html) {
590
+ if (panelEtag.mtime !== panelCache.mtime || panelEtag.file !== PANEL_FILE) {
591
+ panelEtag = { file: PANEL_FILE, mtime: panelCache.mtime, value: htmlEtag(html) };
592
+ }
593
+ return sendHtml(res, 200, html, req, panelEtag.value);
594
+ }
561
595
  // 读不到就别只说「还没构建」:装进来的包几乎从不是这个原因,而是「装完没重启」或
562
596
  // 「装了老版本」(见 panelDiagnosis 的注释)。原因也写进宿主 stderr —— 页面上的
563
597
  // JSON 只有点开那个人看得见,而这类故障通常是在别人的机器上被报出来的。
@@ -568,19 +602,19 @@ function registerControlPlaneRoutes(deps) {
568
602
  // 三条面板页是「人点开的一页」:社区桌面壳会把自己接住的链接原地打开,从自定义协议
569
603
  // 页跳过来必带 `sec-fetch-site: cross-site`,不放开这一种形态,用户看到的就是整屏
570
604
  // 一句 403 JSON(见 `lib/http/routing.js` 的 `documentNavigation`)。
571
- registerRoute({ kind: 'exact', path: '/api/relay/panel', handler: localOnly('GET', async (_req, res) => servePanel(res), { allowDocumentNavigation: true }) })
572
- registerRoute({ kind: 'exact', path: '/api/relay/panel/setup', handler: localOnly('GET', async (_req, res) => servePanel(res), { allowDocumentNavigation: true }) })
573
- registerRoute({ kind: 'exact', path: '/api/relay/panel/settings', handler: localOnly('GET', async (_req, res) => servePanel(res), { allowDocumentNavigation: true }) })
605
+ registerRoute({ kind: 'exact', path: '/api/relay/panel', handler: localOnly('GET', async (req, res) => servePanel(req, res), { allowDocumentNavigation: true }) })
606
+ registerRoute({ kind: 'exact', path: '/api/relay/panel/setup', handler: localOnly('GET', async (req, res) => servePanel(req, res), { allowDocumentNavigation: true }) })
607
+ registerRoute({ kind: 'exact', path: '/api/relay/panel/settings', handler: localOnly('GET', async (req, res) => servePanel(req, res), { allowDocumentNavigation: true }) })
574
608
  // 调试页与上面几条吐同一份 HTML,分流同样在 React 侧(`React/src/Root.tsx` 认 `/debug`)。
575
609
  //
576
610
  // 为什么它也放开 `allowDocumentNavigation`:这一页唯一的入口是桌面端那颗手机图标弹的窗
577
611
  // (同源 iframe),而社区桌面壳会把接住的链接原地打开、从自定义协议页跳过来必带
578
612
  // `sec-fetch-site: cross-site` —— 与面板页同一条理由。页面本身仍是只读 HTML,
579
613
  // 里面的 fetch 照样被 localOnly 与两小时窗口挡着。
580
- registerRoute({ kind: 'exact', path: '/api/relay/panel/debug', handler: localOnly('GET', async (_req, res) => servePanel(res), { allowDocumentNavigation: true }) })
614
+ registerRoute({ kind: 'exact', path: '/api/relay/panel/debug', handler: localOnly('GET', async (req, res) => servePanel(req, res), { allowDocumentNavigation: true }) })
581
615
  // 控制台那一窗(点手机图标进来的第一屏)与上面几条吐同一份 HTML,分流同样在 React 侧。
582
616
  // 它同样放开 `allowDocumentNavigation`:入口就是桌面端弹的那一窗(同源 iframe)。
583
- registerRoute({ kind: 'exact', path: '/api/relay/panel/console', handler: localOnly('GET', async (_req, res) => servePanel(res), { allowDocumentNavigation: true }) })
617
+ registerRoute({ kind: 'exact', path: '/api/relay/panel/console', handler: localOnly('GET', async (req, res) => servePanel(req, res), { allowDocumentNavigation: true }) })
584
618
  // 手机端「已读回执」的下发口:客户端半边每 2s GET 一次,拿 sessionId → readAt 水位,
585
619
  // 对水位前进过的会话在桌面页面里就地清掉 completionUnread(见 lib/client.js)。
586
620
  // 台账由 /api/mobile/v1/session/read 写(lib/mobile/session-send.js)。
@@ -752,7 +786,9 @@ function registerControlPlaneRoutes(deps) {
752
786
  sendJson(res, 200, status())
753
787
  }) })
754
788
  registerRoute({ kind: 'exact', path: '/api/relay/regenerate', handler: localOnly('POST', async (_req, res) => {
755
- state.pairingCode = core.genPairingCode()
789
+ // 换码的同时必须换票据(`core.rotatePairing` 一次换两格):只换码不换票据,截图里那张
790
+ // 二维码的票据还能再配一台;只换票据不换码,旧码在旧形状那条路上还能用。
791
+ core.rotatePairing(state)
756
792
  core.saveState(state)
757
793
  await syncSidecar().catch(() => undefined)
758
794
  sendJson(res, 200, status())
@@ -850,7 +886,9 @@ function registerControlPlaneRoutes(deps) {
850
886
  } catch { /* 中转不可达时仍继续吊销本机凭据与密钥 */ }
851
887
  const localRevoked = credentials.revokeAllByInstance(state.instanceId)
852
888
  state.lanSecret = randomBytes(32).toString('hex')
853
- state.pairingCode = core.genPairingCode()
889
+ // 恢复全部授权也要把二维码那枚票据一起换掉(`core.rotatePairing` 一次换码换票):
890
+ // 只换 pairingCode 的话,截图里那张旧二维码的票据仍能配出新设备。
891
+ core.rotatePairing(state)
854
892
  core.saveState(state)
855
893
  await syncSidecar().catch(() => undefined)
856
894
  sendJson(res, 200, { ok: true, revoked: revoked + localRevoked, revokedRelay: revoked, revokedLocal: localRevoked, ...status() })
@@ -28,6 +28,7 @@ const sessionFile = require('../mobile/session-file.js');
28
28
  const sessionArtifacts = require('../mobile/session-artifacts.js');
29
29
  const sessionLocalImage = require('../mobile/session-local-image.js');
30
30
  const sessionStep = require('../mobile/session-step.js');
31
+ const sessionChanges = require('../mobile/session-changes.js');
31
32
  // 停止后那份「本轮交代」:从这一轮的步骤流折成展示结构(见 mobile/session-stop-summary.js)。
32
33
  // 只读步骤流、只算纯展示数据,不碰 shell / 系统设置 / 任意文件写。
33
34
  const sessionStopSummary = require('../mobile/session-stop-summary.js');
@@ -60,6 +61,10 @@ const skillWrite = require('../mobile/skill-write.js');
60
61
  // 「项目写入暂停」的对外开关(见 mobile/project-writes.js):右栏文件浏览器的工具栏读它 / 切它。
61
62
  const projectWrites = require('../mobile/project-writes.js');
62
63
  const mobileCredentials = require('../mobile/credentials.js');
64
+ // 「这台电脑上还连着哪些手机」:只读清单 + 单台吊销,见 mobile/paired-devices.js。
65
+ const pairedDevices = require('../mobile/paired-devices.js');
66
+ // 「把这一轮的回答落成文件」:带正文落盘,落点与三条写路由同一份允许区,见 mobile/session-write-body.js。
67
+ const sessionWriteBody = require('../mobile/session-write-body.js');
63
68
  const subagents = require('../mobile/subagents.js');
64
69
  const monitor = require('../mobile/monitor.js');
65
70
  const references = require('../mobile/references.js');
@@ -148,7 +153,7 @@ function profileNodeModulesOf(ctx) {
148
153
  }
149
154
 
150
155
  function registerMobileRoutes(deps) {
151
- const { registerRoute, tailcat, p2p, registerUpgradeRoute, guarded, state, hostMetadata, getSidecarSnapshot, safeLanCandidates, safeIpv6Candidates, lanPortInUse, preview, core, pairingApproval, rotatePairing, getHistoryKey } = deps;
156
+ const { registerRoute, tailcat, p2p, registerUpgradeRoute, guarded, state, hostMetadata, getSidecarSnapshot, safeLanCandidates, safeIpv6Candidates, lanPortInUse, preview, core, pairingApproval, rotatePairing, getHistoryKey, credentials, dropDeviceStreams } = deps;
152
157
  const route = (path, handler) => registerRoute({ kind: 'exact', path, handler: guarded(handler) })
153
158
  // 中转配置那一组要**装配期已有的实例**(config store、sidecar 生命周期),不能靠模块级
154
159
  // 单例去拿:同一进程里两份 relay.json 的真值只会打架。所以这里按装配层给的依赖建一次。
@@ -172,7 +177,7 @@ function registerMobileRoutes(deps) {
172
177
  log: (...args) => console.warn('[dsh-mobile-plugin] [sync]', ...args),
173
178
  })
174
179
 
175
- registerRoute({ kind: 'exact', path: '/api/mobile/v1/status', handler: guarded(async (ctx, _req, res) => {
180
+ registerRoute({ kind: 'exact', path: '/api/mobile/v1/status', handler: guarded(async (ctx, req, res) => {
176
181
  // 内存 `state` 是本进程唯一的真值。旧实现这里 `loadRelayState()` 重新读盘,
177
182
  // 于是同一份状态出现两个来源:控制面改完内存立刻返回,而移动端读到的还是
178
183
  // 上一次落盘的内容(多实例/慢盘时甚至永久不一致)。
@@ -226,6 +231,12 @@ function registerMobileRoutes(deps) {
226
231
  // 会话号,读不到 `/session/stats` 的 `agentTeam` 投影;没有它的话,用户一点「新对话」
227
232
  // 那个开关就凭空消失、进了会话才冒出来,看着像坏了。
228
233
  teamAvailable: sessionTeam.hasAgentTeams(ctx),
234
+ // 这台设备**出示的那枚凭据**还能用多久(授权于 / 最近一次续期 / 一直没连会在哪天失效)。
235
+ //
236
+ // 必须按出示的凭据现算:续期是宿主把记录上的到期时刻往后推,手机上那份
237
+ // `credentialExpiresAt` 只在配对 / 升级时写过一次,靠它永远读不出「最近续过没有」。
238
+ // 查不到记录(升级前的无状态通行证)就是 null,手机那边退回会话里存的那一格。
239
+ credential: pairedDevices.credentialTimingFor(credentials, state.instanceId || '', req),
229
240
  })
230
241
  }) })
231
242
  // 地址体检:手机在**配对之前**就要问「这个地址上到底是谁」,那时它手上没有任何
@@ -407,6 +418,7 @@ function registerMobileRoutes(deps) {
407
418
  route('/api/mobile/v1/session/messages', sessions.handleMessages)
408
419
  // 一步的过程详情:清单只带一行摘要,点开某一步才来这里取参数 / 输出 / diff / 思考全文。
409
420
  route('/api/mobile/v1/session/step', sessionStep.handleSessionStep)
421
+ route('/api/mobile/v1/session/changes', sessionChanges.handleSessionChanges)
410
422
  // 停止交代:用户按停止后那张「已停止 · 本轮交代」卡的数据源。直播副本优先,没有就走
411
423
  // 历史最近一轮的 turnProcess.steps。**只读**,取不到回空交代(App 不出卡,不当报错)。
412
424
  route('/api/mobile/v1/session/stop-summary', sessionStopSummary.handleStopSummary)
@@ -581,6 +593,29 @@ function registerMobileRoutes(deps) {
581
593
  route('/api/mobile/v1/credentials', mobileCredentials.handleCredentialsDescribe)
582
594
  route('/api/mobile/v1/credentials/set', mobileCredentials.handleCredentialsSet)
583
595
  route('/api/mobile/v1/credentials/unset', mobileCredentials.handleCredentialsUnset)
596
+ // 「这台电脑上还连着哪些手机」:一读一写。控制面 `/api/relay/devices` 只认本机,手机打不到,
597
+ // 而手机此前也只能看到自己这一台;见 mobile/paired-devices.js。store 取本进程的凭据库,
598
+ // dropDeviceStreams 收掉被吊销设备在途的 SSE(token 换了只挡下一次请求,开着的流不会自己停)。
599
+ route('/api/mobile/v1/paired-devices', (ctx, req, res) => pairedDevices.handlePairedDevices(req, res, {
600
+ store: credentials,
601
+ instanceId: state.instanceId || '',
602
+ }))
603
+ route('/api/mobile/v1/paired-devices/revoke', (ctx, req, res) => pairedDevices.handlePairedDevicesRevoke(req, res, {
604
+ store: credentials,
605
+ instanceId: state.instanceId || '',
606
+ dropDeviceStreams: typeof dropDeviceStreams === 'function' ? dropDeviceStreams : undefined,
607
+ }))
608
+ // 「把这一轮的回答落成文件」:带正文落盘(见 mobile/session-write-body.js),落点与右栏
609
+ // 三条写路由共用 file-ops 的允许区与写队列。上下文走 ctx,不需要额外实例。
610
+ route('/api/mobile/v1/session/write-body', (ctx, req, res) => sessionWriteBody.handleSessionWriteBody(ctx, req, res))
611
+ // 侧边提问(就着这条会话问一句、不写进会话日志)。宿主 apiProxy 没有「跑一轮不落日志」的
612
+ // 入口(`sessions.prompt` 一律追加进会话),所以这条路如实回 `side-question-unsupported`:
613
+ // App 侧据此说「插件要更新」并**不摆入口**(见 app/src/services/side-question.ts 文件头)。
614
+ // 等宿主补上这种能力再在这里接真实现,不在这里用 fork + 归档之类的假路径冒充 —— 那会在
615
+ // 侧栏凭空留一行会话,正是侧边提问要避免的。
616
+ route('/api/mobile/v1/session/side-question', async (_ctx, _req, res) => {
617
+ sendJson(res, 200, { ok: false, error: { code: 'side-question-unsupported', message: '当前插件版本不支持侧边提问(宿主没有跑一轮不落日志的能力)' } })
618
+ })
584
619
  // 子代理目录(宿主 subagent.list 的移动端只读代理)。桌面端会话标题栏挂着
585
620
  // 「N 个子代理」下拉,点进去能读子会话的完整记录;手机端把 origin === 'subagent'
586
621
  // 的行在侧栏里 continue 掉之后就再没有任何入口,见 mobile/subagents.js。
@@ -12,6 +12,7 @@
12
12
  */
13
13
 
14
14
  const zlib = require('node:zlib');
15
+ const { createHash } = require('node:crypto');
15
16
  const { promisify } = require('node:util');
16
17
 
17
18
  /** `zlib.gzip` 的 Promise 版:压缩在线程池里跑,插件主线程不陪着等。 */
@@ -116,24 +117,55 @@ async function sendJson(res, status, body) {
116
117
  } catch { /* 连接已关闭 */ }
117
118
  }
118
119
 
120
+ /**
121
+ * 一段 HTML 的内容校验符(`ETag` 的值,带引号)。
122
+ *
123
+ * 长度 + 摘要前 16 字节:产物是一份自包含的单文件页面,换版时内容一定有变化,够用。
124
+ */
125
+ function htmlEtag(body) {
126
+ const text = body == null ? '' : String(body);
127
+ return `"${Buffer.byteLength(text).toString(16)}-${createHash('sha1').update(text).digest('base64url').slice(0, 16)}"`;
128
+ }
129
+
119
130
  /**
120
131
  * 写 HTML 响应(UTF-8)。连接已关闭时静默忽略。
121
132
  *
122
133
  * 面板页是整页吐给浏览器的,所以必须显式声明 charset:少了它浏览器会按本地编码猜,
123
- * 中文标题直接变乱码。`no-store` 是刻意的——这份 HTML 就是「改完刷新即生效」的那一份,
124
- * 缓存住反而会把刚发布的版式藏起来。
134
+ * 中文标题直接变乱码。
125
135
  *
126
- * @param {object} res node:http ServerResponse
127
- * @param {number} status HTTP 状态码
128
- * @param {string} html 响应体
136
+ * **每次打开都重下一整页是不必要的开销**(面板是 1.4MB 的单文件产物,点一次手机图标就是
137
+ * 一次完整下载)。所以按内容算一个 `ETag` 交出去,浏览器下次带 `if-none-match` 回来就回
138
+ * 304 —— 内容没变时只花几百字节。
139
+ *
140
+ * **仍然是「改完刷新即生效」**:`no-cache` 不是「不缓存」,是「用之前一定回源确认」。
141
+ * 换掉 `no-store` 不会把刚发布的版式藏起来,产物一变 ETag 就变、必然拿到新的那份。
142
+ * 反过来也别改成 `max-age`:那是「一段时间内别再问」,就把这条承诺破坏了。
143
+ *
144
+ * @param {object} res node:http ServerResponse
145
+ * @param {number} status HTTP 状态码
146
+ * @param {string} html 响应体
147
+ * @param {object} [req] 给了就按 `if-none-match` 判 304(缺省照旧吐整页)
148
+ * @param {string} [known] 调用方已经算好的 `ETag`(面板页按产物 mtime 缓存了一份)
129
149
  */
130
- function sendHtml(res, status, html) {
150
+ function sendHtml(res, status, html, req, known) {
151
+ const body = html == null ? '' : html;
152
+ const etag = known || htmlEtag(body);
153
+ const headers = {
154
+ 'content-type': 'text/html; charset=utf-8',
155
+ 'cache-control': 'private, no-cache',
156
+ etag,
157
+ };
158
+ // 浏览器回的可能是 `W/"…"`、也可能是一串候选:只认其中有没有我们这一版。
159
+ const sent = req && req.headers ? req.headers['if-none-match'] : '';
160
+ const fresh = typeof sent === 'string' && sent.split(',').some((item) => item.trim().replace(/^W\//, '') === etag);
131
161
  try {
132
- res.writeHead(status, {
133
- 'content-type': 'text/html; charset=utf-8',
134
- 'cache-control': 'no-store',
135
- });
136
- res.end(html);
162
+ if (fresh) {
163
+ res.writeHead(304, headers);
164
+ res.end();
165
+ return;
166
+ }
167
+ res.writeHead(status, headers);
168
+ res.end(body);
137
169
  } catch { /* 连接已关闭 */ }
138
170
  }
139
171
 
@@ -223,6 +255,7 @@ function readRawBody(req, maxBytes = JSON_MAX_BODY) {
223
255
  module.exports = {
224
256
  sendJson,
225
257
  sendHtml,
258
+ htmlEtag,
226
259
  readJsonBody,
227
260
  readRawBody,
228
261
  encodeJsonBody,
@@ -160,12 +160,17 @@ export function createDeviceOta({ fetchImpl = fetch, installed = () => null, pla
160
160
  const otaVersion = validVersion(release.version) ? release.version : null
161
161
  const newest = [ota?.version, otaVersion].filter(validVersion).sort((a, b) => compareVersion(b, a))[0] || null
162
162
  const absorbed = Boolean(validVersion(officialVersion) && newest && compareVersion(officialVersion, newest) >= 0 && runtime?.status()?.source !== 'ota')
163
+ // 中转没给出合法 sha256 时这里归一成 null,apply 会据此**拒绝安装**(见那里的判据),
164
+ // 绝不能让「没有哈希」被当成「不必校验」。
163
165
  return { available: Boolean(newest && !absorbed && compareVersion(newest, installedVersion || '0.0.0') > 0), version: newest, platform: release.platform || platform, channel: release.channel || channel, installedVersion, otaVersion: ota?.version ?? null, officialVersion, absorbed, packageUrl: release.packageUrl, sha256: typeof release.sha256 === 'string' && /^[0-9a-f]{64}$/i.test(release.sha256) ? release.sha256.toLowerCase() : null }
164
166
  }
165
167
  async function apply() {
166
168
  const info = await check()
167
169
  if (info.otaVersion && compareVersion(info.otaVersion, info.version) === 0) return { installed: true, version: info.version, source: 'ota', alreadyDownloaded: true }
168
170
  if (validVersion(info.officialVersion) && compareVersion(info.officialVersion, info.version) >= 0) return { installed: false, reason: 'npm-current-or-newer', version: info.officialVersion }
171
+ // 没有合法 sha256 就等于完整性校验整段被跳过:从旧库升级上来的记录天然是空 sha,
172
+ // 这种包一律不装 —— 宁可装不上,也不装一份验不了的包。
173
+ if (!info.sha256) throw new Error('OTA 包缺少有效的 sha256,拒绝安装')
169
174
  // 暂存目录**建在目标根里面**,不是系统临时目录:最后一步要 rename 到 `<root>/<version>`,
170
175
  // 跨盘的 rename 在 Windows 上直接 EXDEV(系统临时目录常在 C:,而 profile 可能在别的盘)。
171
176
  fs.mkdirSync(ROOT(), { recursive: true })
@@ -175,8 +180,8 @@ export function createDeviceOta({ fetchImpl = fetch, installed = () => null, pla
175
180
  const response = await fetchImpl(info.packageUrl)
176
181
  if (!response.ok) throw new Error(`OTA 下载失败:HTTP ${response.status}`)
177
182
  const raw = Buffer.from(await response.arrayBuffer())
178
- // 中转记了哈希就一定要对上:半个包、被中间层改过的包都在这里被挡住,而不是装上去再炸。
179
- if (info.sha256 && sha256Hex(raw) !== info.sha256) {
183
+ // 哈希一定在(上面已拦下没有 sha 的记录),且一定要对上:半个包、被中间层改过的包都在这里被挡住,而不是装上去再炸。
184
+ if (sha256Hex(raw) !== info.sha256) {
180
185
  throw new Error(`OTA 包校验失败:下载内容的 sha256 与中转记录不一致(预期 ${info.sha256},实际 ${sha256Hex(raw)})`)
181
186
  }
182
187
  unpackTarGz(raw, staging)
@@ -97,11 +97,22 @@ const REGISTRY_CACHE_MS = 5 * 60 * 1000;
97
97
  const registryCache = new Map();
98
98
 
99
99
  /**
100
- * 从 `<pm> config get registry` 的输出里取地址。
100
+ * 一个源能不能用:只认 https;本机回环(127.0.0.1 / localhost)允许明文,用于本地测试 / 镜像。
101
101
  *
102
- * pnpm / npm 都只回一行地址;升级提示、警告可能在前面,所以从后往前找第一个 http(s) 行。
102
+ * 明文 http 源没有完整性,装的时候谁都能把包换掉,所以不认。
103
103
  */
104
- function parseRegistryOutput(output) {
104
+ function isSecureRegistry(value) {
105
+ try {
106
+ const url = new URL(value);
107
+ if (url.protocol === 'https:') return true;
108
+ return url.protocol === 'http:' && (url.hostname === '127.0.0.1' || url.hostname === 'localhost');
109
+ } catch {
110
+ return false;
111
+ }
112
+ }
113
+
114
+ /** 从 `<pm> config get registry` 的输出里找最后一行 http(s) 地址(升级提示、警告可能在前面)。 */
115
+ function lastRegistryLine(output) {
105
116
  const lines = String(output || '').split('\n').map(line => line.trim()).filter(Boolean);
106
117
  for (let i = lines.length - 1; i >= 0; i -= 1) {
107
118
  if (/^https?:\/\/\S+$/.test(lines[i])) return lines[i].replace(/\/+$/, '');
@@ -109,6 +120,17 @@ function parseRegistryOutput(output) {
109
120
  return null;
110
121
  }
111
122
 
123
+ /**
124
+ * 从 `<pm> config get registry` 的输出里取地址。
125
+ *
126
+ * pnpm / npm 都只回一行地址;升级提示、警告可能在前面,所以从后往前找第一个 http(s) 行。
127
+ * 只有 https(本机回环例外)才算数:命中明文 http 行时返回 null —— 调用方据此拒绝,绝不静默用它。
128
+ */
129
+ function parseRegistryOutput(output) {
130
+ const value = lastRegistryLine(output);
131
+ return value && isSecureRegistry(value) ? value : null;
132
+ }
133
+
112
134
  /**
113
135
  * 这台机器上 pnpm / npm 真正会用的注册表。
114
136
  *
@@ -158,6 +180,15 @@ async function profileRegistry({
158
180
  if (!result.ok) continue;
159
181
  registry = parseRegistryOutput(result.output);
160
182
  if (registry) break;
183
+ // 有地址但不是 https(也不是本机回环):这台机器装包就会从这个明文源取,明确拒绝 ——
184
+ // 不能退回官方源查、再让包管理器照样从明文源真装(查与装必须是同一个源)。
185
+ const insecure = lastRegistryLine(result.output);
186
+ if (insecure) {
187
+ throw new Error(
188
+ `这台机器上包管理器用的注册表是明文 http 源(${insecure}),拒绝用它检查更新、也不从它安装;`
189
+ + '只接受 https,本机回环 127.0.0.1 / localhost 除外。换成 https 源(或设置 DSHM_NPM_REGISTRY)后重试。',
190
+ );
191
+ }
161
192
  }
162
193
  cache.set(profileDir, { at: now(), registry });
163
194
  return registry;
@@ -797,14 +828,30 @@ async function installLatestIfNeeded(options = {}) {
797
828
  }
798
829
  // 查与装用同一个源:问一次这台机器上 pnpm / npm 真正在用的注册表(问不到才退回官方源)。
799
830
  // 不这样做的话,镜像 / 私有源机器上会出现「检查更新说连不上、手动装却是通的」。
800
- const registry = await profileRegistry({
801
- profileNodeModules,
802
- packageManager: options.packageManager ?? null,
803
- env: options.env,
804
- platform: options.platform,
805
- dirs: options.dirs ?? null,
806
- cache: options.registryCache,
807
- });
831
+ let registry;
832
+ try {
833
+ registry = await profileRegistry({
834
+ profileNodeModules,
835
+ packageManager: options.packageManager ?? null,
836
+ env: options.env,
837
+ platform: options.platform,
838
+ dirs: options.dirs ?? null,
839
+ cache: options.registryCache,
840
+ });
841
+ } catch (error) {
842
+ // 注册表是明文 http 源:查与装都不做,如实回一句清楚的原因,别当作「没新版」悄悄放过。
843
+ return {
844
+ installed: false,
845
+ skipped: false,
846
+ beforeVersion,
847
+ installedVersion: beforeVersion,
848
+ source,
849
+ command: null,
850
+ output: '',
851
+ failure: { code: 'REGISTRY_INSECURE', message: String((error && error.message) || error) },
852
+ check: null,
853
+ };
854
+ }
808
855
  const check = await checkForUpdate({ installedVersion: beforeVersion, source, base: registry ?? undefined });
809
856
  // 「有没有新版」排在「有没有人在跑」**前面**:没东西可装的时候,拿一句「有对话在跑」挡住
810
857
  // 真正的答案(已经是最新)是误导。
@@ -21,10 +21,30 @@ const DEFAULT_NAME = 'dsh-mobile-plugin';
21
21
  /** 一次查询的上限。查更新是背景动作,宁可如实报「连不上」也不要挂住面板。 */
22
22
  const REQUEST_TIMEOUT_MS = 8000;
23
23
 
24
- /** 注册表地址(去掉末尾斜杠;空串当没设)。 */
24
+ /**
25
+ * 一个源能不能用:只认 https;本机回环(127.0.0.1 / localhost)允许明文,用于本地测试 / 镜像。
26
+ *
27
+ * 明文 http 源没有完整性,中转 / 网络里谁都能把它换掉,所以不认。
28
+ */
29
+ function isSecureRegistry(value) {
30
+ try {
31
+ const url = new URL(value);
32
+ if (url.protocol === 'https:') return true;
33
+ return url.protocol === 'http:' && (url.hostname === '127.0.0.1' || url.hostname === 'localhost');
34
+ } catch {
35
+ return false;
36
+ }
37
+ }
38
+
39
+ /** 注册表地址(去掉末尾斜杠;空串当没设)。非 https 的显式覆盖直接拒绝,不回退、不静默使用。 */
25
40
  function registryBase(env = process.env) {
26
41
  const value = env && typeof env.DSHM_NPM_REGISTRY === 'string' ? env.DSHM_NPM_REGISTRY.trim() : '';
27
- return value ? value.replace(/\/+$/, '') : DEFAULT_REGISTRY;
42
+ if (!value) return DEFAULT_REGISTRY;
43
+ const base = value.replace(/\/+$/, '');
44
+ if (!isSecureRegistry(base)) {
45
+ throw new RegistryError('registry-insecure', `DSHM_NPM_REGISTRY 指向的不是 https 源(${base});只接受 https,本机回环 127.0.0.1 / localhost 除外`);
46
+ }
47
+ return base;
28
48
  }
29
49
 
30
50
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-mobile-plugin",
3
- "version": "0.5.47",
3
+ "version": "0.5.49",
4
4
  "description": "Mobile API (/api/mobile/v1) and relay client for the DSH mobile app — desktop profile build (dsh 0.2.x, peers resolved by the host)",
5
5
  "license": "MIT",
6
6
  "icon": "./icon.png",