@hyprnos/dsh-remote-plugin 0.0.0-stage → 0.8.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +61 -0
- package/README.md +60 -2
- package/apk/dsh-remote.apk +0 -0
- package/approval-summary.mjs +115 -0
- package/client.js +197 -0
- package/cordis.patch.yml +5 -0
- package/doctor-skill.mjs +99 -0
- package/doctor-target.mjs +24 -0
- package/file-delivery.mjs +84 -0
- package/gateway-stats.cjs +501 -0
- package/gateway.cjs +8451 -0
- package/index.mjs +1788 -0
- package/insights.mjs +111 -0
- package/market.mjs +86 -0
- package/package.json +73 -4
- package/peak-reminders.mjs +50 -0
- package/plugin-center.mjs +777 -0
- package/plugin-transaction.mjs +300 -0
- package/public/activity.js +188 -0
- package/public/admin.html +820 -0
- package/public/admin.js +1167 -0
- package/public/announcement-forms.js +89 -0
- package/public/announcements.json +464 -0
- package/public/app.js +8826 -0
- package/public/approval-records.js +301 -0
- package/public/approval-summary.js +78 -0
- package/public/build.json +5 -0
- package/public/cache-upgrade.js +51 -0
- package/public/chat-copy.js +59 -0
- package/public/chat-files.js +87 -0
- package/public/desktop/desktop.css +816 -0
- package/public/desktop/desktop.html +871 -0
- package/public/desktop/desktop.js +4548 -0
- package/public/desktop/i18n.js +85 -0
- package/public/diagnostics.js +203 -0
- package/public/doctor-entry.js +94 -0
- package/public/doctor.css +205 -0
- package/public/doctor.js +769 -0
- package/public/donate.png +0 -0
- package/public/e2ee-transport.js +219 -0
- package/public/extensions.css +109 -0
- package/public/extensions.js +215 -0
- package/public/file-inbox.css +66 -0
- package/public/file-inbox.js +289 -0
- package/public/genui.css +8 -0
- package/public/genui.js +254 -0
- package/public/history.js +304 -0
- package/public/i18n.js +57 -0
- package/public/icon.svg +12 -0
- package/public/image-cache.js +141 -0
- package/public/image-preview.js +290 -0
- package/public/index.html +1568 -0
- package/public/insights.css +28 -0
- package/public/insights.js +290 -0
- package/public/jsqr.min.js +10104 -0
- package/public/lan-discovery.js +94 -0
- package/public/link-check.js +109 -0
- package/public/manifest.webmanifest +16 -0
- package/public/md.js +333 -0
- package/public/morphicons-init.js +41 -0
- package/public/motion.js +557 -0
- package/public/network.js +100 -0
- package/public/onboarding.css +36 -0
- package/public/onboarding.js +253 -0
- package/public/operations.js +141 -0
- package/public/permission-presets.js +159 -0
- package/public/plugin-center.css +120 -0
- package/public/plugin-center.js +666 -0
- package/public/plugin-icon.svg +5 -0
- package/public/plugin.html +68 -0
- package/public/plugin.js +211 -0
- package/public/qrcode.min.js +2297 -0
- package/public/relay-autopair.js +251 -0
- package/public/relay-devices.js +80 -0
- package/public/relay-settings.css +24 -0
- package/public/relay-settings.js +194 -0
- package/public/remote-state.js +27 -0
- package/public/remote-ui.css +148 -0
- package/public/remote-ui.js +243 -0
- package/public/session-deck.css +79 -0
- package/public/session-deck.js +180 -0
- package/public/session-presets.js +47 -0
- package/public/setup.css +18 -0
- package/public/setup.js +213 -0
- package/public/sha256.js +119 -0
- package/public/skills.css +81 -0
- package/public/skills.js +202 -0
- package/public/skins/blue-fish/DESIGN.md +24 -0
- package/public/skins/blue-fish/face.png +0 -0
- package/public/skins/blue-fish/icon-blush.png +0 -0
- package/public/skins/blue-fish/icon-sleep.png +0 -0
- package/public/skins/blue-fish/icon-smile.png +0 -0
- package/public/skins/blue-fish/icon-star.png +0 -0
- package/public/skins/blue-fish/icon-wink.png +0 -0
- package/public/skins/blue-fish/icon.png +0 -0
- package/public/skins/blue-fish/mascot.png +0 -0
- package/public/skins/blue-fish/pattern.png +0 -0
- package/public/skins/blue-fish/preview.html +12 -0
- package/public/skins/blue-fish/skin.css +122 -0
- package/public/skins/blue-fish/sparkles.svg +18 -0
- package/public/skins/bocchi/DESIGN.md +99 -0
- package/public/skins/bocchi/face.png +0 -0
- package/public/skins/bocchi/grain.png +0 -0
- package/public/skins/bocchi/icon-blush.png +0 -0
- package/public/skins/bocchi/icon-sleep.png +0 -0
- package/public/skins/bocchi/icon-smile.png +0 -0
- package/public/skins/bocchi/icon-star.png +0 -0
- package/public/skins/bocchi/icon-wink.png +0 -0
- package/public/skins/bocchi/icon.png +0 -0
- package/public/skins/bocchi/pattern-soft.png +0 -0
- package/public/skins/bocchi/pattern.png +0 -0
- package/public/skins/bocchi/preview.html +55 -0
- package/public/skins/bocchi/skin.css +233 -0
- package/public/skins/bocchi/stage-bg.png +0 -0
- package/public/skins/bocchi/stage-soft.png +0 -0
- package/public/skins/bocchi/stand.png +0 -0
- package/public/skins/bocchi/sticker-guitar.png +0 -0
- package/public/skins/kessoku/DESIGN.md +38 -0
- package/public/skins/kessoku/grain.png +0 -0
- package/public/skins/kessoku/skin.css +212 -0
- package/public/skins/kita/SOURCES.json +51 -0
- package/public/skins/kita/face.png +0 -0
- package/public/skins/kita/icon-live.png +0 -0
- package/public/skins/kita/icon-reddress.png +0 -0
- package/public/skins/kita/icon-seifuku.png +0 -0
- package/public/skins/kita/pattern.png +0 -0
- package/public/skins/kita/preview.html +56 -0
- package/public/skins/kita/skin.css +26 -0
- package/public/skins/kita/stand.png +0 -0
- package/public/skins/kita/sticker-live.png +0 -0
- package/public/skins/nijika/SOURCES.json +51 -0
- package/public/skins/nijika/face.png +0 -0
- package/public/skins/nijika/icon-live.png +0 -0
- package/public/skins/nijika/icon-reddress.png +0 -0
- package/public/skins/nijika/icon-seifuku.png +0 -0
- package/public/skins/nijika/pattern.png +0 -0
- package/public/skins/nijika/preview.html +56 -0
- package/public/skins/nijika/skin.css +25 -0
- package/public/skins/nijika/stand.png +0 -0
- package/public/skins/nijika/sticker-live.png +0 -0
- package/public/skins/penguin/DESIGN.md +33 -0
- package/public/skins/penguin/SOURCES.json +22 -0
- package/public/skins/penguin/aic-blueprint.svg +24 -0
- package/public/skins/penguin/endfield-triangles.svg +4 -0
- package/public/skins/penguin/face.png +0 -0
- package/public/skins/penguin/icon-blush.png +0 -0
- package/public/skins/penguin/icon-dizzy.png +0 -0
- package/public/skins/penguin/icon-laugh.png +0 -0
- package/public/skins/penguin/icon-sleep.png +0 -0
- package/public/skins/penguin/icon-smile.png +0 -0
- package/public/skins/penguin/icon-star.png +0 -0
- package/public/skins/penguin/icon-wink.png +0 -0
- package/public/skins/penguin/icon.png +0 -0
- package/public/skins/penguin/mascot.png +0 -0
- package/public/skins/penguin/pattern-night.png +0 -0
- package/public/skins/penguin/pattern.png +0 -0
- package/public/skins/penguin/preview.html +12 -0
- package/public/skins/penguin/skin.css +212 -0
- package/public/skins/ryo/SOURCES.json +51 -0
- package/public/skins/ryo/face.png +0 -0
- package/public/skins/ryo/icon-live.png +0 -0
- package/public/skins/ryo/icon-reddress.png +0 -0
- package/public/skins/ryo/icon-seifuku.png +0 -0
- package/public/skins/ryo/pattern.png +0 -0
- package/public/skins/ryo/preview.html +56 -0
- package/public/skins/ryo/skin.css +25 -0
- package/public/skins/ryo/stand.png +0 -0
- package/public/skins/ryo/sticker-live.png +0 -0
- package/public/sponsor-entry.js +21 -0
- package/public/styles.css +1526 -0
- package/public/subagents.css +61 -0
- package/public/subagents.js +275 -0
- package/public/task-board.js +109 -0
- package/public/teams.js +98 -0
- package/public/theme-picker.css +58 -0
- package/public/theme-vars.css +1044 -0
- package/public/theme.js +166 -0
- package/public/transcribe-core.js +74 -0
- package/public/turn-results.js +121 -0
- package/public/update.json +49 -0
- package/public/vendor/gsap/NOTICE.md +10 -0
- package/public/vendor/gsap/gsap.min.js +11 -0
- package/public/vendor/morphicons/LICENSE +21 -0
- package/public/vendor/morphicons/README.md +10 -0
- package/public/vendor/morphicons/controller-CXZuwJ_M.js +152 -0
- package/public/vendor/morphicons/dom.js +206 -0
- package/public/vendor/morphicons/element.js +261 -0
- package/public/vendor/morphicons/normalize-CYnN3Npw.js +540 -0
- package/public/vendor/morphicons/spring-CFHloqPP.js +623 -0
- package/public/version.json +3 -0
- package/public/voice-input.js +1151 -0
- package/public/workflow.css +365 -0
- package/public/workflow.js +419 -0
- package/session-file.mjs +39 -0
- package/skills/dsh-remote-doctor/SKILL.md +186 -0
- package/skills/dsh-remote-doctor/references/wiki/README.md +40 -0
- package/skills/dsh-remote-doctor/references/wiki/ai-guide.md +61 -0
- package/skills/dsh-remote-doctor/references/wiki/connection.md +76 -0
- package/skills/dsh-remote-doctor/references/wiki/errors.md +26 -0
- package/skills/dsh-remote-doctor/references/wiki/evidence.md +44 -0
- package/skills/dsh-remote-doctor/references/wiki/files.md +31 -0
- package/skills/dsh-remote-doctor/references/wiki/maintenance.md +30 -0
- package/skills/dsh-remote-doctor/references/wiki/notifications.md +33 -0
- package/skills/dsh-remote-doctor/references/wiki/operations.md +32 -0
- package/skills/dsh-remote-doctor/references/wiki/plugins.md +90 -0
- package/skills/dsh-remote-doctor/references/wiki/sessions.md +45 -0
- package/skills/dsh-remote-doctor/references/wiki/sources.md +27 -0
- package/skills.mjs +53 -0
- package/speech-whisper.mjs +705 -0
- package/task-board.mjs +57 -0
- package/teams.mjs +58 -0
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
/* Bootstrap a device pairing through an authenticated, user-confirmed LAN host. */
|
|
2
|
+
;(function(root) {
|
|
3
|
+
'use strict'
|
|
4
|
+
const bridge = root.NativeE2ee, attempts = new Set(), pairedOrigins = new Map(), progress = new Map()
|
|
5
|
+
let busy = false
|
|
6
|
+
const text = (zh, en) => root.I18N?.lang === 'en' ? en : zh
|
|
7
|
+
const LOG_KEY = 'dshRelayPairLogV1', LOG_MAX = 240, WAIT_LIMIT_SECONDS = 90, WAIT_STEP_MS = 2000
|
|
8
|
+
let log = []
|
|
9
|
+
try {
|
|
10
|
+
const saved = JSON.parse(root.localStorage?.getItem(LOG_KEY) || '[]')
|
|
11
|
+
if (Array.isArray(saved)) log = saved.filter(row => row && typeof row === 'object' && typeof row.at === 'number' && typeof row.step === 'string').slice(-LOG_MAX)
|
|
12
|
+
} catch {}
|
|
13
|
+
function persist() { try { root.localStorage?.setItem(LOG_KEY, JSON.stringify(log.slice(-LOG_MAX))) } catch {} }
|
|
14
|
+
function scalar(value) {
|
|
15
|
+
if (typeof value === 'number' && Number.isFinite(value)) return value
|
|
16
|
+
if (typeof value === 'boolean' || typeof value === 'string') return typeof value === 'string' ? value.slice(0, 200) : value
|
|
17
|
+
return undefined
|
|
18
|
+
}
|
|
19
|
+
function record(step, detail = {}) {
|
|
20
|
+
const row = { at: Date.now(), step: String(step).slice(0, 40) }
|
|
21
|
+
for (const [key, value] of Object.entries(detail || {})) {
|
|
22
|
+
const clean = scalar(value)
|
|
23
|
+
if (clean !== undefined) row[String(key).slice(0, 32)] = clean
|
|
24
|
+
}
|
|
25
|
+
log.push(row)
|
|
26
|
+
if (log.length > LOG_MAX) log = log.slice(-LOG_MAX)
|
|
27
|
+
persist()
|
|
28
|
+
return row
|
|
29
|
+
}
|
|
30
|
+
function logText() {
|
|
31
|
+
return log.slice(-150).map(row => {
|
|
32
|
+
const rest = {}
|
|
33
|
+
for (const [key, value] of Object.entries(row)) if (key !== 'at' && key !== 'step') rest[key] = value
|
|
34
|
+
return `${new Date(row.at).toISOString()} ${row.step}${Object.keys(rest).length ? ' ' + JSON.stringify(rest) : ''}`
|
|
35
|
+
}).join('\n')
|
|
36
|
+
}
|
|
37
|
+
function clearLog() { log = []; persist() }
|
|
38
|
+
function fail(code) { const error = new Error(code); error.code = code; return error }
|
|
39
|
+
function localUrl(value) {
|
|
40
|
+
try {
|
|
41
|
+
const u = new URL(value), h = u.hostname.replace(/^\[|\]$/g, '')
|
|
42
|
+
if (!['http:', 'https:'].includes(u.protocol) || u.username || u.password) return false
|
|
43
|
+
if (h === 'localhost' || h === '::1' || h.includes(':') && /^(?:fc|fd|fe[89ab])[a-f0-9:]*$/i.test(h)) return true
|
|
44
|
+
const parts = h.split('.').map(Number)
|
|
45
|
+
if (parts.length !== 4 || parts.some(n => !Number.isInteger(n) || n < 0 || n > 255)) return false
|
|
46
|
+
const [a, b] = parts
|
|
47
|
+
return a === 10 || a === 127 || a === 192 && b === 168 || a === 172 && b >= 16 && b <= 31
|
|
48
|
+
} catch { return false }
|
|
49
|
+
}
|
|
50
|
+
const reason = (code, error) => {
|
|
51
|
+
const table = {
|
|
52
|
+
E2EE_NATIVE_UNAVAILABLE: ['自动配对仅支持 Android App(0.8.5 及以上);浏览器请使用“导入本机配对文件”。', 'Auto pairing runs in the Android app (0.8.5+). In a browser, import a pairing file instead.'],
|
|
53
|
+
E2EE_TLS_UNAVAILABLE: ['此设备不支持 TLS 1.3,无法使用端到端加密。', 'This device does not support TLS 1.3, so end-to-end encryption is unavailable.'],
|
|
54
|
+
E2EE_BUSY: ['正在配置配对,请稍候。', 'Pairing is already in progress.'],
|
|
55
|
+
E2EE_CONNECTION_INVALID: ['当前连接已失效,请重新连接局域网地址。', 'The current connection is no longer valid. Reconnect to the LAN address.'],
|
|
56
|
+
E2EE_NOT_LOCAL: ['请先连接自己电脑的局域网地址,再配置公网配对。', 'Connect to your computer’s LAN address before configuring relay pairing.'],
|
|
57
|
+
E2EE_HOST_UNAVAILABLE: ['局域网主机没有响应,请确认电脑上的 Remote 网关正在运行。', 'The LAN host did not respond. Make sure the Remote gateway is running on the computer.'],
|
|
58
|
+
E2EE_LOCAL_ONLY: ['主机没有把这次请求识别为直接局域网连接,无法创建配对。', 'The host did not treat this request as a direct LAN connection, so it cannot create a pairing.'],
|
|
59
|
+
E2EE_HOST_NOT_ENCRYPTED: ['电脑尚未开启端到端加密中转;请先在电脑本机开启后再试。', 'Encrypted relay is not enabled on the computer. Enable it locally first.'],
|
|
60
|
+
E2EE_HOST_INVALID: ['主机返回的公网地址或证书指纹无效。', 'The host returned an invalid public address or certificate fingerprint.'],
|
|
61
|
+
E2EE_HOST_MISMATCH: ['主机证书与返回的公网地址不匹配。', 'The host certificate does not match the returned public address.'],
|
|
62
|
+
E2EE_STORAGE_UNAVAILABLE: ['手机保存配对失败,请检查存储空间后重试。', 'The phone could not store the pairing. Check storage and retry.'],
|
|
63
|
+
E2EE_CANCELLED: ['已取消自动配对。', 'Automatic pairing was cancelled.'],
|
|
64
|
+
E2EE_PAIR_REQUEST_FAILED: ['未收到电脑的配对回执。请先在电脑的中转设备列表检查是否已经创建,再决定是否重试。', 'The computer did not return a pairing receipt. Check its relay device list before retrying.'],
|
|
65
|
+
E2EE_NOT_CONFIGURED: ['电脑尚未开启端到端加密中转。', 'Encrypted relay is not enabled on the computer.'],
|
|
66
|
+
E2EE_PAIRING_CHANGED: ['主机证书已变化,请在手机上重新确认后重试。', 'The host certificate changed. Confirm again on the phone and retry.'],
|
|
67
|
+
LOCAL_PAIRING_REQUIRED: ['配对请求必须来自直接局域网连接。', 'The pairing request must come from a direct LAN connection.'],
|
|
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.'],
|
|
70
|
+
E2EE_DEVICE_LIMIT: ['这台主机的配对设备数量已达上限。', 'This host has reached its paired-device limit.'],
|
|
71
|
+
E2EE_PAIRING_INVALID: ['主机返回的配对数据不完整或无效。', 'The host returned incomplete or invalid pairing data.'],
|
|
72
|
+
E2EE_IMPORT_FAILED: ['手机未能保存配对(证书可能已变化)。', 'The phone could not store the pairing (the certificate may have changed).'],
|
|
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.'],
|
|
75
|
+
E2EE_VERIFY_FAILED: ['公网通道已在线,但主机身份验证未通过,请稍后重试。局域网连接保留。', 'The relay channel was online but the host identity check failed. Retry later; the LAN connection is kept.'],
|
|
76
|
+
E2EE_BAD_RESPONSE: ['主机返回了无法解析的响应。', 'The host returned an unreadable response.'],
|
|
77
|
+
}
|
|
78
|
+
const entry = table[code] || ['公网配对尚未完成,局域网连接保留。请到云服务器中转重试;不会自动关闭加密。', 'Relay pairing did not complete. The LAN connection is kept; retry from Cloud relay. Encryption is never disabled automatically.']
|
|
79
|
+
const status = error?.httpStatus ? ` HTTP ${error.httpStatus}` : ''
|
|
80
|
+
return text(`${entry[0]}(${code}${status})`, `${entry[1]} (${code}${status})`)
|
|
81
|
+
}
|
|
82
|
+
async function read(c, url, timeout = 8000, options = {}) {
|
|
83
|
+
let response
|
|
84
|
+
try {
|
|
85
|
+
response = await root.fetch(url, { headers: c.headers, cache: 'no-store', redirect: 'error', signal: root.AbortSignal.timeout(timeout), ...options })
|
|
86
|
+
} catch {
|
|
87
|
+
throw fail('E2EE_HOST_UNAVAILABLE')
|
|
88
|
+
}
|
|
89
|
+
if (!response.ok) {
|
|
90
|
+
const error = fail('E2EE_HTTP_' + response.status)
|
|
91
|
+
error.httpStatus = response.status
|
|
92
|
+
throw error
|
|
93
|
+
}
|
|
94
|
+
try { return await response.json() } catch { throw fail('E2EE_BAD_RESPONSE') }
|
|
95
|
+
}
|
|
96
|
+
async function waitOnline(c, endpoint, onProgress) {
|
|
97
|
+
let last = ''
|
|
98
|
+
const started = Date.now(), deadline = started + WAIT_LIMIT_SECONDS * 1000
|
|
99
|
+
while (c.valid() && Date.now() < deadline) {
|
|
100
|
+
try {
|
|
101
|
+
const status = await read(c, endpoint.href, Math.max(1, Math.min(8000, deadline - Date.now())))
|
|
102
|
+
const phase = String(status?.phase || 'unknown')
|
|
103
|
+
if (phase !== last) { last = phase; record('relay.phase', { phase }) }
|
|
104
|
+
if (phase === 'online') return true
|
|
105
|
+
} catch (error) {
|
|
106
|
+
record('relay.phase.error', { code: error?.code || 'E2EE_HOST_UNAVAILABLE', httpStatus: error?.httpStatus })
|
|
107
|
+
}
|
|
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)))
|
|
112
|
+
}
|
|
113
|
+
return false
|
|
114
|
+
}
|
|
115
|
+
async function verifyIdentity(c, origin, pin) {
|
|
116
|
+
for (let attempt = 1; attempt <= 4 && c.valid(); attempt++) {
|
|
117
|
+
try {
|
|
118
|
+
const remote = await read(c, origin + '/relay')
|
|
119
|
+
if (remote?.e2ee?.fingerprint !== pin || new URL(remote.publicUrl).origin !== origin) throw fail('E2EE_HOST_MISMATCH')
|
|
120
|
+
record('verify', { attempt, ok: true })
|
|
121
|
+
return true
|
|
122
|
+
} catch (error) {
|
|
123
|
+
record('verify', { attempt, ok: false, code: error?.code || 'E2EE_HOST_UNAVAILABLE', httpStatus: error?.httpStatus })
|
|
124
|
+
}
|
|
125
|
+
if (attempt < 4 && c.valid()) await new Promise(resolve => root.setTimeout(resolve, 1000))
|
|
126
|
+
}
|
|
127
|
+
return false
|
|
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
|
+
}
|
|
154
|
+
async function offer({ connection, onPaired, onStatus = () => {}, force = false }) {
|
|
155
|
+
const manual = force === 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
|
+
}
|
|
161
|
+
if (!bridge?.configure) {
|
|
162
|
+
if (manual) { record('skipped', { reason: 'native-unavailable' }); notify(reason('E2EE_NATIVE_UNAVAILABLE')) }
|
|
163
|
+
return { ok: false, code: 'E2EE_NATIVE_UNAVAILABLE' }
|
|
164
|
+
}
|
|
165
|
+
if (bridge.supported?.() === false) {
|
|
166
|
+
if (manual) { record('skipped', { reason: 'tls13-unavailable' }); notify(reason('E2EE_TLS_UNAVAILABLE')) }
|
|
167
|
+
return { ok: false, code: 'E2EE_TLS_UNAVAILABLE' }
|
|
168
|
+
}
|
|
169
|
+
if (busy) {
|
|
170
|
+
if (manual) notify(reason('E2EE_BUSY'))
|
|
171
|
+
return { ok: false, code: 'E2EE_BUSY' }
|
|
172
|
+
}
|
|
173
|
+
const c = connection()
|
|
174
|
+
if (!c.valid()) { if (manual) notify(reason('E2EE_CONNECTION_INVALID'), true); return { ok: false, code: 'E2EE_CONNECTION_INVALID' } }
|
|
175
|
+
const endpoint = new URL(c.url('/relay'), root.location.href)
|
|
176
|
+
if (!localUrl(endpoint.href)) {
|
|
177
|
+
if (manual) { record('skipped', { reason: 'not-local' }); notify(reason('E2EE_NOT_LOCAL'), true) }
|
|
178
|
+
return { ok: false, code: 'E2EE_NOT_LOCAL' }
|
|
179
|
+
}
|
|
180
|
+
if (!/^Bearer \S+$/i.test(c.headers?.authorization || '')) {
|
|
181
|
+
if (manual) notify(reason('E2EE_CONNECTION_INVALID'), true)
|
|
182
|
+
return { ok: false, code: 'E2EE_CONNECTION_INVALID' }
|
|
183
|
+
}
|
|
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
|
|
188
|
+
const started = Date.now()
|
|
189
|
+
record('start', { force: manual })
|
|
190
|
+
try {
|
|
191
|
+
notify(text('正在读取局域网主机信息…', 'Reading LAN host information…'))
|
|
192
|
+
const host = await read(c, endpoint.href)
|
|
193
|
+
record('host', { enabled: !!host?.enabled, canPairLocally: !!host?.canPairLocally, phase: host?.phase, e2ee: !!host?.e2ee?.enabled })
|
|
194
|
+
if (!host?.canPairLocally) throw fail('E2EE_LOCAL_ONLY')
|
|
195
|
+
if (!host.enabled || !host.e2ee?.configured || !host.e2ee.enabled) throw fail('E2EE_HOST_NOT_ENCRYPTED')
|
|
196
|
+
const origin = new URL(host.publicUrl).origin, pin = host.e2ee.fingerprint
|
|
197
|
+
if (new URL(host.publicUrl).protocol !== 'https:' || !/^[a-f0-9]{64}$/.test(pin || '')) throw fail('E2EE_HOST_INVALID')
|
|
198
|
+
let old = {}
|
|
199
|
+
try { old = JSON.parse(bridge.info(origin) || '{}') } catch { throw fail('E2EE_STORAGE_UNAVAILABLE') }
|
|
200
|
+
if (old.configured && old.fingerprint === pin && !old.error && old.deviceId && old.expiresAt > Date.now()) {
|
|
201
|
+
record('existing', { deviceId: old.deviceId })
|
|
202
|
+
notify(text('已保留配对,正在等待公网通道就绪…', 'Saved pairing found. Waiting for the relay channel…'))
|
|
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')
|
|
204
|
+
await finish(c, endpoint, origin, pin, onPaired, notify)
|
|
205
|
+
record('verified', { mode: 'existing', ms: Date.now() - started })
|
|
206
|
+
return { ok: true, mode: 'existing' }
|
|
207
|
+
}
|
|
208
|
+
if (old.error && old.error !== 'E2EE_DEVICE_EXPIRED') throw fail('E2EE_STORAGE_UNAVAILABLE')
|
|
209
|
+
const message = text('为这台手机自动配置公网加密连接?请确认当前局域网连接是你自己的电脑。\n局域网:', 'Automatically configure this phone’s encrypted relay? Confirm this LAN connection is your own computer.\nLAN: ')
|
|
210
|
+
+ endpoint.origin + '\n' + text('公网:', 'Public: ') + origin
|
|
211
|
+
+ (old.fingerprint && old.fingerprint !== pin ? '\n' + text('主机证书已改变,将替换旧配对。', 'The host certificate changed. This replaces the previous pairing.') : '')
|
|
212
|
+
if (!root.confirm(message) || !c.valid()) {
|
|
213
|
+
record('cancelled')
|
|
214
|
+
notify(text('已取消自动配对。', 'Automatic pairing was cancelled.'), false, 'idle')
|
|
215
|
+
return { ok: false, code: 'E2EE_CANCELLED' }
|
|
216
|
+
}
|
|
217
|
+
notify(text('正在通过局域网创建并保存配对…', 'Creating and storing the pairing over LAN…'))
|
|
218
|
+
const pairUrl = new URL(endpoint.href); pairUrl.pathname = pairUrl.pathname.replace(/\/$/, '') + '/pair'
|
|
219
|
+
let response, data = {}
|
|
220
|
+
try {
|
|
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) })
|
|
222
|
+
data = await response.json().catch(() => ({}))
|
|
223
|
+
} catch { throw fail('E2EE_PAIR_REQUEST_FAILED') }
|
|
224
|
+
record('pair.response', { httpStatus: response.status, error: typeof data?.error === 'string' ? data.error : '' })
|
|
225
|
+
if (!c.valid()) { record('aborted'); return { ok: false, code: 'E2EE_CONNECTION_INVALID' } }
|
|
226
|
+
if (!response.ok) throw fail(typeof data?.error === 'string' ? data.error : 'E2EE_HTTP_' + response.status)
|
|
227
|
+
const pair = data.pairing, url = pair && new URL(pair.relayUrl)
|
|
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…'))
|
|
230
|
+
record('paired', { deviceId: String(pair.deviceId || '').slice(0, 64), expiresAt: Number(pair.expiresAt) || 0 })
|
|
231
|
+
const result = JSON.parse(bridge.configure(JSON.stringify(pair), old.fingerprint || ''))
|
|
232
|
+
if (result?.error || result?.origin !== origin) throw fail('E2EE_IMPORT_FAILED')
|
|
233
|
+
record('configured', { origin })
|
|
234
|
+
notify(text('电脑已确认配对,手机已保存。正在等待公网通道就绪(最多约 90 秒)…', 'The computer confirmed pairing and the phone saved it. Waiting for the relay channel (up to about 90 seconds)…'))
|
|
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')
|
|
236
|
+
await finish(c, endpoint, origin, pin, onPaired, notify)
|
|
237
|
+
record('verified', { mode: 'new', ms: Date.now() - started })
|
|
238
|
+
return { ok: true, mode: 'new' }
|
|
239
|
+
} catch (error) {
|
|
240
|
+
const code = typeof error?.code === 'string' ? error.code : 'E2EE_PAIR_FAILED'
|
|
241
|
+
record('failed', { code, ms: Date.now() - started, httpStatus: error?.httpStatus })
|
|
242
|
+
if (c.valid()) notify(reason(code, error), true)
|
|
243
|
+
return { ok: false, code }
|
|
244
|
+
} finally {
|
|
245
|
+
if (!c.valid() && progress.get(key)?.phase === 'working') progress.delete(key)
|
|
246
|
+
busy = false
|
|
247
|
+
}
|
|
248
|
+
}
|
|
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 '' } } }
|
|
251
|
+
})(typeof window !== 'undefined' ? window : globalThis)
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/* Host-local device administration. Pairing secrets live only in this page's memory. */
|
|
2
|
+
;(function(root) {
|
|
3
|
+
'use strict'
|
|
4
|
+
const text=(zh,en)=>root.I18N?.lang==='en'?en:zh
|
|
5
|
+
const make=(tag,value)=>{const e=document.createElement(tag);if(value)e.textContent=value;return e}
|
|
6
|
+
root.DshRelayDevices={mount(target,{connection,path,credentials}){
|
|
7
|
+
const title=make('h3',text('中转设备与配对','Relay devices and pairing'))
|
|
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
|
+
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'))
|
|
11
|
+
const form=make('form'),label=make('input'),days=make('select'),create=make('button',text('创建设备配对','Create device pairing'))
|
|
12
|
+
form.className='relay-device-form'
|
|
13
|
+
label.placeholder=text('设备名称,例如:我的手机','Device name, e.g. My phone');label.maxLength=80;label.required=true;label.setAttribute('aria-label',label.placeholder)
|
|
14
|
+
days.setAttribute('aria-label',text('配对有效期','Pairing validity'))
|
|
15
|
+
for(const n of [7,14,30]){const option=make('option',text(n+' 天',n+' days'));option.value=String(n);days.append(option)}
|
|
16
|
+
days.value='30';create.type='submit';form.append(label,days,create)
|
|
17
|
+
const list=make('div'),rotate=make('button',text('更换主机证书并清除全部配对','Rotate host certificate and clear all pairings'))
|
|
18
|
+
const notice=make('p'),download=make('button',text('保存配对文件(仅本次可用)','Save pairing file (available this time only)'))
|
|
19
|
+
notice.setAttribute('role','status');download.hidden=true
|
|
20
|
+
for(const b of [enable,refresh,rotate,download])b.type='button'
|
|
21
|
+
manual.append(manualTitle,form,download)
|
|
22
|
+
panel.append(enable,refresh,list,manual,rotate);target.append(title,hint,panel,notice)
|
|
23
|
+
let host=null,data=null,identity='',busy=false,abort=null,pairing=null,disposed=false
|
|
24
|
+
function ctx(){
|
|
25
|
+
const c=connection(),endpoint=new URL(c.url(path.replace(/\/e2ee$/,'')),root.location?.href||'http://localhost/')
|
|
26
|
+
// Workflow adapters may return a fixed relay endpoint regardless of route.
|
|
27
|
+
endpoint.pathname=endpoint.pathname.replace(/\/$/,'')+'/e2ee'
|
|
28
|
+
return {...c,endpoint:endpoint.href}
|
|
29
|
+
}
|
|
30
|
+
function valid(c){return !disposed&&c.valid()&&identity===JSON.stringify([c.endpoint,c.headers?.authorization||''])}
|
|
31
|
+
function render(){
|
|
32
|
+
panel.hidden=host?.canManageDevices!==true
|
|
33
|
+
enable.hidden=host?.e2ee?.enabled===true;manual.hidden=!host?.e2ee?.enabled;rotate.hidden=!host?.configured
|
|
34
|
+
for(const b of [enable,refresh,rotate,create,label,days])b.disabled=busy
|
|
35
|
+
download.hidden=!pairing;list.replaceChildren()
|
|
36
|
+
for(const d of data?.devices||[]){
|
|
37
|
+
const row=make('div');row.className='relay-device-row'
|
|
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)
|
|
43
|
+
const revoke=make('button',text('撤销','Revoke'));revoke.type='button';revoke.disabled=busy||!d.active
|
|
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})})
|
|
45
|
+
row.append(name,revoke);list.append(row)
|
|
46
|
+
}
|
|
47
|
+
if(data&&!data.devices?.length)list.append(make('p',text('尚无中转设备,等待手机配对。','No relay devices yet. Pair a phone to get started.')))
|
|
48
|
+
}
|
|
49
|
+
async function run(value){
|
|
50
|
+
const c=ctx();if(busy||host?.canManageDevices!==true)return
|
|
51
|
+
busy=true;abort?.abort();abort=new AbortController();const own=abort,timer=setTimeout(()=>own.abort(),20000)
|
|
52
|
+
pairing=null;notice.textContent='';render()
|
|
53
|
+
try{
|
|
54
|
+
const response=await root.fetch(c.endpoint,{method:value?'POST':'GET',headers:{...c.headers,...(value?{'content-type':'application/json'}:{})},credentials,cache:'no-store',signal:own.signal,...(value?{body:JSON.stringify(value)}:{})})
|
|
55
|
+
const result=await response.json();if(!valid(c))return
|
|
56
|
+
if(!response.ok)throw Error(result.error||'E2EE_OPERATION_FAILED')
|
|
57
|
+
data=result;host={...host,...result};pairing=result.pairing||null
|
|
58
|
+
if(pairing)notice.textContent=text('配对已创建。请立即保存文件并安全传到对应设备;文件包含访问凭据,不能公开。创建或撤销会短暂断开其他中转连接。','Pairing created. Save it now and transfer it securely to the intended device. It contains access credentials. Creating or revoking a device briefly disconnects other relay clients.')
|
|
59
|
+
else if(value)notice.textContent=text('已保存。中转连接会重新建立;已受理任务继续运行。','Saved. Relay connections will reconnect; accepted tasks continue.')
|
|
60
|
+
}catch(error){if(valid(c))notice.textContent=error.message==='E2EE_DISABLED_BY_POLICY'?text('主机环境已明确关闭加密,请先在主机取消 DSH_REMOTE_RELAY_E2EE=0 并重启网关。','The host environment disables encryption. Remove DSH_REMOTE_RELAY_E2EE=0 and restart the gateway first.'):text('未能确认结果,请刷新设备列表后再决定是否重试。错误:','Result unconfirmed. Refresh the device list before deciding whether to retry. Error: ')+error.message}
|
|
61
|
+
finally{clearTimeout(timer);if(valid(c)){busy=false;render()}}
|
|
62
|
+
}
|
|
63
|
+
form.addEventListener('submit',e=>{e.preventDefault();if(!label.value.trim())return;void run({action:'create-device',label:label.value.trim(),days:Number(days.value)})})
|
|
64
|
+
refresh.addEventListener('click',()=>void run())
|
|
65
|
+
enable.addEventListener('click',()=>{if(root.confirm(text('启用后旧公网入口将停止使用,需要先为 Android 创建并导入配对。当前中转连接会断开,请保留本地管理页面。','Enabling disables the legacy public entry. Create and import an Android pairing. Relay clients will disconnect; keep this local management page open.')))void run({action:'enable-encryption'})})
|
|
66
|
+
rotate.addEventListener('click',()=>{if(root.confirm(text('确认更换主机证书?全部现有配对立即失效,所有设备需要重新配对。此操作无法撤销。','Rotate the host certificate? All existing pairings become invalid and every device must pair again. This cannot be undone.')))void run({action:'rotate-identity',confirm:'REPAIR_ALL_DEVICES'})})
|
|
67
|
+
download.addEventListener('click',()=>{
|
|
68
|
+
if(!pairing)return
|
|
69
|
+
const url=URL.createObjectURL(new Blob([JSON.stringify(pairing,null,2)+'\n'],{type:'application/json'})),a=make('a')
|
|
70
|
+
a.href=url;a.download='dsh-remote-device-'+pairing.deviceId+'.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000)
|
|
71
|
+
})
|
|
72
|
+
return {update(value){
|
|
73
|
+
const c=ctx(),next=JSON.stringify([c.endpoint,c.headers?.authorization||''])
|
|
74
|
+
if(next!==identity){abort?.abort();identity=next;host=null;data=null;pairing=null;busy=false;label.value='';notice.textContent=''}
|
|
75
|
+
const first=value?.canManageDevices===true&&host?.canManageDevices!==true
|
|
76
|
+
// Keep fresh device-operation state until the next host status read.
|
|
77
|
+
host=value;render();if(first)void run()
|
|
78
|
+
},destroy(){disposed=true;abort?.abort();pairing=null;data=null;label.value='';list.replaceChildren()}}
|
|
79
|
+
}}
|
|
80
|
+
})(typeof window!=='undefined'?window:globalThis)
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
.relay-settings{margin:18px 0;padding:20px;border:1px solid var(--dsr-line,var(--border,#ffffff20));border-radius:16px;background:var(--dsr-panel,var(--bg-card,transparent));color:inherit;min-width:0}
|
|
2
|
+
.relay-encryption-switch{display:flex;align-items:center;gap:10px;min-height:44px;font-size:14px}.relay-encryption-switch input{width:20px;height:20px;accent-color:var(--dsr-accent,var(--accent,#527dab))}.relay-encryption-status{font-size:13px;line-height:1.65;overflow-wrap:anywhere}.relay-encryption-status[data-security=legacy]{padding:12px;border:1px solid var(--warning,#d98758);border-radius:9px;color:var(--warning,#d98758)}
|
|
3
|
+
.relay-sponsor{margin:14px 0;padding:14px;border:1px solid var(--dsr-accent-line,var(--border,#ffffff25));border-radius:10px;background:var(--dsr-accent-soft,#527dab18);font-size:13px;line-height:1.7}.relay-sponsor .sponsor-entry{margin:0}.sponsor-entry a{color:var(--dsr-accent-strong,var(--accent,#6ea9e8));font-weight:600}.sponsor-entry span{display:block;font-size:12px;opacity:.75;margin-top:5px}
|
|
4
|
+
.relay-settings [hidden]{display:none!important}.relay-heading,.relay-address,.relay-actions{display:flex;align-items:center;gap:12px;flex-wrap:wrap}.relay-heading{justify-content:space-between}.relay-heading h3{font-size:16px;line-height:1.4;margin:0}.relay-badge{font-size:12px;padding:5px 9px;border-radius:20px;background:#77889920}.relay-badge[data-phase=online]{background:#36b48522;color:var(--success,#35b58a)}.relay-badge[data-phase=quota-exceeded],.relay-badge[data-phase=error]{background:#da704522;color:var(--warning,#d98758)}.relay-muted{font-size:12px;line-height:1.65;opacity:.7;margin:10px 0}.relay-status,.relay-notice,.relay-quota p{font-size:13px;line-height:1.6}.relay-address{padding:12px 0}.relay-address a{color:var(--dsr-accent,var(--accent,#6ea9e8));overflow-wrap:anywhere;flex:1;min-width:120px}.relay-form{display:grid;gap:12px;padding:12px 0}.relay-form label{display:grid;gap:7px;font-size:13px}.relay-form input{width:100%;box-sizing:border-box;min-height:44px;border:1px solid var(--dsr-line,var(--border,#ffffff25));background:transparent;color:inherit;border-radius:9px;padding:10px 12px;font:inherit}.relay-settings button{min-height:44px;border:1px solid var(--dsr-line,var(--border,#ffffff25));border-radius:9px;padding:9px 14px;font:inherit;font-size:13px;cursor:pointer;background:transparent;color:inherit}.relay-settings .relay-primary{background:var(--dsr-accent,var(--accent,#527dab));color:var(--dsr-bg,#fff);justify-self:start;border-color:transparent}.relay-settings button:disabled{opacity:.5;cursor:default}.relay-settings :focus-visible{outline:2px solid var(--dsr-accent,var(--accent,#6ea9e8));outline-offset:3px}.relay-quota progress{display:block;width:100%;height:7px;accent-color:var(--dsr-accent,var(--accent,#6ea9e8))}.relay-notice:empty{display:none}.relay-notice{padding:10px 12px;border-radius:9px;background:#71839c16}.relay-actions{margin-top:6px}@media(max-width:480px){.relay-settings{padding:16px}.relay-heading{align-items:flex-start}.relay-address{align-items:flex-start}.relay-form .relay-primary{width:100%;justify-self:stretch}}
|
|
5
|
+
.relay-device-row{display:flex;align-items:center;justify-content:space-between;gap:12px;margin:8px 0;overflow-wrap:anywhere}
|
|
6
|
+
.relay-device-row>span{min-width:0}
|
|
7
|
+
.relay-device-form{display:flex;gap:8px;flex-wrap:wrap;margin:12px 0}
|
|
8
|
+
.relay-device-form input{min-width:0;flex:1 1 180px}
|
|
9
|
+
.relay-device-form input,.relay-device-form select{min-height:44px;background:var(--dsr-panel,var(--bg-card,transparent));color:inherit;border:1px solid var(--dsr-line,var(--border,#77889950));border-radius:9px;padding:8px;box-sizing:border-box}
|
|
10
|
+
|
|
11
|
+
.relay-pair-log{margin-top:10px;font-size:12px;line-height:1.5}
|
|
12
|
+
.relay-pair-log>summary{cursor:pointer;color:var(--dsr-muted,var(--text-secondary,#9aa4b2))}
|
|
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
|
+
.relay-pair-log-actions{display:flex;gap:8px;flex-wrap:wrap}
|
|
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}
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
/* Shared settings for the host-owned relay; no credentials enter browser storage. */
|
|
2
|
+
;(function(root) {
|
|
3
|
+
'use strict'
|
|
4
|
+
const text = (zh, en) => root.I18N?.lang === 'en' ? en : zh
|
|
5
|
+
const el = (tag, cls, value) => { const node=document.createElement(tag);if(cls)node.className=cls;if(value)node.textContent=value;return node }
|
|
6
|
+
const messages = {
|
|
7
|
+
INVALID_AUTHORIZATION:['中转密钥无效或已到期,请核对运营者发给你的密钥。','The relay key is invalid or expired.'],
|
|
8
|
+
HOST_ALREADY_BOUND:['此密钥已绑定其他主机,请申请新的密钥。','This key is already bound to another host.'],
|
|
9
|
+
RELAY_ADMIN_REQUIRED:['开通或停用需要此主机的管理令牌。','The host admin token is required.'],
|
|
10
|
+
ENROLLMENT_CONNECTION_FAILED:['暂时无法连接中转服务器,密钥未保存到浏览器。','The relay server is unreachable. The key was not saved in the browser.'],
|
|
11
|
+
GATEWAY_UNAVAILABLE:['请先在主机上启动 Remote 网关。','Start the Remote gateway on the host first.'],
|
|
12
|
+
RELAY_OPERATION_BUSY:['主机正在处理上一次操作,请稍后刷新状态。','The previous operation is still running. Refresh shortly.'],
|
|
13
|
+
unauthorized:['请先连接主机,再设置云服务器中转。','Connect to your host before configuring its relay.'],
|
|
14
|
+
INVALID_RESPONSE:['主机返回了无法识别的中转状态,请检查连接地址和主机 Remote 版本。','Unrecognized relay response. Check the host URL and Remote version.'],
|
|
15
|
+
UNSUPPORTED_GATEWAY:['此主机尚不支持云中转设置,请更新主机 Remote。','Update the host Remote to use cloud relay settings.'],
|
|
16
|
+
}
|
|
17
|
+
function mount(target, { connection, path = '/relay', credentials, phonePairingCode, deviceManagement = true } = {}) {
|
|
18
|
+
if (!target || target.dataset.relayMounted) return
|
|
19
|
+
target.dataset.relayMounted='true';target.classList.add('relay-settings')
|
|
20
|
+
const heading=el('div','relay-heading'),title=el('h3'),badge=el('span','relay-badge')
|
|
21
|
+
heading.append(title,badge)
|
|
22
|
+
const intro=el('p','relay-muted'),status=el('p','relay-status');status.setAttribute('aria-live','polite')
|
|
23
|
+
const sponsor=el('div','relay-sponsor');root.DshSponsor?.mount(sponsor)
|
|
24
|
+
const address=el('div','relay-address'),link=el('a'),copy=el('button');copy.type='button';link.target='_blank';link.rel='noopener noreferrer';address.append(link,copy)
|
|
25
|
+
const quota=el('div','relay-quota'),meter=el('progress'),usage=el('p'),reset=el('p','relay-muted');meter.max=100;quota.append(usage,meter,reset)
|
|
26
|
+
const plan=el('p','relay-muted'),binding=el('p','relay-muted'),form=el('form','relay-form'),keyLabel=el('label'),keyInput=el('input')
|
|
27
|
+
keyInput.type='password';keyInput.autocomplete='off';keyInput.spellcheck=false;keyInput.maxLength=128;keyInput.name='relay-key'
|
|
28
|
+
keyLabel.append(el('span'),keyInput)
|
|
29
|
+
const adminLabel=el('label'),adminInput=el('input');adminInput.type='password';adminInput.autocomplete='off';adminInput.name='relay-admin';adminLabel.append(el('span'),adminInput)
|
|
30
|
+
const submit=el('button','relay-primary');submit.type='submit';form.append(keyLabel,adminLabel,submit)
|
|
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
|
+
const hint=el('p','relay-muted'),notice=el('p','relay-notice');notice.setAttribute('role','status')
|
|
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
|
+
})
|
|
73
|
+
let identity='',value=null,lastRead=0,busy=false,loading=false,controller=null,destroyed=false,readError=false,failures=0
|
|
74
|
+
function context() { const ctx=connection();return { ...ctx, endpoint:ctx.url(path) } }
|
|
75
|
+
function current(ctx) { return !destroyed && ctx.valid() && identity===JSON.stringify([ctx.endpoint,ctx.headers?.authorization||'']) }
|
|
76
|
+
function syncIdentity() {
|
|
77
|
+
const ctx=context(),next=JSON.stringify([ctx.endpoint,ctx.headers?.authorization||''])
|
|
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()}
|
|
79
|
+
return ctx
|
|
80
|
+
}
|
|
81
|
+
function render() {
|
|
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
|
+
}
|
|
104
|
+
root.DshSponsor?.mount(sponsor)
|
|
105
|
+
title.textContent=text('云服务器中转','Cloud relay')
|
|
106
|
+
intro.textContent=text('让手机通过公网连接这台主机。每位用户使用自己的中转密钥,首次开通会绑定此主机。','Connect to this host over the internet. Your personal relay key binds to this host when activated.')
|
|
107
|
+
const phase=value?.phase||(readError?'unavailable':loading?'loading':'unconfigured')
|
|
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']}
|
|
109
|
+
badge.textContent=phase==='quota-exceeded'&&value?.daily?.period==='month'?text('本月流量已用完','Monthly quota reached'):text(...(names[phase]||names.error));badge.dataset.phase=phase
|
|
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.')
|
|
111
|
+
let safeUrl=''
|
|
112
|
+
try { const url=new URL(value?.publicUrl);if(url.protocol==='https:'&&!url.username&&!url.password)safeUrl=url.origin } catch {}
|
|
113
|
+
address.hidden=!safeUrl;link.textContent=safeUrl;link.href=safeUrl||'#';copy.textContent=text('复制地址','Copy URL')
|
|
114
|
+
const daily=value?.daily
|
|
115
|
+
plan.hidden=value?.quotaPeriod!=='month'&&daily?.period!=='month'
|
|
116
|
+
plan.textContent=plan.hidden?'':text('基础中转 · 一个服务月 5GB · 单网关绑定 · 支持对话图片,不含文件传输。','Basic relay · 5GB per service month · One gateway · Chat images supported; file transfer excluded.')
|
|
117
|
+
quota.hidden=!daily
|
|
118
|
+
if(daily?.unavailable){usage.textContent=text('无法确认流量额度,云端暂停传输。','Quota unavailable; cloud transfer is paused.');meter.hidden=true;reset.textContent=''}
|
|
119
|
+
else if(daily){
|
|
120
|
+
meter.hidden=false;meter.value=Math.min(100,Math.max(0,Number(daily.usedBytes)/Number(daily.limitBytes)*100))
|
|
121
|
+
const gb=bytes=>(Math.max(0,Number(bytes)||0)/1e9).toFixed(2)
|
|
122
|
+
const monthly=daily.period==='month'
|
|
123
|
+
usage.textContent=text(`${monthly?'本月':'今日'}已用 ${gb(daily.usedBytes)} / ${gb(daily.limitBytes)} GB · 剩余 ${gb(daily.remainingBytes)} GB`,`${monthly?'This month':'Today'} ${gb(daily.usedBytes)} / ${gb(daily.limitBytes)} GB · ${gb(daily.remainingBytes)} GB left`)
|
|
124
|
+
reset.textContent=monthly?text('上传与下载及对话图片合计;额度覆盖本次开通的服务月,不包含文件传输。','Uploads, downloads and chat images share this service month quota; file transfer is excluded.'):text('上传与下载合计;北京时间每天 00:00 重置。','Uploads + downloads; resets daily at 00:00 Beijing time.')
|
|
125
|
+
}
|
|
126
|
+
const expires=value?.expiresAt?new Date(value.expiresAt).toLocaleString():''
|
|
127
|
+
binding.textContent=value?.fingerprint?text(`已绑定此主机 · ${value.fingerprint.slice(0,12)}${expires?' · 有效期至 '+expires:''}`,`Bound to this host · ${value.fingerprint.slice(0,12)}${expires?' · Until '+expires:''}`):''
|
|
128
|
+
keyLabel.firstChild.textContent=text(value?.configured?'更换个人中转密钥':'个人中转密钥',value?.configured?'Replace personal relay key':'Personal relay key')
|
|
129
|
+
keyInput.placeholder='dsrp_…';keyInput.setAttribute('aria-label',keyLabel.firstChild.textContent)
|
|
130
|
+
adminLabel.hidden=value?.canManage!==false
|
|
131
|
+
adminLabel.firstChild.textContent=text('主机管理令牌(仅本次操作)','Host admin token (this operation only)')
|
|
132
|
+
adminInput.setAttribute('aria-label',adminLabel.firstChild.textContent)
|
|
133
|
+
submit.textContent=busy?text('正在处理…','Working…'):text(value?.configured?'绑定新密钥':'绑定并开启',value?.configured?'Bind new key':'Bind and enable')
|
|
134
|
+
submit.disabled=busy||!value;keyInput.disabled=busy;adminInput.disabled=busy
|
|
135
|
+
toggle.hidden=!value?.configured;toggle.disabled=busy;toggle.textContent=text(value?.enabled?'停用中转':'开启中转',value?.enabled?'Disable relay':'Enable relay')
|
|
136
|
+
refresh.textContent=text('刷新状态','Refresh');refresh.disabled=busy||loading
|
|
137
|
+
takeover.hidden=!value?.legacyAvailable;takeover.disabled=busy;takeover.textContent=text('接管已有试用连接','Take over existing trial')
|
|
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.')
|
|
139
|
+
}
|
|
140
|
+
async function load(force=false) {
|
|
141
|
+
const ctx=syncIdentity()
|
|
142
|
+
if(ctx.connected===false){notice.textContent=text('请先连接主机,再查看中转状态。','Connect to your host to read relay status.');return}
|
|
143
|
+
if(busy||loading||!force&&(document.hidden||!target.getClientRects().length||Date.now()-lastRead<Math.min(60000,5000*2**Math.min(failures,4))))return
|
|
144
|
+
loading=true;lastRead=Date.now();const abort=new AbortController();controller=abort
|
|
145
|
+
const timeout=Math.max(15000,root.DshNetwork?.profile().readTimeout||30000)
|
|
146
|
+
const timer=setTimeout(()=>abort.abort(),timeout)
|
|
147
|
+
render()
|
|
148
|
+
try {
|
|
149
|
+
const response=await root.fetch(ctx.endpoint,{headers:ctx.headers,credentials,cache:'no-store',signal:abort.signal})
|
|
150
|
+
let data
|
|
151
|
+
try{data=await response.json()}catch{throw Object.assign(Error('INVALID_RESPONSE'),{code:'INVALID_RESPONSE',status:response.status})}
|
|
152
|
+
if(!current(ctx))return
|
|
153
|
+
if(response.status===429&&data.daily){value={phase:'quota-exceeded',daily:data.daily,configured:false};notice.textContent=data.daily.period==='month'?text('本月额度已用完。请用主机本地地址管理;续期需在当前资格到期后重新申请。','Monthly quota reached. Manage through the local host; apply again after expiry.'):text('今日额度已用完。请用主机本地地址进入设置,或等待零点恢复。','Daily quota reached. Use the local host address or wait until reset.');return}
|
|
154
|
+
if(!response.ok)throw Object.assign(Error(data.error||'HTTP_'+response.status),{code:data.error,status:response.status})
|
|
155
|
+
if(data.supported!==true)throw Object.assign(Error('UNSUPPORTED_GATEWAY'),{code:'UNSUPPORTED_GATEWAY'})
|
|
156
|
+
value=data;notice.textContent='';readError=false;failures=0
|
|
157
|
+
}catch(error){
|
|
158
|
+
if(current(ctx)&&!busy&&controller===abort){
|
|
159
|
+
readError=true;failures++
|
|
160
|
+
notice.textContent=error.status===401?text('访问令牌无效,请在主机与连接中重新连接。','Invalid access token. Reconnect in Hosts and connections.'):error.status===404?text('请将此主机 Remote 升级到 0.8.0-rc.2 或更新版本后使用。','Upgrade this host Remote to 0.8.0-rc.2 or later.'):messages[error.code]?text(...messages[error.code]):abort.signal.aborted?text('读取中转状态超时,请检查网络后刷新。','Relay status timed out. Check the network and refresh.'):text('暂时无法连接主机读取中转状态,可稍后刷新。','Cannot reach the host for relay status. Refresh shortly.')
|
|
161
|
+
}
|
|
162
|
+
}finally{clearTimeout(timer);if(current(ctx)&&controller===abort){loading=false;render()}}
|
|
163
|
+
}
|
|
164
|
+
async function change(action) {
|
|
165
|
+
const ctx=syncIdentity();if(busy)return
|
|
166
|
+
const key=keyInput.value.trim(),admin=adminInput.value.trim()
|
|
167
|
+
if(action==='enroll'&&!/^dsrp_[a-f0-9]{16}\.[A-Za-z0-9_-]{43}$/.test(key)){notice.textContent=text('请填写完整的个人中转密钥。','Enter the complete personal relay key.');return}
|
|
168
|
+
busy=true;controller?.abort();loading=false;notice.textContent='';render()
|
|
169
|
+
const abort=new AbortController();controller=abort;const timer=setTimeout(()=>abort.abort(),20000)
|
|
170
|
+
// Clear immediately, including ambiguous network outcomes. Never store the key.
|
|
171
|
+
keyInput.value='';adminInput.value=''
|
|
172
|
+
try {
|
|
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})
|
|
174
|
+
const data=await response.json();if(!current(ctx))return
|
|
175
|
+
if(!response.ok)throw Object.assign(Error(data.error),{code:data.error})
|
|
176
|
+
value={...data,canManageDevices:value?.canManageDevices};notice.textContent=text(action==='disable'?'中转已停用。':'设置已保存,正在确认云端连接。',action==='disable'?'Relay disabled.':'Saved. Confirming the cloud connection.')
|
|
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.')}
|
|
178
|
+
finally{clearTimeout(timer);if(current(ctx)){busy=false;lastRead=0;render()}}
|
|
179
|
+
}
|
|
180
|
+
form.addEventListener('submit',event=>{event.preventDefault();void change('enroll')})
|
|
181
|
+
toggle.addEventListener('click',()=>void change(value?.enabled?'disable':'enable'))
|
|
182
|
+
takeover.addEventListener('click',()=>void change('import'))
|
|
183
|
+
refresh.addEventListener('click',()=>void load(true))
|
|
184
|
+
copy.addEventListener('click',async()=>{
|
|
185
|
+
const ctx=syncIdentity(),url=link.href
|
|
186
|
+
try{await root.navigator.clipboard.writeText(url);if(current(ctx))notice.textContent=text('地址已复制。','URL copied.')}
|
|
187
|
+
catch{if(current(ctx))notice.textContent=text('请选中上方地址复制。','Select the URL above to copy it.')}
|
|
188
|
+
})
|
|
189
|
+
function tick(){if(destroyed)return;syncIdentity();render();void load()}
|
|
190
|
+
const timer=setInterval(tick,1000);tick()
|
|
191
|
+
return { refresh:()=>load(true),destroy:()=>{destroyed=true;clearInterval(timer);controller?.abort();closeCode();devices?.destroy();keyInput.value='';adminInput.value=''} }
|
|
192
|
+
}
|
|
193
|
+
root.DshRelaySettings={mount}
|
|
194
|
+
})(typeof window!=='undefined'?window:globalThis)
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/* Shared presentation model. Missing evidence is unknown, never healthy or zero. */
|
|
2
|
+
'use strict'
|
|
3
|
+
;(function (root) {
|
|
4
|
+
function derive(state) {
|
|
5
|
+
const st = state || {}
|
|
6
|
+
const gateway = st.mode === 'gateway'
|
|
7
|
+
const processRunning = gateway || st.gatewayRunning === true
|
|
8
|
+
const authenticated = gateway && !st.gatewayAuthError
|
|
9
|
+
const upstream = st.upstream?.reachable === true ? 'ok' : st.upstream?.reachable === false ? 'error' : 'unknown'
|
|
10
|
+
const events = st.events || {}
|
|
11
|
+
const realtime = events.mux?.connected === true && events.host?.connected === true ? 'ok'
|
|
12
|
+
: events.mux?.connected === false || events.host?.connected === false ? 'warning' : 'unknown'
|
|
13
|
+
const connections = Array.isArray(st.devices) ? st.devices.filter(d => d && (d.kind === 'app' || d.kind === 'web')) : null
|
|
14
|
+
const online = connections ? connections.filter(d => d.online === true) : null
|
|
15
|
+
const phase = !state ? 'unknown' : st.gatewayAuthError ? 'auth' : !processRunning ? 'stopped'
|
|
16
|
+
: !authenticated ? 'attention' : upstream === 'error' ? 'upstream' : upstream === 'unknown' ? 'unknown'
|
|
17
|
+
: realtime === 'warning' ? 'partial' : realtime === 'unknown' ? 'unknown' : 'ready'
|
|
18
|
+
return {
|
|
19
|
+
phase, upstream, realtime, processRunning, authenticated,
|
|
20
|
+
gateway: authenticated ? 'ok' : processRunning ? 'warning' : state ? 'error' : 'unknown',
|
|
21
|
+
connections, online, onlineCount: online ? online.length : null,
|
|
22
|
+
history: !!(connections?.length || st.deviceKeys?.entries?.length),
|
|
23
|
+
canStart: !!state && !processRunning && st.gatewayInstalled !== false,
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
root.DshRemoteState = { derive }
|
|
27
|
+
})(globalThis)
|