@andy.ian/dsh-homing 2.4.0 → 2.5.1

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/index.js CHANGED
@@ -54,6 +54,7 @@ import { createLocalAppRegistry, matchAppPath, probeAppPort } from './lib/local-
54
54
  import { proxyLocalAppHttp, proxyLocalAppUpgrade } from './lib/app-proxy.mjs';
55
55
  import { renderLocalAppsPage } from './lib/local-apps-page.mjs';
56
56
  import { MOBILE_CSS, MOBILE_JS } from './lib/mobile-patch.mjs';
57
+ import { OFFLINE_SW_JS, SW_REGISTER_JS } from './lib/offline-sw.mjs';
57
58
  import { formatAge } from './lib/format-age.mjs';
58
59
 
59
60
  export const name = 'dsh-homing';
@@ -397,6 +398,7 @@ function injectedScriptVersion(relative) {
397
398
  const AUTH_GUARD_VER = injectedScriptVersion('./lib/auth-guard.js');
398
399
  const CLIENT_REPORT_VER = injectedScriptVersion('./lib/client-report.js');
399
400
  const IDB_FALLBACK_VER = injectedScriptVersion('./lib/idb-fallback.js');
401
+ const SW_REGISTER_VER = injectedScriptVersion('./lib/offline-sw.mjs');
400
402
 
401
403
  /**
402
404
  * import map:把 `plugins/...` 这类**不带前导斜杠**的说明符映射到绝对路径。
@@ -425,7 +427,8 @@ const IMPORT_MAP = '<script type="importmap">'
425
427
  // MOBILE —— `</head>` 之前:mobile.css + mobile.js(只在未关闭样式时注入)
426
428
  const BASE_INJECTION = '<script src="/dsh_homing/idb-fallback.js?v=' + IDB_FALLBACK_VER + '"></script>'
427
429
  + '<script src="/dsh_homing/auth-guard.js?v=' + AUTH_GUARD_VER + '"></script>'
428
- + '<script src="/dsh_homing/client-report.js?v=' + CLIENT_REPORT_VER + '"></script>';
430
+ + '<script src="/dsh_homing/client-report.js?v=' + CLIENT_REPORT_VER + '"></script>'
431
+ + '<script src="/dsh_homing/sw-register.js?v=' + SW_REGISTER_VER + '" defer></script>';
429
432
 
430
433
  const MOBILE_INJECTION = '<link rel="stylesheet" href="/dsh_homing/mobile.css">'
431
434
  + '<script defer src="/dsh_homing/mobile.js"></script>';
@@ -2134,6 +2137,23 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
2134
2137
  res.end(MOBILE_JS);
2135
2138
  return;
2136
2139
  }
2140
+ // 离线缓存的 Service Worker 与其注册脚本:
2141
+ // SW 必须在作用域根(scope: '/'),所以要带 Service-Worker-Allowed 头;
2142
+ // 脚本本身不缓存(no-store),避免浏览器装到旧版 SW 后缓存策略跟不上。
2143
+ if (url.pathname === '/dsh_homing/sw.js' && req.method === 'GET') {
2144
+ res.writeHead(200, {
2145
+ 'content-type': 'application/javascript; charset=utf-8',
2146
+ 'service-worker-allowed': '/',
2147
+ 'cache-control': 'no-store',
2148
+ });
2149
+ res.end(OFFLINE_SW_JS);
2150
+ return;
2151
+ }
2152
+ if (url.pathname === '/dsh_homing/sw-register.js' && req.method === 'GET') {
2153
+ res.writeHead(200, { 'content-type': 'application/javascript; charset=utf-8', 'cache-control': 'no-store' });
2154
+ res.end(SW_REGISTER_JS);
2155
+ return;
2156
+ }
2137
2157
  // 局域网证书(公开,不含任何秘密):手机装上它就能消除"不安全"警告并挡住中间人
2138
2158
  if ((url.pathname === '/dsh_homing/ca.crt' || url.pathname === '/dsh_homing/ca.der') && caCertPath && fs.existsSync(caCertPath)) {
2139
2159
  // 鸿蒙 / 部分安卓要求 DER(.cer),iOS 和多数安卓吃 PEM(.crt):两种都给
@@ -2176,6 +2196,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
2176
2196
  || url.pathname === '/dsh_homing/auth-state' || url.pathname === '/dsh_homing/auth-guard.js'
2177
2197
  || url.pathname === '/dsh_homing/idb-fallback.js'
2178
2198
  || url.pathname === '/dsh_homing/files-preview.js'
2199
+ || url.pathname === '/dsh_homing/sw.js' || url.pathname === '/dsh_homing/sw-register.js'
2179
2200
  || url.pathname === '/dsh_homing/client-report.js' || url.pathname === '/dsh_homing/client-error'
2180
2201
  // 图标与 manifest 是浏览器自动抓的,挡掉只会让登录页看起来坏掉、并在审计里刷噪音
2181
2202
  || url.pathname === '/manifest.webmanifest' || url.pathname === '/apple-touch-icon.png'
@@ -220,13 +220,15 @@ export const MOBILE_JS = String.raw`(() => {
220
220
  * 手机上没有那台电脑的屏幕,点了只会收到「已在其它设备打开」——纯噪音。
221
221
  * 这里把它(主按钮和小箭头都算)接到文件页 /files。
222
222
  *
223
- * 定位必须稳:页头里还有子智能体面板、更多菜单等 aria-haspopup 控件,而且
224
- * 它们排在分体按钮前面。「找第一个 aria-haspopup 的父容器」会认成子智能体
225
- * 那个容器,于是点分体按钮时判定不命中、补丁失效(手机端历史 bug)。
226
- * 所以:
223
+ * 定位:
227
224
  * 1. 优先用 DSH 的稳定标记 data-open-target="directory"(分体按钮容器);
228
- * 2. 老版本没有标记时退回结构判断 —— 同一容器里恰好两个按钮,一个带
229
- * aria-haspopup="menu"(小箭头),另一个是纯图标主按钮(里面是应用图标)。
225
+ * 2. 老版本没有标记时退回结构判断,但条件必须够严:
226
+ * 同容器恰好两个按钮,一个是纯图标主按钮且**里面是 <img> 应用图标**
227
+ * (分体按钮的真实特征),另一个是 aria-haspopup="menu" 的小箭头,
228
+ * 且整个容器在页头左上角。
229
+ * 2026-11-23 线上回归:新版 DSH 页头把「git 图标 + ⋯ 菜单」放在同一个
230
+ * 容器里(恰好两个按钮、后者 aria-haspopup=menu、前者纯 svg 图标),
231
+ * 只判断 svg 会把「⋯」劫持到文件页 —— 所以主按钮必须真是 <img> 图标。
230
232
  */
231
233
  const splitHost = (node) => {
232
234
  if (node === null || node === undefined || typeof node.closest !== 'function') return null
@@ -247,10 +249,13 @@ export const MOBILE_JS = String.raw`(() => {
247
249
  if (main === null || chevron === null) return null
248
250
  if (chevron.getAttribute('aria-haspopup') !== 'menu') return null
249
251
  if ((main.textContent || '').trim() !== '') return null
250
- if (main.querySelector('img, svg') === null) return null
252
+ // 分体按钮的主按钮是应用图标(<img>);git / ⋯ 这类页头按钮是 <svg>,不能混为一谈
253
+ if (main.querySelector('img') === null) return null
251
254
  const rect = chevron.getBoundingClientRect()
252
255
  if (rect.width === 0 || rect.height === 0) return null
253
- if (rect.top > 200) return null
256
+ if (rect.top > 120) return null
257
+ const hostRect = host.getBoundingClientRect()
258
+ if (hostRect.left > 160) return null
254
259
  return host
255
260
  }
256
261
 
@@ -0,0 +1,145 @@
1
+ /**
2
+ * 离线缓存(Service Worker)的纯逻辑 + 脚本文本。
3
+ *
4
+ * 背景(2026-11-23):手机上「彻底退出浏览器 → 第一次打开」很慢,原因是 DSH
5
+ * 前端每次热更新都会把所有模块 rev 换掉(实测 93 个模块里 91 个 rev 变化,
6
+ * 缓存命中率只剩 2%),浏览器 HTTP 缓存全部作废,要重新下载约 3MB(gzip)。
7
+ * 第二次打开就快,是因为 HTTP 缓存刚建好 —— 但彻底退出浏览器又会被清掉。
8
+ *
9
+ * 方案:用 Cache Storage(不会被"彻底退出浏览器"清掉)缓存静态 bundles,
10
+ * 缓存键归一化掉内容哈希/rev,DSH 再怎么换 rev 也能命中;命中后后台静默
11
+ * 拉新版本更新缓存(stale-while-revalidate),用户感知到的就是"秒开"。
12
+ *
13
+ * 安全边界:只缓存 /assets/、/plugins/ 与几个公开图标;绝不缓存 HTML、
14
+ * /api/、/files/、/dsh_homing/(鉴权、会话、用户私有数据)。
15
+ */
16
+
17
+ /** 归一化缓存键:去掉内容哈希与 rev,让升级后的新 URL 命中旧缓存。 */
18
+ export function swCacheKey(rawUrl) {
19
+ const url = new URL(String(rawUrl))
20
+ if (url.pathname.startsWith('/assets/')) {
21
+ // /assets/index-Ciz7DZxv.js → /assets/index.js
22
+ const name = url.pathname.slice('/assets/'.length)
23
+ .replace(/-[A-Za-z0-9_-]{8,}(\.[cm]?js|\.css)$/u, '$1')
24
+ return '/assets/' + name
25
+ }
26
+ if (url.pathname.startsWith('/plugins/')) {
27
+ // /plugins/??@a/client.js,@b/client.js&rev=xxx → 按模块名排序、去掉 rev
28
+ const raw = url.search.replace(/^\?\??/u, '')
29
+ const names = raw.split(',').map((part) => part.split('&')[0]).filter(Boolean).sort()
30
+ return '/plugins/??' + names.join(',')
31
+ }
32
+ return url.pathname
33
+ }
34
+
35
+ /** 这个请求是否允许被离线缓存(只看公开静态资源)。 */
36
+ export function swCacheable(rawUrl, origin = null) {
37
+ let url
38
+ try { url = new URL(String(rawUrl)) } catch { return false }
39
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') return false
40
+ // 只缓存同源资源:避免把第三方脚本存进来(也避免跨域 no-cors 响应污染缓存)
41
+ if (origin !== null && url.origin !== origin) return false
42
+ const path = url.pathname
43
+ if (path.startsWith('/assets/') || path.startsWith('/plugins/')) return true
44
+ return path === '/manifest.webmanifest' || path === '/favicon.svg'
45
+ || path === '/favicon-dark.svg' || path === '/favicon.ico'
46
+ || path === '/apple-touch-icon.png'
47
+ }
48
+
49
+ /**
50
+ * Service Worker 脚本文本。纯函数用 toString() 注入(Worker 里不能 import)。
51
+ * 必须同源、HTTPS(或 localhost)才生效;浏览器不支持时注册脚本会静默跳过。
52
+ */
53
+ export const OFFLINE_SW_JS = String.raw`/* DSH 离线缓存 Service Worker */
54
+ const CACHE = 'dsh-homing-offline-v1'
55
+ const swCacheKey = ${swCacheKey.toString()}
56
+ const swCacheable = ${swCacheable.toString()}
57
+
58
+ self.addEventListener('install', () => {
59
+ self.skipWaiting()
60
+ })
61
+
62
+ self.addEventListener('activate', (event) => {
63
+ event.waitUntil((async () => {
64
+ const keys = await caches.keys()
65
+ await Promise.all(keys.filter((key) => key !== CACHE).map((key) => caches.delete(key)))
66
+ await self.clients.claim()
67
+ })())
68
+ })
69
+
70
+ self.addEventListener('fetch', (event) => {
71
+ const request = event.request
72
+ if (request.method !== 'GET' || !swCacheable(request.url, self.location.origin)) return
73
+ const key = swCacheKey(request.url)
74
+ event.respondWith((async () => {
75
+ const cache = await caches.open(CACHE)
76
+ const cached = await cache.match(key)
77
+ const network = fetch(request).then(async (response) => {
78
+ if (response && response.ok && response.status === 200) {
79
+ try { await cache.put(key, response.clone()) } catch (error) { /* 配额不足等:忽略 */ }
80
+ }
81
+ return response
82
+ })
83
+ if (cached) {
84
+ // 先返回旧缓存(秒开),后台拉新版本静默更新;失败不影响本次
85
+ network.catch(() => {})
86
+ return cached
87
+ }
88
+ return network
89
+ })())
90
+ })
91
+
92
+ // 首次访问结束时由页面把已加载的资源列表发来,后台预热缓存,
93
+ // 这样"彻底退出浏览器再打开"的第一次也能秒开。
94
+ self.addEventListener('message', (event) => {
95
+ const data = event.data
96
+ if (!data || data.type !== 'WARM' || !Array.isArray(data.urls)) return
97
+ event.waitUntil((async () => {
98
+ const cache = await caches.open(CACHE)
99
+ for (const raw of data.urls) {
100
+ if (typeof raw !== 'string' || !swCacheable(raw, self.location.origin)) continue
101
+ const key = swCacheKey(raw)
102
+ if (await cache.match(key)) continue
103
+ try {
104
+ const response = await fetch(raw, { cache: 'reload' })
105
+ if (response && response.ok) await cache.put(key, response)
106
+ } catch (error) { /* 单个资源失败不影响其它 */ }
107
+ }
108
+ })())
109
+ })
110
+ `
111
+
112
+ /**
113
+ * 注册 + 预热脚本(外部文件,符合页面 CSP 的 script-src 'self')。
114
+ */
115
+ export const SW_REGISTER_JS = String.raw`(() => {
116
+ if (!('serviceWorker' in navigator)) return
117
+ const secure = location.protocol === 'https:'
118
+ || location.hostname === 'localhost' || location.hostname === '127.0.0.1'
119
+ if (!secure) return
120
+
121
+ const warm = (registration) => {
122
+ const worker = registration && registration.active
123
+ if (!worker) return
124
+ let urls = []
125
+ try {
126
+ urls = [...new Set(performance.getEntriesByType('resource').map((entry) => entry.name))]
127
+ .filter((raw) => {
128
+ try {
129
+ const parsed = new URL(raw)
130
+ return parsed.origin === location.origin
131
+ && (parsed.pathname.startsWith('/assets/') || parsed.pathname.startsWith('/plugins/'))
132
+ } catch (error) { return false }
133
+ })
134
+ } catch (error) { return }
135
+ if (urls.length > 0) worker.postMessage({ type: 'WARM', urls })
136
+ }
137
+
138
+ navigator.serviceWorker.register('/dsh_homing/sw.js', { scope: '/' })
139
+ .then((registration) => {
140
+ if (registration.active) { warm(registration); return }
141
+ navigator.serviceWorker.addEventListener('controllerchange', () => warm(registration), { once: true })
142
+ })
143
+ .catch(() => { /* 不支持或权限受限时静默降级,不影响页面 */ })
144
+ })()
145
+ `
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@andy.ian/dsh-homing",
3
- "version": "2.4.0",
3
+ "version": "2.5.1",
4
4
  "type": "module",
5
5
  "description": "把本机 DSH 通过 SSH 反向隧道安全开放到手机浏览器:TLS 端到端(服务器只透传)、账号 + TOTP、局域网与公网双入口,随 DSH 启动。",
6
6
  "keywords": [