dsh-plugin-weapp-gateway 0.8.60 → 0.8.62
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.md +12 -0
- package/docs/tailscale-node.md +53 -0
- package/helper/tsnet-node/README.md +35 -0
- package/helper/tsnet-node/build.sh +19 -0
- package/helper/tsnet-node/go.mod +51 -0
- package/helper/tsnet-node/go.sum +239 -0
- package/helper/tsnet-node/main.go +326 -0
- package/lib/client.js +1901 -1911
- package/lib/cloudflare-tunnel.mjs +23 -0
- package/lib/index.mjs +41 -10
- package/lib/tailscale-node.mjs +325 -0
- package/package.json +1 -1
|
@@ -82,6 +82,7 @@ export function createCloudflareTunnel({ file, port = 3082, wsPath, executable =
|
|
|
82
82
|
let endpointHealth = { state: 'unchecked', message: '尚未检测公网 DNS、TLS 和 WebSocket 路由。' }
|
|
83
83
|
let healthGeneration = 0
|
|
84
84
|
let healthPending = null
|
|
85
|
+
let healthTimer = null
|
|
85
86
|
const checkEndpoint = () => {
|
|
86
87
|
const endpoint = publicUrl()
|
|
87
88
|
if (!shouldRun() || !endpoint || phase !== 'online') return Promise.resolve(snapshot())
|
|
@@ -115,6 +116,8 @@ export function createCloudflareTunnel({ file, port = 3082, wsPath, executable =
|
|
|
115
116
|
})
|
|
116
117
|
|
|
117
118
|
const stop = async () => {
|
|
119
|
+
if (healthTimer) clearInterval(healthTimer)
|
|
120
|
+
healthTimer = null
|
|
118
121
|
healthGeneration += 1
|
|
119
122
|
healthPending = null
|
|
120
123
|
endpointHealth = { state: 'unchecked', message: '尚未检测公网 DNS、TLS 和 WebSocket 路由。' }
|
|
@@ -182,6 +185,22 @@ export function createCloudflareTunnel({ file, port = 3082, wsPath, executable =
|
|
|
182
185
|
phase = 'online'
|
|
183
186
|
error = null
|
|
184
187
|
if (firstOnline) void checkEndpoint()
|
|
188
|
+
// 定时健康检查:quick tunnel 的 URL 会随重启变化/失效,检测到不可达就重启隧道并刷新 URL
|
|
189
|
+
if (!healthTimer) {
|
|
190
|
+
healthTimer = setInterval(() => {
|
|
191
|
+
if (phase !== 'online' || !shouldRun()) return
|
|
192
|
+
const endpoint = publicUrl()
|
|
193
|
+
if (!endpoint) return
|
|
194
|
+
void probeEndpoint(endpoint).then((health) => {
|
|
195
|
+
endpointHealth = health
|
|
196
|
+
if (health.state !== 'reachable') {
|
|
197
|
+
log('Cloudflare endpoint unreachable, restarting tunnel: ' + endpoint)
|
|
198
|
+
try { running.kill() } catch { /* already gone */ }
|
|
199
|
+
}
|
|
200
|
+
}).catch(() => {})
|
|
201
|
+
}, 60_000)
|
|
202
|
+
healthTimer.unref?.()
|
|
203
|
+
}
|
|
185
204
|
}
|
|
186
205
|
}
|
|
187
206
|
running.stderr?.on('data', onOutput)
|
|
@@ -189,6 +208,10 @@ export function createCloudflareTunnel({ file, port = 3082, wsPath, executable =
|
|
|
189
208
|
const exited = (reason) => {
|
|
190
209
|
if (child !== running) return
|
|
191
210
|
child = null
|
|
211
|
+
// 隧道进程结束时要停掉健康检查,否则重启后会残留一个持有旧进程句柄的定时器,
|
|
212
|
+
// 导致新隧道不可达时无法触发重启。
|
|
213
|
+
if (healthTimer) clearInterval(healthTimer)
|
|
214
|
+
healthTimer = null
|
|
192
215
|
healthGeneration += 1
|
|
193
216
|
healthPending = null
|
|
194
217
|
endpointHealth = { state: 'unchecked', message: '隧道已断开,需重新检测公网入口。' }
|
package/lib/index.mjs
CHANGED
|
@@ -170,7 +170,7 @@ import { createFileUploadManager, FILE_UPLOAD_REQUEST_TYPES, FILE_UPLOAD_DEFAULT
|
|
|
170
170
|
import { assistantFinish, failureDetails, toolResultDetails, turnReasonDetails } from './session-event-details.mjs'
|
|
171
171
|
import { createNetworkDiagnostics } from './network-diagnostics.mjs'
|
|
172
172
|
import { isTailscaleIp, tailscaleInterfaceStatus } from './tailscale-addresses.mjs'
|
|
173
|
-
import {
|
|
173
|
+
import { createTailscaleNode } from './tailscale-node.mjs'
|
|
174
174
|
import { createUiState } from './ui-state.mjs'
|
|
175
175
|
|
|
176
176
|
const { createRegistry } = devicesModule
|
|
@@ -324,8 +324,11 @@ const Config = Schema.object({
|
|
|
324
324
|
cloudflareStateFile: Schema.string().default(''),
|
|
325
325
|
tailscaleEnabled: Schema.boolean().default(false),
|
|
326
326
|
tailscaleAuthKey: Schema.string().default(''),
|
|
327
|
-
tailscaleHostname: Schema.string().default('
|
|
327
|
+
tailscaleHostname: Schema.string().default(''),
|
|
328
328
|
tailscaleServePort: Schema.natural().min(1).max(65535).default(3081),
|
|
329
|
+
tailscaleMode: Schema.string().default('auto'),
|
|
330
|
+
tailscaleControlUrl: Schema.string().default('https://controlplane.tailscale.com'),
|
|
331
|
+
tailscaleHelperPath: Schema.string().default(''),
|
|
329
332
|
logFile: Schema.string().default(''),
|
|
330
333
|
})
|
|
331
334
|
|
|
@@ -2948,8 +2951,11 @@ const plugin = {
|
|
|
2948
2951
|
cloudflareStateFile: '',
|
|
2949
2952
|
tailscaleEnabled: false,
|
|
2950
2953
|
tailscaleAuthKey: '',
|
|
2951
|
-
tailscaleHostname: '
|
|
2954
|
+
tailscaleHostname: '',
|
|
2952
2955
|
tailscaleServePort: 3081,
|
|
2956
|
+
tailscaleMode: 'auto',
|
|
2957
|
+
tailscaleControlUrl: 'https://controlplane.tailscale.com',
|
|
2958
|
+
tailscaleHelperPath: '',
|
|
2953
2959
|
logFile: '',
|
|
2954
2960
|
...(config || {}),
|
|
2955
2961
|
}
|
|
@@ -3096,12 +3102,15 @@ const plugin = {
|
|
|
3096
3102
|
|
|
3097
3103
|
const tailscaleStatus = () => {
|
|
3098
3104
|
const base = tailscaleInterfaceStatus({ listening: lanListening, host: options.lanHost, port: lanBoundPort, wsPath })
|
|
3099
|
-
const serveUrl = tailscaleServe?.snapshot().publicUrl || ''
|
|
3100
3105
|
const serveState = tailscaleServe ? tailscaleServe.snapshot() : { enabled: false, backendState: 'disabled', loginUrl: '', error: '' }
|
|
3106
|
+
// 只有节点真的 Running 才暴露 serveUrl,避免状态在「等待授权/已授权」之间闪
|
|
3107
|
+
const serveUrl = serveState.backendState === 'Running' ? (serveState.publicUrl || '') : ''
|
|
3101
3108
|
return {
|
|
3102
3109
|
...base,
|
|
3103
3110
|
serveUrl,
|
|
3104
3111
|
urls: serveUrl ? [serveUrl, ...(base.urls || [])] : (base.urls || []),
|
|
3112
|
+
nodeSource: serveState.nodeSource || 'none',
|
|
3113
|
+
node: serveState,
|
|
3105
3114
|
serve: serveState,
|
|
3106
3115
|
}
|
|
3107
3116
|
}
|
|
@@ -3667,14 +3676,26 @@ const plugin = {
|
|
|
3667
3676
|
if (!url) throw badRequest('tailscale login url unavailable')
|
|
3668
3677
|
res.writeHead(302, { Location: url })
|
|
3669
3678
|
res.end()
|
|
3679
|
+
} else if (req.method === 'POST' && p === '/mgw/tailscale/hostname') {
|
|
3680
|
+
if (!tailscaleServe) throw badRequest('tailscale is not available')
|
|
3681
|
+
const body = await readBody(req)
|
|
3682
|
+
tailscaleServe.setHostname(body && body.hostname ? String(body.hostname) : '')
|
|
3683
|
+
await tailscaleServe.stop()
|
|
3684
|
+
await tailscaleServe.start({ forceEmbedded: true })
|
|
3685
|
+
sendJson(res, 200, tailscaleServe.snapshot())
|
|
3670
3686
|
} else if (req.method === 'POST' && p === '/mgw/tailscale') {
|
|
3671
3687
|
if (!tailscaleServe) throw badRequest('tailscale is not available')
|
|
3672
3688
|
const body = await readBody(req)
|
|
3689
|
+
if (body && typeof body.authKey === 'string' && body.authKey.trim() !== '') {
|
|
3690
|
+
tailscaleServe.setAuthKey(body.authKey.trim())
|
|
3691
|
+
}
|
|
3673
3692
|
await tailscaleServe.stop()
|
|
3674
3693
|
if (body && body.action === 'stop') {
|
|
3675
3694
|
sendJson(res, 200, tailscaleServe.snapshot())
|
|
3676
3695
|
} else {
|
|
3677
|
-
|
|
3696
|
+
// 面板点「启动隧道/重新连接」时强制走内嵌节点,这样没装系统 Tailscale
|
|
3697
|
+
// 也没有 Auth Key 的用户也能拿到登录链接(去授权)。
|
|
3698
|
+
sendJson(res, 200, await tailscaleServe.start({ forceEmbedded: true }))
|
|
3678
3699
|
}
|
|
3679
3700
|
} else if (req.method === 'GET' && p === '/mgw/public-setup') {
|
|
3680
3701
|
sendJson(res, 200, await systemHelperStatus())
|
|
@@ -3784,6 +3805,7 @@ const plugin = {
|
|
|
3784
3805
|
const serveTailscaleUrl = tailscaleServe?.snapshot().publicUrl || ''
|
|
3785
3806
|
const tailscaleUrls = [
|
|
3786
3807
|
...(serveTailscaleUrl ? [serveTailscaleUrl] : []),
|
|
3808
|
+
...(tailscaleServe ? (tailscaleServe.snapshot().urls || []) : []),
|
|
3787
3809
|
...(lanListening
|
|
3788
3810
|
? tailscaleInterfaceStatus({ listening: true, host: options.lanHost, port: lanBoundPort, wsPath }).urls
|
|
3789
3811
|
: []),
|
|
@@ -3880,8 +3902,13 @@ const plugin = {
|
|
|
3880
3902
|
})
|
|
3881
3903
|
.slice(0, 16)
|
|
3882
3904
|
: advertisedEndpoints(appUrl).filter(isRoutablePrivateEndpoint)
|
|
3905
|
+
// auto 路线:公网入口同时带上 Cloudflare 与 Tailscale Serve,客户端按
|
|
3906
|
+
// 「Tailscale → Cloudflare → 局域网」优先级自行选择;两者可同时启用。
|
|
3907
|
+
const tailscaleServeEndpoints = clientRoute === 'auto' && serveTailscaleUrl &&
|
|
3908
|
+
isPublicSecureEndpoint(serveTailscaleUrl) ? [serveTailscaleUrl] : []
|
|
3883
3909
|
const appEndpoints = [...new Set([
|
|
3884
3910
|
...(clientRoute !== 'lan' && clientRoute !== 'tailscale' && hasPublicRoute ? [publicUrl] : []),
|
|
3911
|
+
...tailscaleServeEndpoints,
|
|
3885
3912
|
...lanEndpoints,
|
|
3886
3913
|
])].slice(0, 16)
|
|
3887
3914
|
// 全网络自动选路路由表:客户端按自身能力从 lan/public/relay 中挑选,
|
|
@@ -4509,16 +4536,20 @@ const plugin = {
|
|
|
4509
4536
|
})
|
|
4510
4537
|
void tunnel.reconcile()
|
|
4511
4538
|
|
|
4512
|
-
tailscaleServe =
|
|
4513
|
-
|
|
4539
|
+
tailscaleServe = createTailscaleNode({
|
|
4540
|
+
mode: options.tailscaleMode,
|
|
4541
|
+
stateDir: path.join(os.homedir(), '.dsh', 'tailscale'),
|
|
4514
4542
|
wsPath,
|
|
4515
|
-
|
|
4543
|
+
listenPort: options.tailscaleServePort,
|
|
4516
4544
|
hostname: options.tailscaleHostname,
|
|
4517
4545
|
authKey: options.tailscaleAuthKey,
|
|
4546
|
+
controlUrl: options.tailscaleControlUrl,
|
|
4547
|
+
helperPath: options.tailscaleHelperPath,
|
|
4548
|
+
forceEmbedded: options.tailscaleEnabled === true,
|
|
4518
4549
|
log,
|
|
4519
4550
|
})
|
|
4520
|
-
if (options.tailscaleEnabled === true) {
|
|
4521
|
-
void tailscaleServe.start().then((snap) => log('tailscale
|
|
4551
|
+
if (options.tailscaleEnabled === true || String(options.tailscaleMode || 'auto') !== 'off') {
|
|
4552
|
+
void tailscaleServe.start().then((snap) => log('tailscale node: ' + JSON.stringify(snap)))
|
|
4522
4553
|
}
|
|
4523
4554
|
|
|
4524
4555
|
const disposeEvents = ctx.on('session/event', (session, event) => {
|
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
// 网关内嵌 Tailscale 节点管理(轻量模式)。
|
|
2
|
+
//
|
|
3
|
+
// 两种节点来源,按 tailscaleMode 自动选择:
|
|
4
|
+
// 1) system —— 用户电脑本身已安装并登录 Tailscale:直接读取本机 100.64/10 私网地址,
|
|
5
|
+
// 不做任何 spawn(零安装、零权限,账号归用户)。
|
|
6
|
+
// 2) embedded —— 电脑没有 Tailscale:spawn 自研 helper(helper/tsnet-node,tsnet 1.104.5),
|
|
7
|
+
// 由用户在插件里填自己的 Auth Key,或通过登录链接授权自己的账号。
|
|
8
|
+
// 不依赖系统 tailscaled、不占系统 VPN / TUN。
|
|
9
|
+
//
|
|
10
|
+
// 与旧版 tailscale-serve.mjs 保持相同的方法面(start/stop/refresh/snapshot/loginUrl/enableServe),
|
|
11
|
+
// 便于 index.mjs 无痛替换;snapshot 额外带 nodeSource / dnsName / ipv4 / urls 等字段。
|
|
12
|
+
import fs from 'node:fs'
|
|
13
|
+
import path from 'node:path'
|
|
14
|
+
import os from 'node:os'
|
|
15
|
+
import { spawn } from 'node:child_process'
|
|
16
|
+
import { tailscaleInterfaceStatus } from './tailscale-addresses.mjs'
|
|
17
|
+
|
|
18
|
+
const DEFAULT_CONTROL_URL = 'https://controlplane.tailscale.com'
|
|
19
|
+
const EMBEDDED_STATUS = 'embedded-node.json'
|
|
20
|
+
const MODES = new Set(['auto', 'system', 'embedded', 'off'])
|
|
21
|
+
|
|
22
|
+
function normalizeMode(value) {
|
|
23
|
+
const mode = String(value || 'auto').trim().toLowerCase()
|
|
24
|
+
return MODES.has(mode) ? mode : 'auto'
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function platformDir(platform = process.platform) {
|
|
28
|
+
if (platform === 'win32') return 'windows'
|
|
29
|
+
if (platform === 'darwin') return 'darwin'
|
|
30
|
+
return 'linux'
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function archDir(arch = process.arch) {
|
|
34
|
+
if (arch === 'x64') return 'amd64'
|
|
35
|
+
if (arch === 'ia32') return '386'
|
|
36
|
+
return arch
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** helper 二进制位置:显式配置 > 环境变量 > 插件仓库内构建产物 */
|
|
40
|
+
export function resolveHelperBinary(explicit) {
|
|
41
|
+
const name = process.platform === 'win32' ? 'dsh-tailscale-node.exe' : 'dsh-tailscale-node'
|
|
42
|
+
const candidates = []
|
|
43
|
+
if (explicit) candidates.push(explicit)
|
|
44
|
+
if (process.env.DSH_TSNET_HELPER) candidates.push(process.env.DSH_TSNET_HELPER)
|
|
45
|
+
candidates.push(path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')),
|
|
46
|
+
'..', 'helper', 'tsnet-node', 'bin', platformDir() + '-' + archDir(), name))
|
|
47
|
+
candidates.push(path.join(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')),
|
|
48
|
+
'..', 'helper', 'tsnet-node', 'bin', platformDir() + '-' + archDir(), name))
|
|
49
|
+
for (const candidate of candidates) {
|
|
50
|
+
try {
|
|
51
|
+
if (candidate && fs.existsSync(candidate)) return candidate
|
|
52
|
+
} catch (error) { /* ignore */ }
|
|
53
|
+
}
|
|
54
|
+
return ''
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** 系统 Tailscale 检测:只看本机网卡,不执行任何命令、不推断登录状态 */
|
|
58
|
+
export function detectSystemTailscale({ port = 3081, wsPath = '/ws/mobile', host = '0.0.0.0' } = {}) {
|
|
59
|
+
try {
|
|
60
|
+
const status = tailscaleInterfaceStatus({ listening: true, host, port, wsPath })
|
|
61
|
+
return { addresses: status.addresses || [], urls: status.urls || [] }
|
|
62
|
+
} catch (error) {
|
|
63
|
+
return { addresses: [], urls: [] }
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function createTailscaleNode(options = {}) {
|
|
68
|
+
const log = typeof options.log === 'function' ? options.log : () => {}
|
|
69
|
+
const mode = normalizeMode(options.mode)
|
|
70
|
+
const stateDir = options.stateDir || path.join(os.homedir(), '.dsh', 'tailscale')
|
|
71
|
+
const statusFile = options.statusFile || path.join(stateDir, EMBEDDED_STATUS)
|
|
72
|
+
const snapshotFile = options.snapshotFile || path.join(stateDir, 'tailscale-node.json')
|
|
73
|
+
const wsPath = options.wsPath || '/ws/mobile'
|
|
74
|
+
const listenPort = Number(options.listenPort) || 3081
|
|
75
|
+
const httpsPort = Number(options.httpsPort) || 0
|
|
76
|
+
function defaultHostname() {
|
|
77
|
+
const platform = process.platform === 'win32' ? 'win' : (process.platform === 'darwin' ? 'mac' : (process.platform === 'linux' ? 'linux' : 'os'))
|
|
78
|
+
return 'dsh-gateway-' + platform
|
|
79
|
+
}
|
|
80
|
+
const configuredHostname = String(options.hostname || '').trim()
|
|
81
|
+
// 旧版本默认值是 'dsh-gateway':视为未配置,改用平台默认名(dsh-gateway-win/mac/linux)
|
|
82
|
+
let hostname = (configuredHostname && configuredHostname !== 'dsh-gateway') ? configuredHostname : defaultHostname()
|
|
83
|
+
const controlURL = String(options.controlUrl || DEFAULT_CONTROL_URL).trim() || DEFAULT_CONTROL_URL
|
|
84
|
+
let authKey = String(options.authKey || '').trim()
|
|
85
|
+
if (authKey && !hostname.endsWith('-ak')) hostname += '-ak'
|
|
86
|
+
const helperPath = resolveHelperBinary(options.helperPath)
|
|
87
|
+
const forceEmbedded = options.forceEmbedded === true
|
|
88
|
+
|
|
89
|
+
let child = null
|
|
90
|
+
let timer = null
|
|
91
|
+
let stopping = false
|
|
92
|
+
let last = {
|
|
93
|
+
enabled: false,
|
|
94
|
+
mode,
|
|
95
|
+
state: 'disabled',
|
|
96
|
+
backendState: 'disabled',
|
|
97
|
+
nodeSource: 'none',
|
|
98
|
+
loginUrl: '',
|
|
99
|
+
publicUrl: '',
|
|
100
|
+
error: '',
|
|
101
|
+
dnsName: '',
|
|
102
|
+
ipv4: '',
|
|
103
|
+
authMode: authKey ? 'authkey' : 'login',
|
|
104
|
+
listenPort,
|
|
105
|
+
hostname,
|
|
106
|
+
urls: [],
|
|
107
|
+
helper: helperPath,
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const snapshot = () => ({ ...last })
|
|
111
|
+
|
|
112
|
+
function persist() {
|
|
113
|
+
try {
|
|
114
|
+
fs.mkdirSync(path.dirname(snapshotFile), { recursive: true, mode: 0o700 })
|
|
115
|
+
fs.writeFileSync(snapshotFile, JSON.stringify(snapshot(), null, 2), { mode: 0o600 })
|
|
116
|
+
} catch (error) {
|
|
117
|
+
log('tailscale-node: persist failed ' + (error && error.message ? error.message : String(error)))
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function embeddedUrls(state) {
|
|
122
|
+
const urls = []
|
|
123
|
+
if (state.ipv4) urls.push('ws://' + state.ipv4 + ':' + listenPort + wsPath)
|
|
124
|
+
if (state.httpsUrl) urls.push(state.httpsUrl)
|
|
125
|
+
return urls
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function readEmbedded() {
|
|
129
|
+
try {
|
|
130
|
+
const raw = JSON.parse(fs.readFileSync(statusFile, 'utf8'))
|
|
131
|
+
return raw && typeof raw === 'object' ? raw : null
|
|
132
|
+
} catch (error) {
|
|
133
|
+
return null
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function applyEmbedded() {
|
|
138
|
+
const state = readEmbedded()
|
|
139
|
+
if (!state) {
|
|
140
|
+
if (child && child.exitCode === null) return
|
|
141
|
+
return
|
|
142
|
+
}
|
|
143
|
+
const urls = embeddedUrls(state)
|
|
144
|
+
last = {
|
|
145
|
+
...last,
|
|
146
|
+
enabled: true,
|
|
147
|
+
nodeSource: 'embedded',
|
|
148
|
+
state: String(state.state || 'starting'),
|
|
149
|
+
authMode: state.authMode || last.authMode,
|
|
150
|
+
loginUrl: state.loginUrl || '',
|
|
151
|
+
dnsName: state.dnsName || '',
|
|
152
|
+
ipv4: state.ipv4 || '',
|
|
153
|
+
error: state.error || '',
|
|
154
|
+
urls,
|
|
155
|
+
publicUrl: state.httpsUrl || (state.ipv4 ? 'ws://' + state.ipv4 + ':' + listenPort + wsPath : ''),
|
|
156
|
+
backendState: state.state === 'running' ? 'Running'
|
|
157
|
+
: state.state === 'needs-login' ? 'NeedsLogin'
|
|
158
|
+
: state.state === 'failed' ? 'Failed'
|
|
159
|
+
: state.state === 'stopped' ? 'disabled' : 'Starting',
|
|
160
|
+
}
|
|
161
|
+
if (last.state === 'running') last.error = ''
|
|
162
|
+
persist()
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function stopTimer() {
|
|
166
|
+
if (timer) {
|
|
167
|
+
clearInterval(timer)
|
|
168
|
+
timer = null
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function startTimer() {
|
|
173
|
+
stopTimer()
|
|
174
|
+
timer = setInterval(() => {
|
|
175
|
+
try {
|
|
176
|
+
applyEmbedded()
|
|
177
|
+
} catch (error) {
|
|
178
|
+
log('tailscale-node: poll failed ' + (error && error.message ? error.message : String(error)))
|
|
179
|
+
}
|
|
180
|
+
}, 1500)
|
|
181
|
+
if (typeof timer.unref === 'function') timer.unref()
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function applySystem() {
|
|
185
|
+
const detected = detectSystemTailscale({ port: listenPort, wsPath })
|
|
186
|
+
if (detected.urls.length > 0) {
|
|
187
|
+
last = {
|
|
188
|
+
...last,
|
|
189
|
+
enabled: true,
|
|
190
|
+
nodeSource: 'system',
|
|
191
|
+
state: 'running',
|
|
192
|
+
backendState: 'Running',
|
|
193
|
+
authMode: 'system',
|
|
194
|
+
loginUrl: '',
|
|
195
|
+
error: '',
|
|
196
|
+
urls: detected.urls,
|
|
197
|
+
publicUrl: detected.urls[0],
|
|
198
|
+
ipv4: detected.addresses[0] || '',
|
|
199
|
+
dnsName: '',
|
|
200
|
+
}
|
|
201
|
+
persist()
|
|
202
|
+
return true
|
|
203
|
+
}
|
|
204
|
+
return false
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
async function start(overrides = {}) {
|
|
208
|
+
stopping = false
|
|
209
|
+
const force = forceEmbedded || overrides.forceEmbedded === true
|
|
210
|
+
last = { ...last, enabled: true, error: '' }
|
|
211
|
+
if (mode === 'off') {
|
|
212
|
+
last = { ...last, enabled: false, state: 'disabled', backendState: 'disabled', nodeSource: 'none' }
|
|
213
|
+
persist()
|
|
214
|
+
return snapshot()
|
|
215
|
+
}
|
|
216
|
+
// 1) 系统安装优先(system / auto)
|
|
217
|
+
if (mode !== 'embedded' && applySystem()) {
|
|
218
|
+
log('tailscale-node: using system Tailscale ' + (last.urls[0] || ''))
|
|
219
|
+
return snapshot()
|
|
220
|
+
}
|
|
221
|
+
if (mode === 'system') {
|
|
222
|
+
last = { ...last, nodeSource: 'none', state: 'failed', backendState: 'Failed',
|
|
223
|
+
error: 'system Tailscale not detected; install Tailscale or switch mode to embedded' }
|
|
224
|
+
persist()
|
|
225
|
+
return snapshot()
|
|
226
|
+
}
|
|
227
|
+
// 2) 内嵌节点:用户配置了 authKey、显式开启、mode=embedded,或已有登录态(重启后自愈)时才 spawn,
|
|
228
|
+
// 避免在用户完全没配置 Tailscale 时凭空起一个等待登录的节点。
|
|
229
|
+
const hasEmbeddedState = fs.existsSync(path.join(stateDir, 'tailscaled.state'))
|
|
230
|
+
if (!force && !authKey && mode !== 'embedded' && !hasEmbeddedState) {
|
|
231
|
+
last = { ...last, enabled: false, nodeSource: 'none', state: 'disabled', backendState: 'disabled',
|
|
232
|
+
error: 'no system Tailscale detected; set an Auth Key (or use the login link) to start the embedded node' }
|
|
233
|
+
persist()
|
|
234
|
+
return snapshot()
|
|
235
|
+
}
|
|
236
|
+
if (!helperPath) {
|
|
237
|
+
last = { ...last, nodeSource: 'none', state: 'failed', backendState: 'Failed',
|
|
238
|
+
error: 'tailscale helper not found; build helper/tsnet-node or set tailscaleHelperPath' }
|
|
239
|
+
persist()
|
|
240
|
+
return snapshot()
|
|
241
|
+
}
|
|
242
|
+
try {
|
|
243
|
+
fs.rmSync(statusFile, { force: true })
|
|
244
|
+
} catch (error) { /* ignore */ }
|
|
245
|
+
const args = [
|
|
246
|
+
'--state-dir', stateDir,
|
|
247
|
+
'--hostname', hostname,
|
|
248
|
+
'--control-url', controlURL,
|
|
249
|
+
'--listen-port', String(listenPort),
|
|
250
|
+
'--status-file', statusFile,
|
|
251
|
+
]
|
|
252
|
+
if (httpsPort > 0) args.push('--https-port', String(httpsPort))
|
|
253
|
+
if (authKey) args.push('--auth-key', authKey)
|
|
254
|
+
log('tailscale-node: spawning embedded helper ' + helperPath)
|
|
255
|
+
child = spawn(helperPath, args, { stdio: ['ignore', 'pipe', 'pipe'] })
|
|
256
|
+
child.stdout.on('data', (chunk) => log('tsnet-node: ' + String(chunk).trim()))
|
|
257
|
+
child.stderr.on('data', (chunk) => log('tsnet-node: ' + String(chunk).trim()))
|
|
258
|
+
child.on('error', (error) => {
|
|
259
|
+
last = { ...last, state: 'failed', backendState: 'Failed', error: 'helper spawn failed: ' + error.message }
|
|
260
|
+
child = null
|
|
261
|
+
persist()
|
|
262
|
+
})
|
|
263
|
+
child.on('exit', (code) => {
|
|
264
|
+
child = null
|
|
265
|
+
if (stopping) return
|
|
266
|
+
last = { ...last, state: 'failed', backendState: 'Failed', error: 'helper exited (code=' + code + ')' }
|
|
267
|
+
persist()
|
|
268
|
+
log('tailscale-node: helper exited code=' + code)
|
|
269
|
+
})
|
|
270
|
+
last = { ...last, nodeSource: 'embedded', state: 'starting', backendState: 'Starting' }
|
|
271
|
+
persist()
|
|
272
|
+
startTimer()
|
|
273
|
+
applyEmbedded()
|
|
274
|
+
return snapshot()
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
async function stop() {
|
|
278
|
+
stopping = true
|
|
279
|
+
stopTimer()
|
|
280
|
+
if (child) {
|
|
281
|
+
try { child.kill('SIGTERM') } catch (error) { /* ignore */ }
|
|
282
|
+
child = null
|
|
283
|
+
}
|
|
284
|
+
last = { ...last, enabled: false, nodeSource: 'none', state: 'disabled', backendState: 'disabled',
|
|
285
|
+
loginUrl: '', publicUrl: '', urls: [], error: '' }
|
|
286
|
+
persist()
|
|
287
|
+
return snapshot()
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
async function refresh() {
|
|
291
|
+
if (mode !== 'embedded' && last.nodeSource !== 'embedded') {
|
|
292
|
+
if (!applySystem() && last.nodeSource === 'system') {
|
|
293
|
+
last = { ...last, nodeSource: 'none', state: 'disabled', backendState: 'disabled', urls: [], publicUrl: '' }
|
|
294
|
+
persist()
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
if (last.nodeSource === 'embedded') applyEmbedded()
|
|
298
|
+
return snapshot()
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
function setAuthKey(nextKey) {
|
|
302
|
+
authKey = String(nextKey || '').trim()
|
|
303
|
+
if (authKey && !hostname.endsWith('-ak')) hostname += '-ak'
|
|
304
|
+
if (!authKey && hostname.endsWith('-ak')) hostname = hostname.slice(0, -3)
|
|
305
|
+
last = { ...last, authMode: authKey ? 'authkey' : 'login', hostname }
|
|
306
|
+
persist()
|
|
307
|
+
return snapshot()
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
function setHostname(nextName) {
|
|
311
|
+
const value = String(nextName || '').trim()
|
|
312
|
+
hostname = value || defaultHostname()
|
|
313
|
+
if (authKey && !hostname.endsWith('-ak')) hostname += '-ak'
|
|
314
|
+
last = { ...last, hostname }
|
|
315
|
+
persist()
|
|
316
|
+
return snapshot()
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
async function loginUrl() {
|
|
320
|
+
const embedded = readEmbedded()
|
|
321
|
+
return (embedded && embedded.loginUrl) || last.loginUrl || ''
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
return { start, stop, refresh, snapshot, loginUrl, setAuthKey, setHostname, enableServe: refresh, resolveHelperBinary }
|
|
325
|
+
}
|