@andy.ian/dsh-homing 2.3.9 → 2.5.0

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'
@@ -6,7 +6,8 @@
6
6
  * 1. 捕获 window.onerror / unhandledrejection / 资源加载失败 → 立即上报
7
7
  * 2. 捕获 console.error / console.warn 的前 2 条(插件初始化失败常被应用
8
8
  * try/catch 后写 logger,window.onerror 看不到)
9
- * 3. 12 秒后若仍在启动页:先自动换 URL 重载一次,仍不行则显示自救提示
9
+ * 3. 启动检测:只在连续 60 秒毫无加载进展时才提示,不自动重载
10
+ * (首次打开要下载约 3MB 脚本,慢网络下 20–40 秒属正常,别误报)
10
11
  *
11
12
  * 必须是外部文件(页面 CSP 只有 script-src 'self')。
12
13
  */
@@ -67,6 +68,16 @@
67
68
  })
68
69
  })
69
70
 
71
+ // 记录"还有进展":资源加载、DOM 状态变化、console 输出都会刷新它。
72
+ // 首次打开手机端要下载约 3MB(gzip 后)的 DSH 前端脚本,慢 networks 下
73
+ // 需要 20–40 秒;只要还在进展就耐心等,不能当成"卡住"(2026-11-23 实测:
74
+ // 旧的 12 秒检测会误报,还会自动重载把已下载的资源丢掉,反而更慢)。
75
+ let lastProgressAt = Date.now()
76
+ const markProgress = () => { lastProgressAt = Date.now() }
77
+ window.addEventListener('load', markProgress, true)
78
+ window.addEventListener('error', markProgress, true)
79
+ document.addEventListener('readystatechange', markProgress, true)
80
+
70
81
  // 只拦 error / warn,每级 2 条:足够定位插件初始化失败,又不影响性能
71
82
  for (const level of ['error', 'warn']) {
72
83
  const original = console[level]
@@ -74,6 +85,7 @@
74
85
  let reported = 0
75
86
  console[level] = function patched(...args) {
76
87
  try {
88
+ markProgress()
77
89
  if (reported < 2) {
78
90
  reported += 1
79
91
  report({
@@ -90,51 +102,46 @@
90
102
  }
91
103
  }
92
104
 
93
- // 12 秒后检查应用是否挂载:仍在启动页或 #root 为空,
94
- // 先自动换一个带随机参数的 URL 重载一次(破解缓存壳/浏览器进程中的旧状态),
95
- // 再不行才显示自救提示。
96
- setTimeout(() => {
105
+ // 启动检测:12 秒后第一次检查,若仍在启动页:
106
+ // - 最近 60 秒内有任何加载进展 → 继续等(每 10 秒复查),不提示、不重载;
107
+ // - 连续 60 秒毫无进展 → 才上报并显示温和提示。
108
+ // 不再自动换 URL 重载:慢网络下重载会丢弃已经下好的资源,让首次打开更慢。
109
+ const BOOT_IDLE_LIMIT_MS = 60_000
110
+ const BOOT_RECHECK_MS = 10_000
111
+
112
+ function checkBoot() {
97
113
  try {
98
114
  const root = document.getElementById('root')
99
115
  const splash = document.querySelector('[data-dsh-boot]')
100
116
  const mounted = Boolean(root && root.childElementCount > 0) && !splash
101
- if (mounted) return
117
+ if (mounted) return true
118
+ const idleMs = Date.now() - lastProgressAt
119
+ if (idleMs < BOOT_IDLE_LIMIT_MS) {
120
+ setTimeout(checkBoot, BOOT_RECHECK_MS)
121
+ return false
122
+ }
102
123
  report({
103
124
  kind: 'boot-timeout',
104
125
  message: String(document.body?.innerText ?? '').replace(/\s+/g, ' ').slice(0, 400) || '(页面无文字)',
105
126
  rootExists: Boolean(root),
106
127
  splashPresent: Boolean(splash),
107
128
  readyState: document.readyState,
129
+ idleMs,
108
130
  })
109
-
110
- // 自动重载:每次会话只尝试一次,避免死循环
111
- let tried = false
112
- try {
113
- tried = sessionStorage.getItem('dsh-homing-boot-retry') === '1'
114
- if (!tried) sessionStorage.setItem('dsh-homing-boot-retry', '1')
115
- } catch (error) {
116
- tried = true // 拿不到 sessionStorage 就不要再自动刷新
117
- }
118
- if (!tried) {
119
- const url = new URL(location.href)
120
- url.searchParams.set('_r', Date.now().toString(36))
121
- location.replace(url.href)
122
- return
123
- }
124
-
125
131
  showStuckOverlay()
126
132
  } catch (error) {
127
133
  // 忽略
128
134
  }
129
- }, 12000)
135
+ return false
136
+ }
137
+ setTimeout(checkBoot, 12_000)
130
138
 
131
139
  /**
132
- * 启动卡住时给出可见的自救提示。
140
+ * 真正长时间无进展时给出的提示。
133
141
  *
134
- * 为什么需要(2026-11-15 实测):手机浏览器进程会积累坏状态(泄漏的 IndexedDB 连接等),
135
- * 表现就是界面永远停在 "Loading plugins…",而**刷新、重开标签都没用**,
136
- * 必须把浏览器从后台彻底关掉再打开才恢复。用户当时试了很多次都不知道这一点,
137
- * 所以卡住时直接把这句话显示出来,配一个重新加载按钮。
142
+ * 注意措辞(2026-11-23 修正):首次打开要下载 DSH 前端约 3MB 脚本,慢网络
143
+ * 本来就要几十秒,不能一上来就让人"彻底关浏览器";只有在确认毫无进展时才
144
+ * 给出自救建议,且把"重新加载"作为首选而不是自动执行。
138
145
  */
139
146
  function showStuckOverlay() {
140
147
  if (document.getElementById('dsh-homing-stuck')) return
@@ -145,12 +152,12 @@
145
152
  + 'padding:14px;font:14px/1.6 system-ui,-apple-system,"Noto Sans SC",sans-serif;'
146
153
  + 'box-shadow:0 8px 28px rgba(0,0,0,.5)'
147
154
  const title = document.createElement('div')
148
- title.textContent = 'DSH 启动卡住了'
155
+ title.textContent = '页面加载较慢或暂时没有进展'
149
156
  title.style.cssText = 'font-weight:700;margin-bottom:6px'
150
157
  const hint = document.createElement('div')
151
158
  hint.style.cssText = 'color:#b7bec9;margin-bottom:10px'
152
- hint.textContent = '请在手机的多任务里把这个浏览器彻底关掉(不是切后台),再重新打开。'
153
- + '今天多次刷新都无效、只有彻底关掉浏览器才恢复,原因通常是浏览器进程里的旧状态没被清掉。'
159
+ hint.textContent = '首次打开需要下载约 3MB 的页面资源,网络慢时可能需要 30–60 秒。'
160
+ + '如果一直不动,可先点「重新加载」;仍不行再在手机多任务里彻底关闭浏览器后重开。'
154
161
  const row = document.createElement('div')
155
162
  row.style.cssText = 'display:flex;gap:8px'
156
163
  const reload = document.createElement('button')
@@ -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.3.9",
3
+ "version": "2.5.0",
4
4
  "type": "module",
5
5
  "description": "把本机 DSH 通过 SSH 反向隧道安全开放到手机浏览器:TLS 端到端(服务器只透传)、账号 + TOTP、局域网与公网双入口,随 DSH 启动。",
6
6
  "keywords": [