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,314 +1,314 @@
|
|
|
1
|
-
import fs from 'node:fs'
|
|
2
|
-
import http from 'node:http'
|
|
3
|
-
import path from 'node:path'
|
|
4
|
-
import crypto from 'node:crypto'
|
|
5
|
-
import { spawn } from 'node:child_process'
|
|
6
|
-
import { ensureCloudflared } from './cloudflared-binary.mjs'
|
|
7
|
-
import { checkPublicEndpoint } from './public-endpoint-check.mjs'
|
|
8
|
-
|
|
9
|
-
function hostnameOf(value) {
|
|
10
|
-
if (typeof value !== 'string') throw new TypeError('Cloudflare hostname is required')
|
|
11
|
-
const hostname = value.trim().toLowerCase()
|
|
12
|
-
if (hostname.length > 253 || !/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/.test(hostname) ||
|
|
13
|
-
!hostname.includes('.') || hostname.includes('..') ||
|
|
14
|
-
hostname.split('.').some((label) => label.length > 63 || label.startsWith('-') || label.endsWith('-'))) {
|
|
15
|
-
throw new TypeError('Cloudflare hostname must be a domain name, for example gateway.example.com')
|
|
16
|
-
}
|
|
17
|
-
return hostname
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
function tokenOf(value) {
|
|
21
|
-
if (typeof value !== 'string' || !value.trim() || value.length > 8192 || /\s/.test(value)) {
|
|
22
|
-
throw new TypeError('Cloudflare Tunnel Token must be a nonempty token without whitespace')
|
|
23
|
-
}
|
|
24
|
-
return value
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
function readState(file) {
|
|
28
|
-
try {
|
|
29
|
-
const value = JSON.parse(fs.readFileSync(file, 'utf8'))
|
|
30
|
-
if (value?.version !== 1 || typeof value.enabled !== 'boolean' ||
|
|
31
|
-
typeof value.hostname !== 'string' || typeof value.token !== 'string') {
|
|
32
|
-
throw new TypeError('invalid Cloudflare Tunnel settings')
|
|
33
|
-
}
|
|
34
|
-
if (value.hostname) hostnameOf(value.hostname)
|
|
35
|
-
if (value.token) tokenOf(value.token)
|
|
36
|
-
value.mode ??= 'named'
|
|
37
|
-
if (!['named', 'quick'].includes(value.mode)) throw new TypeError('invalid Cloudflare Tunnel mode')
|
|
38
|
-
if (value.enabled && value.mode === 'named' && (!value.hostname || !value.token)) {
|
|
39
|
-
throw new TypeError('enabled named tunnel has no hostname or token')
|
|
40
|
-
}
|
|
41
|
-
fs.chmodSync(file, 0o600)
|
|
42
|
-
return value
|
|
43
|
-
} catch (error) {
|
|
44
|
-
if (error.code === 'ENOENT') return { version: 1, enabled: false, mode: 'quick', hostname: '', token: '' }
|
|
45
|
-
throw new Error(`failed to load Cloudflare Tunnel settings ${file}: ${error.message}`, { cause: error })
|
|
46
|
-
}
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
function writeState(file, value) {
|
|
50
|
-
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 })
|
|
51
|
-
const temporary = `${file}.${process.pid}.${crypto.randomUUID()}.tmp`
|
|
52
|
-
try {
|
|
53
|
-
fs.writeFileSync(temporary, `${JSON.stringify(value)}\n`, { mode: 0o600, flag: 'wx' })
|
|
54
|
-
fs.renameSync(temporary, file)
|
|
55
|
-
fs.chmodSync(file, 0o600)
|
|
56
|
-
} finally {
|
|
57
|
-
fs.rmSync(temporary, { force: true })
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
// A separate loopback listener exposes only the mobile WebSocket. In particular,
|
|
62
|
-
// Cloudflare can never reach the DSH WebUI or the /mgw management API through it.
|
|
63
|
-
export function createCloudflareTunnel({ file, port = 3082, wsPath, executable = 'cloudflared',
|
|
64
|
-
supported = true, isGatewayEnabled, onUpgrade, log = () => {}, spawnProcess = spawn,
|
|
65
|
-
prepareExecutable = ensureCloudflared, probeEndpoint = checkPublicEndpoint,
|
|
66
|
-
protocol = 'http2' } = {}) {
|
|
67
|
-
let settings = supported ? readState(file) : { version: 1, enabled: false, mode: 'quick', hostname: '', token: '' }
|
|
68
|
-
let server = null
|
|
69
|
-
let child = null
|
|
70
|
-
let preparing = null
|
|
71
|
-
let retryTimer = null
|
|
72
|
-
let disposed = false
|
|
73
|
-
let phase = 'disabled'
|
|
74
|
-
let error = null
|
|
75
|
-
let quickUrl = null
|
|
76
|
-
let queue = Promise.resolve()
|
|
77
|
-
const sockets = new Set()
|
|
78
|
-
let endpointHealth = { state: 'unchecked', message: '尚未检测公网 DNS、TLS 和 WebSocket 路由。' }
|
|
79
|
-
let healthGeneration = 0
|
|
80
|
-
let healthPending = null
|
|
81
|
-
const checkEndpoint = () => {
|
|
82
|
-
const endpoint = publicUrl()
|
|
83
|
-
if (!shouldRun() || !endpoint || phase !== 'online') return Promise.resolve(snapshot())
|
|
84
|
-
if (healthPending) return healthPending
|
|
85
|
-
const generation = healthGeneration
|
|
86
|
-
endpointHealth = { state: 'checking', message: '正在检测公网 DNS、TLS 和 WebSocket 路由…' }
|
|
87
|
-
const pending = Promise.resolve().then(() => probeEndpoint(endpoint)).catch(() => ({ state: 'network-error', message: '公网检测失败,请稍后重试。', checkedAt: new Date().toISOString() })).then((health) => {
|
|
88
|
-
if (generation === healthGeneration) endpointHealth = health
|
|
89
|
-
return snapshot()
|
|
90
|
-
}).finally(() => { if (healthPending === pending) healthPending = null })
|
|
91
|
-
healthPending = pending
|
|
92
|
-
return pending
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
const shouldRun = () => supported && !disposed && settings.enabled && isGatewayEnabled()
|
|
96
|
-
const publicUrl = () => settings.mode === 'quick'
|
|
97
|
-
? quickUrl
|
|
98
|
-
: settings.hostname ? `wss://${settings.hostname}${wsPath}` : null
|
|
99
|
-
const snapshot = () => ({
|
|
100
|
-
supported,
|
|
101
|
-
enabled: settings.enabled,
|
|
102
|
-
mode: settings.mode,
|
|
103
|
-
configured: !!(settings.hostname && settings.token),
|
|
104
|
-
hostname: settings.hostname || null,
|
|
105
|
-
publicUrl: settings.enabled ? publicUrl() : null,
|
|
106
|
-
port,
|
|
107
|
-
state: !settings.enabled ? 'disabled' : !isGatewayEnabled() ? 'waiting-for-gateway' : phase,
|
|
108
|
-
error,
|
|
109
|
-
endpointHealth,
|
|
110
|
-
publicReady: phase === 'online' && shouldRun() && endpointHealth.state === 'reachable',
|
|
111
|
-
})
|
|
112
|
-
|
|
113
|
-
const stop = async () => {
|
|
114
|
-
healthGeneration += 1
|
|
115
|
-
healthPending = null
|
|
116
|
-
endpointHealth = { state: 'unchecked', message: '尚未检测公网 DNS、TLS 和 WebSocket 路由。' }
|
|
117
|
-
if (retryTimer) clearTimeout(retryTimer)
|
|
118
|
-
retryTimer = null
|
|
119
|
-
const previous = child
|
|
120
|
-
child = null
|
|
121
|
-
if (previous && !previous.killed) previous.kill()
|
|
122
|
-
quickUrl = null
|
|
123
|
-
for (const socket of sockets) socket.destroy()
|
|
124
|
-
sockets.clear()
|
|
125
|
-
const listener = server
|
|
126
|
-
server = null
|
|
127
|
-
phase = 'disabled'
|
|
128
|
-
error = null
|
|
129
|
-
if (listener) await new Promise((resolve) => listener.close(resolve))
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
const startChild = () => {
|
|
133
|
-
if (!shouldRun() || !server || child || preparing) return
|
|
134
|
-
phase = 'preparing'
|
|
135
|
-
error = null
|
|
136
|
-
preparing = prepareExecutable({ cacheDir: path.join(path.dirname(file), 'cloudflared-bin'), executable })
|
|
137
|
-
.then((binary) => {
|
|
138
|
-
preparing = null
|
|
139
|
-
if (!shouldRun() || !server || child) return
|
|
140
|
-
phase = 'connecting'
|
|
141
|
-
const quick = settings.mode === 'quick'
|
|
142
|
-
// Fork: force http2. cloudflared defaults to QUIC/UDP, and networks
|
|
143
|
-
// that drop UDP to Cloudflare's edge (typical behind a NAS router)
|
|
144
|
-
// leave the tunnel stuck at "connecting" forever — the edge dial times
|
|
145
|
-
// out, no "Registered tunnel connection" ever arrives. TCP 443 works.
|
|
146
|
-
const args = quick
|
|
147
|
-
? ['tunnel', '--no-autoupdate', '--loglevel', 'info', '--protocol', protocol, '--url', `http://127.0.0.1:${port}`]
|
|
148
|
-
: ['tunnel', '--no-autoupdate', '--loglevel', 'info', '--protocol', protocol, 'run']
|
|
149
|
-
const childEnv = { ...process.env }
|
|
150
|
-
delete childEnv.TUNNEL_TOKEN
|
|
151
|
-
if (!quick) childEnv.TUNNEL_TOKEN = settings.token
|
|
152
|
-
const running = spawnProcess(binary, args, {
|
|
153
|
-
env: childEnv,
|
|
154
|
-
stdio: ['ignore', 'pipe', 'pipe'],
|
|
155
|
-
windowsHide: true,
|
|
156
|
-
})
|
|
157
|
-
child = running
|
|
158
|
-
let diagnostics = ''
|
|
159
|
-
let outputTail = ''
|
|
160
|
-
let registered = false
|
|
161
|
-
const onOutput = (chunk) => {
|
|
162
|
-
if (child !== running) return
|
|
163
|
-
const lines = chunk.toString().slice(0, 4096)
|
|
164
|
-
outputTail = (outputTail + lines).slice(-4096)
|
|
165
|
-
if (quick) {
|
|
166
|
-
const match = /https:\/\/([a-z0-9-]+)\.trycloudflare\.com\b/i.exec(outputTail)
|
|
167
|
-
if (match) quickUrl = `wss://${match[1].toLowerCase()}.trycloudflare.com${wsPath}`
|
|
168
|
-
}
|
|
169
|
-
if (/Registered tunnel connection/i.test(outputTail)) {
|
|
170
|
-
registered = true
|
|
171
|
-
outputTail = ''
|
|
172
|
-
} else if (/ERR|error/i.test(lines)) {
|
|
173
|
-
diagnostics = (settings.token ? outputTail.replaceAll(settings.token, '[redacted]') : outputTail)
|
|
174
|
-
.replace(/eyJ[A-Za-z0-9._=-]+/g, '[redacted]').trim().slice(-500)
|
|
175
|
-
}
|
|
176
|
-
if (registered && (!quick || quickUrl)) {
|
|
177
|
-
const firstOnline = phase !== 'online'
|
|
178
|
-
phase = 'online'
|
|
179
|
-
error = null
|
|
180
|
-
if (firstOnline) void checkEndpoint()
|
|
181
|
-
}
|
|
182
|
-
}
|
|
183
|
-
running.stderr?.on('data', onOutput)
|
|
184
|
-
running.stdout?.on('data', onOutput)
|
|
185
|
-
const exited = (reason) => {
|
|
186
|
-
if (child !== running) return
|
|
187
|
-
child = null
|
|
188
|
-
healthGeneration += 1
|
|
189
|
-
healthPending = null
|
|
190
|
-
endpointHealth = { state: 'unchecked', message: '隧道已断开,需重新检测公网入口。' }
|
|
191
|
-
quickUrl = null
|
|
192
|
-
phase = 'error'
|
|
193
|
-
error = reason || diagnostics || 'cloudflared exited unexpectedly'
|
|
194
|
-
log(`Cloudflare Tunnel stopped: ${error}`)
|
|
195
|
-
if (shouldRun()) retryTimer = setTimeout(() => { retryTimer = null; startChild() }, 10_000)
|
|
196
|
-
}
|
|
197
|
-
running.once('error', (cause) => exited(cause.code === 'ENOENT'
|
|
198
|
-
? 'cloudflared is not installed or is not on PATH'
|
|
199
|
-
: `cloudflared failed: ${cause.message}`))
|
|
200
|
-
running.once('exit', (code, signal) => exited(diagnostics || `cloudflared exited (${signal || code})`))
|
|
201
|
-
})
|
|
202
|
-
.catch((cause) => {
|
|
203
|
-
preparing = null
|
|
204
|
-
if (!shouldRun()) return
|
|
205
|
-
phase = 'error'
|
|
206
|
-
error = `Cloudflare binary preparation failed: ${cause.message}`
|
|
207
|
-
log(error)
|
|
208
|
-
retryTimer = setTimeout(() => { retryTimer = null; startChild() }, 30_000)
|
|
209
|
-
})
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
const start = async () => {
|
|
213
|
-
if (server || !shouldRun()) return
|
|
214
|
-
phase = 'starting'
|
|
215
|
-
error = null
|
|
216
|
-
const listener = http.createServer((_req, res) => {
|
|
217
|
-
res.writeHead(404, { 'Content-Type': 'text/plain', 'Cache-Control': 'no-store' })
|
|
218
|
-
res.end('Not found')
|
|
219
|
-
})
|
|
220
|
-
listener.on('connection', (socket) => {
|
|
221
|
-
sockets.add(socket)
|
|
222
|
-
socket.on('close', () => sockets.delete(socket))
|
|
223
|
-
})
|
|
224
|
-
listener.on('upgrade', (req, socket, head) => {
|
|
225
|
-
let pathname
|
|
226
|
-
try { pathname = new URL(req.url || '/', 'http://localhost').pathname } catch { pathname = '' }
|
|
227
|
-
if (pathname !== wsPath) {
|
|
228
|
-
socket.end('HTTP/1.1 404 Not Found\r\nConnection: close\r\n\r\n')
|
|
229
|
-
return
|
|
230
|
-
}
|
|
231
|
-
onUpgrade(req, socket, head, { lan: true, port })
|
|
232
|
-
})
|
|
233
|
-
try {
|
|
234
|
-
await new Promise((resolve, reject) => {
|
|
235
|
-
listener.once('error', reject)
|
|
236
|
-
listener.listen(port, '127.0.0.1', () => {
|
|
237
|
-
listener.off('error', reject)
|
|
238
|
-
resolve()
|
|
239
|
-
})
|
|
240
|
-
})
|
|
241
|
-
if (!shouldRun()) {
|
|
242
|
-
listener.close()
|
|
243
|
-
return
|
|
244
|
-
}
|
|
245
|
-
server = listener
|
|
246
|
-
listener.on('error', (cause) => {
|
|
247
|
-
const message = `Cloudflare origin listener failed: ${cause.message}`
|
|
248
|
-
void stop().then(() => {
|
|
249
|
-
if (!shouldRun()) return
|
|
250
|
-
phase = 'error'
|
|
251
|
-
error = message
|
|
252
|
-
log(message)
|
|
253
|
-
retryTimer = setTimeout(() => { retryTimer = null; void reconcile() }, 10_000)
|
|
254
|
-
})
|
|
255
|
-
})
|
|
256
|
-
startChild()
|
|
257
|
-
} catch (cause) {
|
|
258
|
-
try { listener.close() } catch { /* The listener never opened. */ }
|
|
259
|
-
if (shouldRun()) {
|
|
260
|
-
phase = 'error'
|
|
261
|
-
error = `Cloudflare origin listener failed: ${cause.message}`
|
|
262
|
-
log(error)
|
|
263
|
-
retryTimer = setTimeout(() => { retryTimer = null; void reconcile() }, 10_000)
|
|
264
|
-
}
|
|
265
|
-
}
|
|
266
|
-
}
|
|
267
|
-
|
|
268
|
-
const reconcile = () => {
|
|
269
|
-
queue = queue.catch(() => {}).then(async () => {
|
|
270
|
-
if (shouldRun()) await start()
|
|
271
|
-
else await stop()
|
|
272
|
-
})
|
|
273
|
-
return queue
|
|
274
|
-
}
|
|
275
|
-
|
|
276
|
-
const configure = async ({ enabled, mode, hostname, token }) => {
|
|
277
|
-
if (!supported) throw new TypeError('Cloudflare Tunnel is available on PC only')
|
|
278
|
-
if (typeof enabled !== 'boolean') throw new TypeError('enabled must be a boolean')
|
|
279
|
-
const next = {
|
|
280
|
-
version: 1,
|
|
281
|
-
enabled,
|
|
282
|
-
mode: mode === undefined ? settings.mode : mode,
|
|
283
|
-
hostname: hostname === undefined ? settings.hostname : hostnameOf(hostname),
|
|
284
|
-
token: token === undefined || token === '' ? settings.token : tokenOf(token),
|
|
285
|
-
}
|
|
286
|
-
if (!['named', 'quick'].includes(next.mode)) throw new TypeError('mode must be named or quick')
|
|
287
|
-
if (enabled && next.mode === 'named' && (!next.hostname || !next.token)) {
|
|
288
|
-
throw new TypeError('hostname and Tunnel Token are required')
|
|
289
|
-
}
|
|
290
|
-
const changed = next.mode !== settings.mode || next.hostname !== settings.hostname || next.token !== settings.token
|
|
291
|
-
writeState(file, next)
|
|
292
|
-
settings = next
|
|
293
|
-
if (changed) await stop()
|
|
294
|
-
await reconcile()
|
|
295
|
-
return snapshot()
|
|
296
|
-
}
|
|
297
|
-
|
|
298
|
-
const restart = () => {
|
|
299
|
-
queue = queue.catch(() => {}).then(async () => {
|
|
300
|
-
if (!shouldRun()) {
|
|
301
|
-
const cause = new Error('请先开启移动网关和 Cloudflare Tunnel')
|
|
302
|
-
cause.status = 409
|
|
303
|
-
throw cause
|
|
304
|
-
}
|
|
305
|
-
await stop()
|
|
306
|
-
await start()
|
|
307
|
-
return snapshot()
|
|
308
|
-
})
|
|
309
|
-
return queue
|
|
310
|
-
}
|
|
311
|
-
|
|
312
|
-
const dispose = () => { disposed = true; void stop() }
|
|
313
|
-
return { snapshot, configure, reconcile, restart, checkEndpoint, dispose }
|
|
314
|
-
}
|
|
1
|
+
import fs from 'node:fs'
|
|
2
|
+
import http from 'node:http'
|
|
3
|
+
import path from 'node:path'
|
|
4
|
+
import crypto from 'node:crypto'
|
|
5
|
+
import { spawn } from 'node:child_process'
|
|
6
|
+
import { ensureCloudflared } from './cloudflared-binary.mjs'
|
|
7
|
+
import { checkPublicEndpoint } from './public-endpoint-check.mjs'
|
|
8
|
+
|
|
9
|
+
function hostnameOf(value) {
|
|
10
|
+
if (typeof value !== 'string') throw new TypeError('Cloudflare hostname is required')
|
|
11
|
+
const hostname = value.trim().toLowerCase()
|
|
12
|
+
if (hostname.length > 253 || !/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/.test(hostname) ||
|
|
13
|
+
!hostname.includes('.') || hostname.includes('..') ||
|
|
14
|
+
hostname.split('.').some((label) => label.length > 63 || label.startsWith('-') || label.endsWith('-'))) {
|
|
15
|
+
throw new TypeError('Cloudflare hostname must be a domain name, for example gateway.example.com')
|
|
16
|
+
}
|
|
17
|
+
return hostname
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function tokenOf(value) {
|
|
21
|
+
if (typeof value !== 'string' || !value.trim() || value.length > 8192 || /\s/.test(value)) {
|
|
22
|
+
throw new TypeError('Cloudflare Tunnel Token must be a nonempty token without whitespace')
|
|
23
|
+
}
|
|
24
|
+
return value
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function readState(file) {
|
|
28
|
+
try {
|
|
29
|
+
const value = JSON.parse(fs.readFileSync(file, 'utf8'))
|
|
30
|
+
if (value?.version !== 1 || typeof value.enabled !== 'boolean' ||
|
|
31
|
+
typeof value.hostname !== 'string' || typeof value.token !== 'string') {
|
|
32
|
+
throw new TypeError('invalid Cloudflare Tunnel settings')
|
|
33
|
+
}
|
|
34
|
+
if (value.hostname) hostnameOf(value.hostname)
|
|
35
|
+
if (value.token) tokenOf(value.token)
|
|
36
|
+
value.mode ??= 'named'
|
|
37
|
+
if (!['named', 'quick'].includes(value.mode)) throw new TypeError('invalid Cloudflare Tunnel mode')
|
|
38
|
+
if (value.enabled && value.mode === 'named' && (!value.hostname || !value.token)) {
|
|
39
|
+
throw new TypeError('enabled named tunnel has no hostname or token')
|
|
40
|
+
}
|
|
41
|
+
fs.chmodSync(file, 0o600)
|
|
42
|
+
return value
|
|
43
|
+
} catch (error) {
|
|
44
|
+
if (error.code === 'ENOENT') return { version: 1, enabled: false, mode: 'quick', hostname: '', token: '' }
|
|
45
|
+
throw new Error(`failed to load Cloudflare Tunnel settings ${file}: ${error.message}`, { cause: error })
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function writeState(file, value) {
|
|
50
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 })
|
|
51
|
+
const temporary = `${file}.${process.pid}.${crypto.randomUUID()}.tmp`
|
|
52
|
+
try {
|
|
53
|
+
fs.writeFileSync(temporary, `${JSON.stringify(value)}\n`, { mode: 0o600, flag: 'wx' })
|
|
54
|
+
fs.renameSync(temporary, file)
|
|
55
|
+
fs.chmodSync(file, 0o600)
|
|
56
|
+
} finally {
|
|
57
|
+
fs.rmSync(temporary, { force: true })
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// A separate loopback listener exposes only the mobile WebSocket. In particular,
|
|
62
|
+
// Cloudflare can never reach the DSH WebUI or the /mgw management API through it.
|
|
63
|
+
export function createCloudflareTunnel({ file, port = 3082, wsPath, executable = 'cloudflared',
|
|
64
|
+
supported = true, isGatewayEnabled, onUpgrade, log = () => {}, spawnProcess = spawn,
|
|
65
|
+
prepareExecutable = ensureCloudflared, probeEndpoint = checkPublicEndpoint,
|
|
66
|
+
protocol = 'http2' } = {}) {
|
|
67
|
+
let settings = supported ? readState(file) : { version: 1, enabled: false, mode: 'quick', hostname: '', token: '' }
|
|
68
|
+
let server = null
|
|
69
|
+
let child = null
|
|
70
|
+
let preparing = null
|
|
71
|
+
let retryTimer = null
|
|
72
|
+
let disposed = false
|
|
73
|
+
let phase = 'disabled'
|
|
74
|
+
let error = null
|
|
75
|
+
let quickUrl = null
|
|
76
|
+
let queue = Promise.resolve()
|
|
77
|
+
const sockets = new Set()
|
|
78
|
+
let endpointHealth = { state: 'unchecked', message: '尚未检测公网 DNS、TLS 和 WebSocket 路由。' }
|
|
79
|
+
let healthGeneration = 0
|
|
80
|
+
let healthPending = null
|
|
81
|
+
const checkEndpoint = () => {
|
|
82
|
+
const endpoint = publicUrl()
|
|
83
|
+
if (!shouldRun() || !endpoint || phase !== 'online') return Promise.resolve(snapshot())
|
|
84
|
+
if (healthPending) return healthPending
|
|
85
|
+
const generation = healthGeneration
|
|
86
|
+
endpointHealth = { state: 'checking', message: '正在检测公网 DNS、TLS 和 WebSocket 路由…' }
|
|
87
|
+
const pending = Promise.resolve().then(() => probeEndpoint(endpoint)).catch(() => ({ state: 'network-error', message: '公网检测失败,请稍后重试。', checkedAt: new Date().toISOString() })).then((health) => {
|
|
88
|
+
if (generation === healthGeneration) endpointHealth = health
|
|
89
|
+
return snapshot()
|
|
90
|
+
}).finally(() => { if (healthPending === pending) healthPending = null })
|
|
91
|
+
healthPending = pending
|
|
92
|
+
return pending
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const shouldRun = () => supported && !disposed && settings.enabled && isGatewayEnabled()
|
|
96
|
+
const publicUrl = () => settings.mode === 'quick'
|
|
97
|
+
? quickUrl
|
|
98
|
+
: settings.hostname ? `wss://${settings.hostname}${wsPath}` : null
|
|
99
|
+
const snapshot = () => ({
|
|
100
|
+
supported,
|
|
101
|
+
enabled: settings.enabled,
|
|
102
|
+
mode: settings.mode,
|
|
103
|
+
configured: !!(settings.hostname && settings.token),
|
|
104
|
+
hostname: settings.hostname || null,
|
|
105
|
+
publicUrl: settings.enabled ? publicUrl() : null,
|
|
106
|
+
port,
|
|
107
|
+
state: !settings.enabled ? 'disabled' : !isGatewayEnabled() ? 'waiting-for-gateway' : phase,
|
|
108
|
+
error,
|
|
109
|
+
endpointHealth,
|
|
110
|
+
publicReady: phase === 'online' && shouldRun() && endpointHealth.state === 'reachable',
|
|
111
|
+
})
|
|
112
|
+
|
|
113
|
+
const stop = async () => {
|
|
114
|
+
healthGeneration += 1
|
|
115
|
+
healthPending = null
|
|
116
|
+
endpointHealth = { state: 'unchecked', message: '尚未检测公网 DNS、TLS 和 WebSocket 路由。' }
|
|
117
|
+
if (retryTimer) clearTimeout(retryTimer)
|
|
118
|
+
retryTimer = null
|
|
119
|
+
const previous = child
|
|
120
|
+
child = null
|
|
121
|
+
if (previous && !previous.killed) previous.kill()
|
|
122
|
+
quickUrl = null
|
|
123
|
+
for (const socket of sockets) socket.destroy()
|
|
124
|
+
sockets.clear()
|
|
125
|
+
const listener = server
|
|
126
|
+
server = null
|
|
127
|
+
phase = 'disabled'
|
|
128
|
+
error = null
|
|
129
|
+
if (listener) await new Promise((resolve) => listener.close(resolve))
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const startChild = () => {
|
|
133
|
+
if (!shouldRun() || !server || child || preparing) return
|
|
134
|
+
phase = 'preparing'
|
|
135
|
+
error = null
|
|
136
|
+
preparing = prepareExecutable({ cacheDir: path.join(path.dirname(file), 'cloudflared-bin'), executable })
|
|
137
|
+
.then((binary) => {
|
|
138
|
+
preparing = null
|
|
139
|
+
if (!shouldRun() || !server || child) return
|
|
140
|
+
phase = 'connecting'
|
|
141
|
+
const quick = settings.mode === 'quick'
|
|
142
|
+
// Fork: force http2. cloudflared defaults to QUIC/UDP, and networks
|
|
143
|
+
// that drop UDP to Cloudflare's edge (typical behind a NAS router)
|
|
144
|
+
// leave the tunnel stuck at "connecting" forever — the edge dial times
|
|
145
|
+
// out, no "Registered tunnel connection" ever arrives. TCP 443 works.
|
|
146
|
+
const args = quick
|
|
147
|
+
? ['tunnel', '--no-autoupdate', '--loglevel', 'info', '--protocol', protocol, '--url', `http://127.0.0.1:${port}`]
|
|
148
|
+
: ['tunnel', '--no-autoupdate', '--loglevel', 'info', '--protocol', protocol, 'run']
|
|
149
|
+
const childEnv = { ...process.env }
|
|
150
|
+
delete childEnv.TUNNEL_TOKEN
|
|
151
|
+
if (!quick) childEnv.TUNNEL_TOKEN = settings.token
|
|
152
|
+
const running = spawnProcess(binary, args, {
|
|
153
|
+
env: childEnv,
|
|
154
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
155
|
+
windowsHide: true,
|
|
156
|
+
})
|
|
157
|
+
child = running
|
|
158
|
+
let diagnostics = ''
|
|
159
|
+
let outputTail = ''
|
|
160
|
+
let registered = false
|
|
161
|
+
const onOutput = (chunk) => {
|
|
162
|
+
if (child !== running) return
|
|
163
|
+
const lines = chunk.toString().slice(0, 4096)
|
|
164
|
+
outputTail = (outputTail + lines).slice(-4096)
|
|
165
|
+
if (quick) {
|
|
166
|
+
const match = /https:\/\/([a-z0-9-]+)\.trycloudflare\.com\b/i.exec(outputTail)
|
|
167
|
+
if (match) quickUrl = `wss://${match[1].toLowerCase()}.trycloudflare.com${wsPath}`
|
|
168
|
+
}
|
|
169
|
+
if (/Registered tunnel connection/i.test(outputTail)) {
|
|
170
|
+
registered = true
|
|
171
|
+
outputTail = ''
|
|
172
|
+
} else if (/ERR|error/i.test(lines)) {
|
|
173
|
+
diagnostics = (settings.token ? outputTail.replaceAll(settings.token, '[redacted]') : outputTail)
|
|
174
|
+
.replace(/eyJ[A-Za-z0-9._=-]+/g, '[redacted]').trim().slice(-500)
|
|
175
|
+
}
|
|
176
|
+
if (registered && (!quick || quickUrl)) {
|
|
177
|
+
const firstOnline = phase !== 'online'
|
|
178
|
+
phase = 'online'
|
|
179
|
+
error = null
|
|
180
|
+
if (firstOnline) void checkEndpoint()
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
running.stderr?.on('data', onOutput)
|
|
184
|
+
running.stdout?.on('data', onOutput)
|
|
185
|
+
const exited = (reason) => {
|
|
186
|
+
if (child !== running) return
|
|
187
|
+
child = null
|
|
188
|
+
healthGeneration += 1
|
|
189
|
+
healthPending = null
|
|
190
|
+
endpointHealth = { state: 'unchecked', message: '隧道已断开,需重新检测公网入口。' }
|
|
191
|
+
quickUrl = null
|
|
192
|
+
phase = 'error'
|
|
193
|
+
error = reason || diagnostics || 'cloudflared exited unexpectedly'
|
|
194
|
+
log(`Cloudflare Tunnel stopped: ${error}`)
|
|
195
|
+
if (shouldRun()) retryTimer = setTimeout(() => { retryTimer = null; startChild() }, 10_000)
|
|
196
|
+
}
|
|
197
|
+
running.once('error', (cause) => exited(cause.code === 'ENOENT'
|
|
198
|
+
? 'cloudflared is not installed or is not on PATH'
|
|
199
|
+
: `cloudflared failed: ${cause.message}`))
|
|
200
|
+
running.once('exit', (code, signal) => exited(diagnostics || `cloudflared exited (${signal || code})`))
|
|
201
|
+
})
|
|
202
|
+
.catch((cause) => {
|
|
203
|
+
preparing = null
|
|
204
|
+
if (!shouldRun()) return
|
|
205
|
+
phase = 'error'
|
|
206
|
+
error = `Cloudflare binary preparation failed: ${cause.message}`
|
|
207
|
+
log(error)
|
|
208
|
+
retryTimer = setTimeout(() => { retryTimer = null; startChild() }, 30_000)
|
|
209
|
+
})
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
const start = async () => {
|
|
213
|
+
if (server || !shouldRun()) return
|
|
214
|
+
phase = 'starting'
|
|
215
|
+
error = null
|
|
216
|
+
const listener = http.createServer((_req, res) => {
|
|
217
|
+
res.writeHead(404, { 'Content-Type': 'text/plain', 'Cache-Control': 'no-store' })
|
|
218
|
+
res.end('Not found')
|
|
219
|
+
})
|
|
220
|
+
listener.on('connection', (socket) => {
|
|
221
|
+
sockets.add(socket)
|
|
222
|
+
socket.on('close', () => sockets.delete(socket))
|
|
223
|
+
})
|
|
224
|
+
listener.on('upgrade', (req, socket, head) => {
|
|
225
|
+
let pathname
|
|
226
|
+
try { pathname = new URL(req.url || '/', 'http://localhost').pathname } catch { pathname = '' }
|
|
227
|
+
if (pathname !== wsPath) {
|
|
228
|
+
socket.end('HTTP/1.1 404 Not Found\r\nConnection: close\r\n\r\n')
|
|
229
|
+
return
|
|
230
|
+
}
|
|
231
|
+
onUpgrade(req, socket, head, { lan: true, cloudflare: true, port })
|
|
232
|
+
})
|
|
233
|
+
try {
|
|
234
|
+
await new Promise((resolve, reject) => {
|
|
235
|
+
listener.once('error', reject)
|
|
236
|
+
listener.listen(port, '127.0.0.1', () => {
|
|
237
|
+
listener.off('error', reject)
|
|
238
|
+
resolve()
|
|
239
|
+
})
|
|
240
|
+
})
|
|
241
|
+
if (!shouldRun()) {
|
|
242
|
+
listener.close()
|
|
243
|
+
return
|
|
244
|
+
}
|
|
245
|
+
server = listener
|
|
246
|
+
listener.on('error', (cause) => {
|
|
247
|
+
const message = `Cloudflare origin listener failed: ${cause.message}`
|
|
248
|
+
void stop().then(() => {
|
|
249
|
+
if (!shouldRun()) return
|
|
250
|
+
phase = 'error'
|
|
251
|
+
error = message
|
|
252
|
+
log(message)
|
|
253
|
+
retryTimer = setTimeout(() => { retryTimer = null; void reconcile() }, 10_000)
|
|
254
|
+
})
|
|
255
|
+
})
|
|
256
|
+
startChild()
|
|
257
|
+
} catch (cause) {
|
|
258
|
+
try { listener.close() } catch { /* The listener never opened. */ }
|
|
259
|
+
if (shouldRun()) {
|
|
260
|
+
phase = 'error'
|
|
261
|
+
error = `Cloudflare origin listener failed: ${cause.message}`
|
|
262
|
+
log(error)
|
|
263
|
+
retryTimer = setTimeout(() => { retryTimer = null; void reconcile() }, 10_000)
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
const reconcile = () => {
|
|
269
|
+
queue = queue.catch(() => {}).then(async () => {
|
|
270
|
+
if (shouldRun()) await start()
|
|
271
|
+
else await stop()
|
|
272
|
+
})
|
|
273
|
+
return queue
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
const configure = async ({ enabled, mode, hostname, token }) => {
|
|
277
|
+
if (!supported) throw new TypeError('Cloudflare Tunnel is available on PC only')
|
|
278
|
+
if (typeof enabled !== 'boolean') throw new TypeError('enabled must be a boolean')
|
|
279
|
+
const next = {
|
|
280
|
+
version: 1,
|
|
281
|
+
enabled,
|
|
282
|
+
mode: mode === undefined ? settings.mode : mode,
|
|
283
|
+
hostname: hostname === undefined ? settings.hostname : hostnameOf(hostname),
|
|
284
|
+
token: token === undefined || token === '' ? settings.token : tokenOf(token),
|
|
285
|
+
}
|
|
286
|
+
if (!['named', 'quick'].includes(next.mode)) throw new TypeError('mode must be named or quick')
|
|
287
|
+
if (enabled && next.mode === 'named' && (!next.hostname || !next.token)) {
|
|
288
|
+
throw new TypeError('hostname and Tunnel Token are required')
|
|
289
|
+
}
|
|
290
|
+
const changed = next.mode !== settings.mode || next.hostname !== settings.hostname || next.token !== settings.token
|
|
291
|
+
writeState(file, next)
|
|
292
|
+
settings = next
|
|
293
|
+
if (changed) await stop()
|
|
294
|
+
await reconcile()
|
|
295
|
+
return snapshot()
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
const restart = () => {
|
|
299
|
+
queue = queue.catch(() => {}).then(async () => {
|
|
300
|
+
if (!shouldRun()) {
|
|
301
|
+
const cause = new Error('请先开启移动网关和 Cloudflare Tunnel')
|
|
302
|
+
cause.status = 409
|
|
303
|
+
throw cause
|
|
304
|
+
}
|
|
305
|
+
await stop()
|
|
306
|
+
await start()
|
|
307
|
+
return snapshot()
|
|
308
|
+
})
|
|
309
|
+
return queue
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
const dispose = () => { disposed = true; void stop() }
|
|
313
|
+
return { snapshot, configure, reconcile, restart, checkEndpoint, dispose }
|
|
314
|
+
}
|