@hyprnos/dsh-remote-plugin 0.0.0-stage → 0.8.8

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.
Files changed (210) hide show
  1. package/README.en.md +61 -0
  2. package/README.md +60 -2
  3. package/apk/dsh-remote.apk +0 -0
  4. package/approval-summary.mjs +115 -0
  5. package/client.js +197 -0
  6. package/cordis.patch.yml +5 -0
  7. package/doctor-skill.mjs +99 -0
  8. package/doctor-target.mjs +24 -0
  9. package/file-delivery.mjs +84 -0
  10. package/gateway-stats.cjs +501 -0
  11. package/gateway.cjs +8451 -0
  12. package/index.mjs +1784 -0
  13. package/insights.mjs +111 -0
  14. package/market.mjs +86 -0
  15. package/package.json +71 -4
  16. package/peak-reminders.mjs +50 -0
  17. package/plugin-center.mjs +777 -0
  18. package/plugin-transaction.mjs +300 -0
  19. package/public/activity.js +188 -0
  20. package/public/admin.html +820 -0
  21. package/public/admin.js +1167 -0
  22. package/public/announcement-forms.js +89 -0
  23. package/public/announcements.json +464 -0
  24. package/public/app.js +8826 -0
  25. package/public/approval-records.js +301 -0
  26. package/public/approval-summary.js +78 -0
  27. package/public/build.json +5 -0
  28. package/public/cache-upgrade.js +51 -0
  29. package/public/chat-copy.js +59 -0
  30. package/public/chat-files.js +87 -0
  31. package/public/desktop/desktop.css +816 -0
  32. package/public/desktop/desktop.html +871 -0
  33. package/public/desktop/desktop.js +4548 -0
  34. package/public/desktop/i18n.js +85 -0
  35. package/public/diagnostics.js +203 -0
  36. package/public/doctor-entry.js +94 -0
  37. package/public/doctor.css +205 -0
  38. package/public/doctor.js +769 -0
  39. package/public/donate.png +0 -0
  40. package/public/e2ee-transport.js +219 -0
  41. package/public/extensions.css +109 -0
  42. package/public/extensions.js +215 -0
  43. package/public/file-inbox.css +66 -0
  44. package/public/file-inbox.js +289 -0
  45. package/public/genui.css +8 -0
  46. package/public/genui.js +254 -0
  47. package/public/history.js +304 -0
  48. package/public/i18n.js +57 -0
  49. package/public/icon.svg +12 -0
  50. package/public/image-cache.js +141 -0
  51. package/public/image-preview.js +290 -0
  52. package/public/index.html +1548 -0
  53. package/public/insights.css +28 -0
  54. package/public/insights.js +290 -0
  55. package/public/jsqr.min.js +10104 -0
  56. package/public/lan-discovery.js +94 -0
  57. package/public/link-check.js +109 -0
  58. package/public/manifest.webmanifest +16 -0
  59. package/public/md.js +333 -0
  60. package/public/morphicons-init.js +41 -0
  61. package/public/motion.js +557 -0
  62. package/public/network.js +100 -0
  63. package/public/onboarding.css +36 -0
  64. package/public/onboarding.js +253 -0
  65. package/public/operations.js +141 -0
  66. package/public/permission-presets.js +159 -0
  67. package/public/plugin-center.css +120 -0
  68. package/public/plugin-center.js +666 -0
  69. package/public/plugin-icon.svg +5 -0
  70. package/public/plugin.html +68 -0
  71. package/public/plugin.js +211 -0
  72. package/public/qrcode.min.js +2297 -0
  73. package/public/relay-autopair.js +251 -0
  74. package/public/relay-devices.js +80 -0
  75. package/public/relay-settings.css +24 -0
  76. package/public/relay-settings.js +194 -0
  77. package/public/remote-state.js +27 -0
  78. package/public/remote-ui.css +148 -0
  79. package/public/remote-ui.js +243 -0
  80. package/public/session-deck.css +79 -0
  81. package/public/session-deck.js +180 -0
  82. package/public/session-presets.js +47 -0
  83. package/public/setup.css +18 -0
  84. package/public/setup.js +213 -0
  85. package/public/sha256.js +119 -0
  86. package/public/skills.css +81 -0
  87. package/public/skills.js +202 -0
  88. package/public/skins/blue-fish/DESIGN.md +24 -0
  89. package/public/skins/blue-fish/face.png +0 -0
  90. package/public/skins/blue-fish/icon-blush.png +0 -0
  91. package/public/skins/blue-fish/icon-sleep.png +0 -0
  92. package/public/skins/blue-fish/icon-smile.png +0 -0
  93. package/public/skins/blue-fish/icon-star.png +0 -0
  94. package/public/skins/blue-fish/icon-wink.png +0 -0
  95. package/public/skins/blue-fish/icon.png +0 -0
  96. package/public/skins/blue-fish/mascot.png +0 -0
  97. package/public/skins/blue-fish/pattern.png +0 -0
  98. package/public/skins/blue-fish/preview.html +12 -0
  99. package/public/skins/blue-fish/skin.css +122 -0
  100. package/public/skins/blue-fish/sparkles.svg +18 -0
  101. package/public/skins/bocchi/DESIGN.md +99 -0
  102. package/public/skins/bocchi/face.png +0 -0
  103. package/public/skins/bocchi/grain.png +0 -0
  104. package/public/skins/bocchi/icon-blush.png +0 -0
  105. package/public/skins/bocchi/icon-sleep.png +0 -0
  106. package/public/skins/bocchi/icon-smile.png +0 -0
  107. package/public/skins/bocchi/icon-star.png +0 -0
  108. package/public/skins/bocchi/icon-wink.png +0 -0
  109. package/public/skins/bocchi/icon.png +0 -0
  110. package/public/skins/bocchi/pattern-soft.png +0 -0
  111. package/public/skins/bocchi/pattern.png +0 -0
  112. package/public/skins/bocchi/preview.html +55 -0
  113. package/public/skins/bocchi/skin.css +233 -0
  114. package/public/skins/bocchi/stage-bg.png +0 -0
  115. package/public/skins/bocchi/stage-soft.png +0 -0
  116. package/public/skins/bocchi/stand.png +0 -0
  117. package/public/skins/bocchi/sticker-guitar.png +0 -0
  118. package/public/skins/kessoku/DESIGN.md +38 -0
  119. package/public/skins/kessoku/grain.png +0 -0
  120. package/public/skins/kessoku/skin.css +212 -0
  121. package/public/skins/kita/SOURCES.json +51 -0
  122. package/public/skins/kita/face.png +0 -0
  123. package/public/skins/kita/icon-live.png +0 -0
  124. package/public/skins/kita/icon-reddress.png +0 -0
  125. package/public/skins/kita/icon-seifuku.png +0 -0
  126. package/public/skins/kita/pattern.png +0 -0
  127. package/public/skins/kita/preview.html +56 -0
  128. package/public/skins/kita/skin.css +26 -0
  129. package/public/skins/kita/stand.png +0 -0
  130. package/public/skins/kita/sticker-live.png +0 -0
  131. package/public/skins/nijika/SOURCES.json +51 -0
  132. package/public/skins/nijika/face.png +0 -0
  133. package/public/skins/nijika/icon-live.png +0 -0
  134. package/public/skins/nijika/icon-reddress.png +0 -0
  135. package/public/skins/nijika/icon-seifuku.png +0 -0
  136. package/public/skins/nijika/pattern.png +0 -0
  137. package/public/skins/nijika/preview.html +56 -0
  138. package/public/skins/nijika/skin.css +25 -0
  139. package/public/skins/nijika/stand.png +0 -0
  140. package/public/skins/nijika/sticker-live.png +0 -0
  141. package/public/skins/penguin/DESIGN.md +33 -0
  142. package/public/skins/penguin/SOURCES.json +22 -0
  143. package/public/skins/penguin/aic-blueprint.svg +24 -0
  144. package/public/skins/penguin/endfield-triangles.svg +4 -0
  145. package/public/skins/penguin/face.png +0 -0
  146. package/public/skins/penguin/icon-blush.png +0 -0
  147. package/public/skins/penguin/icon-dizzy.png +0 -0
  148. package/public/skins/penguin/icon-laugh.png +0 -0
  149. package/public/skins/penguin/icon-sleep.png +0 -0
  150. package/public/skins/penguin/icon-smile.png +0 -0
  151. package/public/skins/penguin/icon-star.png +0 -0
  152. package/public/skins/penguin/icon-wink.png +0 -0
  153. package/public/skins/penguin/icon.png +0 -0
  154. package/public/skins/penguin/mascot.png +0 -0
  155. package/public/skins/penguin/pattern-night.png +0 -0
  156. package/public/skins/penguin/pattern.png +0 -0
  157. package/public/skins/penguin/preview.html +12 -0
  158. package/public/skins/penguin/skin.css +212 -0
  159. package/public/skins/ryo/SOURCES.json +51 -0
  160. package/public/skins/ryo/face.png +0 -0
  161. package/public/skins/ryo/icon-live.png +0 -0
  162. package/public/skins/ryo/icon-reddress.png +0 -0
  163. package/public/skins/ryo/icon-seifuku.png +0 -0
  164. package/public/skins/ryo/pattern.png +0 -0
  165. package/public/skins/ryo/preview.html +56 -0
  166. package/public/skins/ryo/skin.css +25 -0
  167. package/public/skins/ryo/stand.png +0 -0
  168. package/public/skins/ryo/sticker-live.png +0 -0
  169. package/public/sponsor-entry.js +21 -0
  170. package/public/styles.css +1494 -0
  171. package/public/subagents.css +61 -0
  172. package/public/subagents.js +275 -0
  173. package/public/task-board.js +109 -0
  174. package/public/teams.js +98 -0
  175. package/public/theme-picker.css +58 -0
  176. package/public/theme-vars.css +1044 -0
  177. package/public/theme.js +166 -0
  178. package/public/transcribe-core.js +74 -0
  179. package/public/turn-results.js +121 -0
  180. package/public/update.json +49 -0
  181. package/public/vendor/gsap/NOTICE.md +10 -0
  182. package/public/vendor/gsap/gsap.min.js +11 -0
  183. package/public/vendor/morphicons/LICENSE +21 -0
  184. package/public/vendor/morphicons/README.md +10 -0
  185. package/public/vendor/morphicons/controller-CXZuwJ_M.js +152 -0
  186. package/public/vendor/morphicons/dom.js +206 -0
  187. package/public/vendor/morphicons/element.js +261 -0
  188. package/public/vendor/morphicons/normalize-CYnN3Npw.js +540 -0
  189. package/public/vendor/morphicons/spring-CFHloqPP.js +623 -0
  190. package/public/version.json +3 -0
  191. package/public/voice-input.js +739 -0
  192. package/public/workflow.css +365 -0
  193. package/public/workflow.js +409 -0
  194. package/session-file.mjs +39 -0
  195. package/skills/dsh-remote-doctor/SKILL.md +186 -0
  196. package/skills/dsh-remote-doctor/references/wiki/README.md +40 -0
  197. package/skills/dsh-remote-doctor/references/wiki/ai-guide.md +61 -0
  198. package/skills/dsh-remote-doctor/references/wiki/connection.md +76 -0
  199. package/skills/dsh-remote-doctor/references/wiki/errors.md +26 -0
  200. package/skills/dsh-remote-doctor/references/wiki/evidence.md +44 -0
  201. package/skills/dsh-remote-doctor/references/wiki/files.md +31 -0
  202. package/skills/dsh-remote-doctor/references/wiki/maintenance.md +30 -0
  203. package/skills/dsh-remote-doctor/references/wiki/notifications.md +33 -0
  204. package/skills/dsh-remote-doctor/references/wiki/operations.md +32 -0
  205. package/skills/dsh-remote-doctor/references/wiki/plugins.md +90 -0
  206. package/skills/dsh-remote-doctor/references/wiki/sessions.md +45 -0
  207. package/skills/dsh-remote-doctor/references/wiki/sources.md +27 -0
  208. package/skills.mjs +53 -0
  209. package/task-board.mjs +57 -0
  210. package/teams.mjs +58 -0
@@ -0,0 +1,1167 @@
1
+ /* DSH Remote 网关/插件管理页 · 零依赖 */
2
+ 'use strict'
3
+
4
+ const $ = (id) => document.getElementById(id)
5
+ const I18N = window.I18N
6
+ const t = (k, v) => I18N.t(k, v)
7
+ I18N.init(window.ADMIN_STR)
8
+ // 插件内嵌(/remote/ 或 ?embedded=1)直接进管理面板, 不需要任何令牌门禁;
9
+ // 独立网关模式(/admin/)仍保留令牌输入。路径判断兼容无尾斜杠 /remote。
10
+ const pluginMode = location.pathname === '/remote'
11
+ || location.pathname.startsWith('/remote/')
12
+ || new URLSearchParams(location.search).get('embedded') === '1'
13
+ const API = pluginMode ? '/remote/admin/api' : '/admin/api'
14
+ window.mountAdminRelaySettings = () => window.DshRelaySettings?.mount($('relay-settings'), {
15
+ connection: () => { const saved=token;return {url:route=>API+route,headers:adminHeaders({},saved),valid:()=>token===saved} },
16
+ path:'/relay', credentials:'same-origin', phonePairingCode, deviceManagement:!pluginMode
17
+ })
18
+ // 沙箱 iframe/隐私模式里 localStorage 可能抛 SecurityError, 不能让它杀死整个页面
19
+ const store = {
20
+ get(k) { try { return localStorage.getItem(k) } catch { return null } },
21
+ set(k, v) { try { localStorage.setItem(k, v) } catch {} },
22
+ del(k) { try { localStorage.removeItem(k) } catch {} }
23
+ }
24
+ let token = store.get('dshAdminToken') || new URLSearchParams(location.search).get('token') || ''
25
+ function adminHeaders(extra = {}, accessToken = token) {
26
+ const headers = { 'x-dsh-remote-client': 'admin', ...extra }
27
+ // /remote/* 可能由 Caddy Basic Auth 保护。插件路由自身已在 DSH 登录态内,
28
+ // 这里不能再写 Authorization: Bearer,否则会覆盖浏览器的 Basic 凭据并形成 401 循环。
29
+ if (!pluginMode && accessToken) headers.authorization = 'Bearer ' + accessToken
30
+ return headers
31
+ }
32
+ let timer = null
33
+ let gatewayRunning = false
34
+ let gatewayBusy = false
35
+ let shownToken = token
36
+ let lastState = null
37
+ let qrShown = false
38
+ let qrToken = ''
39
+ let qrLabel = ''
40
+ let deviceKeyBusy = false
41
+ let lanBusy = false, lanCode = '', lanExpiry = 0, lanRevision = 0, lanRead = null
42
+ const lanText = (zh, en) => I18N.lang === 'en' ? en : zh
43
+ function lanError(code) {
44
+ return {
45
+ DEVICE_KEYS_REQUIRED: lanText('请先启用独立设备密钥。', 'Enable independent device keys first.'),
46
+ LAN_LISTENER_REQUIRED: lanText('网关目前仅允许本机访问,请改用可从局域网访问的监听地址。', 'The gateway only accepts local connections. Configure a LAN-accessible listener.'),
47
+ DISCOVERY_PORT_UNAVAILABLE: lanText('发现端口被占用,请检查是否运行了其他网关。', 'The discovery port is occupied. Check for another gateway.'),
48
+ GATEWAY_UNAVAILABLE: lanText('网关暂不可用,请检查运行状态。', 'The gateway is unavailable. Check its status.'),
49
+ PAIRING_CLOSED: lanText('配对已关闭,请重新开放。', 'Pairing is closed. Open a new window.'),
50
+ }[code] || lanText('操作失败,请检查网关后重试。', 'Operation failed. Check the gateway and try again.')
51
+ }
52
+ function renderLan(state = {}) {
53
+ $('lan-pairing-title').textContent = lanText('局域网发现与配对', 'LAN discovery and pairing')
54
+ $('lan-pairing-hint').textContent = lanText('需先启用上方的独立设备密钥,再开放配对。Android 手机可搜索同一 Wi-Fi 下的电脑,输入限时配对码连接。配对码仅显示本次,成功后自动关闭;扫码与手动连接仍可使用。', 'Enable independent device keys above, then open pairing. Find this computer from the Android app on the same Wi-Fi and enter the one-time code. Pairing closes after success; QR and manual connections remain available.')
55
+ $('btn-lan-open').textContent = lanText('开放 10 分钟配对', 'Open pairing for 10 minutes')
56
+ $('btn-lan-close').textContent = lanText('关闭配对', 'Close pairing')
57
+ const enabled = state.enabled === true
58
+ if (!enabled || state.expiresAt !== lanExpiry || Date.now() >= lanExpiry) lanCode = ''
59
+ $('lan-pairing-code').textContent = lanCode
60
+ $('lan-pairing-code').hidden = !lanCode
61
+ $('btn-lan-open').disabled = lanBusy || !lastState?.deviceKeys?.enabled
62
+ $('btn-lan-close').disabled = lanBusy || !enabled
63
+ $('lan-pairing-status').textContent = enabled ? lanText('配对开放至 ', 'Pairing open until ') + new Date(state.expiresAt).toLocaleTimeString()
64
+ : state.error ? lanError(state.error) : lanText('当前未开放配对。', 'Pairing is closed.')
65
+ }
66
+ async function refreshLan() {
67
+ if (lanBusy || lanRead || !lastState) return
68
+ const savedToken = token, revision = lanRevision, job = {}
69
+ lanRead = job
70
+ try {
71
+ const response = await fetch(API + '/lan', { headers: adminHeaders(), credentials: 'same-origin', signal: AbortSignal.timeout(5000) })
72
+ const state = await response.json()
73
+ if (savedToken !== token || lanBusy || revision !== lanRevision) return
74
+ if (!response.ok) { lanCode = ''; renderLan({ error: state.error || 'GATEWAY_UNAVAILABLE' }); return }
75
+ renderLan(state)
76
+ } catch { if (savedToken === token && !lanBusy && revision === lanRevision) { lanCode = ''; renderLan({ error: 'GATEWAY_UNAVAILABLE' }) } }
77
+ finally { if (lanRead === job) lanRead = null }
78
+ }
79
+ async function changeLan(enabled) {
80
+ if (lanBusy) return
81
+ lanRevision++
82
+ lanBusy = true
83
+ $('btn-lan-open').disabled = true; $('btn-lan-close').disabled = true
84
+ const savedToken = token, revision = lanRevision
85
+ try {
86
+ const response = await fetch(API + '/lan', { method: 'POST', headers: adminHeaders({ 'content-type': 'application/json' }),
87
+ credentials: 'same-origin', signal: AbortSignal.timeout(8000), body: JSON.stringify({ enabled }) })
88
+ const state = await response.json()
89
+ if (savedToken !== token || revision !== lanRevision) return
90
+ if (!response.ok || !state.ok) throw Error(state.error || 'PAIRING_FAILED')
91
+ lanCode = state.code || ''; lanExpiry = state.expiresAt || 0
92
+ lanBusy = false; renderLan(state)
93
+ } catch (error) { if (savedToken === token && revision === lanRevision) { lanCode = ''; lanBusy = false; renderLan({ error: error.message }); toast(lanError(error.message), 'err') } }
94
+ finally { if (revision === lanRevision) lanBusy = false }
95
+ }
96
+ $('btn-lan-open').addEventListener('click', () => changeLan(true))
97
+ $('btn-lan-close').addEventListener('click', () => changeLan(false))
98
+ const revealedDeviceKeys = new Set()
99
+ let gatewayPort = 8787
100
+ let gatewayPortLoaded = false
101
+ let loginStartup = null
102
+ let loginStartupBusy = false
103
+ let loginStartupGeneration = 0
104
+ function renderLoginStartup() {
105
+ const state = loginStartup
106
+ const key = !state ? 'unavailable' : !state.supported ? 'unsupported' : state.code === 'STARTUP_CONFLICT' ? 'conflict'
107
+ : state.code ? 'broken' : state.enabled ? 'on' : 'off'
108
+ $('login-startup-status').textContent = t('startup.' + key)
109
+ const btn = $('btn-login-startup')
110
+ btn.disabled = loginStartupBusy || !state?.supported || state.code === 'STARTUP_CONFLICT'
111
+ btn.textContent = t('startup.' + (loginStartupBusy ? 'busy' : state?.enabled ? 'disable' : 'enable'))
112
+ $('btn-login-startup-repair').classList.toggle('hidden', state?.code !== 'STARTUP_FILES_MISSING')
113
+ $('btn-login-startup-repair').disabled = loginStartupBusy
114
+ $('btn-login-startup-refresh').disabled = loginStartupBusy
115
+ }
116
+ async function loadLoginStartup() {
117
+ if (loginStartupBusy) return
118
+ const generation = ++loginStartupGeneration, accessToken = token
119
+ try {
120
+ const res = await fetch(`${API}/autostart`, { headers: adminHeaders(), credentials: 'same-origin', signal: AbortSignal.timeout(20000) })
121
+ const out = await res.json()
122
+ if (generation !== loginStartupGeneration || token !== accessToken) return
123
+ loginStartup = res.ok && out.ok ? out : null
124
+ } catch { if (generation === loginStartupGeneration && token === accessToken) loginStartup = null }
125
+ if (generation === loginStartupGeneration && token === accessToken) renderLoginStartup()
126
+ }
127
+ async function changeLoginStartup(enabled) {
128
+ if (loginStartupBusy) return
129
+ loginStartupBusy = true
130
+ ++loginStartupGeneration
131
+ const accessToken = token
132
+ renderLoginStartup()
133
+ try {
134
+ const res = await fetch(`${API}/autostart`, { method: 'POST', headers: adminHeaders({ 'content-type': 'application/json' }),
135
+ credentials: 'same-origin', signal: AbortSignal.timeout(30000), body: JSON.stringify({ enabled }) })
136
+ const out = await res.json()
137
+ if (token !== accessToken) return
138
+ if (!res.ok || !out.ok) throw Error(out.detail || out.error || t('toast.opFailed'))
139
+ loginStartup = out
140
+ toast(t('startup.' + (out.enabled ? 'savedOn' : 'savedOff')), 'ok')
141
+ } catch (error) { if (token === accessToken) toast(error.message || t('toast.opFailed'), 'err') }
142
+ finally {
143
+ loginStartupBusy = false
144
+ renderLoginStartup()
145
+ if (token || pluginMode) void loadLoginStartup()
146
+ }
147
+ }
148
+ $('btn-login-startup').addEventListener('click', () => changeLoginStartup(!loginStartup?.enabled))
149
+ $('btn-login-startup-repair').addEventListener('click', () => changeLoginStartup(true))
150
+ $('btn-login-startup-refresh').addEventListener('click', loadLoginStartup)
151
+ let doctorExpanded = store.get('dshAdminDoctorCollapsed') !== '1'
152
+ let doctorChecks = []
153
+ const HOST_IP_SELECTION_KEY = 'dshAdminEnabledHostIPsV1'
154
+ const MANUAL_HOST_IP_KEY = 'dshAdminManualHostIPsV1'
155
+ const setup = window.DshSetup?.mount($('admin-setup'), {
156
+ base: pluginMode ? '/remote/' : '/',
157
+ canStart: pluginMode,
158
+ inConsole: true,
159
+ start: () => pluginMode ? $('btn-gateway').click() : $('doctor-card').scrollIntoView({ behavior: 'smooth' }),
160
+ console: () => { window.DshConsole?.select('diagnostics'); $('doctor-card').scrollIntoView({ behavior: 'smooth' }) },
161
+ deviceKey: () => $('btn-device-key-add').click(), hosts: st => enabledHostIPs(st),
162
+ })
163
+ window.addEventListener('dsh-remote-setup', event => setup?.show(event.detail?.step))
164
+ document.addEventListener('dsh-remote-section', event => {
165
+ if (event.detail.section !== 'devices') {
166
+ qrShown = false; qrToken = ''; qrLabel = ''
167
+ $('pair-box').classList.add('hidden')
168
+ revealedDeviceKeys.clear()
169
+ if (lastState) renderDeviceKeys(lastState,lastState.mode === 'gateway')
170
+ setup?.conceal?.()
171
+ }
172
+ })
173
+
174
+ function normalizedHostIPs(st) {
175
+ const detected = Array.isArray(st?.lanIPs) ? st.lanIPs : []
176
+ return [...new Set([...detected, ...manualHostIPs(st)].map(validManualHost).filter(Boolean))]
177
+ }
178
+
179
+ function validManualHost(value) {
180
+ const host = String(value || '').trim()
181
+ if (!host || host.length > 253 || host === '0.0.0.0' || host === '127.0.0.1') return ''
182
+ if (!/^[A-Za-z0-9.-]+$/.test(host) || host.startsWith('.') || host.endsWith('.') || host.includes('..')) return ''
183
+ if (/^\d+(?:\.\d+){3}$/.test(host) && host.split('.').some(part => Number(part) > 255)) return ''
184
+ const labels = host.split('.')
185
+ if (labels.some(label => !label || label.length > 63 || label.startsWith('-') || label.endsWith('-'))) return ''
186
+ return host
187
+ }
188
+
189
+ function hostIPScope(st) {
190
+ return [st?.hostname || location.hostname || 'host', st?.host || ''].join('|')
191
+ }
192
+
193
+ function manualHostIPScope(st) {
194
+ return st?.hostname || location.hostname || 'host'
195
+ }
196
+
197
+ function hostIPPreferences() {
198
+ try {
199
+ const value = JSON.parse(store.get(HOST_IP_SELECTION_KEY) || '{}')
200
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : {}
201
+ } catch {
202
+ return {}
203
+ }
204
+ }
205
+
206
+ function manualHostPreferences() {
207
+ try {
208
+ const value = JSON.parse(store.get(MANUAL_HOST_IP_KEY) || '{}')
209
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : {}
210
+ } catch {
211
+ return {}
212
+ }
213
+ }
214
+
215
+ function manualHostIPs(st) {
216
+ const values = manualHostPreferences()[manualHostIPScope(st)]
217
+ return Array.isArray(values) ? [...new Set(values.map(validManualHost).filter(Boolean))] : []
218
+ }
219
+
220
+ function saveManualHostIPs(st, values) {
221
+ const prefs = manualHostPreferences()
222
+ prefs[manualHostIPScope(st)] = [...new Set(values.map(validManualHost).filter(Boolean))]
223
+ store.set(MANUAL_HOST_IP_KEY, JSON.stringify(prefs))
224
+ }
225
+
226
+ function enabledHostIPs(st) {
227
+ const all = normalizedHostIPs(st)
228
+ if (!all.length) return []
229
+ const saved = hostIPPreferences()[hostIPScope(st)]
230
+ if (!Array.isArray(saved)) return all
231
+ const selected = all.filter(ip => saved.includes(ip))
232
+ return selected.length ? selected : all
233
+ }
234
+
235
+ function saveEnabledHostIPs(st, selected) {
236
+ const prefs = hostIPPreferences()
237
+ prefs[hostIPScope(st)] = normalizedHostIPs(st).filter(ip => selected.includes(ip))
238
+ store.set(HOST_IP_SELECTION_KEY, JSON.stringify(prefs))
239
+ }
240
+
241
+ function addManualHostIP() {
242
+ if (!lastState) return
243
+ const input = prompt(t('hostIPs.addPrompt'), '')
244
+ if (input === null) return
245
+ const host = validManualHost(input)
246
+ if (!host) {
247
+ toast(t('hostIPs.invalid'), 'err')
248
+ return
249
+ }
250
+ if (normalizedHostIPs(lastState).includes(host)) {
251
+ toast(t('hostIPs.exists'), 'err')
252
+ return
253
+ }
254
+ saveManualHostIPs(lastState, [...manualHostIPs(lastState), host])
255
+ saveEnabledHostIPs(lastState, [...enabledHostIPs(lastState), host])
256
+ render(lastState)
257
+ }
258
+
259
+ function removeManualHostIP(st, host) {
260
+ saveManualHostIPs(st, manualHostIPs(st).filter(value => value !== host))
261
+ render(st)
262
+ }
263
+
264
+ function renderHostIPs(st) {
265
+ const all = normalizedHostIPs(st)
266
+ const selected = enabledHostIPs(st)
267
+ const manual = new Set(manualHostIPs(st))
268
+ const rows = $('host-ip-rows')
269
+ const empty = $('host-ip-empty')
270
+ const summary = $('host-ip-summary')
271
+ if (!rows || !empty || !summary) return
272
+ summary.textContent = all.length
273
+ ? t('hostIPs.summary', { enabled: selected.length, total: all.length })
274
+ : t('hostIPs.empty')
275
+ rows.innerHTML = all.map(ip => `<tr>
276
+ <td class="host-ip-toggle"><label class="host-ip-switch" title="${esc(t('hostIPs.enable'))}"><input type="checkbox" data-host-ip-toggle="${esc(ip)}" ${selected.includes(ip) ? 'checked' : ''}><span aria-hidden="true"></span></label></td>
277
+ <td class="mono host-ip-value">${esc(ip)}</td>
278
+ <td class="host-ip-use">${esc(t(selected.includes(ip) ? 'hostIPs.enabled' : 'hostIPs.disabled'))}${manual.has(ip) ? ` <button class="mini-btn host-ip-remove" type="button" data-host-ip-remove="${esc(ip)}">${esc(t('hostIPs.remove'))}</button>` : ''}</td>
279
+ </tr>`).join('')
280
+ empty.classList.toggle('hidden', all.length > 0)
281
+ rows.querySelectorAll('[data-host-ip-toggle]').forEach(input => input.addEventListener('change', () => {
282
+ const ip = input.dataset.hostIpToggle
283
+ const next = enabledHostIPs(st).filter(value => value !== ip)
284
+ if (input.checked) next.push(ip)
285
+ if (!next.length) {
286
+ input.checked = true
287
+ toast(t('hostIPs.keepOne'), 'err')
288
+ return
289
+ }
290
+ saveEnabledHostIPs(st, next)
291
+ render(st)
292
+ }))
293
+ rows.querySelectorAll('[data-host-ip-remove]').forEach(button => button.addEventListener('click', () => {
294
+ removeManualHostIP(st, button.dataset.hostIpRemove)
295
+ }))
296
+ }
297
+
298
+ function onlineClientDevices(st) {
299
+ return (st.devices || []).filter(device => device.online && (device.kind === 'app' || device.kind === 'web'))
300
+ }
301
+
302
+ function firewallCommand(st) {
303
+ const port = Number(st.port || gatewayPort) || 8787
304
+ const ip = enabledHostIPs(st).find(value => /^10\.|^192\.168\.|^172\.(1[6-9]|2\d|3[01])\.|^100\.(6[4-9]|[7-9]\d|1[01]\d|12[0-7])\./.test(value || ''))
305
+ let cidr = 'LocalSubnet'
306
+ if (/^10\./.test(ip || '')) cidr = '10.0.0.0/8'
307
+ else if (/^192\.168\./.test(ip || '')) cidr = '192.168.0.0/16'
308
+ else if (/^172\./.test(ip || '')) cidr = '172.16.0.0/12'
309
+ else if (/^100\./.test(ip || '')) cidr = '100.64.0.0/10'
310
+ if (st.platform === 'win32') return `New-NetFirewallRule -DisplayName "DSH Remote ${port}" -Direction Inbound -Protocol TCP -LocalPort ${port} -RemoteAddress ${cidr} -Action Allow -Profile Private`
311
+ if (st.platform === 'darwin') return `系统设置 → 网络 → 防火墙;仅允许 Node.js / DSH Remote 接受可信网络入站连接(TCP ${port})`
312
+ return `sudo ufw allow from ${cidr} to any port ${port} proto tcp\n# firewalld: sudo firewall-cmd --zone=home --add-source=${cidr} --permanent && sudo firewall-cmd --zone=home --add-port=${port}/tcp --permanent && sudo firewall-cmd --reload`
313
+ }
314
+
315
+ function buildDoctorChecks(st) {
316
+ const isGateway = st.mode === 'gateway'
317
+ const port = Number(st.port || gatewayPort) || 8787
318
+ const ip = enabledHostIPs(st).find(value => value && value !== '127.0.0.1' && value !== '0.0.0.0')
319
+ const base = ip ? `http://${ip}:${port}` : ''
320
+ const clients = onlineClientDevices(st)
321
+ const events = st.events || {}
322
+ const realtime = !!(events.mux?.connected && events.host?.connected)
323
+ return [
324
+ { id: 'dsh', status: st.upstream?.reachable === true ? 'pass' : st.upstream?.reachable === false ? 'fail' : 'warn', title: t('doctor.dsh'), detail: st.upstream?.reachable == null ? window.DshRemoteUI?.t('waiting') || '尚未确认' : t(st.upstream.reachable ? 'doctor.dshPass' : 'doctor.dshFail') },
325
+ { id: 'gateway', status: isGateway && !st.gatewayAuthError ? 'pass' : st.gatewayRunning ? 'warn' : 'fail', title: t('doctor.gateway'), detail: st.gatewayAuthError || (isGateway ? t('doctor.gatewayPass', { host: st.host, port }) : st.gatewayRunning ? window.DshRemoteUI?.t('attention') || '管理状态尚未确认' : t('doctor.gatewayFail')), action: !isGateway && !st.gatewayRunning && pluginMode ? 'start' : '' },
326
+ { id: 'network', status: isGateway && ip && st.host !== '127.0.0.1' ? 'pass' : 'fail', title: t('doctor.network'), detail: base ? t('doctor.networkPass', { base }) : t('doctor.networkFail'), action: base ? 'address' : '' },
327
+ { id: 'firewall', status: clients.length ? 'pass' : 'warn', title: t('doctor.firewall'), detail: t(clients.length ? 'doctor.firewallPass' : 'doctor.firewallWarn', { port }), action: clients.length ? '' : 'firewall' },
328
+ { id: 'device', status: clients.length ? 'pass' : 'warn', title: t('doctor.device'), detail: t(clients.length ? 'doctor.devicePass' : 'doctor.deviceWait', { n: clients.length }), action: isGateway && !clients.length ? 'qr' : '' },
329
+ { id: 'realtime', status: realtime ? 'pass' : 'warn', title: t('doctor.realtime'), detail: t(realtime ? 'doctor.realtimePass' : 'doctor.realtimeFail') },
330
+ ]
331
+ }
332
+
333
+ function renderDoctor(st) {
334
+ doctorChecks = buildDoctorChecks(st)
335
+ const passed = doctorChecks.filter(check => check.status === 'pass').length
336
+ const remaining = doctorChecks.length - passed
337
+ const allGood = remaining === 0
338
+ const card = $('doctor-card')
339
+ card.classList.toggle('expanded', doctorExpanded)
340
+ $('doctor-toggle').setAttribute('aria-expanded', String(doctorExpanded))
341
+ $('doctor-progress').textContent = `${passed}/${doctorChecks.length}`
342
+ $('doctor-subtitle').textContent = t(allGood ? 'doctor.ready' : 'doctor.needsWork', { n: remaining })
343
+ $('doctor-summary').textContent = t(allGood ? 'doctor.allGood' : 'doctor.partial')
344
+ $('doctor-summary').classList.toggle('ok', allGood)
345
+ const actionText = { start: 'doctor.start', qr: 'doctor.showQr', address: 'doctor.copyAddress', firewall: 'doctor.copyCommand' }
346
+ $('doctor-steps').innerHTML = doctorChecks.map(check => `<div class="doctor-step ${check.status}">
347
+ <span class="doctor-mark" aria-hidden="true">${check.status === 'pass' ? '✓' : check.status === 'fail' ? '!' : '·'}</span>
348
+ <span class="doctor-copy"><strong>${esc(check.title)}</strong><span>${esc(check.detail)}</span></span>
349
+ ${check.action ? `<button class="mini-btn doctor-action" type="button" data-doctor-action="${check.action}">${esc(t(actionText[check.action]))}</button>` : ''}
350
+ </div>`).join('')
351
+ }
352
+
353
+ async function doctorCopy(value, messageKey) {
354
+ try {
355
+ await navigator.clipboard.writeText(value)
356
+ toast(t(messageKey), 'ok')
357
+ } catch {
358
+ toast(t('toast.copyFailed'), 'err')
359
+ }
360
+ }
361
+
362
+ async function loadGatewayConfig() {
363
+ if (!pluginMode) return
364
+ try {
365
+ const res = await fetch(`${API}/config`, {
366
+ headers: adminHeaders(), credentials: 'same-origin'
367
+ })
368
+ const out = await res.json().catch(() => ({}))
369
+ if (out.ok) {
370
+ gatewayPort = Number(out.port) || 8787
371
+ gatewayPortLoaded = true
372
+ const row = $('gateway-port-row')
373
+ const input = $('gateway-port-input')
374
+ if (row) row.classList.toggle('hidden', !pluginMode)
375
+ if (input && document.activeElement !== input) input.value = gatewayPort
376
+ const cur = $('gateway-port-current')
377
+ if (cur) cur.textContent = t('gatewayPort.current', { port: gatewayPort })
378
+ }
379
+ } catch {}
380
+ }
381
+
382
+ function toast(text, kind = '') {
383
+ const el = $('toast')
384
+ el.textContent = text
385
+ el.className = 'toast ' + kind
386
+ clearTimeout(toast._t)
387
+ toast._t = setTimeout(() => el.classList.add('hidden'), 2600)
388
+ }
389
+
390
+ /* ---------------- 反馈 ---------------- */
391
+ function openFeedbackMenu() {
392
+ const menu = $('fb-menu')
393
+ // Escape header clipping/stacking contexts. The top layer remains inside
394
+ // this iframe, so also constrain the menu to its actual viewport.
395
+ if (menu.parentElement !== document.body) document.body.append(menu)
396
+ menu.classList.remove('hidden')
397
+ if (typeof menu.showPopover === 'function') {
398
+ menu.setAttribute('popover', 'manual')
399
+ menu.showPopover()
400
+ }
401
+ positionFeedbackMenu()
402
+ $('btn-feedback').setAttribute('aria-expanded', 'true')
403
+ const first = $('fb-menu').querySelector('[role="menuitem"]')
404
+ if (first) first.focus()
405
+ }
406
+ function closeFeedbackMenu() {
407
+ const menu = $('fb-menu')
408
+ if (typeof menu.hidePopover === 'function' && menu.matches(':popover-open')) menu.hidePopover()
409
+ menu.classList.add('hidden')
410
+ $('btn-feedback').setAttribute('aria-expanded', 'false')
411
+ }
412
+ function toggleFeedbackMenu() {
413
+ $('fb-menu').classList.contains('hidden') ? openFeedbackMenu() : closeFeedbackMenu()
414
+ }
415
+ function positionFeedbackMenu() {
416
+ const menu = $('fb-menu')
417
+ if (menu.classList.contains('hidden')) return
418
+ const trigger = $('btn-feedback').getBoundingClientRect()
419
+ const gap = 8, width = Math.max(0, Math.min(280, window.innerWidth - gap * 2))
420
+ menu.style.width = width + 'px'
421
+ menu.style.maxHeight = Math.max(0, window.innerHeight - gap * 2) + 'px'
422
+ const height = menu.getBoundingClientRect().height
423
+ const left = Math.max(gap, Math.min(trigger.right - width, window.innerWidth - width - gap))
424
+ const below = trigger.bottom + gap
425
+ const top = below + height <= window.innerHeight - gap ? below : Math.max(gap, Math.min(trigger.top - gap - height, window.innerHeight - height - gap))
426
+ menu.style.left = left + 'px'; menu.style.top = top + 'px'
427
+ }
428
+
429
+ function fmtUptime(sec) {
430
+ if (sec < 60) return sec + t('unit.sec')
431
+ if (sec < 3600) return Math.floor(sec / 60) + t('unit.min')
432
+ if (sec < 86400) return Math.floor(sec / 3600) + t('unit.hour') + Math.floor(sec % 3600 / 60) + t('unit.minShort')
433
+ return Math.floor(sec / 86400) + t('unit.day') + Math.floor(sec % 86400 / 3600) + t('unit.hour')
434
+ }
435
+
436
+ function fmtTime(ts) {
437
+ const d = new Date(ts)
438
+ const p = (n) => String(n).padStart(2, '0')
439
+ return `${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`
440
+ }
441
+
442
+ function esc(value) {
443
+ return String(value ?? '').replace(/[<>&"]/g, c => ({ '<': '&lt;', '>': '&gt;', '&': '&amp;', '"': '&quot;' }[c]))
444
+ }
445
+
446
+ function renderDeviceKeys(st, isGateway) {
447
+ const config = st.deviceKeys || { supported: false, enabled: false, entries: [] }
448
+ const supported = isGateway && config.supported !== false
449
+ const enabled = supported && config.enabled === true
450
+ const toggleWrap = $('device-key-toggle')
451
+ toggleWrap.classList.toggle('hidden', !isGateway && !pluginMode)
452
+ const toggle = $('device-key-enabled')
453
+ toggle.checked = enabled
454
+ toggle.disabled = !supported || deviceKeyBusy
455
+ $('btn-device-key-add').classList.toggle('hidden', !enabled)
456
+ $('btn-device-key-add').disabled = deviceKeyBusy
457
+ $('shared-token-row').classList.toggle('hidden', enabled)
458
+ $('device-key-panel').classList.toggle('hidden', !enabled)
459
+ if (!enabled) {
460
+ $('device-key-rows').innerHTML = ''
461
+ $('device-key-empty').classList.add('hidden')
462
+ return
463
+ }
464
+ const entries = Array.isArray(config.entries) ? config.entries : []
465
+ $('device-key-empty').classList.toggle('hidden', entries.length > 0)
466
+ const keyHtml = entries.map(entry => {
467
+ const note = entry.note || t('deviceKeys.neverUsed')
468
+ const ip = entry.lastIp || t('deviceKeys.neverUsed')
469
+ return `<div class="device-key-grid" data-device-key-id="${esc(entry.id)}">
470
+ <div class="device-key-note" data-label="${esc(t('deviceKeys.note'))}"><span>${esc(note)}</span><button class="mini-btn" type="button" data-device-key-note="${esc(entry.id)}">${esc(t('deviceKeys.edit'))}</button></div>
471
+ <div class="device-key-ip" data-label="${esc(t('deviceKeys.ip'))}">${esc(ip)}</div>
472
+ <code data-label="Token">${revealedDeviceKeys.has(entry.id) ? esc(entry.token) : '•••• •••• ••••'}</code>
473
+ <div class="device-key-actions">
474
+ <button class="mini-btn" type="button" data-device-key-show="${esc(entry.id)}">${esc(window.DshRemoteUI?.t(revealedDeviceKeys.has(entry.id) ? 'hide' : 'show') || '显示令牌')}</button>
475
+ <button class="mini-btn" type="button" data-device-key-qr="${esc(entry.id)}">${esc(t('qrCode'))}</button>
476
+ <button class="mini-btn" type="button" data-device-key-rotate="${esc(entry.id)}">${esc(t('rotateToken'))}</button>
477
+ <button class="mini-btn" type="button" data-device-key-copy="${esc(entry.id)}">${esc(t('copyToken'))}</button>
478
+ <button class="mini-btn danger" type="button" data-device-key-revoke="${esc(entry.id)}">${esc(t('deviceKeys.revoke'))}</button>
479
+ </div>
480
+ </div>`
481
+ }).join('')
482
+ if ($('device-key-rows').innerHTML !== keyHtml) $('device-key-rows').innerHTML = keyHtml
483
+ }
484
+
485
+ let stateLoadJob = null
486
+ async function loadState() {
487
+ if (!token && !pluginMode) return
488
+ if (stateLoadJob?.token === token) return stateLoadJob.promise
489
+ const job = { token }
490
+ stateLoadJob = job
491
+ job.promise = readState(job).finally(() => { if (stateLoadJob === job) stateLoadJob = null })
492
+ return job.promise
493
+ }
494
+ async function readState(job) {
495
+ try {
496
+ const res = await fetch(`${API}/state`, {
497
+ headers: adminHeaders({}, job.token), credentials: 'same-origin',
498
+ signal: typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function' ? AbortSignal.timeout(10000) : undefined
499
+ })
500
+ if (stateLoadJob !== job || token !== job.token) return
501
+ if (!res.ok && res.status !== 401) throw new Error('HTTP ' + res.status)
502
+ if (res.status === 401) throw new Error(pluginMode ? 'AUTH_LAYER' : 'AUTH')
503
+ if (pluginMode && !String(res.headers.get('content-type') || '').includes('application/json')) throw new Error('AUTH_LAYER')
504
+ const st = await res.json()
505
+ if (stateLoadJob !== job || token !== job.token) return
506
+ render(st)
507
+ } catch (e) {
508
+ if (stateLoadJob !== job || token !== job.token) return
509
+ setup?.update(null)
510
+ window.DshConsole?.update(null)
511
+ qrShown = false; qrToken = ''; qrLabel = ''
512
+ $('pair-box').classList.add('hidden')
513
+ revealedDeviceKeys.clear()
514
+ if (lastState) renderDeviceKeys(lastState,lastState.mode === 'gateway')
515
+ if (e.message === 'AUTH') {
516
+ toast(t('toast.tokenInvalid'), 'err')
517
+ logout()
518
+ } else if (e.message === 'AUTH_LAYER') {
519
+ $('conn-badge').textContent = t('toast.authLayer')
520
+ $('conn-badge').className = 'conn-badge off'
521
+ } else {
522
+ $('conn-badge').textContent = t('toast.connFailed')
523
+ $('conn-badge').className = 'conn-badge off'
524
+ }
525
+ }
526
+ }
527
+
528
+ function render(st) {
529
+ lastState = st
530
+ void refreshLan()
531
+ const isPlugin = st.mode === 'plugin'
532
+ const isGateway = st.mode === 'gateway'
533
+ shownToken = st.gatewayAuthError ? '' : st.token || token
534
+ setup?.update({ ...st, token: shownToken })
535
+ $('conn-badge').textContent = t(st.gatewayRunning ? 'badge.gateway' : isPlugin ? 'badge.embedded' : isGateway ? 'badge.gateway' : 'badge.connected')
536
+ $('conn-badge').className = 'conn-badge ' + (isPlugin || isGateway ? 'on' : 'off')
537
+ $('conn-badge').title = st.gatewayAuthError || t(isGateway ? 'badge.gateway.title' : 'badge.gatewayDown')
538
+ $('token-full').textContent = shownToken || t(st.gatewayAuthError ? 'token.unavailable' : isPlugin ? 'token.pluginNoGateway' : 'token.unavailable')
539
+ // 主机端插件模式: 显示真实令牌(复制可用), 只隐藏退出按钮; 令牌门禁本身不存在
540
+ $('btn-copy').classList.toggle('hidden', !shownToken)
541
+ $('btn-logout').classList.toggle('hidden', pluginMode)
542
+ // 二维码与轮换只在网关模式下可用(二维码里有完整令牌, 不能在没有网关时生成)
543
+ $('btn-qr').classList.toggle('hidden', isGateway !== true || !shownToken)
544
+ $('btn-rotate').classList.toggle('hidden', isGateway !== true || !shownToken || !!st.tokenFromEnv)
545
+ renderDeviceKeys(st, isGateway)
546
+ renderHostIPs(st)
547
+ renderQr(st)
548
+ renderDoctor(st)
549
+ // 网关开关: 仅插件内嵌页提供, 网关运行/停止两种状态
550
+ gatewayRunning = isGateway || st.gatewayRunning === true
551
+ $('btn-gateway').classList.toggle('hidden', !pluginMode)
552
+ $('btn-gateway').textContent = gatewayBusy
553
+ ? t(gatewayRunning ? 'stopping' : 'starting')
554
+ : t(gatewayRunning ? 'stopGateway' : 'startGateway')
555
+ $('btn-gateway').disabled = gatewayBusy
556
+ // 网关端口配置: 仅插件内嵌页提供
557
+ $('gateway-port-row').classList.toggle('hidden', !pluginMode || !gatewayPortLoaded)
558
+ if (pluginMode) {
559
+ const cur = $('gateway-port-current')
560
+ if (cur) cur.textContent = t('gatewayPort.current', { port: gatewayPort })
561
+ }
562
+ const upOk = st.upstream?.reachable === true
563
+ const hero = $('admin-hero')
564
+ if (hero) {
565
+ const heroState = st.gatewayAuthError ? 'attention' : isGateway ? (upOk ? 'running' : 'attention') : isPlugin ? 'plugin' : 'offline'
566
+ hero.className = 'admin-hero ' + heroState
567
+ const titleKey = heroState === 'running' ? 'hero.running' : heroState === 'attention' ? 'hero.attention' : heroState === 'plugin' ? 'hero.plugin' : 'hero.offline'
568
+ const descKey = heroState === 'running' ? 'hero.runningDesc' : heroState === 'attention' ? 'hero.attentionDesc' : heroState === 'plugin' ? 'hero.pluginDesc' : 'hero.offlineDesc'
569
+ $('admin-hero-title').textContent = t(titleKey)
570
+ $('admin-hero-desc').textContent = heroState === 'running'
571
+ ? t(descKey, { online: st.onlineCount || 0, requests: st.totalRequests || 0 })
572
+ : st.gatewayAuthError || t(descKey)
573
+ $('admin-hero-status').textContent = st.gatewayAuthError ? t('hero.attention') : isGateway ? (upOk ? t('stat.reachable') : t('stat.unreachable')) : t(isPlugin ? 'badge.embedded' : 'badge.gatewayDown')
574
+ const action = $('admin-hero-action')
575
+ if (action) {
576
+ const actionKey = heroState === 'plugin' ? 'hero.startGateway' : heroState === 'offline' ? 'hero.copyToken' : 'hero.openDevices'
577
+ action.textContent = t(actionKey)
578
+ action.dataset.heroAction = heroState === 'plugin' ? 'start' : heroState === 'offline' ? 'copy' : 'devices'
579
+ }
580
+ }
581
+ const latestHtml = st.latest?.newer
582
+ ? `<div class="v">${t('stat.updateAvailable', { version: st.latest.version })}</div><div class="k">${t('stat.currentV', { version: st.version })} · <a href="${st.latest.url || '#'}" target="_blank" rel="noopener" style="color:var(--dsr-accent-strong)">${t('stat.download')}</a></div>`
583
+ : `<div class="v">v${st.version}</div><div class="k">${isPlugin ? t('stat.embedded') : st.latest?.error ? t('stat.updateCheck', { error: st.latest.error }) : st.latest?.version ? t('stat.latest') : t('stat.notChecked')}</div>`
584
+ $('stats').innerHTML = `
585
+ <div class="stat-card"><div class="v">v${st.version}</div><div class="k">${t(isPlugin ? 'stat.pluginVersion' : 'stat.gatewayVersion')}</div></div>
586
+ <div class="stat-card ${st.latest?.newer ? 'warn' : 'ok'}">${latestHtml}</div>
587
+ <div class="stat-card ${upOk ? 'ok' : 'warn'}"><div class="v">${t(upOk ? 'stat.reachable' : 'stat.unreachable')}</div><div class="k">${t('stat.dshUpstream', { url: st.upstream.url })}</div></div>
588
+ <div class="stat-card"><div class="v">${st.onlineCount}/${st.deviceCount}</div><div class="k">${t('stat.devicesOnline')}</div></div>
589
+ <div class="stat-card"><div class="v">${st.totalRequests}</div><div class="k">${t('stat.totalRequests')}</div></div>
590
+ <div class="stat-card"><div class="v">${st.authFailures}</div><div class="k">${t('stat.authFailures')}</div></div>
591
+ <div class="stat-card"><div class="v">${fmtUptime(st.uptimeSec)}</div><div class="k">${t('stat.uptime', { host: st.host, port: st.port })}</div></div>`
592
+
593
+ $('device-summary').textContent = st.gatewayAuthError || (isPlugin
594
+ ? t(st.gatewayInstalled ? 'device.installedNotRunning' : 'device.noGatewayBinary')
595
+ : t('device.ipRefresh', { n: st.devices.length }))
596
+ if (isPlugin && !st.devices.length) {
597
+ $('device-rows').innerHTML = ''
598
+ const rel = 'https://github.com/Blank-not-black/dsh-Remote/releases/latest/download/'
599
+ const apkBtn = `<a class="mini-btn" href="#admin-setup">${t('device.downloadApp')}</a>`
600
+ if (st.gatewayAuthError) {
601
+ $('device-empty').textContent = st.gatewayAuthError
602
+ } else if (!st.gatewayInstalled) {
603
+ // 只有插件包真的没有内置网关程序时, 才引导下载网关
604
+ const isWin = /windows|win32/i.test(navigator.userAgent)
605
+ const gwAsset = isWin ? 'dsh-remote-win-x64.exe' : 'dsh-remote-linux-x64'
606
+ $('device-empty').innerHTML = `
607
+ <div>${t('device.noBinaryGuide')}</div>
608
+ <div class="empty-actions">
609
+ <a class="mini-btn" href="${rel}${gwAsset}" target="_blank" rel="noopener">${t('device.downloadGateway', { os: isWin ? 'Windows x64' : 'Linux x64' })}</a>
610
+ ${apkBtn}
611
+ </div>
612
+ <div class="muted" style="margin-top:10px">${t('device.afterRunGuide')}</div>`
613
+ } else {
614
+ $('device-empty').innerHTML = `
615
+ <div>${t('device.installedGuide')}</div>
616
+ <div class="empty-actions">${apkBtn}</div>
617
+ <div class="muted" style="margin-top:10px">${t('device.afterStartGuide')}</div>`
618
+ }
619
+ $('device-empty').classList.remove('hidden')
620
+ } else {
621
+ // 网关模式: 清掉可能残留的引导文案, 设备为空时只显示中性提示
622
+ $('device-empty').textContent = t('noDevices')
623
+ $('device-empty').classList.toggle('hidden', st.devices.length > 0)
624
+ const deviceHtml = st.devices.map(d => {
625
+ const kindText = t(d.kind === 'app' ? 'device.kind.app' : d.kind === 'admin' ? 'device.kind.admin' : d.kind === 'web' ? 'device.kind.web' : 'device.kind.unknown')
626
+ const noteHtml = d.note ? `<b>${d.note.replace(/[<>&"]/g, c => ({'<':'&lt;','>':'&gt;','&':'&amp;','"':'&quot;'}[c]))}</b>` : '<span class="muted">—</span>'
627
+ const ch = `${d.channels.mux ? 'mux' : ''}${d.channels.mux && d.channels.host ? ' · ' : ''}${d.channels.host ? 'host' : ''}${!d.channels.mux && !d.channels.host ? '—' : ''}`
628
+ return `
629
+ <tr data-remote-key="${esc(d.id || d.ip)}">
630
+ <td data-label="${t('th.status')}"><span class="dot ${d.online ? 'on' : 'off'}"></span>${t(d.online ? 'device.online' : 'device.offline')}</td>
631
+ <td data-label="${t('th.name')}">${noteHtml}<button class="mini-btn" data-note-ip="${d.ip}" data-note="${d.note.replace(/"/g, '&quot;')}" style="margin-left:6px;padding:1px 7px">${t('device.note')}</button></td>
632
+ <td data-label="${t('th.type')}"><span class="badge ${d.kind}">${kindText}</span></td>
633
+ <td data-label="${t('th.ip')}" class="mono nowrap">${d.ip}</td>
634
+ <td data-label="${t('th.channels')}" class="mono nowrap">${ch}</td>
635
+ <td data-label="${t('th.requests')}">${d.requests}</td>
636
+ <td data-label="${t('th.lastSeen')}" class="nowrap">${fmtTime(d.lastSeen)}</td>
637
+ <td data-label="${t('th.ua')}" class="ua" title="${d.ua.replace(/"/g, '&quot;')}">${d.ua || '—'}</td>
638
+ <td class="act">${d.online && d.kind !== 'admin' ? `<button class="mini-btn" data-kick="${d.ip}">${t('device.kick')}</button>` : ''}</td>
639
+ </tr>`
640
+ }).join('')
641
+ if (window.DshRemoteUI) window.DshRemoteUI.reconcileRows($('device-rows'),deviceHtml)
642
+ else $('device-rows').innerHTML = deviceHtml
643
+ }
644
+ window.DshConsole?.update({ ...st, token: shownToken })
645
+ }
646
+
647
+ function pairTarget(st, accessToken) {
648
+ const port = st.port || 8787
649
+ const hosts = enabledHostIPs(st).slice()
650
+ if (!hosts.length) {
651
+ const fallback = st.host && st.host !== '0.0.0.0' ? String(st.host).trim() : location.hostname
652
+ if (fallback) hosts.push(fallback)
653
+ }
654
+ const bases = hosts.map(host => `http://${host}:${port}`)
655
+ const query = new URLSearchParams({ token: String(accessToken || '') })
656
+ for (const base of bases) query.append('server', base)
657
+ return {
658
+ url: `dshremote://pair?${query.toString()}`,
659
+ base: bases[0] || '',
660
+ bases
661
+ }
662
+ }
663
+
664
+ function pairQrSvg(url) {
665
+ const qr = window.qrcode(0, 'M')
666
+ qr.addData(url)
667
+ qr.make()
668
+ return qr.createSvgTag({ cellSize: 4, margin: 2, scalable: true })
669
+ }
670
+
671
+ async function phonePairingCode(setupId) {
672
+ const st = lastState, currentToken = token
673
+ if (st?.mode !== 'gateway' || st.gatewayAuthError || !enabledHostIPs(st).length) return ''
674
+ let access = shownToken
675
+ if (st.deviceKeys?.enabled) {
676
+ const note = I18N.lang === 'en' ? 'Android phone' : 'Android 手机'
677
+ access = (await deviceKeyMutation('create', { note }))?.entry?.token
678
+ }
679
+ if (!access || token !== currentToken) return ''
680
+ const url = new URL(pairTarget(st, access).url)
681
+ url.searchParams.set('relaySetup', setupId)
682
+ return pairQrSvg(url.href)
683
+ }
684
+
685
+ function renderQr(st) {
686
+ const box = $('pair-box')
687
+ const accessToken = qrToken || shownToken
688
+ if (!qrShown || !accessToken || st.mode !== 'gateway') {
689
+ box.classList.add('hidden')
690
+ return
691
+ }
692
+ try {
693
+ const pt = pairTarget(st, accessToken)
694
+ $('pair-qr').innerHTML = pairQrSvg(pt.url)
695
+ $('pair-hint').textContent = `${qrLabel ? qrLabel + ' · ' : ''}${t('pair.hint', { base: pt.base })}`
696
+ box.classList.remove('hidden')
697
+ } catch (e) {
698
+ $('pair-qr').textContent = t('pair.failed')
699
+ box.classList.remove('hidden')
700
+ }
701
+ }
702
+
703
+ async function setNote(ip, current) {
704
+ const name = prompt(t('prompt.note', { ip }), current || '')
705
+ if (name === null) return
706
+ const res = await fetch(`${API}/note`, {
707
+ method: 'POST',
708
+ headers: adminHeaders({ 'content-type': 'application/json' }), credentials: 'same-origin',
709
+ body: JSON.stringify({ ip, name })
710
+ })
711
+ if (res.ok) {
712
+ toast(t('toast.noteSaved'), 'ok')
713
+ setTimeout(loadState, 300)
714
+ } else {
715
+ toast(t('toast.noteFailed'), 'err')
716
+ }
717
+ }
718
+
719
+ async function kick(ip) {
720
+ if (!confirm(t('confirm.kick'))) return
721
+ const res = await fetch(`${API}/kick`, {
722
+ method: 'POST',
723
+ headers: adminHeaders({ 'content-type': 'application/json' }), credentials: 'same-origin',
724
+ body: JSON.stringify({ ip })
725
+ })
726
+ if (res.ok) {
727
+ toast(t('toast.kicked', { ip }), 'ok')
728
+ setTimeout(loadState, 400)
729
+ } else {
730
+ toast(t('toast.opFailed'), 'err')
731
+ }
732
+ }
733
+
734
+ async function deviceKeyMutation(action, payload = {}) {
735
+ deviceKeyBusy = true
736
+ const toggle = $('device-key-enabled')
737
+ if (toggle) toggle.disabled = true
738
+ try {
739
+ const res = await fetch(`${API}/device-keys/${action}`, {
740
+ method: 'POST',
741
+ headers: adminHeaders({ 'content-type': 'application/json' }), credentials: 'same-origin',
742
+ body: JSON.stringify(payload),
743
+ })
744
+ const out = await res.json().catch(() => ({}))
745
+ if (!res.ok || !out.ok) throw new Error(out.detail || out.error || `HTTP ${res.status}`)
746
+ return out
747
+ } catch (error) {
748
+ toast(t('deviceKeys.failed', { msg: error?.message || error }), 'err')
749
+ return null
750
+ } finally {
751
+ deviceKeyBusy = false
752
+ if (toggle) toggle.disabled = false
753
+ }
754
+ }
755
+
756
+ async function setDeviceKeyMode(enabled) {
757
+ const toggle = $('device-key-enabled')
758
+ const confirmKey = enabled ? 'deviceKeys.enableConfirm' : 'deviceKeys.disableConfirm'
759
+ if (!confirm(t(confirmKey))) {
760
+ toggle.checked = !enabled
761
+ return
762
+ }
763
+ const out = await deviceKeyMutation('mode', { enabled })
764
+ if (!out) {
765
+ toggle.checked = !enabled
766
+ return
767
+ }
768
+ qrShown = false
769
+ qrToken = ''
770
+ qrLabel = ''
771
+ toast(t(enabled ? 'deviceKeys.enabled' : 'deviceKeys.disabled'), 'ok')
772
+ await loadState()
773
+ }
774
+
775
+ async function createDeviceKey() {
776
+ const note = prompt(t('deviceKeys.notePrompt'), '')
777
+ if (note === null) return
778
+ const out = await deviceKeyMutation('create', { note })
779
+ if (!out) return
780
+ toast(t('deviceKeys.created'), 'ok')
781
+ await loadState()
782
+ if (out.entry) showDeviceKeyQr(out.entry)
783
+ }
784
+
785
+ async function editDeviceKeyNote(entry) {
786
+ if (!entry) return
787
+ const note = prompt(t('deviceKeys.notePrompt'), entry.note || '')
788
+ if (note === null) return
789
+ const out = await deviceKeyMutation('note', { id: entry.id, note })
790
+ if (!out) return
791
+ toast(t('deviceKeys.saved'), 'ok')
792
+ await loadState()
793
+ }
794
+
795
+ function showDeviceKeyQr(entry) {
796
+ if (!entry?.token) return
797
+ window.DshConsole?.select('devices')
798
+ qrToken = entry.token
799
+ qrLabel = entry.note || ''
800
+ qrShown = true
801
+ renderQr(lastState || { mode: '', token: '' })
802
+ $('pair-box').scrollIntoView?.({ behavior: 'smooth', block: 'nearest' })
803
+ }
804
+
805
+ async function copyDeviceKey(entry) {
806
+ if (!entry?.token) return
807
+ try {
808
+ await navigator.clipboard.writeText(entry.token)
809
+ toast(t('toast.tokenCopied'), 'ok')
810
+ } catch {
811
+ toast(t('toast.copyFailed'), 'err')
812
+ }
813
+ }
814
+
815
+ async function rotateDeviceKey(entry) {
816
+ if (!entry || !confirm(t('deviceKeys.rotateConfirm'))) return
817
+ const out = await deviceKeyMutation('rotate', { id: entry.id })
818
+ if (!out) return
819
+ qrShown = false
820
+ qrToken = ''
821
+ qrLabel = ''
822
+ toast(t('deviceKeys.rotated'), 'ok')
823
+ await loadState()
824
+ }
825
+
826
+ async function revokeDeviceKey(entry) {
827
+ if (!entry || !confirm(t('deviceKeys.revokeConfirm'))) return
828
+ const out = await deviceKeyMutation('revoke', { id: entry.id })
829
+ if (!out) return
830
+ if (qrToken === entry.token) {
831
+ qrShown = false
832
+ qrToken = ''
833
+ qrLabel = ''
834
+ }
835
+ toast(t('deviceKeys.revoked'), 'ok')
836
+ await loadState()
837
+ }
838
+
839
+ function enter() {
840
+ const val = $('token-input').value.trim()
841
+ if (!val) return
842
+ token = val
843
+ store.set('dshAdminToken', val)
844
+ history.replaceState(null, '', location.pathname)
845
+ showMain()
846
+ loadState()
847
+ timer = setInterval(loadState, 5000)
848
+ }
849
+
850
+ function showMain() {
851
+ $('login-view').classList.add('hidden')
852
+ $('main-view').classList.remove('hidden')
853
+ }
854
+
855
+ function logout() {
856
+ lanRevision++; lanBusy = false; lanCode = ''; lanExpiry = 0
857
+ $('lan-pairing-code').textContent = ''; $('lan-pairing-code').hidden = true
858
+ token = ''
859
+ store.del('dshAdminToken')
860
+ clearInterval(timer)
861
+ $('main-view').classList.add('hidden')
862
+ $('login-view').classList.remove('hidden')
863
+ $('conn-badge').textContent = t('unauth')
864
+ $('conn-badge').className = 'conn-badge off'
865
+ $('token-input').value = ''
866
+ revealedDeviceKeys.clear()
867
+ $('device-key-rows').innerHTML = ''
868
+ window.DshConsole?.update(null)
869
+ window.DshConsole?.conceal()
870
+ setup?.conceal?.()
871
+ }
872
+
873
+ $('btn-login').addEventListener('click', enter)
874
+ $('token-input').addEventListener('keydown', (e) => { if (e.key === 'Enter') enter() })
875
+ $('btn-logout').addEventListener('click', logout)
876
+ $('device-key-enabled').addEventListener('change', (event) => setDeviceKeyMode(event.target.checked))
877
+ $('btn-device-key-add').addEventListener('click', createDeviceKey)
878
+ $('device-key-rows').addEventListener('click', event => {
879
+ const button = event.target.closest('button')
880
+ if (!button) return
881
+ for (const [name,handler] of [['note',editDeviceKeyNote],['qr',showDeviceKeyQr],['rotate',rotateDeviceKey],['copy',copyDeviceKey],['revoke',revokeDeviceKey]]) {
882
+ const id=button.dataset['deviceKey'+name[0].toUpperCase()+name.slice(1)]
883
+ if (id) { handler(lastState?.deviceKeys?.entries?.find(entry=>entry.id===id)); return }
884
+ }
885
+ const id=button.dataset.deviceKeyShow
886
+ if(id) {
887
+ if(revealedDeviceKeys.has(id))revealedDeviceKeys.delete(id);else revealedDeviceKeys.add(id)
888
+ if(lastState)renderDeviceKeys(lastState,lastState.mode==='gateway')
889
+ }
890
+ })
891
+ $('device-rows').addEventListener('click', event => {
892
+ const kickButton=event.target.closest('[data-kick]')
893
+ if(kickButton)return kick(kickButton.dataset.kick)
894
+ const noteButton=event.target.closest('[data-note-ip]')
895
+ if(noteButton)setNote(noteButton.dataset.noteIp,noteButton.dataset.note)
896
+ })
897
+ // 插件内嵌: 收起面板按钮 → postMessage 给父窗口(同源)关闭右侧抽屉
898
+ $('btn-close-drawer').addEventListener('click', () => {
899
+ window.parent.postMessage({ source: 'dsh-remote-admin', type: 'close' }, location.origin)
900
+ })
901
+ $('admin-hero-action').addEventListener('click', () => {
902
+ const action = $('admin-hero-action').dataset.heroAction
903
+ if (action === 'start') return $('btn-gateway').click()
904
+ if (action === 'copy') return $('btn-copy').click()
905
+ window.DshConsole?.select('devices')
906
+ $('device-rows').closest('.table-wrap')?.scrollIntoView({ behavior: 'smooth', block: 'start' })
907
+ })
908
+ $('doctor-toggle').addEventListener('click', () => {
909
+ doctorExpanded = !doctorExpanded
910
+ store.set('dshAdminDoctorCollapsed', doctorExpanded ? '0' : '1')
911
+ if (lastState) renderDoctor(lastState)
912
+ })
913
+ $('doctor-refresh').addEventListener('click', () => {
914
+ $('doctor-subtitle').textContent = t('doctor.checking')
915
+ loadState()
916
+ })
917
+ $('doctor-copy-report').addEventListener('click', () => {
918
+ const report = doctorChecks.map(check => `[${check.status.toUpperCase()}] ${check.title}: ${check.detail}`).join('\n')
919
+ doctorCopy(`DSH Remote Doctor\n${report}`, 'doctor.reportCopied')
920
+ })
921
+ $('doctor-steps').addEventListener('click', (event) => {
922
+ const button = event.target.closest('[data-doctor-action]')
923
+ if (!button || !lastState) return
924
+ const action = button.dataset.doctorAction
925
+ if (action === 'start') return $('btn-gateway').click()
926
+ if (action === 'address') return doctorCopy(pairTarget(lastState, shownToken || token).base, 'doctor.addressCopied')
927
+ if (action === 'firewall') return doctorCopy(firewallCommand(lastState), 'doctor.commandCopied')
928
+ if (action === 'qr') {
929
+ window.DshConsole?.select('devices')
930
+ const firstKey = lastState.deviceKeys?.enabled && lastState.deviceKeys.entries?.[0]
931
+ if (firstKey) showDeviceKeyQr(firstKey)
932
+ else {
933
+ qrToken = shownToken
934
+ qrLabel = ''
935
+ qrShown = true
936
+ renderQr(lastState)
937
+ $('pair-box').scrollIntoView?.({ behavior: 'smooth', block: 'nearest' })
938
+ }
939
+ }
940
+ })
941
+ $('btn-copy').addEventListener('click', async () => {
942
+ try {
943
+ await navigator.clipboard.writeText(shownToken || token)
944
+ toast(t('toast.tokenCopied'), 'ok')
945
+ } catch {
946
+ toast(t('toast.copyFailed'), 'err')
947
+ }
948
+ })
949
+
950
+ $('btn-qr').addEventListener('click', () => {
951
+ qrToken = shownToken
952
+ qrLabel = ''
953
+ qrShown = !qrShown
954
+ renderQr(lastState || { mode: '', token: shownToken })
955
+ })
956
+
957
+ $('btn-host-ip-add').addEventListener('click', addManualHostIP)
958
+
959
+ /* 右上角「网关」徽章: 新标签页打开独立网关管理面板(带 token 免登录) */
960
+ $('conn-badge').addEventListener('click', () => {
961
+ const st = lastState
962
+ if (!st || st.mode !== 'gateway') { toast(t('toast.gatewayDown'), 'err'); return }
963
+ const host = location.protocol === 'dsh-app:' ? '127.0.0.1' : location.hostname || '127.0.0.1'
964
+ const port = st.port || 8787
965
+ const url = `http://${host}:${port}/admin?token=${encodeURIComponent(shownToken || token)}`
966
+ try {
967
+ window.open(url, '_blank', 'noopener')
968
+ } catch {
969
+ toast(t('toast.popupBlocked'), 'err')
970
+ }
971
+ })
972
+
973
+ $('btn-rotate').addEventListener('click', async () => {
974
+ if (!confirm(t('confirm.rotate'))) return
975
+ try {
976
+ const res = await fetch(`${API}/token/rotate`, {
977
+ method: 'POST',
978
+ headers: adminHeaders({}, token || shownToken), credentials: 'same-origin'
979
+ })
980
+ const out = await res.json().catch(() => ({}))
981
+ if (out.ok && out.token) {
982
+ token = out.token
983
+ store.set('dshAdminToken', out.token)
984
+ toast(t('toast.rotated'), 'ok')
985
+ setTimeout(loadState, 300)
986
+ } else {
987
+ toast(out.detail || out.error || t('toast.rotateFailed'), 'err')
988
+ }
989
+ } catch (e) {
990
+ toast(t('toast.rotateFailedMsg', { msg: e.message || e }), 'err')
991
+ }
992
+ })
993
+
994
+ $('btn-gateway').addEventListener('click', async () => {
995
+ if (gatewayBusy) return
996
+ if (gatewayRunning && !confirm(window.DshRemoteUI?.t('runtimeHint') || '停止网关会中断连接,继续?')) return
997
+ gatewayBusy = true
998
+ const btn = $('btn-gateway')
999
+ btn.disabled = true
1000
+ btn.textContent = t(gatewayRunning ? 'stopping' : 'starting')
1001
+ try {
1002
+ const res = await fetch(`${API}/gateway`, {
1003
+ method: 'POST',
1004
+ headers: adminHeaders({ 'content-type': 'application/json' }), credentials: 'same-origin',
1005
+ body: JSON.stringify({ action: gatewayRunning ? 'stop' : 'start' })
1006
+ })
1007
+ const out = await res.json().catch(() => ({}))
1008
+ if (out.ok) {
1009
+ toast(out.started ? t('toast.gatewayStarted') : out.running ? t('toast.gatewayAlready') : gatewayRunning ? t('toast.gatewayStopped') : (out.pending ? t('toast.gatewayPending') : t('toast.done')), 'ok')
1010
+ } else {
1011
+ toast(out.error || t('toast.opFailed'), 'err')
1012
+ }
1013
+ } catch (e) {
1014
+ toast(t('toast.opFailedMsg', { msg: e.message || e }), 'err')
1015
+ }
1016
+ gatewayBusy = false
1017
+ setTimeout(loadState, 700)
1018
+ setTimeout(loadLoginStartup, 800)
1019
+ })
1020
+
1021
+ $('btn-save-port').addEventListener('click', async () => {
1022
+ const input = $('gateway-port-input')
1023
+ const raw = input.value.trim()
1024
+ const port = Number(raw)
1025
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
1026
+ toast(t('toast.portInvalid'), 'err')
1027
+ return
1028
+ }
1029
+ const btn = $('btn-save-port')
1030
+ const wasRunning = gatewayRunning
1031
+ btn.disabled = true
1032
+ try {
1033
+ const res = await fetch(`${API}/config`, {
1034
+ method: 'PUT',
1035
+ headers: adminHeaders({ 'content-type': 'application/json' }), credentials: 'same-origin',
1036
+ body: JSON.stringify({ port })
1037
+ })
1038
+ const out = await res.json().catch(() => ({}))
1039
+ if (out.ok) {
1040
+ const saved = Number(out.port) || port
1041
+ const effective = Number(out.effectivePort || out.port) || saved
1042
+ if (out.effectivePort && effective !== saved) {
1043
+ toast(t('toast.portEnv', { port: effective }), 'ok')
1044
+ } else if (wasRunning) {
1045
+ toast(t('toast.portSaved', { port: effective }), 'ok')
1046
+ } else {
1047
+ toast(t('toast.portSavedIdle', { port: effective }), 'ok')
1048
+ }
1049
+ loadGatewayConfig()
1050
+ setTimeout(loadLoginStartup, 1000)
1051
+ setTimeout(loadState, 800)
1052
+ } else {
1053
+ toast(out.error || t('toast.portFailedMsg', { msg: res.status }), 'err')
1054
+ }
1055
+ } catch (e) {
1056
+ toast(t('toast.portFailedMsg', { msg: e.message || e }), 'err')
1057
+ }
1058
+ btn.disabled = false
1059
+ })
1060
+
1061
+ function renderLangBtn() {
1062
+ const btn = $('btn-lang')
1063
+ if (btn) btn.textContent = I18N.lang === 'zh' ? 'EN' : '中文'
1064
+ document.title = t('login.title')
1065
+ }
1066
+
1067
+ const THEME_META = [
1068
+ { id: 'default', sw: ['#0D1117', '#21262D', '#58A6FF'] },
1069
+ { id: 'dark', sw: ['#161316', '#302323', '#FFB86B'] },
1070
+ { id: 'light', sw: ['#F5F7F8', '#FFFFFF', '#176B87'] },
1071
+ { id: 'neutral', sw: ['#EEF1E8', '#FAFBF6', '#47643C'] },
1072
+ { id: 'mono', sw: ['#050505', '#333333', '#F5F5F5'] },
1073
+ { id: 'fish', sw: ['#EAF6FF', '#FFFFFF', '#2F52D0'] },
1074
+ { id: 'penguin', sw: ['#EDF3FA', '#FFFFFF', '#2B6CB0'] },
1075
+ { id: 'penguin-night', sw: ['#10151B', '#1A222C', '#F2C230'] },
1076
+ { id: 'bocchi', sw: ['#FFD9E8', '#FFFFFF', '#D0105A'] },
1077
+ { id: 'nijika', sw: ['#FFF3D5', '#FFFFFF', '#94600C'] },
1078
+ { id: 'ryo', sw: ['#E9F1FA', '#FFFFFF', '#315D91'] },
1079
+ { id: 'kita', sw: ['#FFE9E5', '#FFFFFF', '#B6373C'] }
1080
+ ]
1081
+
1082
+ function renderThemeBtn() {
1083
+ const cur = window.DSHTheme.get()
1084
+ const meta = THEME_META.find(m => m.id === cur)
1085
+ const label = $('theme-label')
1086
+ const swatch = $('theme-swatch')
1087
+ if (label) label.textContent = t('theme.' + cur)
1088
+ if (swatch && meta) swatch.style.background = meta.sw[0]
1089
+ const btn = $('btn-theme')
1090
+ if (btn) btn.title = t('theme.' + cur)
1091
+ }
1092
+
1093
+ function openThemePanel() {
1094
+ window.DSHTheme.openPicker({
1095
+ themes: THEME_META, label: id => t('theme.' + id), lang: I18N.lang,
1096
+ onSelect: id => { window.DSHTheme.set(id); renderThemeBtn() }
1097
+ })
1098
+ }
1099
+
1100
+ function openDonateModal() {
1101
+ const m = $('modal-donate')
1102
+ if (m) m.classList.remove('hidden')
1103
+ }
1104
+
1105
+ $('btn-lang').addEventListener('click', () => {
1106
+ I18N.setLang(I18N.lang === 'zh' ? 'en' : 'zh')
1107
+ renderLangBtn()
1108
+ renderThemeBtn()
1109
+ renderLoginStartup()
1110
+ if (lastState) render(lastState)
1111
+ else if (!token && !pluginMode) $('conn-badge').textContent = t('unauth')
1112
+ })
1113
+
1114
+ $('btn-theme').addEventListener('click', openThemePanel)
1115
+ // 赞赏支持
1116
+ $('btn-support').addEventListener('click', openDonateModal)
1117
+ $('donate-close').addEventListener('click', () => $('modal-donate').classList.add('hidden'))
1118
+ $('modal-donate').addEventListener('click', (e) => { if (e.target === $('modal-donate')) $('modal-donate').classList.add('hidden') })
1119
+ // 反馈
1120
+ $('btn-feedback').addEventListener('click', (e) => { e.stopPropagation(); toggleFeedbackMenu() })
1121
+ for(const id of ['btn-ai-doctor','admin-doctor'])$(id)?.addEventListener('click', () => {
1122
+ closeFeedbackMenu()
1123
+ if(typeof window.DshDoctorEntry?.open!=='function'){toast('诊疗组件未能加载,请刷新页面后重试。','err');return}
1124
+ window.DshDoctorEntry.open({state:()=>lastState,pluginMode,token:()=>token,copy:async text=>{try{await navigator.clipboard.writeText(text);return true}catch{return false}},toast})
1125
+ })
1126
+ $('fb-menu').addEventListener('click', (e) => {
1127
+ if (e.target.closest('a[role="menuitem"]')) closeFeedbackMenu()
1128
+ })
1129
+ document.addEventListener('click', (e) => {
1130
+ if (!e.target.closest('#btn-feedback,#fb-menu')) closeFeedbackMenu()
1131
+ })
1132
+ window.addEventListener('resize', positionFeedbackMenu)
1133
+ window.addEventListener('scroll', closeFeedbackMenu, { passive: true })
1134
+ document.addEventListener('keydown', (e) => {
1135
+ if (e.key === 'Escape' && !$('fb-menu').classList.contains('hidden')) { closeFeedbackMenu(); $('btn-feedback').focus() }
1136
+ })
1137
+
1138
+ function start(showLogin) {
1139
+ if (!showLogin) {
1140
+ $('login-view').classList.add('hidden')
1141
+ } else {
1142
+ $('login-view').classList.remove('hidden')
1143
+ }
1144
+ showMain()
1145
+ loadState()
1146
+ loadGatewayConfig()
1147
+ loginStartup = null
1148
+ renderLoginStartup()
1149
+ loadLoginStartup()
1150
+ timer = setInterval(loadState, 5000)
1151
+ }
1152
+
1153
+ if (pluginMode) {
1154
+ $('login-view').classList.add('hidden')
1155
+ $('btn-console').classList.add('hidden')
1156
+ if (location.protocol === 'dsh-app:' && window.parent !== window) $('btn-plugin-panel').classList.remove('hidden')
1157
+ $('btn-close-drawer').classList.remove('hidden')
1158
+ start(false)
1159
+ } else if (token) {
1160
+ $('token-input').value = token
1161
+ start(false)
1162
+ } else {
1163
+ $('main-view').classList.add('hidden')
1164
+ $('login-view').classList.remove('hidden')
1165
+ }
1166
+ renderLangBtn()
1167
+ renderThemeBtn()