dsh-remote-plugin 0.8.6 → 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 (45) hide show
  1. package/apk/dsh-remote.apk +0 -0
  2. package/gateway.cjs +169 -63
  3. package/index.mjs +36 -1
  4. package/package.json +1 -1
  5. package/public/activity.js +144 -49
  6. package/public/admin.html +33 -32
  7. package/public/admin.js +25 -6
  8. package/public/app.js +199 -57
  9. package/public/build.json +2 -2
  10. package/public/desktop/desktop.html +85 -74
  11. package/public/desktop/desktop.js +52 -27
  12. package/public/diagnostics.js +30 -4
  13. package/public/doctor.css +1 -1
  14. package/public/e2ee-transport.js +189 -18
  15. package/public/history.js +15 -2
  16. package/public/index.html +97 -76
  17. package/public/operations.js +59 -14
  18. package/public/plugin.html +27 -26
  19. package/public/relay-autopair.js +60 -26
  20. package/public/relay-devices.js +11 -5
  21. package/public/relay-settings.css +9 -0
  22. package/public/relay-settings.js +67 -9
  23. package/public/skins/blue-fish/preview.html +3 -3
  24. package/public/skins/bocchi/preview.html +5 -5
  25. package/public/skins/kita/preview.html +6 -6
  26. package/public/skins/nijika/preview.html +6 -6
  27. package/public/skins/penguin/preview.html +3 -3
  28. package/public/skins/penguin-logistics/cargo.svg +4 -0
  29. package/public/skins/penguin-logistics/console.svg +4 -0
  30. package/public/skins/penguin-logistics/mark.svg +4 -0
  31. package/public/skins/penguin-logistics/radio.svg +4 -0
  32. package/public/skins/penguin-logistics/skin.css +292 -0
  33. package/public/skins/penguin-logistics/standing.png +0 -0
  34. package/public/skins/ryo/preview.html +6 -6
  35. package/public/slash-suggestions.css +43 -0
  36. package/public/slash-suggestions.js +184 -0
  37. package/public/subagents.css +2 -0
  38. package/public/subagents.js +31 -10
  39. package/public/theme-vars.css +37 -2
  40. package/public/theme.js +4 -2
  41. package/public/update.json +12 -12
  42. package/public/version.json +1 -1
  43. package/public/workflow.css +19 -11
  44. package/public/workflow.js +25 -14
  45. package/skills/dsh-remote-doctor/references/wiki/connection.md +2 -0
@@ -6,10 +6,20 @@
6
6
  'goal.edit','goal.pause','goal.resume','goal.complete','goal.clear'])
7
7
  const pending = new Map()
8
8
  const storageKey = 'dshRemoteOperationReceiptsV1'
9
+ // Scope of the connection the UI is currently showing. Receipts from another
10
+ // connection stay visible as "unconfirmed" so a pending write is never lost
11
+ // from the user's view merely because the address/token changed.
12
+ let currentScope = ''
9
13
  function saved() { try { return JSON.parse(root.localStorage?.getItem(storageKey) || '[]').filter(row => Date.now()-row.createdAt<86400000).slice(-100) } catch { return [] } }
14
+ function originOf(config) {
15
+ try {
16
+ const base = String(config?.server || config?.url?.('/') || '')
17
+ return base ? new URL(base, root.location?.href || 'http://localhost').origin : ''
18
+ } catch { return '' }
19
+ }
10
20
  function persist() {
11
21
  const rows=new Map(saved().map(row=>[row.id,row]))
12
- for(const row of pending.values())rows.set(row.id,{id:row.id,scope:row.scope,intent:row.intent,method:row.method,sessionId:row.sessionId,createdAt:row.createdAt})
22
+ for(const row of pending.values())rows.set(row.id,{id:row.id,scope:row.scope,intent:row.intent,method:row.method,sessionId:row.sessionId,origin:row.origin,createdAt:row.createdAt})
13
23
  try { root.localStorage?.setItem(storageKey,JSON.stringify([...rows.values()].slice(-100))) } catch {}
14
24
  root.dispatchEvent?.(new Event('dsh-operation-change'))
15
25
  }
@@ -34,23 +44,35 @@
34
44
  }
35
45
  async function restore(config) {
36
46
  const scope=await digest(config.url('/api/operations')+'\0'+config.headers.authorization)
47
+ currentScope=scope
37
48
  if(!config.valid())return scope
38
- for(const row of saved())if(row.scope===scope&&!pending.has(row.id))pending.set(row.id,{...row,phase:'unknown',config})
39
- for(const row of pending.values())if(row.scope===scope)row.config=config
49
+ const origin=originOf(config)
50
+ for(const row of saved())if(row.scope===scope&&!pending.has(row.id))pending.set(row.id,{...row,origin:row.origin||origin,phase:'unknown',config})
51
+ for(const row of pending.values())if(row.scope===scope){row.config=config;if(!row.origin)row.origin=origin}
40
52
  return scope
41
53
  }
42
54
  const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))
43
- function unknown(id) {
44
- const error = new Error((root.I18N?.lang === 'en' ? 'Result unconfirmed. The operation may already have been applied. Check before trying again. Operation: ' : '结果未确认,操作可能已生效。请先核对会话,再决定是否重试。操作编号:') + id)
45
- error.operationId = id; error.operationPending = true
55
+ function unknown(id, receiptMissing = false) {
56
+ const en = root.I18N?.lang === 'en'
57
+ const message = receiptMissing
58
+ ? (en ? 'The gateway has no receipt for this operation. Check the conversation, then use Check receipts to finish tracking before resending. Operation: '
59
+ : '网关找不到这笔操作的回执。请先核对会话,再到「查看回执」结束跟踪,然后重新提交。操作编号:')
60
+ : (en ? 'Result unconfirmed. The operation may already have been applied. Check before trying again. Operation: '
61
+ : '结果未确认,操作可能已生效。请先核对会话,再决定是否重试。操作编号:')
62
+ const error = new Error(message + id)
63
+ error.operationId = id; error.operationPending = true; error.receiptMissing = receiptMissing
46
64
  return error
47
65
  }
66
+ const isMissingReceipt = (response, body) => response.status === 404 && body?.error === 'operation-not-found'
48
67
  async function execute(config) {
49
68
  const scope=await restore(config),intent=await digest(JSON.stringify([config.method,config.payload]))
50
69
  if(!config.valid())throw unknown('connection-changed')
51
70
  const existing=[...pending.values()].find(row=>row.scope===scope&&row.intent===intent)
52
71
  const id = existing?.id || newId(), createdAt = Date.now()
53
- const entry = existing || { id, scope, intent, method: config.method, sessionId: config.payload.sessionId || '', createdAt, phase: 'running', config }
72
+ if (existing?.inFlight) throw unknown(id)
73
+ const entry = existing || { id, scope, intent, method: config.method, sessionId: config.payload.sessionId || '', origin: originOf(config), createdAt, phase: 'running', config }
74
+ if (!entry.origin) entry.origin = originOf(config)
75
+ entry.inFlight = true
54
76
  pending.set(id, entry)
55
77
  persist()
56
78
  const statusUrl = config.url('/api/operations?id=' + encodeURIComponent(id))
@@ -63,7 +85,7 @@
63
85
  if (!config.valid()) throw unknown(id)
64
86
  if (response.status >= 400) {
65
87
  if (response.status >= 500) throw unknown(id)
66
- if (method === 'GET' && response.status === 404) throw unknown(id)
88
+ if (method === 'GET' && response.status === 404) throw unknown(id, isMissingReceipt(response, value))
67
89
  const error = new Error(value.error || ('HTTP ' + response.status)); error.rpcRejected = true; throw error
68
90
  }
69
91
  return value
@@ -71,7 +93,7 @@
71
93
  let status
72
94
  try {
73
95
  try { status = existing ? await request('GET') : await request('POST', { method: config.method, payload: config.payload }) }
74
- catch (error) { if (error.message === 'AUTH' || error.rpcRejected || !config.valid()) throw error }
96
+ catch (error) { if (error.message === 'AUTH' || error.rpcRejected || (existing && error.receiptMissing) || !config.valid()) throw error }
75
97
  for (let attempt = 0; config.valid() && Date.now() - createdAt < 90000; attempt++) {
76
98
  if (status?.phase === 'complete' || status?.phase === 'rejected') {
77
99
  entry.phase = status.phase; forget(id)
@@ -80,30 +102,53 @@
80
102
  if (status?.phase === 'unknown') { entry.phase = 'unknown'; throw unknown(id) }
81
103
  await sleep(Math.min(3000, 400 + attempt * 250))
82
104
  try { status = await request('GET') }
83
- catch (error) { if (error.message === 'AUTH' || error.rpcRejected) throw error }
105
+ catch (error) { if (error.message === 'AUTH' || error.rpcRejected || (existing && error.receiptMissing)) throw error }
84
106
  }
85
107
  throw unknown(id)
86
108
  } catch (error) {
87
109
  if (error.rpcRejected || error.message === 'AUTH') forget(id)
88
- else entry.phase = 'unknown'
110
+ else { entry.phase = 'unknown'; entry.receiptMissing = error.receiptMissing === true }
89
111
  persist()
90
112
  throw error
113
+ } finally {
114
+ entry.inFlight = false
91
115
  }
92
116
  }
93
117
  async function check(id) {
94
118
  const entry = pending.get(id)
95
- if (!entry || !entry.config.valid()) return null
119
+ if (!entry || !entry.config || !entry.config.valid()) return null
96
120
  const response = await root.fetch(entry.config.url('/api/operations?id=' + encodeURIComponent(id)), {
97
121
  headers: entry.config.headers, signal: AbortSignal.timeout(15000) })
98
122
  if (!entry.config.valid()) return null
99
123
  const value = await response.json()
100
124
  if (!entry.config.valid()) return null
125
+ if (isMissingReceipt(response, value)) return { receiptMissing: true }
101
126
  if (response.ok) { entry.phase = value.phase; if (['complete','rejected'].includes(value.phase)) forget(id) }
102
127
  return response.ok ? value : null
103
128
  }
129
+ function pendingRows() {
130
+ const rows = new Map()
131
+ for (const row of pending.values()) rows.set(row.id, { id: row.id, method: row.method, sessionId: row.sessionId,
132
+ createdAt: row.createdAt, phase: row.phase, origin: row.origin || '', receiptMissing: row.receiptMissing === true,
133
+ current: !!(row.config && row.config.valid()) })
134
+ // Receipts persisted for another address/token are still shown, as unknown.
135
+ // They cannot be queried until the user switches back to that connection,
136
+ // but hiding them would let an ambiguous write disappear from the UI.
137
+ for (const row of saved()) {
138
+ if (rows.has(row.id) || (currentScope && row.scope === currentScope)) continue
139
+ rows.set(row.id, { id: row.id, method: row.method, sessionId: row.sessionId, createdAt: row.createdAt,
140
+ phase: 'unknown', origin: row.origin || '', current: false })
141
+ }
142
+ return [...rows.values()].filter(row => row.current || row.phase === 'unknown')
143
+ }
104
144
  const api = { supports: method => methods.has(method), execute, check, restore,
105
- dismiss: id => { const row=pending.get(id);if(!row||row.phase!=='unknown'||!row.config.valid())return false;forget(id);return true },
106
- pending: () => [...pending.values()].filter(row => row.config.valid()).map(({id,method,sessionId,createdAt,phase}) => ({id,method,sessionId,createdAt,phase})) }
145
+ dismiss: id => {
146
+ const row = pending.get(id) || saved().find(value => value.id === id)
147
+ if (!row || row.inFlight || (row.phase && row.phase !== 'unknown')) return false
148
+ forget(id)
149
+ return true
150
+ },
151
+ pending: pendingRows }
107
152
  root.DshOperations = api
108
153
  if (typeof module !== 'undefined') module.exports = api
109
154
  })(typeof window === 'undefined' ? globalThis : window)
@@ -1,23 +1,24 @@
1
1
  <!doctype html>
2
2
  <html lang="zh-CN">
3
3
  <head>
4
- <meta name="dsh-remote-build" content="d76fba47d9b6c34d9a5d32c0e87d24222e6845b382ba95f08151758c5325a3b6">
4
+ <meta name="dsh-remote-build" content="84d998ae3a1302b3e1d02d3cdde5d8f3ad3f8bd963ec0323fd18a675015e1184">
5
5
  <meta charset="utf-8">
6
6
  <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
7
7
  <title>DSH Remote</title>
8
- <script>(function(){try{var t=localStorage.getItem('dshTheme');if(t!=='default'&&t!=='dark'&&t!=='light'&&t!=='neutral'&&t!=='mono'&&t!=='fish'&&t!=='penguin'&&t!=='penguin-night'&&t!=='bocchi'&&t!=='nijika'&&t!=='ryo'&&t!=='kita'){t='fish'}}catch(e){t='fish'}document.documentElement.setAttribute('data-theme',t)})()</script>
9
- <link rel="stylesheet" href="theme-vars.css?dsr-build=d76fba47d9b6c34d9a5d32c0e87d24222e6845b382ba95f08151758c5325a3b6">
10
- <link rel="stylesheet" href="setup.css?dsr-build=d76fba47d9b6c34d9a5d32c0e87d24222e6845b382ba95f08151758c5325a3b6">
11
- <link rel="stylesheet" href="insights.css?dsr-build=d76fba47d9b6c34d9a5d32c0e87d24222e6845b382ba95f08151758c5325a3b6">
12
- <link rel="stylesheet" href="remote-ui.css?dsr-build=d76fba47d9b6c34d9a5d32c0e87d24222e6845b382ba95f08151758c5325a3b6">
13
- <link rel="stylesheet" href="doctor.css?dsr-build=d76fba47d9b6c34d9a5d32c0e87d24222e6845b382ba95f08151758c5325a3b6">
14
- <link rel="stylesheet" href="skins/blue-fish/skin.css?dsr-build=d76fba47d9b6c34d9a5d32c0e87d24222e6845b382ba95f08151758c5325a3b6">
15
- <link rel="stylesheet" href="skins/penguin/skin.css?dsr-build=d76fba47d9b6c34d9a5d32c0e87d24222e6845b382ba95f08151758c5325a3b6">
16
- <link rel="stylesheet" href="skins/bocchi/skin.css?dsr-build=d76fba47d9b6c34d9a5d32c0e87d24222e6845b382ba95f08151758c5325a3b6">
17
- <link rel="stylesheet" href="skins/kessoku/skin.css?dsr-build=d76fba47d9b6c34d9a5d32c0e87d24222e6845b382ba95f08151758c5325a3b6">
18
- <link rel="stylesheet" href="skins/nijika/skin.css?dsr-build=d76fba47d9b6c34d9a5d32c0e87d24222e6845b382ba95f08151758c5325a3b6">
19
- <link rel="stylesheet" href="skins/ryo/skin.css?dsr-build=d76fba47d9b6c34d9a5d32c0e87d24222e6845b382ba95f08151758c5325a3b6">
20
- <link rel="stylesheet" href="skins/kita/skin.css?dsr-build=d76fba47d9b6c34d9a5d32c0e87d24222e6845b382ba95f08151758c5325a3b6">
8
+ <script>(function(){try{var t=localStorage.getItem('dshTheme');if(t!=='default'&&t!=='dark'&&t!=='light'&&t!=='neutral'&&t!=='mono'&&t!=='fish'&&t!=='penguin'&&t!=='penguin-night'&&t!=='bocchi'&&t!=='nijika'&&t!=='ryo'&&t!=='kita'&&t!=='penguin-logistics'){t='fish'}}catch(e){t='fish'}document.documentElement.setAttribute('data-theme',t)})()</script>
9
+ <link rel="stylesheet" href="theme-vars.css?dsr-build=84d998ae3a1302b3e1d02d3cdde5d8f3ad3f8bd963ec0323fd18a675015e1184">
10
+ <link rel="stylesheet" href="setup.css?dsr-build=84d998ae3a1302b3e1d02d3cdde5d8f3ad3f8bd963ec0323fd18a675015e1184">
11
+ <link rel="stylesheet" href="insights.css?dsr-build=84d998ae3a1302b3e1d02d3cdde5d8f3ad3f8bd963ec0323fd18a675015e1184">
12
+ <link rel="stylesheet" href="remote-ui.css?dsr-build=84d998ae3a1302b3e1d02d3cdde5d8f3ad3f8bd963ec0323fd18a675015e1184">
13
+ <link rel="stylesheet" href="doctor.css?dsr-build=84d998ae3a1302b3e1d02d3cdde5d8f3ad3f8bd963ec0323fd18a675015e1184">
14
+ <link rel="stylesheet" href="skins/blue-fish/skin.css?dsr-build=84d998ae3a1302b3e1d02d3cdde5d8f3ad3f8bd963ec0323fd18a675015e1184">
15
+ <link rel="stylesheet" href="skins/penguin/skin.css?dsr-build=84d998ae3a1302b3e1d02d3cdde5d8f3ad3f8bd963ec0323fd18a675015e1184">
16
+ <link rel="stylesheet" href="skins/bocchi/skin.css?dsr-build=84d998ae3a1302b3e1d02d3cdde5d8f3ad3f8bd963ec0323fd18a675015e1184">
17
+ <link rel="stylesheet" href="skins/kessoku/skin.css?dsr-build=84d998ae3a1302b3e1d02d3cdde5d8f3ad3f8bd963ec0323fd18a675015e1184">
18
+ <link rel="stylesheet" href="skins/nijika/skin.css?dsr-build=84d998ae3a1302b3e1d02d3cdde5d8f3ad3f8bd963ec0323fd18a675015e1184">
19
+ <link rel="stylesheet" href="skins/ryo/skin.css?dsr-build=84d998ae3a1302b3e1d02d3cdde5d8f3ad3f8bd963ec0323fd18a675015e1184">
20
+ <link rel="stylesheet" href="skins/kita/skin.css?dsr-build=84d998ae3a1302b3e1d02d3cdde5d8f3ad3f8bd963ec0323fd18a675015e1184">
21
+ <link rel="stylesheet" href="skins/penguin-logistics/skin.css?dsr-build=84d998ae3a1302b3e1d02d3cdde5d8f3ad3f8bd963ec0323fd18a675015e1184">
21
22
  <style>html[data-theme="light"],html[data-theme="neutral"],html[data-theme="fish"],html[data-theme="penguin"],html[data-theme="bocchi"],html[data-theme="nijika"],html[data-theme="ryo"],html[data-theme="kita"]{color-scheme:light}</style>
22
23
  </head>
23
24
  <body class="remote-panel-body">
@@ -52,17 +53,17 @@
52
53
  </section>
53
54
  <footer class="plugin-foot"><span id="plugin-version">—</span><a id="plugin-about" href="/remote/admin/#remote/settings" target="_blank" rel="noopener">关于与支持</a></footer>
54
55
  </main>
55
- <script src="i18n.js?dsr-build=d76fba47d9b6c34d9a5d32c0e87d24222e6845b382ba95f08151758c5325a3b6"></script>
56
- <script src="vendor/gsap/gsap.min.js?dsr-build=d76fba47d9b6c34d9a5d32c0e87d24222e6845b382ba95f08151758c5325a3b6"></script>
57
- <script src="motion.js?dsr-build=d76fba47d9b6c34d9a5d32c0e87d24222e6845b382ba95f08151758c5325a3b6"></script>
58
- <script type="module" src="morphicons-init.js?dsr-build=d76fba47d9b6c34d9a5d32c0e87d24222e6845b382ba95f08151758c5325a3b6"></script>
59
- <script src="qrcode.min.js?dsr-build=d76fba47d9b6c34d9a5d32c0e87d24222e6845b382ba95f08151758c5325a3b6"></script>
60
- <script src="remote-state.js?dsr-build=d76fba47d9b6c34d9a5d32c0e87d24222e6845b382ba95f08151758c5325a3b6"></script>
61
- <script src="remote-ui.js?dsr-build=d76fba47d9b6c34d9a5d32c0e87d24222e6845b382ba95f08151758c5325a3b6"></script>
62
- <script src="setup.js?dsr-build=d76fba47d9b6c34d9a5d32c0e87d24222e6845b382ba95f08151758c5325a3b6"></script>
63
- <script src="insights.js?dsr-build=d76fba47d9b6c34d9a5d32c0e87d24222e6845b382ba95f08151758c5325a3b6"></script>
64
- <script src="plugin.js?dsr-build=d76fba47d9b6c34d9a5d32c0e87d24222e6845b382ba95f08151758c5325a3b6"></script>
65
- <script src="doctor.js?dsr-build=d76fba47d9b6c34d9a5d32c0e87d24222e6845b382ba95f08151758c5325a3b6"></script>
66
- <script src="doctor-entry.js?dsr-build=d76fba47d9b6c34d9a5d32c0e87d24222e6845b382ba95f08151758c5325a3b6"></script>
56
+ <script src="i18n.js?dsr-build=84d998ae3a1302b3e1d02d3cdde5d8f3ad3f8bd963ec0323fd18a675015e1184"></script>
57
+ <script src="vendor/gsap/gsap.min.js?dsr-build=84d998ae3a1302b3e1d02d3cdde5d8f3ad3f8bd963ec0323fd18a675015e1184"></script>
58
+ <script src="motion.js?dsr-build=84d998ae3a1302b3e1d02d3cdde5d8f3ad3f8bd963ec0323fd18a675015e1184"></script>
59
+ <script type="module" src="morphicons-init.js?dsr-build=84d998ae3a1302b3e1d02d3cdde5d8f3ad3f8bd963ec0323fd18a675015e1184"></script>
60
+ <script src="qrcode.min.js?dsr-build=84d998ae3a1302b3e1d02d3cdde5d8f3ad3f8bd963ec0323fd18a675015e1184"></script>
61
+ <script src="remote-state.js?dsr-build=84d998ae3a1302b3e1d02d3cdde5d8f3ad3f8bd963ec0323fd18a675015e1184"></script>
62
+ <script src="remote-ui.js?dsr-build=84d998ae3a1302b3e1d02d3cdde5d8f3ad3f8bd963ec0323fd18a675015e1184"></script>
63
+ <script src="setup.js?dsr-build=84d998ae3a1302b3e1d02d3cdde5d8f3ad3f8bd963ec0323fd18a675015e1184"></script>
64
+ <script src="insights.js?dsr-build=84d998ae3a1302b3e1d02d3cdde5d8f3ad3f8bd963ec0323fd18a675015e1184"></script>
65
+ <script src="plugin.js?dsr-build=84d998ae3a1302b3e1d02d3cdde5d8f3ad3f8bd963ec0323fd18a675015e1184"></script>
66
+ <script src="doctor.js?dsr-build=84d998ae3a1302b3e1d02d3cdde5d8f3ad3f8bd963ec0323fd18a675015e1184"></script>
67
+ <script src="doctor-entry.js?dsr-build=84d998ae3a1302b3e1d02d3cdde5d8f3ad3f8bd963ec0323fd18a675015e1184"></script>
67
68
  </body>
68
69
  </html>
@@ -1,7 +1,7 @@
1
1
  /* Bootstrap a device pairing through an authenticated, user-confirmed LAN host. */
2
2
  ;(function(root) {
3
3
  'use strict'
4
- const bridge = root.NativeE2ee, attempts = new Set(), pairedOrigins = new Map()
4
+ const bridge = root.NativeE2ee, attempts = new Set(), pairedOrigins = new Map(), progress = new Map()
5
5
  let busy = false
6
6
  const text = (zh, en) => root.I18N?.lang === 'en' ? en : zh
7
7
  const LOG_KEY = 'dshRelayPairLogV1', LOG_MAX = 240, WAIT_LIMIT_SECONDS = 90, WAIT_STEP_MS = 2000
@@ -61,15 +61,17 @@
61
61
  E2EE_HOST_MISMATCH: ['主机证书与返回的公网地址不匹配。', 'The host certificate does not match the returned public address.'],
62
62
  E2EE_STORAGE_UNAVAILABLE: ['手机保存配对失败,请检查存储空间后重试。', 'The phone could not store the pairing. Check storage and retry.'],
63
63
  E2EE_CANCELLED: ['已取消自动配对。', 'Automatic pairing was cancelled.'],
64
- E2EE_PAIR_REQUEST_FAILED: ['无法通过局域网创建配对,请确认访问令牌后重试。', 'Could not create the pairing over LAN. Check the access token and retry.'],
64
+ E2EE_PAIR_REQUEST_FAILED: ['未收到电脑的配对回执。请先在电脑的中转设备列表检查是否已经创建,再决定是否重试。', 'The computer did not return a pairing receipt. Check its relay device list before retrying.'],
65
65
  E2EE_NOT_CONFIGURED: ['电脑尚未开启端到端加密中转。', 'Encrypted relay is not enabled on the computer.'],
66
66
  E2EE_PAIRING_CHANGED: ['主机证书已变化,请在手机上重新确认后重试。', 'The host certificate changed. Confirm again on the phone and retry.'],
67
67
  LOCAL_PAIRING_REQUIRED: ['配对请求必须来自直接局域网连接。', 'The pairing request must come from a direct LAN connection.'],
68
68
  RELAY_OPERATION_BUSY: ['主机正在处理另一项中转操作,请稍后重试。', 'The host is busy with another relay operation. Retry shortly.'],
69
+ E2EE_SETUP_ALREADY_USED: ['电脑已收到这张连接码的配对请求。若手机未保存配对,请在电脑关闭连接码,再生成新码。', 'The computer already received a pairing for this code. If the phone did not save it, close the code on the computer and generate a new one.'],
69
70
  E2EE_DEVICE_LIMIT: ['这台主机的配对设备数量已达上限。', 'This host has reached its paired-device limit.'],
70
71
  E2EE_PAIRING_INVALID: ['主机返回的配对数据不完整或无效。', 'The host returned incomplete or invalid pairing data.'],
71
72
  E2EE_IMPORT_FAILED: ['手机未能保存配对(证书可能已变化)。', 'The phone could not store the pairing (the certificate may have changed).'],
72
73
  E2EE_RELAY_OFFLINE: ['配对已保存,但主机公网通道在约 90 秒内未就绪;请稍后重试。局域网连接保留。', 'The pairing was saved, but the host relay channel did not become ready within about 90 seconds. Retry later; the LAN connection is kept.'],
74
+ E2EE_SESSION_VERIFY_FAILED: ['已验证公网主机身份,但未能读取会话列表。请检查电脑上的 DSH 后重新验证。', 'The public host identity was verified, but the session list could not be read. Check DSH on the computer, then verify again.'],
73
75
  E2EE_VERIFY_FAILED: ['公网通道已在线,但主机身份验证未通过,请稍后重试。局域网连接保留。', 'The relay channel was online but the host identity check failed. Retry later; the LAN connection is kept.'],
74
76
  E2EE_BAD_RESPONSE: ['主机返回了无法解析的响应。', 'The host returned an unreadable response.'],
75
77
  }
@@ -77,10 +79,10 @@
77
79
  const status = error?.httpStatus ? ` HTTP ${error.httpStatus}` : ''
78
80
  return text(`${entry[0]}(${code}${status})`, `${entry[1]} (${code}${status})`)
79
81
  }
80
- async function read(c, url, timeout = 8000) {
82
+ async function read(c, url, timeout = 8000, options = {}) {
81
83
  let response
82
84
  try {
83
- response = await root.fetch(url, { headers: c.headers, cache: 'no-store', redirect: 'error', signal: root.AbortSignal.timeout(timeout) })
85
+ response = await root.fetch(url, { headers: c.headers, cache: 'no-store', redirect: 'error', signal: root.AbortSignal.timeout(timeout), ...options })
84
86
  } catch {
85
87
  throw fail('E2EE_HOST_UNAVAILABLE')
86
88
  }
@@ -93,21 +95,24 @@
93
95
  }
94
96
  async function waitOnline(c, endpoint, onProgress) {
95
97
  let last = ''
96
- for (let i = 0; i < Math.ceil(WAIT_LIMIT_SECONDS * 1000 / WAIT_STEP_MS) && c.valid(); i++) {
98
+ const started = Date.now(), deadline = started + WAIT_LIMIT_SECONDS * 1000
99
+ while (c.valid() && Date.now() < deadline) {
97
100
  try {
98
- const status = await read(c, endpoint.href)
101
+ const status = await read(c, endpoint.href, Math.max(1, Math.min(8000, deadline - Date.now())))
99
102
  const phase = String(status?.phase || 'unknown')
100
103
  if (phase !== last) { last = phase; record('relay.phase', { phase }) }
101
104
  if (phase === 'online') return true
102
105
  } catch (error) {
103
106
  record('relay.phase.error', { code: error?.code || 'E2EE_HOST_UNAVAILABLE', httpStatus: error?.httpStatus })
104
107
  }
105
- onProgress?.(Math.min(WAIT_LIMIT_SECONDS, (i + 1) * Math.round(WAIT_STEP_MS / 1000)))
106
- await new Promise(resolve => root.setTimeout(resolve, WAIT_STEP_MS))
108
+ if (!c.valid()) return false
109
+ onProgress?.(Math.min(WAIT_LIMIT_SECONDS, Math.floor((Date.now() - started) / 1000)))
110
+ const remaining = deadline - Date.now()
111
+ if (remaining > 0) await new Promise(resolve => root.setTimeout(resolve, Math.min(WAIT_STEP_MS, remaining)))
107
112
  }
108
113
  return false
109
114
  }
110
- async function verify(c, origin, pin) {
115
+ async function verifyIdentity(c, origin, pin) {
111
116
  for (let attempt = 1; attempt <= 4 && c.valid(); attempt++) {
112
117
  try {
113
118
  const remote = await read(c, origin + '/relay')
@@ -121,9 +126,38 @@
121
126
  }
122
127
  return false
123
128
  }
129
+ async function verifySessions(c, origin) {
130
+ const method = 'session.list', rpcId = 'relay-check-' + Date.now()
131
+ try {
132
+ const response = await read(c, origin + '/api/' + method, 8000, {
133
+ method: 'POST',
134
+ headers: { ...c.headers, 'content-type': 'application/json', 'x-dsh-remote-client': 'app' },
135
+ body: JSON.stringify({ type: 'client-request', rpcId, method, payload: {} }),
136
+ })
137
+ return response?.result?.ok === true && Array.isArray(response.result.value?.items)
138
+ } catch { return false }
139
+ }
140
+ function contextKey(c) {
141
+ return JSON.stringify([new URL(c.url('/relay'), root.location.href).origin, c.headers?.authorization || ''])
142
+ }
143
+ async function finish(c, endpoint, origin, pin, onPaired, notify) {
144
+ notify(text('公网通道已在线,正在验证主机身份…', 'Relay channel is online. Verifying the host…'))
145
+ if (!await verifyIdentity(c, origin, pin)) throw fail('E2EE_VERIFY_FAILED')
146
+ if (!c.valid()) throw fail('E2EE_CONNECTION_INVALID')
147
+ notify(text('公网主机身份已验证,正在读取会话列表…', 'Public host identity verified. Reading the session list…'))
148
+ if (!await verifySessions(c, origin)) throw fail('E2EE_SESSION_VERIFY_FAILED')
149
+ if (!c.valid()) throw fail('E2EE_CONNECTION_INVALID')
150
+ pairedOrigins.set(endpoint.origin, origin)
151
+ onPaired?.(origin, c)
152
+ notify(text('电脑已确认配对,公网会话读取已验证。局域网连接保留。', 'The computer confirmed pairing and the session list was read over the relay. The LAN connection is kept.'), false, 'ready')
153
+ }
124
154
  async function offer({ connection, onPaired, onStatus = () => {}, force = false }) {
125
155
  const manual = force === true
126
- const notify = (message, error) => onStatus?.(message, error === true)
156
+ let key = ''
157
+ const notify = (message, error, phase = error ? 'error' : 'working') => {
158
+ if (key) progress.set(key, { message, phase })
159
+ onStatus?.(message, error === true)
160
+ }
127
161
  if (!bridge?.configure) {
128
162
  if (manual) { record('skipped', { reason: 'native-unavailable' }); notify(reason('E2EE_NATIVE_UNAVAILABLE')) }
129
163
  return { ok: false, code: 'E2EE_NATIVE_UNAVAILABLE' }
@@ -147,9 +181,10 @@
147
181
  if (manual) notify(reason('E2EE_CONNECTION_INVALID'), true)
148
182
  return { ok: false, code: 'E2EE_CONNECTION_INVALID' }
149
183
  }
150
- const key = JSON.stringify([endpoint.href, c.headers.authorization])
151
- if (!force && attempts.has(key)) return { ok: false, code: 'E2EE_ALREADY_ATTEMPTED' }
152
- attempts.add(key); busy = true
184
+ key = contextKey(c)
185
+ const attempt = JSON.stringify([key, c.setupId || ''])
186
+ if (!force && attempts.has(attempt)) return { ok: false, code: 'E2EE_ALREADY_ATTEMPTED' }
187
+ attempts.add(attempt); busy = true
153
188
  const started = Date.now()
154
189
  record('start', { force: manual })
155
190
  try {
@@ -166,11 +201,8 @@
166
201
  record('existing', { deviceId: old.deviceId })
167
202
  notify(text('已保留配对,正在等待公网通道就绪…', 'Saved pairing found. Waiting for the relay channel…'))
168
203
  if (host.phase !== 'online' && !await waitOnline(c, endpoint, seconds => notify(text(`已保留配对,正在等待公网通道就绪(${seconds}s)…`, `Saved pairing found. Waiting for the relay channel (${seconds}s)…`)))) throw fail('E2EE_RELAY_OFFLINE')
169
- notify(text('公网通道已在线,正在验证主机身份…', 'Relay channel is online. Verifying the host…'))
170
- if (!await verify(c, origin, pin)) throw fail('E2EE_VERIFY_FAILED')
171
- if (c.valid()) { pairedOrigins.set(endpoint.origin, origin); onPaired?.(origin, c) }
204
+ await finish(c, endpoint, origin, pin, onPaired, notify)
172
205
  record('verified', { mode: 'existing', ms: Date.now() - started })
173
- notify(text('公网配对已验证,局域网连接保留。', 'Relay pairing verified. The LAN connection is kept.'))
174
206
  return { ok: true, mode: 'existing' }
175
207
  }
176
208
  if (old.error && old.error !== 'E2EE_DEVICE_EXPIRED') throw fail('E2EE_STORAGE_UNAVAILABLE')
@@ -179,14 +211,14 @@
179
211
  + (old.fingerprint && old.fingerprint !== pin ? '\n' + text('主机证书已改变,将替换旧配对。', 'The host certificate changed. This replaces the previous pairing.') : '')
180
212
  if (!root.confirm(message) || !c.valid()) {
181
213
  record('cancelled')
182
- notify(text('已取消自动配对。', 'Automatic pairing was cancelled.'))
214
+ notify(text('已取消自动配对。', 'Automatic pairing was cancelled.'), false, 'idle')
183
215
  return { ok: false, code: 'E2EE_CANCELLED' }
184
216
  }
185
217
  notify(text('正在通过局域网创建并保存配对…', 'Creating and storing the pairing over LAN…'))
186
218
  const pairUrl = new URL(endpoint.href); pairUrl.pathname = pairUrl.pathname.replace(/\/$/, '') + '/pair'
187
219
  let response, data = {}
188
220
  try {
189
- response = await root.fetch(pairUrl.href, { headers: { ...c.headers, 'content-type': 'application/json' }, cache: 'no-store', redirect: 'error', method: 'POST', body: JSON.stringify({ fingerprint: pin, label: text('Android 手机', 'Android phone') }), signal: root.AbortSignal.timeout(15000) })
221
+ response = await root.fetch(pairUrl.href, { headers: { ...c.headers, 'content-type': 'application/json' }, cache: 'no-store', redirect: 'error', method: 'POST', body: JSON.stringify({ fingerprint: pin, label: text('Android 手机', 'Android phone'), ...(c.setupId ? {setupId:c.setupId} : {}) }), signal: root.AbortSignal.timeout(15000) })
190
222
  data = await response.json().catch(() => ({}))
191
223
  } catch { throw fail('E2EE_PAIR_REQUEST_FAILED') }
192
224
  record('pair.response', { httpStatus: response.status, error: typeof data?.error === 'string' ? data.error : '' })
@@ -194,24 +226,26 @@
194
226
  if (!response.ok) throw fail(typeof data?.error === 'string' ? data.error : 'E2EE_HTTP_' + response.status)
195
227
  const pair = data.pairing, url = pair && new URL(pair.relayUrl)
196
228
  if (!pair || pair.fingerprint !== pin || url.origin !== origin || url.protocol !== 'https:' || url.pathname !== '/relay/v1/e2ee' || url.search || url.hash || url.username || url.password) throw fail('E2EE_PAIRING_INVALID')
229
+ notify(text('电脑已收到并创建设备,正在保存到手机…', 'The computer received the request and created a device. Saving to this phone…'))
197
230
  record('paired', { deviceId: String(pair.deviceId || '').slice(0, 64), expiresAt: Number(pair.expiresAt) || 0 })
198
231
  const result = JSON.parse(bridge.configure(JSON.stringify(pair), old.fingerprint || ''))
199
232
  if (result?.error || result?.origin !== origin) throw fail('E2EE_IMPORT_FAILED')
200
233
  record('configured', { origin })
201
- notify(text('配对已保存,正在等待主机公网通道就绪(最多约 90 秒)…', 'Pairing saved. Waiting for the host relay channel (up to about 90 seconds)…'))
234
+ notify(text('电脑已确认配对,手机已保存。正在等待公网通道就绪(最多约 90 秒)…', 'The computer confirmed pairing and the phone saved it. Waiting for the relay channel (up to about 90 seconds)…'))
202
235
  if (!await waitOnline(c, endpoint, seconds => notify(text(`配对已保存,正在等待主机公网通道就绪(${seconds}s)…`, `Pairing saved. Waiting for the host relay channel (${seconds}s)…`)))) throw fail('E2EE_RELAY_OFFLINE')
203
- notify(text('公网通道已在线,正在验证主机身份…', 'Relay channel is online. Verifying the host…'))
204
- if (!await verify(c, origin, pin)) throw fail('E2EE_VERIFY_FAILED')
205
- if (c.valid()) { pairedOrigins.set(endpoint.origin, origin); onPaired?.(origin, c) }
236
+ await finish(c, endpoint, origin, pin, onPaired, notify)
206
237
  record('verified', { mode: 'new', ms: Date.now() - started })
207
- notify(text('公网配对已保存并验证,局域网连接保留。', 'Relay pairing saved and verified. The LAN connection is kept.'))
208
238
  return { ok: true, mode: 'new' }
209
239
  } catch (error) {
210
240
  const code = typeof error?.code === 'string' ? error.code : 'E2EE_PAIR_FAILED'
211
241
  record('failed', { code, ms: Date.now() - started, httpStatus: error?.httpStatus })
212
242
  if (c.valid()) notify(reason(code, error), true)
213
243
  return { ok: false, code }
214
- } finally { busy = false }
244
+ } finally {
245
+ if (!c.valid() && progress.get(key)?.phase === 'working') progress.delete(key)
246
+ busy = false
247
+ }
215
248
  }
216
- root.DshRelayAutoPair = { offer, localUrl, logText, clearLog, pairedOrigin: value => { try { return pairedOrigins.get(new URL(value, root.location.href).origin) || '' } catch { return '' } } }
249
+ root.DshRelayAutoPair = { offer, localUrl, logText, clearLog,
250
+ progress: c => { try { return progress.get(contextKey(c)) } catch { return undefined } }, pairedOrigin: value => { try { return pairedOrigins.get(new URL(value, root.location.href).origin) || '' } catch { return '' } } }
217
251
  })(typeof window !== 'undefined' ? window : globalThis)
@@ -5,8 +5,9 @@
5
5
  const make=(tag,value)=>{const e=document.createElement(tag);if(value)e.textContent=value;return e}
6
6
  root.DshRelayDevices={mount(target,{connection,path,credentials}){
7
7
  const title=make('h3',text('中转设备与配对','Relay devices and pairing'))
8
- const hint=make('p',text('设备管理请在主机本地地址打开。每台设备独立配对,最长有效 30 天;到期后重新创建并导入。浏览器暂不支持此加密入口。','Open a local host address to manage devices. Each device has a separate pairing valid for up to 30 days. Create and import a new pairing after expiry. This encrypted entry does not support browsers yet.'))
8
+ const hint=make('p',text('设备管理请在主机本地地址打开。手机扫码后创建的配对会出现在这里。每台设备的配对独立,最长有效 30 天。','Open management locally on the host. Devices appear here after they pair. Each device pairing is separate and valid for up to 30 days.'))
9
9
  const panel=make('div'),enable=make('button',text('启用主机加密入口','Enable encrypted host entry')),refresh=make('button',text('刷新设备','Refresh devices'))
10
+ const manual=make('details'),manualTitle=make('summary',text('手动创建配对文件','Create a pairing file manually'))
10
11
  const form=make('form'),label=make('input'),days=make('select'),create=make('button',text('创建设备配对','Create device pairing'))
11
12
  form.className='relay-device-form'
12
13
  label.placeholder=text('设备名称,例如:我的手机','Device name, e.g. My phone');label.maxLength=80;label.required=true;label.setAttribute('aria-label',label.placeholder)
@@ -17,7 +18,8 @@
17
18
  const notice=make('p'),download=make('button',text('保存配对文件(仅本次可用)','Save pairing file (available this time only)'))
18
19
  notice.setAttribute('role','status');download.hidden=true
19
20
  for(const b of [enable,refresh,rotate,download])b.type='button'
20
- panel.append(enable,form,refresh,list,rotate,download);target.append(title,hint,panel,notice)
21
+ manual.append(manualTitle,form,download)
22
+ panel.append(enable,refresh,list,manual,rotate);target.append(title,hint,panel,notice)
21
23
  let host=null,data=null,identity='',busy=false,abort=null,pairing=null,disposed=false
22
24
  function ctx(){
23
25
  const c=connection(),endpoint=new URL(c.url(path.replace(/\/e2ee$/,'')),root.location?.href||'http://localhost/')
@@ -28,17 +30,21 @@
28
30
  function valid(c){return !disposed&&c.valid()&&identity===JSON.stringify([c.endpoint,c.headers?.authorization||''])}
29
31
  function render(){
30
32
  panel.hidden=host?.canManageDevices!==true
31
- enable.hidden=host?.e2ee?.enabled===true;form.hidden=!host?.e2ee?.enabled;rotate.hidden=!host?.configured
33
+ enable.hidden=host?.e2ee?.enabled===true;manual.hidden=!host?.e2ee?.enabled;rotate.hidden=!host?.configured
32
34
  for(const b of [enable,refresh,rotate,create,label,days])b.disabled=busy
33
35
  download.hidden=!pairing;list.replaceChildren()
34
36
  for(const d of data?.devices||[]){
35
37
  const row=make('div');row.className='relay-device-row'
36
- const name=make('span',d.label+' · '+(d.active?text('有效至 ','Valid until ')+new Date(d.expiresAt).toLocaleString():d.revokedAt?text('已撤销','Revoked'):text('已到期','Expired')))
38
+ const connection=d.firstPublicAccessAt
39
+ ?text('已从公网访问','Reached host over public relay')
40
+ :text('已创建设备','Device created')
41
+ const state=d.active?connection+' · '+text('有效至 ','Valid until ')+new Date(d.expiresAt).toLocaleString():d.revokedAt?text('已撤销','Revoked'):text('已到期','Expired')
42
+ const name=make('span',d.label+' · '+state)
37
43
  const revoke=make('button',text('撤销','Revoke'));revoke.type='button';revoke.disabled=busy||!d.active
38
44
  revoke.addEventListener('click',()=>{if(root.confirm(text('撤销此设备?连接会立即断开,需要新配对才能再次访问。\n','Revoke this device? Its connections will close and a new pairing will be required.\n')+d.label))void run({action:'revoke-device',id:d.id})})
39
45
  row.append(name,revoke);list.append(row)
40
46
  }
41
- if(data&&!data.devices?.length)list.append(make('p',text('尚无设备,请创建配对后在 Android App 导入。','No devices. Create a pairing and import it in the Android app.')))
47
+ if(data&&!data.devices?.length)list.append(make('p',text('尚无中转设备,等待手机配对。','No relay devices yet. Pair a phone to get started.')))
42
48
  }
43
49
  async function run(value){
44
50
  const c=ctx();if(busy||host?.canManageDevices!==true)return
@@ -13,3 +13,12 @@
13
13
  .relay-pair-log-text{max-height:190px;overflow:auto;white-space:pre-wrap;overflow-wrap:anywhere;font:11px/1.5 ui-monospace,Consolas,monospace;padding:8px;margin:8px 0;border-radius:8px;background:var(--dsr-soft,rgba(127,127,127,.08));color:var(--dsr-muted,var(--text-secondary,#9aa4b2))}
14
14
  .relay-pair-log-actions{display:flex;gap:8px;flex-wrap:wrap}
15
15
  .relay-pair-log-hint{margin:6px 0 0;color:var(--dsr-muted,var(--text-secondary,#9aa4b2))}
16
+
17
+ .relay-pair-guide{margin:14px 0;padding:14px;border:1px solid var(--dsr-accent-line,var(--border,#77889950));border-radius:12px;scroll-margin-top:70px}
18
+ .relay-pair-guide h3{margin:0 0 8px;font-size:16px}
19
+ .relay-pair-guide p{font-size:13px;line-height:1.6;overflow-wrap:anywhere}
20
+ .relay-pair-guide button{margin:0 8px 6px 0}
21
+ .relay-pair-progress[data-phase=ready]{color:var(--success,#237858)}
22
+ .relay-pair-progress[data-phase=error]{color:var(--warning,#9d4b27)}
23
+ .relay-phone-code:not(:empty){display:block;width:min(220px,100%);padding:8px;margin:8px 0;background:#fff;border-radius:8px}
24
+ .relay-phone-code svg{display:block;width:100%;height:auto}
@@ -14,7 +14,7 @@
14
14
  INVALID_RESPONSE:['主机返回了无法识别的中转状态,请检查连接地址和主机 Remote 版本。','Unrecognized relay response. Check the host URL and Remote version.'],
15
15
  UNSUPPORTED_GATEWAY:['此主机尚不支持云中转设置,请更新主机 Remote。','Update the host Remote to use cloud relay settings.'],
16
16
  }
17
- function mount(target, { connection, path = '/relay', credentials } = {}) {
17
+ function mount(target, { connection, path = '/relay', credentials, phonePairingCode, deviceManagement = true } = {}) {
18
18
  if (!target || target.dataset.relayMounted) return
19
19
  target.dataset.relayMounted='true';target.classList.add('relay-settings')
20
20
  const heading=el('div','relay-heading'),title=el('h3'),badge=el('span','relay-badge')
@@ -30,24 +30,82 @@
30
30
  const submit=el('button','relay-primary');submit.type='submit';form.append(keyLabel,adminLabel,submit)
31
31
  const actions=el('div','relay-actions'),toggle=el('button'),refresh=el('button'),takeover=el('button');toggle.type=refresh.type=takeover.type='button';actions.append(takeover,toggle,refresh)
32
32
  const hint=el('p','relay-muted'),notice=el('p','relay-notice');notice.setAttribute('role','status')
33
- target.append(heading,intro,sponsor,status,address,plan,quota,binding,form,actions,hint,notice)
34
- const deviceTarget=el('div');target.append(deviceTarget)
35
- const devices=root.DshRelayDevices?.mount(deviceTarget,{connection,path:path+'/e2ee',credentials})
33
+ const phoneGuide=el('section','relay-pair-guide'),phoneTitle=el('h3'),phoneHint=el('p','relay-muted')
34
+ const showCode=el('button','relay-primary'),hideCode=el('button'),code=el('div','relay-phone-code'),phoneStatus=el('p','relay-pair-progress')
35
+ showCode.type=hideCode.type='button';phoneStatus.setAttribute('role','status')
36
+ phoneTitle.textContent=text('配对一台 Android 手机','Pair an Android phone')
37
+ phoneHint.textContent=text('手机与电脑连接同一局域网。在 DSH Remote 的「主机与连接」扫描下方连接码,并在手机确认。连接码含访问凭据,请私下使用。','Connect the phone and computer to the same LAN. Scan this code in DSH Remote under Hosts and connections, then confirm on the phone. Keep the code private.')
38
+ showCode.textContent=text('添加手机并显示连接码','Add a phone and show connection code')
39
+ hideCode.textContent=text('关闭连接码','Close connection code')
40
+ const recentPair=el('p','relay-muted')
41
+ phoneGuide.append(phoneTitle,phoneHint,showCode,hideCode,code,phoneStatus,recentPair)
42
+ target.append(heading,intro,status)
43
+ if(phonePairingCode)target.append(phoneGuide)
44
+ target.append(sponsor,address,plan,quota,binding,form,actions,hint,notice)
45
+ const deviceTarget=el('div')
46
+ if(deviceManagement)target.append(deviceTarget)
47
+ const devices=deviceManagement?root.DshRelayDevices?.mount(deviceTarget,{connection,path:path+'/e2ee',credentials}):null
48
+ let activeSetup='',pendingSetup=''
49
+ function closeCode(){
50
+ activeSetup='';pendingSetup='';code.textContent='';phoneStatus.textContent=''
51
+ hideCode.hidden=true;showCode.disabled=false
52
+ }
53
+ hideCode.addEventListener('click',closeCode)
54
+ showCode.addEventListener('click',async()=>{
55
+ const ctx=syncIdentity()
56
+ if(pendingSetup||activeSetup||value?.canManageDevices!==true||!value.enabled||!value.e2ee?.configured)return
57
+ const random=root.crypto.getRandomValues(new Uint8Array(16))
58
+ const setup=Array.from(random,byte=>byte.toString(16).padStart(2,'0')).join('')
59
+ pendingSetup=setup;showCode.disabled=true
60
+ phoneStatus.textContent=text('正在生成连接码…','Preparing the connection code…')
61
+ try{
62
+ const svg=await phonePairingCode(setup)
63
+ if(!current(ctx)||pendingSetup!==setup)return
64
+ if(!svg)throw Error('PAIR_CODE_UNAVAILABLE')
65
+ code.innerHTML=svg;activeSetup=setup;hideCode.hidden=false
66
+ phoneStatus.textContent=text('等待手机扫码并确认…','Waiting for the phone to scan and confirm…')
67
+ lastRead=0
68
+ void load()
69
+ }catch{
70
+ if(current(ctx)&&pendingSetup===setup)phoneStatus.textContent=text('暂时无法生成连接码。请确认网关已启动、存在可用局域网地址,再试一次。','Could not prepare the connection code. Check that the gateway is running and has a LAN address, then retry.')
71
+ }finally{if(current(ctx)&&pendingSetup===setup){pendingSetup='';showCode.disabled=!!activeSetup}}
72
+ })
36
73
  let identity='',value=null,lastRead=0,busy=false,loading=false,controller=null,destroyed=false,readError=false,failures=0
37
74
  function context() { const ctx=connection();return { ...ctx, endpoint:ctx.url(path) } }
38
75
  function current(ctx) { return !destroyed && ctx.valid() && identity===JSON.stringify([ctx.endpoint,ctx.headers?.authorization||'']) }
39
76
  function syncIdentity() {
40
77
  const ctx=context(),next=JSON.stringify([ctx.endpoint,ctx.headers?.authorization||''])
41
- if(next!==identity){identity=next;controller?.abort();controller=null;keyInput.value='';adminInput.value='';value=null;notice.textContent='';lastRead=0;loading=false;busy=false;readError=false;failures=0;render()}
78
+ if(next!==identity){identity=next;controller?.abort();controller=null;keyInput.value='';adminInput.value='';value=null;notice.textContent='';lastRead=0;loading=false;busy=false;readError=false;failures=0;closeCode();render()}
42
79
  return ctx
43
80
  }
44
81
  function render() {
45
82
  devices?.update(value)
83
+ if(phonePairingCode){
84
+ phoneGuide.hidden=value?.canManageDevices!==true||!value.enabled||!value.e2ee?.configured
85
+ if(phoneGuide.hidden&&(activeSetup||pendingSetup))closeCode()
86
+ const activity=Array.isArray(value?.pairingActivity)?value.pairingActivity:[]
87
+ if(activeSetup){
88
+ const recent=activity.find(device=>device.setupId===activeSetup)
89
+ const message=recent?.firstPublicAccessAt
90
+ ?text('手机已从公网访问这台电脑。请在手机查看会话验证结果。','The phone reached this computer over the relay. Check the session verification result on the phone.')
91
+ :recent?text('电脑已收到配对,等待手机验证公网。','Pairing received. Waiting for the phone to verify public access.')
92
+ :text('等待手机扫码并确认…','Waiting for the phone to scan and confirm…')
93
+ if(phoneStatus.textContent!==message)phoneStatus.textContent=message
94
+ }
95
+ const latest=activity[activity.length-1]
96
+ recentPair.hidden=!latest
97
+ if(latest){
98
+ const when=new Date(latest.createdAt).toLocaleString()
99
+ const state=latest.firstPublicAccessAt?text('已从公网访问','Reached over public relay'):text('已创建设备,等待公网验证','Device created, awaiting public verification')
100
+ const message=text('最近的设备配对 · ','Most recent device pairing · ')+when+' · '+state
101
+ if(recentPair.textContent!==message)recentPair.textContent=message
102
+ }
103
+ }
46
104
  root.DshSponsor?.mount(sponsor)
47
105
  title.textContent=text('云服务器中转','Cloud relay')
48
106
  intro.textContent=text('让手机通过公网连接这台主机。每位用户使用自己的中转密钥,首次开通会绑定此主机。','Connect to this host over the internet. Your personal relay key binds to this host when activated.')
49
107
  const phase=value?.phase||(readError?'unavailable':loading?'loading':'unconfigured')
50
- const names={loading:['正在读取','Loading'],unavailable:['状态读取失败','Status unavailable'],unconfigured:['尚未开通','Not configured'],disabled:['已停用','Disabled'],connecting:['正在连接','Connecting'],online:['已连接','Connected'],reconnecting:['正在重连','Reconnecting'],expired:['授权已到期','Expired'],'authorization-inactive':['授权已撤销或到期','Authorization inactive'],'quota-exceeded':['今日流量已用完','Daily quota reached'],'quota-unavailable':['流量服务暂不可用','Quota service unavailable'],error:['连接异常','Connection error']}
108
+ const names={loading:['正在读取','Loading'],unavailable:['状态读取失败','Status unavailable'],unconfigured:['尚未开通','Not configured'],disabled:['已停用','Disabled'],connecting:['正在连接','Connecting'],online:['主机中转在线','Host relay online'],reconnecting:['正在重连','Reconnecting'],expired:['授权已到期','Expired'],'authorization-inactive':['授权已撤销或到期','Authorization inactive'],'quota-exceeded':['今日流量已用完','Daily quota reached'],'quota-unavailable':['流量服务暂不可用','Quota service unavailable'],error:['连接异常','Connection error']}
51
109
  badge.textContent=phase==='quota-exceeded'&&value?.daily?.period==='month'?text('本月流量已用完','Monthly quota reached'):text(...(names[phase]||names.error));badge.dataset.phase=phase
52
110
  status.textContent=busy?text('正在保存并绑定,请稍候…','Saving and binding…'):value?.error?text('请检查主机配置或刷新状态。','Check the host configuration or refresh.'):text('开通后会随 Remote 网关启动,无需单独运行工具。','Starts with the Remote gateway after activation.')
53
111
  let safeUrl=''
@@ -77,7 +135,7 @@
77
135
  toggle.hidden=!value?.configured;toggle.disabled=busy;toggle.textContent=text(value?.enabled?'停用中转':'开启中转',value?.enabled?'Disable relay':'Enable relay')
78
136
  refresh.textContent=text('刷新状态','Refresh');refresh.disabled=busy||loading
79
137
  takeover.hidden=!value?.legacyAvailable;takeover.disabled=busy;takeover.textContent=text('接管已有试用连接','Take over existing trial')
80
- hint.textContent=value?.quotaPending?text('等待云端确认流量额度…','Waiting for cloud quota…'):value?.e2ee?.configured?text('请先在 App 导入主机本地的配对文件。端到端加密默认开启;关闭前须确认风险,普通浏览器暂不支持此配对入口。','Import the host’s local pairing file in the app. End-to-end encryption is on by default; disabling requires confirmation. Ordinary browsers do not support this paired entry.'):text('手机使用此公网地址和原 Remote 访问令牌。停用会断开通过此入口的连接;授权到期或用满后,请通过本地地址管理。','Use this URL and your existing Remote access token. Disabling disconnects this route; use a local address after expiry or quota exhaustion.')
138
+ hint.textContent=value?.quotaPending?text('等待云端确认流量额度…','Waiting for cloud quota…'):value?.e2ee?.configured?text('Android 可从局域网扫码配对。配对文件可在设备管理中手动创建。','Pair Android over the LAN using a connection code. Manual pairing files are available in device management.'):text('手机使用此公网地址和原 Remote 访问令牌。停用会断开通过此入口的连接;授权到期或用满后,请通过本地地址管理。','Use this URL and your existing Remote access token. Disabling disconnects this route; use a local address after expiry or quota exhaustion.')
81
139
  }
82
140
  async function load(force=false) {
83
141
  const ctx=syncIdentity()
@@ -115,7 +173,7 @@
115
173
  const response=await root.fetch(ctx.endpoint,{method:'POST',headers:{...ctx.headers,...(admin?{authorization:'Bearer '+admin}:{}),'content-type':'application/json'},credentials,body:JSON.stringify({action,...(action==='enroll'?{key}:{})}),signal:abort.signal})
116
174
  const data=await response.json();if(!current(ctx))return
117
175
  if(!response.ok)throw Object.assign(Error(data.error),{code:data.error})
118
- value=data;notice.textContent=text(action==='disable'?'中转已停用。':'设置已保存,正在确认云端连接。',action==='disable'?'Relay disabled.':'Saved. Confirming the cloud connection.')
176
+ value={...data,canManageDevices:value?.canManageDevices};notice.textContent=text(action==='disable'?'中转已停用。':'设置已保存,正在确认云端连接。',action==='disable'?'Relay disabled.':'Saved. Confirming the cloud connection.')
119
177
  }catch(error){if(current(ctx))notice.textContent=messages[error.code]?text(...messages[error.code]):text('暂时无法确认操作结果。请刷新状态后再决定是否重试。','Result unconfirmed. Refresh status before deciding whether to retry.')}
120
178
  finally{clearTimeout(timer);if(current(ctx)){busy=false;lastRead=0;render()}}
121
179
  }
@@ -130,7 +188,7 @@
130
188
  })
131
189
  function tick(){if(destroyed)return;syncIdentity();render();void load()}
132
190
  const timer=setInterval(tick,1000);tick()
133
- return { refresh:()=>load(true),destroy:()=>{destroyed=true;clearInterval(timer);controller?.abort();devices?.destroy();keyInput.value='';adminInput.value=''} }
191
+ return { refresh:()=>load(true),destroy:()=>{destroyed=true;clearInterval(timer);controller?.abort();closeCode();devices?.destroy();keyInput.value='';adminInput.value=''} }
134
192
  }
135
193
  root.DshRelaySettings={mount}
136
194
  })(typeof window!=='undefined'?window:globalThis)