@andy.ian/dsh-homing 2.3.8 → 2.4.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
@@ -1661,6 +1661,8 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1661
1661
  result = current ? appRegistry.update(id, { enabled: !current.enabled }) : { ok: false, error: '应用不存在' };
1662
1662
  } else if (action === 'delete') {
1663
1663
  result = appRegistry.remove(form.get('id') ?? '');
1664
+ } else if (action === 'lan') {
1665
+ result = appRegistry.setAllowLan(form.get('allowLan') === '1');
1664
1666
  }
1665
1667
  appendAudit(dir, 'app-registry-' + action, { id: String(form.get('id') ?? form.get('originalId') ?? ''), ok: result.ok, error: result.error ?? null });
1666
1668
  // appRegistry 的每条失败路径都带 error 字符串(门禁证明 `?? '保存失败'` 不可达)
@@ -1690,6 +1692,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1690
1692
  });
1691
1693
  res.end(renderLocalAppsPage({
1692
1694
  apps, health, editing, confirmDelete,
1695
+ allowLan: appRegistry.allowLan(),
1693
1696
  message: url.searchParams.get('msg') ?? '',
1694
1697
  isError: url.searchParams.get('error') === '1',
1695
1698
  }));
@@ -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')
@@ -20,8 +20,12 @@ form{margin:0}label{display:block;margin:10px 0 4px;color:#9aa4b2;font-size:12px
20
20
  @media(max-width:640px){.grid{grid-template-columns:1fr}.card{padding:12px}}
21
21
  `
22
22
 
23
- export function renderLocalAppsPage({ apps, health = {}, editing = null, confirmDelete = null, message = '', isError = false }) {
23
+ export function renderLocalAppsPage({ apps, health = {}, editing = null, confirmDelete = null, allowLan = false, message = '', isError = false }) {
24
24
  const formApp = editing ?? { id: '', name: '', target: 'http://127.0.0.1:', enabled: true, trusted: false, allowInsecureTls: false }
25
+ const targetPlaceholder = allowLan ? 'http://192.168.1.26:8899' : 'http://127.0.0.1:8765'
26
+ const targetLabel = allowLan
27
+ ? '目标地址(回环 127.0.0.1 / ::1,或局域网私网 10.x / 172.16–31.x / 192.168.x)'
28
+ : '目标地址(仅允许 127.0.0.1 / ::1;需要局域网服务请先在上方开启)'
25
29
  const rows = apps.length === 0
26
30
  ? '<div class="empty">还没有本地应用。先在下方添加一个本机服务。</div>'
27
31
  : apps.map((app) => {
@@ -41,17 +45,27 @@ export function renderLocalAppsPage({ apps, health = {}, editing = null, confirm
41
45
  ? `<div class="card"><h2>确认删除「${escapeHtml(confirmDelete.name)}」?</h2><p class="sub">只删除网关入口,不会停止或删除电脑上的服务。</p><div class="ops"><form method="post"><input type="hidden" name="action" value="delete"><input type="hidden" name="id" value="${escapeHtml(confirmDelete.id)}"><button class="danger" type="submit">确认删除</button></form><a class="btn ghost" href="/dsh_homing/apps">取消</a></div></div>`
42
46
  : ''
43
47
 
48
+ const lanCard = `<div class="card"><h2>局域网服务(可选)</h2>
49
+ <p class="note">默认只允许本机回环地址(127.0.0.1 / ::1)。要接入同一局域网内的服务(如 <code>192.168.1.26:8899</code>),先在这里开启。</p>
50
+ <p class="note">${allowLan
51
+ ? '<b style="color:#f0b46b">已开启</b>:允许 10.x / 172.16–31.x / 192.168.x / 169.254.x 等私网地址;公网地址仍会被拒绝。'
52
+ : '当前未开启:目标地址只能是 127.0.0.1 / ::1。'}</p>
53
+ <form method="post"><input type="hidden" name="action" value="lan"><input type="hidden" name="allowLan" value="${allowLan ? '0' : '1'}"><button class="${allowLan ? 'danger' : 'primary'}" type="submit">${allowLan ? '关闭局域网访问' : '允许局域网地址(LAN)'}</button></form>
54
+ <p class="note">安全提示:只允许私网地址,不会变成公网开放代理;局域网服务本身也不要暴露到公网。</p>
55
+ </div>`
56
+
44
57
  return `<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>本地应用 · DSH</title><style>${STYLE}${NAV_CSS}</style></head><body><div class="wrap">
45
58
  ${topNav({ current: '/dsh_homing/apps' })}
46
- <h1>本地应用</h1><p class="sub">把本机回环服务接入同一个安全入口。每个应用独立启用,互不影响。</p>
59
+ <h1>本地应用</h1><p class="sub">把本机回环(可选局域网)服务接入同一个安全入口。每个应用独立启用,互不影响。</p>
47
60
  ${message ? `<div class="msg${isError ? ' err' : ''}">${escapeHtml(message)}</div>` : ''}
48
61
  ${deleteCard}
62
+ ${lanCard}
49
63
  <div class="card"><h2>已登记应用(${apps.length})</h2>${rows}</div>
50
64
  <div class="card"><h2>${editing ? '编辑应用' : '添加应用'}</h2>
51
65
  <form method="post"><input type="hidden" name="action" value="save"><input type="hidden" name="originalId" value="${escapeHtml(editing?.id ?? '')}">
52
66
  <div class="grid"><div><label for="app-id">应用 ID(小写字母、数字、中划线)</label><input id="app-id" name="id" type="text" required maxlength="32" pattern="[a-z0-9]([a-z0-9-]*[a-z0-9])?" value="${escapeHtml(formApp.id)}" placeholder="m0"></div>
53
67
  <div><label for="app-name">显示名称</label><input id="app-name" name="name" type="text" required maxlength="60" value="${escapeHtml(formApp.name)}" placeholder="M0 决策弹窗"></div></div>
54
- <label for="app-target">目标地址(仅允许 127.0.0.1 / ::1)</label><input id="app-target" name="target" type="url" required value="${escapeHtml(formApp.target)}" placeholder="http://127.0.0.1:8765">
68
+ <label for="app-target">${targetLabel}</label><input id="app-target" name="target" type="url" required value="${escapeHtml(formApp.target)}" placeholder="${targetPlaceholder}">
55
69
  <label class="check"><input name="enabled" type="checkbox" value="1"${formApp.enabled ? ' checked' : ''}>启用这个应用</label>
56
70
  <label class="check"><input name="trusted" type="checkbox" value="1"${formApp.trusted ? ' checked' : ''}>我信任此应用的网页脚本(允许 HTML / JavaScript)</label>
57
71
  <p class="note">默认只允许 JSON、文本、图片等安全内容。勾选前请确认应用代码可信:网页脚本与 DSH 同源,能发起 DSH 操作;不可信应用或存在 XSS 的应用不要勾选。</p>
@@ -59,6 +73,6 @@ export function renderLocalAppsPage({ apps, health = {}, editing = null, confirm
59
73
  <div class="ops"><button class="primary" type="submit">${editing ? '保存修改' : '添加并启用'}</button>${editing ? '<a class="btn ghost" href="/dsh_homing/apps">取消编辑</a>' : ''}</div>
60
74
  </form>
61
75
  </div>
62
- <div class="card"><h2>访问方式</h2><p class="note">保存后立即生效,无需重启 DSH。公开地址为 <code>/apps/应用ID/</code>。所有访问仍要求 DSH 登录或有效设备令牌;管理操作要求重新处于登录会话中。<br>只代理本机回环地址,不会把插件会话 Cookie 转发给你的服务。网页如果写死根路径,请使用支持 base path 的服务或后续独立域名模式。</p></div>
76
+ <div class="card"><h2>访问方式</h2><p class="note">保存后立即生效,无需重启 DSH。公开地址为 <code>/apps/应用ID/</code>。所有访问仍要求 DSH 登录或有效设备令牌;管理操作要求重新处于登录会话中。<br>默认只代理本机回环地址;开启局域网后也只允许私网地址(10.x / 172.16–31.x / 192.168.x / link-local),公网地址会被拒绝,不会把插件变成开放代理。不会把插件会话 Cookie 转发给你的服务。网页如果写死根路径,请使用支持 base path 的服务或后续独立域名模式。</p></div>
63
77
  </div></body></html>`
64
78
  }
@@ -14,7 +14,35 @@ export function normalizeAppId(value) {
14
14
  return String(value ?? '').trim().toLowerCase()
15
15
  }
16
16
 
17
- export function appUrlError(value) {
17
+ /** 是否本机回环(与历史行为一致:只认 127.0.0.1 / ::1)。 */
18
+ export function isLoopbackHost(hostname) {
19
+ return hostname === '127.0.0.1' || hostname === '::1'
20
+ }
21
+
22
+ /**
23
+ * 是否局域网私网地址:10/8、172.16/12、192.168/16、169.254/16(IPv4 链路本地)、
24
+ * fc00::/7(IPv6 ULA)、fe80::/10(IPv6 链路本地)。
25
+ * 公网地址一律返回 false —— 开启局域网支持也不能把插件变成公网跳板。
26
+ */
27
+ export function isPrivateLanHost(hostname) {
28
+ const v4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/u.exec(hostname)
29
+ if (v4 !== null) {
30
+ const a = Number(v4[1]); const b = Number(v4[2]); const c = Number(v4[3]); const d = Number(v4[4])
31
+ if (a > 255 || b > 255 || c > 255 || d > 255) return false
32
+ if (a === 10) return true
33
+ if (a === 172 && b >= 16 && b <= 31) return true
34
+ if (a === 192 && b === 168) return true
35
+ if (a === 169 && b === 254) return true
36
+ return false
37
+ }
38
+ const v6 = hostname.toLowerCase()
39
+ if (v6 === '::1') return false
40
+ if (/^f[cd][0-9a-f]{0,2}:/u.test(v6)) return true
41
+ if (/^fe[89ab][0-9a-f]?:/u.test(v6)) return true
42
+ return false
43
+ }
44
+
45
+ export function appUrlError(value, { allowLan = false } = {}) {
18
46
  let target
19
47
  try {
20
48
  target = new URL(String(value ?? '').trim())
@@ -24,20 +52,23 @@ export function appUrlError(value) {
24
52
  if (target.protocol !== 'http:' && target.protocol !== 'https:') return '目标只支持 http / https'
25
53
  if (target.username || target.password) return '目标地址不能带用户名或密码'
26
54
  const hostname = target.hostname.replace(/^\[|\]$/gu, '')
27
- if (hostname !== '127.0.0.1' && hostname !== '::1') return '只允许代理本机回环地址(127.0.0.1 / ::1)'
55
+ if (!isLoopbackHost(hostname)) {
56
+ if (!allowLan) return '只允许代理本机回环地址(127.0.0.1 / ::1);如需访问局域网服务,请先开启「允许局域网地址」'
57
+ if (!isPrivateLanHost(hostname)) return '只允许本机回环或局域网私网地址(10.x / 172.16–31.x / 192.168.x / link-local)'
58
+ }
28
59
  if (target.search || target.hash) return '目标地址不能带查询参数或锚点'
29
60
  const port = target.port === '' ? (target.protocol === 'https:' ? 443 : 80) : Number(target.port)
30
61
  if (!Number.isInteger(port) || port < 1 || port > 65535) return '目标端口无效'
31
62
  return ''
32
63
  }
33
64
 
34
- export function validateApp(input, deniedPorts = []) {
65
+ export function validateApp(input, deniedPorts = [], { allowLan = false } = {}) {
35
66
  const id = normalizeAppId(input?.id)
36
67
  const name = String(input?.name ?? '').trim().slice(0, 60)
37
68
  const targetText = String(input?.target ?? '').trim()
38
69
  if (!APP_ID_RE.test(id)) return { ok: false, error: '应用 ID 只能用小写字母、数字和中划线,长度 1–32 位' }
39
70
  if (name === '') return { ok: false, error: '请填写应用名称' }
40
- const targetError = appUrlError(targetText)
71
+ const targetError = appUrlError(targetText, { allowLan })
41
72
  if (targetError) return { ok: false, error: targetError }
42
73
  const target = new URL(targetText)
43
74
  const port = Number(target.port || (target.protocol === 'https:' ? 443 : 80))
@@ -77,13 +108,14 @@ function readSettingsFile(file, { strict = false } = {}) {
77
108
 
78
109
  function normalizedList(raw, deniedPorts = []) {
79
110
  const list = Array.isArray(raw?.apps) ? raw.apps : []
111
+ const allowLan = raw?.allowLanApps === true
80
112
  const seen = new Set()
81
113
  const result = []
82
114
  for (const item of list) {
83
115
  if (!item || typeof item !== 'object') continue
84
116
  const id = normalizeAppId(item.id)
85
117
  if (!APP_ID_RE.test(id) || seen.has(id)) continue
86
- const app = validateApp({ ...item, id }, deniedPorts)
118
+ const app = validateApp({ ...item, id }, deniedPorts, { allowLan })
87
119
  if (!app.ok) continue
88
120
  seen.add(id)
89
121
  result.push(app.app)
@@ -198,9 +230,7 @@ export function createLocalAppRegistry({ settingsPath, deniedPorts = () => [] })
198
230
  return cache.apps.map(cloneApp)
199
231
  }
200
232
 
201
- function writeApps(apps) {
202
- const settings = readSettingsFile(settingsPath, { strict: true })
203
- settings.apps = apps
233
+ function writeSettings(settings) {
204
234
  fs.mkdirSync(path.dirname(settingsPath), { recursive: true })
205
235
  const temp = `${settingsPath}.${process.pid}.tmp`
206
236
  fs.writeFileSync(temp, JSON.stringify(settings, null, 2) + '\n', { encoding: 'utf8', mode: 0o600 })
@@ -208,17 +238,45 @@ export function createLocalAppRegistry({ settingsPath, deniedPorts = () => [] })
208
238
  cache = { mtime: fs.statSync(settingsPath).mtimeMs, apps: normalizedList(settings, deniedPorts()) }
209
239
  }
210
240
 
241
+ function writeApps(apps) {
242
+ const settings = readSettingsFile(settingsPath, { strict: true })
243
+ settings.apps = apps
244
+ writeSettings(settings)
245
+ }
246
+
247
+ /** 当前是否允许局域网目标(读 settings.json,由管理页切换)。 */
248
+ function allowLan() {
249
+ return readSettingsFile(settingsPath).allowLanApps === true
250
+ }
251
+
252
+ /** 打开/关闭局域网目标支持。关闭后已登记的局域网应用会在下次读取时被过滤掉。 */
253
+ function setAllowLan(value) {
254
+ let settings
255
+ try {
256
+ settings = readSettingsFile(settingsPath, { strict: true })
257
+ } catch {
258
+ return { ok: false, error: 'settings.json 已损坏,未做任何修改;请先修复配置文件' }
259
+ }
260
+ settings.allowLanApps = value === true
261
+ try {
262
+ writeSettings(settings)
263
+ } catch (error) {
264
+ return { ok: false, error: '配置写入失败:' + String(error?.message ?? error).slice(0, 160) }
265
+ }
266
+ return { ok: true, allowLan: value === true }
267
+ }
268
+
211
269
  function save(input) {
212
- const validated = validateApp(input, deniedPorts())
213
- if (!validated.ok) return validated
214
- const id = validated.app.id
215
- const originalId = normalizeAppId(input.originalId ?? '')
216
270
  let raw
217
271
  try {
218
272
  raw = readSettingsFile(settingsPath, { strict: true })
219
273
  } catch {
220
274
  return { ok: false, error: 'settings.json 已损坏,未做任何修改;请先修复配置文件' }
221
275
  }
276
+ const validated = validateApp(input, deniedPorts(), { allowLan: raw.allowLanApps === true })
277
+ if (!validated.ok) return validated
278
+ const id = validated.app.id
279
+ const originalId = normalizeAppId(input.originalId ?? '')
222
280
  const current = Array.isArray(raw.apps) ? raw.apps.filter((item) => item && typeof item === 'object') : []
223
281
  if (current.some((item) => normalizeAppId(item.id) === id && normalizeAppId(item.id) !== originalId)) {
224
282
  return { ok: false, error: `应用 ID ${id} 已存在` }
@@ -253,7 +311,7 @@ export function createLocalAppRegistry({ settingsPath, deniedPorts = () => [] })
253
311
  return { ok: true }
254
312
  }
255
313
 
256
- return { list, save, update, remove }
314
+ return { list, save, update, remove, allowLan, setAllowLan }
257
315
  }
258
316
 
259
317
  /** 管理页的端口探活;不是完整的应用健康检查,文案必须写“端口可达”。 */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@andy.ian/dsh-homing",
3
- "version": "2.3.8",
3
+ "version": "2.4.0",
4
4
  "type": "module",
5
5
  "description": "把本机 DSH 通过 SSH 反向隧道安全开放到手机浏览器:TLS 端到端(服务器只透传)、账号 + TOTP、局域网与公网双入口,随 DSH 启动。",
6
6
  "keywords": [