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.
Files changed (71) hide show
  1. package/LICENSE +21 -21
  2. package/PROTOCOL.md +1545 -1486
  3. package/README.md +503 -464
  4. package/THIRD-PARTY-NOTICES/dsh-cost-meter.txt +31 -31
  5. package/bin/setup-ip.mjs +474 -474
  6. package/cordis.patch.yml +50 -50
  7. package/docs/agent-team-app-integration.md +945 -0
  8. package/docs/blog-mobile-gateway.md +542 -542
  9. package/docs/dsh-0.1.5-rc.2-compatibility-audit.md +255 -255
  10. package/docs/dsh-0.1.6-alpha.1-compatibility-audit.md +122 -122
  11. package/docs/dsh-0.1.7-rc.1-compatibility-audit.md +52 -52
  12. package/docs/dsh-0.2.0-rc.2-plugin-management-mobile-integration.md +109 -109
  13. package/docs/dsh-rc2-mobile-integration.md +155 -155
  14. package/docs/file-upload-app-integration.md +250 -0
  15. package/docs/multi-gateway-app-integration.md +141 -125
  16. package/docs/multi-gateway-phase1-acceptance.md +179 -179
  17. package/docs/multi-gateway-todo.md +137 -137
  18. package/docs/remote-gateway-refactor-plan.md +52 -52
  19. package/docs/runtime-architecture.architecture.json +264 -264
  20. package/docs/runtime-architecture.html +15001 -15001
  21. package/docs/runtime-architecture.visual-check.html +32 -32
  22. package/docs/runtime-architecture.visual-check.json +548 -548
  23. package/docs/session-agent-preset-app-integration.md +93 -93
  24. package/docs/turn-outline-app-integration.md +196 -0
  25. package/docs/typert-remote-gateway-feature-checklist.md +294 -294
  26. package/docs/voice-input-implementation.md +219 -219
  27. package/docs/workspace-changes-mobile-integration.md +32 -32
  28. package/helper/dsh_mobile_gateway_helper.py +227 -227
  29. package/lib/account-bridge.mjs +57 -57
  30. package/lib/client.js +1409 -1361
  31. package/lib/cloudflare-tunnel.mjs +314 -314
  32. package/lib/cloudflared-binary.mjs +135 -135
  33. package/lib/context-bridge.mjs +3338 -1715
  34. package/lib/cost-meter-bridge.mjs +794 -794
  35. package/lib/cost-meter-dashboard-bridge.mjs +1655 -1449
  36. package/lib/devices.js +273 -245
  37. package/lib/dsh-host-adapter.mjs +508 -426
  38. package/lib/file-upload.mjs +205 -0
  39. package/lib/gateway-probe.mjs +6 -6
  40. package/lib/gateway-state.mjs +57 -57
  41. package/lib/gateway-tools.mjs +36 -36
  42. package/lib/history-cache.mjs +66 -0
  43. package/lib/index.mjs +4390 -3803
  44. package/lib/plugin-management.mjs +251 -233
  45. package/lib/public-endpoint-check.mjs +61 -61
  46. package/lib/relay-connector.mjs +213 -181
  47. package/lib/relay-state.mjs +83 -76
  48. package/lib/session-follower.mjs +140 -136
  49. package/lib/session-resume-bridge.mjs +86 -0
  50. package/lib/session-target.mjs +29 -0
  51. package/lib/speech-input.mjs +192 -192
  52. package/lib/vendor/cost-meter/aliyun-balance.mjs +123 -123
  53. package/lib/vendor/cost-meter/coding-plans.mjs +1668 -1668
  54. package/lib/vendor/cost-meter/credentials-shim.mjs +8 -8
  55. package/lib/vendor/cost-meter/custom-balance.mjs +281 -281
  56. package/lib/vendor/cost-meter/factory-quota.mjs +69 -69
  57. package/lib/vendor/cost-meter/gateway-quota-adapters.mjs +1006 -1006
  58. package/lib/vendor/cost-meter/gateway-quotas.mjs +664 -664
  59. package/lib/vendor/cost-meter/home-paths-shim.mjs +13 -13
  60. package/lib/vendor/cost-meter/net.mjs +183 -183
  61. package/lib/vendor/cost-meter/opendesign.mjs +204 -204
  62. package/lib/vendor/cost-meter/tokenrhythm-balance.mjs +95 -95
  63. package/lib/vendor/cost-meter/workbuddy-accounts.mjs +44 -44
  64. package/lib/vendor/cost-meter/workbuddy-transport.mjs +38 -38
  65. package/lib/vendor/cost-meter/workbuddy.mjs +356 -356
  66. package/lib/web-restart.mjs +47 -47
  67. package/lib/wire-json.mjs +7 -7
  68. package/lib/workspace-changes-bridge.mjs +32 -32
  69. package/package.json +54 -54
  70. package/relay/agent-connector.js +588 -569
  71. 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
+ }
@@ -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 stopped = false
57
- let restarts = 0
58
- let windowStart = now()
59
- let lastError = null
60
- let delegatedTo = null
61
-
62
- const snapshot = () => ({
63
- running: child !== null && child.exitCode === null && child.signalCode === null,
64
- pid: child === null ? null : child.pid,
65
- stateDir,
66
- relay: relay || null,
67
- lastError,
68
- delegatedTo,
69
- })
70
-
71
- const clearTimer = () => {
72
- if (restartTimer === null) return
73
- clearTimeout(restartTimer)
74
- restartTimer = null
75
- }
76
-
77
- const stop = () => {
78
- stopped = true
79
- clearTimer()
80
- const previous = child
81
- child = null
82
- if (previous === null || previous.exitCode !== null || previous.signalCode !== null) return
83
- previous.kill('SIGTERM')
84
- // The connector exits on SIGTERM; do not wait forever if it is wedged.
85
- const killTimer = setTimeout(() => {
86
- if (previous.exitCode === null && previous.signalCode === null) previous.kill('SIGKILL')
87
- }, 3_000)
88
- killTimer.unref?.()
89
- }
90
-
91
- // A live pid in the lock file means somebody else already owns this identity
92
- // (the documented systemd install). Spawning would just exit, so report the
93
- // delegation instead — and, crucially, do not treat a stale registration as
94
- // proof that a bridge is alive: our own child dies with the plugin.
95
- const lockHolder = () => {
96
- try {
97
- const held = JSON.parse(fs.readFileSync(path.join(stateDir, 'connector.lock'), 'utf8'))
98
- if (!Number.isInteger(held.pid) || held.pid === process.pid) return null
99
- try { process.kill(held.pid, 0); return held.pid } catch (error) { if (error.code !== 'ESRCH') return held.pid }
100
- return null
101
- } catch { return null }
102
- }
103
-
104
- const start = ({ force = false } = {}) => {
105
- if (child !== null && child.exitCode === null && child.signalCode === null) return snapshot()
106
- if (!force) {
107
- const holder = lockHolder()
108
- if (holder !== null) {
109
- delegatedTo = holder
110
- lastError = null
111
- return snapshot()
112
- }
113
- }
114
- if (!relay) {
115
- lastError = '未配置中继地址(relayUrl),无法启动内置连接器'
116
- return snapshot()
117
- }
118
- if (!force && !commandExists(process.execPath)) {
119
- lastError = `node 可执行文件不可用:${process.execPath}`
120
- return snapshot()
121
- }
122
- stopped = false
123
- lastError = null
124
- let spawned
125
- try {
126
- spawned = spawnProcess(process.execPath, [CONNECTOR_SCRIPT], {
127
- env: {
128
- ...process.env,
129
- // Desktop runs under Electron; child scripts must execute as Node.
130
- ...(process.versions.electron ? { ELECTRON_RUN_AS_NODE: '1' } : {}),
131
- RELAY_URL: relay,
132
- GATEWAY_URL: gatewayUrl,
133
- GATEWAY_NAME: gatewayName || '',
134
- MGMT_URL: mgmtUrl,
135
- STATE_DIR: stateDir,
136
- },
137
- stdio: ['ignore', 'ignore', 'ignore'],
138
- windowsHide: true,
139
- })
140
- } catch (error) {
141
- lastError = `启动内置连接器失败:${error.message}`
142
- return snapshot()
143
- }
144
- child = spawned
145
- delegatedTo = null
146
- log(`bundled connector starting: pid=${spawned.pid} relay=${relay} state=${stateDir}`)
147
- spawned.on('error', (error) => {
148
- if (child !== spawned) return
149
- lastError = `内置连接器启动失败:${error.message}`
150
- log(lastError)
151
- })
152
- spawned.on('exit', (code, signal) => {
153
- if (child !== spawned) return
154
- child = null
155
- // Exit 0 with the pid lock held elsewhere is the expected "an installed
156
- // connector already owns this identity" path — not a failure.
157
- if (code === 0) {
158
- log('bundled connector exited; an installed connector likely owns the identity')
159
- return
160
- }
161
- lastError = `内置连接器退出(${signal || code})`
162
- log(lastError)
163
- if (stopped) return
164
- const at = now()
165
- if (at - windowStart > 60_000) { restarts = 0; windowStart = at }
166
- restarts += 1
167
- if (restarts > MAX_RAPID_RESTARTS) {
168
- lastError = '内置连接器反复退出,已停止自动重启'
169
- log(lastError)
170
- return
171
- }
172
- restartTimer = setTimeout(() => { restartTimer = null; start() }, restartDelayMs)
173
- restartTimer.unref?.()
174
- })
175
- return snapshot()
176
- }
177
-
178
- const dispose = () => { stop() }
179
-
180
- return { start, stop, snapshot, dispose }
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
+ }