dsh-plugin-weapp-gateway 0.8.23 → 0.8.34
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/LICENSE +21 -21
- package/PROTOCOL.md +1545 -1486
- package/README.md +503 -464
- package/THIRD-PARTY-NOTICES/dsh-cost-meter.txt +31 -31
- package/bin/setup-ip.mjs +474 -474
- package/cordis.patch.yml +50 -50
- package/docs/agent-team-app-integration.md +945 -0
- package/docs/blog-mobile-gateway.md +542 -542
- package/docs/dsh-0.1.5-rc.2-compatibility-audit.md +255 -255
- package/docs/dsh-0.1.6-alpha.1-compatibility-audit.md +122 -122
- package/docs/dsh-0.1.7-rc.1-compatibility-audit.md +52 -52
- package/docs/dsh-0.2.0-rc.2-plugin-management-mobile-integration.md +109 -109
- package/docs/dsh-rc2-mobile-integration.md +155 -155
- package/docs/file-upload-app-integration.md +250 -0
- package/docs/multi-gateway-app-integration.md +141 -125
- package/docs/multi-gateway-phase1-acceptance.md +179 -179
- package/docs/multi-gateway-todo.md +137 -137
- package/docs/remote-gateway-refactor-plan.md +52 -52
- package/docs/runtime-architecture.architecture.json +264 -264
- package/docs/runtime-architecture.html +15001 -15001
- package/docs/runtime-architecture.visual-check.html +32 -32
- package/docs/runtime-architecture.visual-check.json +548 -548
- package/docs/session-agent-preset-app-integration.md +93 -93
- package/docs/turn-outline-app-integration.md +196 -0
- package/docs/typert-remote-gateway-feature-checklist.md +294 -294
- package/docs/voice-input-implementation.md +219 -219
- package/docs/workspace-changes-mobile-integration.md +32 -32
- package/helper/dsh_mobile_gateway_helper.py +227 -227
- package/lib/account-bridge.mjs +57 -57
- package/lib/client.js +1409 -1361
- package/lib/cloudflare-tunnel.mjs +314 -314
- package/lib/cloudflared-binary.mjs +135 -135
- package/lib/context-bridge.mjs +3338 -1715
- package/lib/cost-meter-bridge.mjs +794 -794
- package/lib/cost-meter-dashboard-bridge.mjs +1655 -1449
- package/lib/devices.js +273 -245
- package/lib/dsh-host-adapter.mjs +508 -426
- package/lib/file-upload.mjs +205 -0
- package/lib/gateway-probe.mjs +6 -6
- package/lib/gateway-state.mjs +57 -57
- package/lib/gateway-tools.mjs +36 -36
- package/lib/history-cache.mjs +66 -0
- package/lib/index.mjs +4390 -3803
- package/lib/plugin-management.mjs +251 -233
- package/lib/public-endpoint-check.mjs +61 -61
- package/lib/relay-connector.mjs +213 -181
- package/lib/relay-state.mjs +83 -76
- package/lib/session-follower.mjs +140 -136
- package/lib/session-resume-bridge.mjs +86 -0
- package/lib/session-target.mjs +29 -0
- package/lib/speech-input.mjs +192 -192
- package/lib/vendor/cost-meter/aliyun-balance.mjs +123 -123
- package/lib/vendor/cost-meter/coding-plans.mjs +1668 -1668
- package/lib/vendor/cost-meter/credentials-shim.mjs +8 -8
- package/lib/vendor/cost-meter/custom-balance.mjs +281 -281
- package/lib/vendor/cost-meter/factory-quota.mjs +69 -69
- package/lib/vendor/cost-meter/gateway-quota-adapters.mjs +1006 -1006
- package/lib/vendor/cost-meter/gateway-quotas.mjs +664 -664
- package/lib/vendor/cost-meter/home-paths-shim.mjs +13 -13
- package/lib/vendor/cost-meter/net.mjs +183 -183
- package/lib/vendor/cost-meter/opendesign.mjs +204 -204
- package/lib/vendor/cost-meter/tokenrhythm-balance.mjs +95 -95
- package/lib/vendor/cost-meter/workbuddy-accounts.mjs +44 -44
- package/lib/vendor/cost-meter/workbuddy-transport.mjs +38 -38
- package/lib/vendor/cost-meter/workbuddy.mjs +356 -356
- package/lib/web-restart.mjs +47 -47
- package/lib/wire-json.mjs +7 -7
- package/lib/workspace-changes-bridge.mjs +32 -32
- package/package.json +54 -54
- package/relay/agent-connector.js +588 -569
- package/relay/vendor/tweetnacl.js +2391 -2391
|
@@ -1,61 +1,61 @@
|
|
|
1
|
-
import dns from 'node:dns/promises'
|
|
2
|
-
import https from 'node:https'
|
|
3
|
-
import crypto from 'node:crypto'
|
|
4
|
-
|
|
5
|
-
// No credentials, redirects or certificate exceptions. A 401 alone is ambiguous:
|
|
6
|
-
// require the gateway to echo our random probe nonce in its auth rejection.
|
|
7
|
-
export async function checkPublicEndpoint(endpoint, { timeoutMs = 8000, lookup = dns.lookup, request = https.request } = {}) {
|
|
8
|
-
const checkedAt = new Date().toISOString()
|
|
9
|
-
const result = (state, message, extra = {}) => ({ state, message, checkedAt, ...extra })
|
|
10
|
-
let url
|
|
11
|
-
try {
|
|
12
|
-
url = new URL(endpoint)
|
|
13
|
-
if (url.protocol !== 'wss:' || url.username || url.password || url.search || url.hash) throw new Error()
|
|
14
|
-
} catch { return result('invalid-url', '公网入口必须是无凭证的 wss:// 地址。') }
|
|
15
|
-
let timer
|
|
16
|
-
try {
|
|
17
|
-
await Promise.race([
|
|
18
|
-
lookup(url.hostname),
|
|
19
|
-
new Promise((_, reject) => { timer = setTimeout(() => reject(Object.assign(new Error(), { code: 'ETIMEDOUT' })), timeoutMs) }),
|
|
20
|
-
])
|
|
21
|
-
} catch (error) {
|
|
22
|
-
return result('dns-error', ['ENOTFOUND', 'ENODATA'].includes(error.code)
|
|
23
|
-
? '本机无法解析公网域名,不代表公共 DNS 记录一定不存在。请核对域名、DNS 缓存、网络代理及 Cloudflare 已代理的 CNAME 记录;若刚保存配置,请稍后重试。'
|
|
24
|
-
: 'DNS 查询失败或超时,请检查本机网络和 DNS 后重试。', { code: error.code || 'DNS_ERROR' })
|
|
25
|
-
} finally { clearTimeout(timer) }
|
|
26
|
-
return new Promise((resolve) => {
|
|
27
|
-
let done = false
|
|
28
|
-
let deadline
|
|
29
|
-
const finish = (value) => {
|
|
30
|
-
if (done) return
|
|
31
|
-
done = true
|
|
32
|
-
clearTimeout(deadline)
|
|
33
|
-
resolve(value)
|
|
34
|
-
}
|
|
35
|
-
let req
|
|
36
|
-
try {
|
|
37
|
-
const key = crypto.randomBytes(16).toString('base64')
|
|
38
|
-
const nonce = crypto.randomBytes(16).toString('hex')
|
|
39
|
-
req = request({ hostname: url.hostname, port: url.port || 443, path: url.pathname || '/', method: 'GET', rejectUnauthorized: true,
|
|
40
|
-
headers: { Upgrade: 'websocket', Connection: 'Upgrade', 'Sec-WebSocket-Key': key, 'Sec-WebSocket-Version': '13', 'Sec-WebSocket-Protocol': 'dsh-mobile-v1', 'X-DSH-Gateway-Probe': nonce } })
|
|
41
|
-
deadline = setTimeout(() => { finish(result('network-error', '公网 TLS/WebSocket 检测超时;请检查网络、代理和 Cloudflare 源站配置。', { code: 'ETIMEDOUT' })); req.destroy() }, timeoutMs)
|
|
42
|
-
req.on('response', (res) => {
|
|
43
|
-
const status = res.statusCode
|
|
44
|
-
finish(status === 401 && res.headers['x-dsh-gateway-probe'] === nonce ? result('reachable', '本机检测:TLS 校验通过,移动网关路由已确认且要求鉴权;不代表手机网络可达或会话同步成功。', { httpStatus: status })
|
|
45
|
-
: result('route-error', `公网返回 HTTP ${status},未确认移动网关路由。命名 Tunnel 的 Service 应为 HTTP,指向本机专用源站端口;同时检查 Cloudflare Access/安全规则。`, { httpStatus: status }))
|
|
46
|
-
res.destroy()
|
|
47
|
-
})
|
|
48
|
-
req.on('upgrade', (res, socket) => {
|
|
49
|
-
finish(result('auth-warning', '公网 WebSocket 未提供凭证即被接受,请检查设备鉴权设置。', { httpStatus: res.statusCode }))
|
|
50
|
-
socket.destroy()
|
|
51
|
-
})
|
|
52
|
-
req.on('error', (error) => {
|
|
53
|
-
const tlsError = /CERT|TLS|SSL|SELF_SIGNED|UNABLE_TO_VERIFY/.test(error.code || '')
|
|
54
|
-
finish(result(tlsError ? 'tls-error' : 'network-error', tlsError
|
|
55
|
-
? '公网 TLS 握手或证书校验失败;请检查域名证书、系统时间及网络代理,不要关闭证书校验。'
|
|
56
|
-
: '公网连接失败;请检查 DNS、网络、代理及隧道源站配置。', { code: error.code || 'CONNECT_ERROR' }))
|
|
57
|
-
})
|
|
58
|
-
req.end()
|
|
59
|
-
} catch { finish(result('network-error', '无法发起公网检测。')); req?.destroy() }
|
|
60
|
-
})
|
|
61
|
-
}
|
|
1
|
+
import dns from 'node:dns/promises'
|
|
2
|
+
import https from 'node:https'
|
|
3
|
+
import crypto from 'node:crypto'
|
|
4
|
+
|
|
5
|
+
// No credentials, redirects or certificate exceptions. A 401 alone is ambiguous:
|
|
6
|
+
// require the gateway to echo our random probe nonce in its auth rejection.
|
|
7
|
+
export async function checkPublicEndpoint(endpoint, { timeoutMs = 8000, lookup = dns.lookup, request = https.request } = {}) {
|
|
8
|
+
const checkedAt = new Date().toISOString()
|
|
9
|
+
const result = (state, message, extra = {}) => ({ state, message, checkedAt, ...extra })
|
|
10
|
+
let url
|
|
11
|
+
try {
|
|
12
|
+
url = new URL(endpoint)
|
|
13
|
+
if (url.protocol !== 'wss:' || url.username || url.password || url.search || url.hash) throw new Error()
|
|
14
|
+
} catch { return result('invalid-url', '公网入口必须是无凭证的 wss:// 地址。') }
|
|
15
|
+
let timer
|
|
16
|
+
try {
|
|
17
|
+
await Promise.race([
|
|
18
|
+
lookup(url.hostname),
|
|
19
|
+
new Promise((_, reject) => { timer = setTimeout(() => reject(Object.assign(new Error(), { code: 'ETIMEDOUT' })), timeoutMs) }),
|
|
20
|
+
])
|
|
21
|
+
} catch (error) {
|
|
22
|
+
return result('dns-error', ['ENOTFOUND', 'ENODATA'].includes(error.code)
|
|
23
|
+
? '本机无法解析公网域名,不代表公共 DNS 记录一定不存在。请核对域名、DNS 缓存、网络代理及 Cloudflare 已代理的 CNAME 记录;若刚保存配置,请稍后重试。'
|
|
24
|
+
: 'DNS 查询失败或超时,请检查本机网络和 DNS 后重试。', { code: error.code || 'DNS_ERROR' })
|
|
25
|
+
} finally { clearTimeout(timer) }
|
|
26
|
+
return new Promise((resolve) => {
|
|
27
|
+
let done = false
|
|
28
|
+
let deadline
|
|
29
|
+
const finish = (value) => {
|
|
30
|
+
if (done) return
|
|
31
|
+
done = true
|
|
32
|
+
clearTimeout(deadline)
|
|
33
|
+
resolve(value)
|
|
34
|
+
}
|
|
35
|
+
let req
|
|
36
|
+
try {
|
|
37
|
+
const key = crypto.randomBytes(16).toString('base64')
|
|
38
|
+
const nonce = crypto.randomBytes(16).toString('hex')
|
|
39
|
+
req = request({ hostname: url.hostname, port: url.port || 443, path: url.pathname || '/', method: 'GET', rejectUnauthorized: true,
|
|
40
|
+
headers: { Upgrade: 'websocket', Connection: 'Upgrade', 'Sec-WebSocket-Key': key, 'Sec-WebSocket-Version': '13', 'Sec-WebSocket-Protocol': 'dsh-mobile-v1', 'X-DSH-Gateway-Probe': nonce } })
|
|
41
|
+
deadline = setTimeout(() => { finish(result('network-error', '公网 TLS/WebSocket 检测超时;请检查网络、代理和 Cloudflare 源站配置。', { code: 'ETIMEDOUT' })); req.destroy() }, timeoutMs)
|
|
42
|
+
req.on('response', (res) => {
|
|
43
|
+
const status = res.statusCode
|
|
44
|
+
finish(status === 401 && res.headers['x-dsh-gateway-probe'] === nonce ? result('reachable', '本机检测:TLS 校验通过,移动网关路由已确认且要求鉴权;不代表手机网络可达或会话同步成功。', { httpStatus: status })
|
|
45
|
+
: result('route-error', `公网返回 HTTP ${status},未确认移动网关路由。命名 Tunnel 的 Service 应为 HTTP,指向本机专用源站端口;同时检查 Cloudflare Access/安全规则。`, { httpStatus: status }))
|
|
46
|
+
res.destroy()
|
|
47
|
+
})
|
|
48
|
+
req.on('upgrade', (res, socket) => {
|
|
49
|
+
finish(result('auth-warning', '公网 WebSocket 未提供凭证即被接受,请检查设备鉴权设置。', { httpStatus: res.statusCode }))
|
|
50
|
+
socket.destroy()
|
|
51
|
+
})
|
|
52
|
+
req.on('error', (error) => {
|
|
53
|
+
const tlsError = /CERT|TLS|SSL|SELF_SIGNED|UNABLE_TO_VERIFY/.test(error.code || '')
|
|
54
|
+
finish(result(tlsError ? 'tls-error' : 'network-error', tlsError
|
|
55
|
+
? '公网 TLS 握手或证书校验失败;请检查域名证书、系统时间及网络代理,不要关闭证书校验。'
|
|
56
|
+
: '公网连接失败;请检查 DNS、网络、代理及隧道源站配置。', { code: error.code || 'CONNECT_ERROR' }))
|
|
57
|
+
})
|
|
58
|
+
req.end()
|
|
59
|
+
} catch { finish(result('network-error', '无法发起公网检测。')); req?.destroy() }
|
|
60
|
+
})
|
|
61
|
+
}
|
package/lib/relay-connector.mjs
CHANGED
|
@@ -1,181 +1,213 @@
|
|
|
1
|
-
// Supervisor for the bundled relay connector (relay/agent-connector.js).
|
|
2
|
-
//
|
|
3
|
-
// Relay mode needs a local bridge: an outbound WebSocket to the VPS relay that
|
|
4
|
-
// registers this gateway's identity with the plugin and pipes mini-program
|
|
5
|
-
// traffic to the local mobile endpoint. Historically that bridge was a manual
|
|
6
|
-
// deployment (copy files, npm install, systemd unit), and a missed
|
|
7
|
-
// registration — e.g. the plugin restarting while the connector dialled — left
|
|
8
|
-
// the pairing QR dead with a healthy-looking process.
|
|
9
|
-
//
|
|
10
|
-
// This module closes that gap: when relay mode is on and nothing has
|
|
11
|
-
// registered, the plugin starts its own bundled copy. The copy takes a pid
|
|
12
|
-
// lock on the identity directory, so an already-installed connector (systemd)
|
|
13
|
-
// keeps ownership and the spawned one exits immediately. When an external
|
|
14
|
-
// connector is registered the supervisor stays idle, and the operator's
|
|
15
|
-
// existing deployment is untouched.
|
|
16
|
-
import { spawn } from 'node:child_process'
|
|
17
|
-
import fs from 'node:fs'
|
|
18
|
-
import os from 'node:os'
|
|
19
|
-
import path from 'node:path'
|
|
20
|
-
import { fileURLToPath } from 'node:url'
|
|
21
|
-
|
|
22
|
-
const CONNECTOR_SCRIPT = fileURLToPath(new URL('../relay/agent-connector.js', import.meta.url))
|
|
23
|
-
const MAX_RAPID_RESTARTS = 5
|
|
24
|
-
|
|
25
|
-
function commandExists(file) {
|
|
26
|
-
if (path.isAbsolute(file)) return fs.existsSync(file)
|
|
27
|
-
return (process.env.PATH || '').split(path.delimiter).some((dir) => fs.existsSync(path.join(dir, file)))
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
// Prefer an identity that already exists so a spawned copy keeps the nodeId the
|
|
31
|
-
// relay and paired mini-program know. Candidates, in order: the plugin's own
|
|
32
|
-
// home, then the root home used by the documented systemd install.
|
|
33
|
-
export function resolveStateDir(env = process.env, home = os.homedir(), legacyHome = '/root') {
|
|
34
|
-
if (env.STATE_DIR) return env.STATE_DIR
|
|
35
|
-
const candidates = [path.join(home, '.dsh-weapp-relay')]
|
|
36
|
-
if (legacyHome && path.resolve(legacyHome) !== path.resolve(home)) {
|
|
37
|
-
candidates.push(path.join(legacyHome, '.dsh-weapp-relay'))
|
|
38
|
-
}
|
|
39
|
-
for (const candidate of candidates) {
|
|
40
|
-
try {
|
|
41
|
-
if (fs.statSync(path.join(candidate, 'identity.json')).isFile()) return candidate
|
|
42
|
-
} catch { /* no identity here */ }
|
|
43
|
-
}
|
|
44
|
-
return candidates[0]
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
export function createRelayConnector({ relay, gatewayUrl, gatewayName, mgmtUrl,
|
|
48
|
-
stateDir = resolveStateDir(), log = () => {}, spawnProcess = spawn, now = () => Date.now(),
|
|
49
|
-
restartDelayMs = 5_000 } = {}) {
|
|
50
|
-
// Whale public service is configured internally, not a user-facing domain.
|
|
51
|
-
const configuredRelay = String(relay || '').replace(/[/]$/, '')
|
|
52
|
-
relay = ['', 'wss://relay.ahwe.top', 'wss://relay.ahwe.top/relay'].includes(configuredRelay)
|
|
53
|
-
? 'wss://dsh.ahwe.top/relay' : configuredRelay
|
|
54
|
-
let child = null
|
|
55
|
-
let restartTimer = null
|
|
56
|
-
let
|
|
57
|
-
let
|
|
58
|
-
let
|
|
59
|
-
let
|
|
60
|
-
let
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
restartTimer
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
if (
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
}
|
|
1
|
+
// Supervisor for the bundled relay connector (relay/agent-connector.js).
|
|
2
|
+
//
|
|
3
|
+
// Relay mode needs a local bridge: an outbound WebSocket to the VPS relay that
|
|
4
|
+
// registers this gateway's identity with the plugin and pipes mini-program
|
|
5
|
+
// traffic to the local mobile endpoint. Historically that bridge was a manual
|
|
6
|
+
// deployment (copy files, npm install, systemd unit), and a missed
|
|
7
|
+
// registration — e.g. the plugin restarting while the connector dialled — left
|
|
8
|
+
// the pairing QR dead with a healthy-looking process.
|
|
9
|
+
//
|
|
10
|
+
// This module closes that gap: when relay mode is on and nothing has
|
|
11
|
+
// registered, the plugin starts its own bundled copy. The copy takes a pid
|
|
12
|
+
// lock on the identity directory, so an already-installed connector (systemd)
|
|
13
|
+
// keeps ownership and the spawned one exits immediately. When an external
|
|
14
|
+
// connector is registered the supervisor stays idle, and the operator's
|
|
15
|
+
// existing deployment is untouched.
|
|
16
|
+
import { spawn } from 'node:child_process'
|
|
17
|
+
import fs from 'node:fs'
|
|
18
|
+
import os from 'node:os'
|
|
19
|
+
import path from 'node:path'
|
|
20
|
+
import { fileURLToPath } from 'node:url'
|
|
21
|
+
|
|
22
|
+
const CONNECTOR_SCRIPT = fileURLToPath(new URL('../relay/agent-connector.js', import.meta.url))
|
|
23
|
+
const MAX_RAPID_RESTARTS = 5
|
|
24
|
+
|
|
25
|
+
function commandExists(file) {
|
|
26
|
+
if (path.isAbsolute(file)) return fs.existsSync(file)
|
|
27
|
+
return (process.env.PATH || '').split(path.delimiter).some((dir) => fs.existsSync(path.join(dir, file)))
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// Prefer an identity that already exists so a spawned copy keeps the nodeId the
|
|
31
|
+
// relay and paired mini-program know. Candidates, in order: the plugin's own
|
|
32
|
+
// home, then the root home used by the documented systemd install.
|
|
33
|
+
export function resolveStateDir(env = process.env, home = os.homedir(), legacyHome = '/root') {
|
|
34
|
+
if (env.STATE_DIR) return env.STATE_DIR
|
|
35
|
+
const candidates = [path.join(home, '.dsh-weapp-relay')]
|
|
36
|
+
if (legacyHome && path.resolve(legacyHome) !== path.resolve(home)) {
|
|
37
|
+
candidates.push(path.join(legacyHome, '.dsh-weapp-relay'))
|
|
38
|
+
}
|
|
39
|
+
for (const candidate of candidates) {
|
|
40
|
+
try {
|
|
41
|
+
if (fs.statSync(path.join(candidate, 'identity.json')).isFile()) return candidate
|
|
42
|
+
} catch { /* no identity here */ }
|
|
43
|
+
}
|
|
44
|
+
return candidates[0]
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function createRelayConnector({ relay, gatewayUrl, gatewayName, mgmtUrl,
|
|
48
|
+
stateDir = resolveStateDir(), log = () => {}, spawnProcess = spawn, now = () => Date.now(),
|
|
49
|
+
restartDelayMs = 5_000, delegationRecheckMs = 15_000 } = {}) {
|
|
50
|
+
// Whale public service is configured internally, not a user-facing domain.
|
|
51
|
+
const configuredRelay = String(relay || '').replace(/[/]$/, '')
|
|
52
|
+
relay = ['', 'wss://relay.ahwe.top', 'wss://relay.ahwe.top/relay'].includes(configuredRelay)
|
|
53
|
+
? 'wss://dsh.ahwe.top/relay' : configuredRelay
|
|
54
|
+
let child = null
|
|
55
|
+
let restartTimer = null
|
|
56
|
+
let delegationTimer = null
|
|
57
|
+
let stopped = false
|
|
58
|
+
let restarts = 0
|
|
59
|
+
let windowStart = now()
|
|
60
|
+
let lastError = null
|
|
61
|
+
let delegatedTo = null
|
|
62
|
+
|
|
63
|
+
const snapshot = () => ({
|
|
64
|
+
running: child !== null && child.exitCode === null && child.signalCode === null,
|
|
65
|
+
pid: child === null ? null : child.pid,
|
|
66
|
+
stateDir,
|
|
67
|
+
relay: relay || null,
|
|
68
|
+
lastError,
|
|
69
|
+
delegatedTo,
|
|
70
|
+
})
|
|
71
|
+
|
|
72
|
+
const clearTimer = () => {
|
|
73
|
+
if (restartTimer === null) return
|
|
74
|
+
clearTimeout(restartTimer)
|
|
75
|
+
restartTimer = null
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const clearDelegationTimer = () => {
|
|
79
|
+
if (delegationTimer === null) return
|
|
80
|
+
clearTimeout(delegationTimer)
|
|
81
|
+
delegationTimer = null
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// A holder can disappear after we deferred to it (a zombie from an
|
|
85
|
+
// unclean DSH exit that only now noticed, or an operator connector that
|
|
86
|
+
// died). Without a re-check the delegation would be permanent: relay-
|
|
87
|
+
// routed phones would keep failing against a bridge that dials a dead
|
|
88
|
+
// port, and no restart would help because the next one defers again.
|
|
89
|
+
const scheduleDelegationRecheck = () => {
|
|
90
|
+
if (delegationTimer !== null || stopped) return
|
|
91
|
+
delegationTimer = setTimeout(() => {
|
|
92
|
+
delegationTimer = null
|
|
93
|
+
if (stopped || child !== null) return
|
|
94
|
+
start()
|
|
95
|
+
}, delegationRecheckMs)
|
|
96
|
+
delegationTimer.unref?.()
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const stop = () => {
|
|
100
|
+
stopped = true
|
|
101
|
+
clearTimer()
|
|
102
|
+
clearDelegationTimer()
|
|
103
|
+
const previous = child
|
|
104
|
+
child = null
|
|
105
|
+
if (previous === null || previous.exitCode !== null || previous.signalCode !== null) return
|
|
106
|
+
previous.kill('SIGTERM')
|
|
107
|
+
// The connector exits on SIGTERM; do not wait forever if it is wedged.
|
|
108
|
+
const killTimer = setTimeout(() => {
|
|
109
|
+
if (previous.exitCode === null && previous.signalCode === null) previous.kill('SIGKILL')
|
|
110
|
+
}, 3_000)
|
|
111
|
+
killTimer.unref?.()
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// A live pid in the lock file means somebody else already owns this identity
|
|
115
|
+
// (the documented systemd install). Spawning would just exit, so report the
|
|
116
|
+
// delegation instead — and, crucially, do not treat a stale registration as
|
|
117
|
+
// proof that a bridge is alive: our own child dies with the plugin.
|
|
118
|
+
const lockHolder = () => {
|
|
119
|
+
try {
|
|
120
|
+
const held = JSON.parse(fs.readFileSync(path.join(stateDir, 'connector.lock'), 'utf8'))
|
|
121
|
+
if (!Number.isInteger(held.pid) || held.pid === process.pid) return null
|
|
122
|
+
try { process.kill(held.pid, 0); return held.pid } catch (error) { if (error.code !== 'ESRCH') return held.pid }
|
|
123
|
+
return null
|
|
124
|
+
} catch { return null }
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const start = ({ force = false } = {}) => {
|
|
128
|
+
if (child !== null && child.exitCode === null && child.signalCode === null) return snapshot()
|
|
129
|
+
if (!force) {
|
|
130
|
+
const holder = lockHolder()
|
|
131
|
+
if (holder !== null) {
|
|
132
|
+
delegatedTo = holder
|
|
133
|
+
lastError = null
|
|
134
|
+
scheduleDelegationRecheck()
|
|
135
|
+
return snapshot()
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
if (!relay) {
|
|
139
|
+
lastError = '未配置中继地址(relayUrl),无法启动内置连接器'
|
|
140
|
+
return snapshot()
|
|
141
|
+
}
|
|
142
|
+
if (!force && !commandExists(process.execPath)) {
|
|
143
|
+
lastError = `node 可执行文件不可用:${process.execPath}`
|
|
144
|
+
return snapshot()
|
|
145
|
+
}
|
|
146
|
+
stopped = false
|
|
147
|
+
lastError = null
|
|
148
|
+
let spawned
|
|
149
|
+
try {
|
|
150
|
+
spawned = spawnProcess(process.execPath, [CONNECTOR_SCRIPT], {
|
|
151
|
+
env: {
|
|
152
|
+
...process.env,
|
|
153
|
+
// Desktop runs under Electron; child scripts must execute as Node.
|
|
154
|
+
...(process.versions.electron ? { ELECTRON_RUN_AS_NODE: '1' } : {}),
|
|
155
|
+
// The bundled connector must not outlive the DSH process that
|
|
156
|
+
// spawned it: after a crash or force-quit a survivor would keep
|
|
157
|
+
// the pid lock and keep dialling the dead web port, so every
|
|
158
|
+
// later restart would delegate to it and relay-routed phones
|
|
159
|
+
// could never reconnect. Manually run connectors
|
|
160
|
+
// (systemd/nohup) never receive this variable.
|
|
161
|
+
PARENT_PID: String(process.pid),
|
|
162
|
+
RELAY_URL: relay,
|
|
163
|
+
GATEWAY_URL: gatewayUrl,
|
|
164
|
+
GATEWAY_NAME: gatewayName || '',
|
|
165
|
+
MGMT_URL: mgmtUrl,
|
|
166
|
+
STATE_DIR: stateDir,
|
|
167
|
+
},
|
|
168
|
+
stdio: ['ignore', 'ignore', 'ignore'],
|
|
169
|
+
windowsHide: true,
|
|
170
|
+
})
|
|
171
|
+
} catch (error) {
|
|
172
|
+
lastError = `启动内置连接器失败:${error.message}`
|
|
173
|
+
return snapshot()
|
|
174
|
+
}
|
|
175
|
+
child = spawned
|
|
176
|
+
delegatedTo = null
|
|
177
|
+
clearDelegationTimer()
|
|
178
|
+
log(`bundled connector starting: pid=${spawned.pid} relay=${relay} state=${stateDir}`)
|
|
179
|
+
spawned.on('error', (error) => {
|
|
180
|
+
if (child !== spawned) return
|
|
181
|
+
lastError = `内置连接器启动失败:${error.message}`
|
|
182
|
+
log(lastError)
|
|
183
|
+
})
|
|
184
|
+
spawned.on('exit', (code, signal) => {
|
|
185
|
+
if (child !== spawned) return
|
|
186
|
+
child = null
|
|
187
|
+
// Exit 0 with the pid lock held elsewhere is the expected "an installed
|
|
188
|
+
// connector already owns this identity" path — not a failure.
|
|
189
|
+
if (code === 0) {
|
|
190
|
+
log('bundled connector exited; an installed connector likely owns the identity')
|
|
191
|
+
return
|
|
192
|
+
}
|
|
193
|
+
lastError = `内置连接器退出(${signal || code})`
|
|
194
|
+
log(lastError)
|
|
195
|
+
if (stopped) return
|
|
196
|
+
const at = now()
|
|
197
|
+
if (at - windowStart > 60_000) { restarts = 0; windowStart = at }
|
|
198
|
+
restarts += 1
|
|
199
|
+
if (restarts > MAX_RAPID_RESTARTS) {
|
|
200
|
+
lastError = '内置连接器反复退出,已停止自动重启'
|
|
201
|
+
log(lastError)
|
|
202
|
+
return
|
|
203
|
+
}
|
|
204
|
+
restartTimer = setTimeout(() => { restartTimer = null; start() }, restartDelayMs)
|
|
205
|
+
restartTimer.unref?.()
|
|
206
|
+
})
|
|
207
|
+
return snapshot()
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
const dispose = () => { stop() }
|
|
211
|
+
|
|
212
|
+
return { start, stop, snapshot, dispose }
|
|
213
|
+
}
|