dsh-ris-ide 1.8.5 → 1.8.7
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/bin/run-with-log.sh +28 -10
- package/lib/client.js +402 -111
- package/lib/index.js +224 -64
- package/lib/proxy-lifecycle.js +502 -0
- package/lib/proxy.js +50 -0
- package/lib/risd/server.js +144 -38
- package/lib/risd/ui.js +114 -23
- package/package.json +2 -2
- package/test/client-viewer.test.mjs +229 -31
- package/test/clipboard.test.mjs +41 -2
- package/test/host-tail.test.mjs +137 -1
- package/test/proxy-lifecycle.test.mjs +251 -0
- package/test/proxy.test.mjs +48 -0
- package/test/risd-api.test.mjs +4 -1
- package/test/risd-engine.test.mjs +45 -3
- package/test/risd-follow-start.test.mjs +3 -2
- package/test/risd-handoff.test.mjs +4 -2
- package/test/risd-helpers.mjs +23 -2
- package/test/risd-teardown.test.mjs +4 -2
- package/test/risd-ui.test.mjs +21 -2
|
@@ -0,0 +1,502 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Proxy service lifecycle: the engine only runs while its upstream SOCKS is up.
|
|
3
|
+
*
|
|
4
|
+
* Three phases, persisted in `<proxyHome>/proxy-state.json` so the plugin, the
|
|
5
|
+
* daemon and the maintenance page all read the same story:
|
|
6
|
+
*
|
|
7
|
+
* running the engine + bridge + git entry are up and the upstream answered
|
|
8
|
+
* the last probe;
|
|
9
|
+
* pending 待启动 — the user asked for the service but the SOCKS host is not
|
|
10
|
+
* reachable (or was lost while running): nothing is forwarded, and a
|
|
11
|
+
* watcher keeps probing so it can come up on its own;
|
|
12
|
+
* stopped the user (or a teardown) asked for it to be down.
|
|
13
|
+
*
|
|
14
|
+
* Rules that the phases encode (and that a plain "is the process alive?" check
|
|
15
|
+
* cannot):
|
|
16
|
+
* - start first probes SOCKS; an unreachable upstream never spawns an engine
|
|
17
|
+
* that would only fail per-connection, it parks in `pending`;
|
|
18
|
+
* - a running engine that loses SOCKS for SOCKS_DOWN_STOP_MS is stopped, the
|
|
19
|
+
* phase becomes `pending`, and the same watcher re-starts it when SOCKS
|
|
20
|
+
* returns (never with an elevation prompt: see `toggle` in ui.js);
|
|
21
|
+
* - the system-level bridge (ProxyBridge) follows the service: started with it,
|
|
22
|
+
* stopped with it, including the automatic stop/restart above.
|
|
23
|
+
*
|
|
24
|
+
* `pending` deliberately does NOT survive the process that owns it: the file names
|
|
25
|
+
* `owner` and a snapshot from another process treats a pending state whose owner
|
|
26
|
+
* is gone as `stopped`. That is the "不跨进程保留" rule — a wait only exists while
|
|
27
|
+
* somebody is there to do the waiting.
|
|
28
|
+
*/
|
|
29
|
+
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
|
30
|
+
import { dirname, join } from 'node:path'
|
|
31
|
+
import { pidAlive, probeSocks, proxyHomeDir, proxyPid, readProxyConfig, startProxy, stopProxy } from './proxy.js'
|
|
32
|
+
import { startRedirectors, stopRedirector } from './redirector.js'
|
|
33
|
+
|
|
34
|
+
export const PROXY_STATE_FILENAME = 'proxy-state.json'
|
|
35
|
+
export const PHASE_RUNNING = 'running'
|
|
36
|
+
export const PHASE_STOPPED = 'stopped'
|
|
37
|
+
export const PHASE_PENDING = 'pending'
|
|
38
|
+
/** While 待启动: how often to re-probe the SOCKS host. */
|
|
39
|
+
export const WAIT_PROBE_MS = 5000
|
|
40
|
+
/** While running: how often to check the upstream is still there. */
|
|
41
|
+
export const RUNNING_PROBE_MS = 10000
|
|
42
|
+
/** How long a running engine may be cut off from SOCKS before it is stopped. */
|
|
43
|
+
export const SOCKS_DOWN_STOP_MS = 60000
|
|
44
|
+
/** A single probe may not hang the watcher. */
|
|
45
|
+
export const SOCKS_PROBE_TIMEOUT_MS = 3000
|
|
46
|
+
|
|
47
|
+
const defaultDeps = {
|
|
48
|
+
now: () => Date.now(),
|
|
49
|
+
probe: (socks) => probeSocks(socks, { timeoutMs: SOCKS_PROBE_TIMEOUT_MS }),
|
|
50
|
+
startEngine: (cwd) => startProxy(cwd),
|
|
51
|
+
stopEngine: (cwd) => stopProxy(cwd),
|
|
52
|
+
startBridge: (options) => startRedirectors(options),
|
|
53
|
+
stopBridge: (options) => stopRedirector(options),
|
|
54
|
+
readConfig: (cwd) => readProxyConfig(cwd),
|
|
55
|
+
readPid: (cwd) => proxyPid(cwd),
|
|
56
|
+
isAlive: (pid) => pidAlive(pid),
|
|
57
|
+
timers: {
|
|
58
|
+
setTimeout: (fn, ms) => setTimeout(fn, ms),
|
|
59
|
+
clearTimeout: (handle) => clearTimeout(handle),
|
|
60
|
+
},
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** @type {typeof defaultDeps} */
|
|
64
|
+
let deps = { ...defaultDeps }
|
|
65
|
+
|
|
66
|
+
/** The workspace this process is watching, or null when nothing is armed. */
|
|
67
|
+
let watch = null
|
|
68
|
+
/** The single pending timer (one probe loop, never one per call). */
|
|
69
|
+
let timer = null
|
|
70
|
+
let ticking = false
|
|
71
|
+
let listener = null
|
|
72
|
+
let phase = {
|
|
73
|
+
phase: PHASE_STOPPED,
|
|
74
|
+
since: 0,
|
|
75
|
+
owner: 0,
|
|
76
|
+
cwd: '',
|
|
77
|
+
pid: null,
|
|
78
|
+
socksOk: null,
|
|
79
|
+
socksError: '',
|
|
80
|
+
downSince: null,
|
|
81
|
+
waitingSince: null,
|
|
82
|
+
checkedAt: 0,
|
|
83
|
+
reason: '',
|
|
84
|
+
bridge: null,
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Where the shared phase lives. */
|
|
88
|
+
export function proxyStatePath() {
|
|
89
|
+
return join(proxyHomeDir(), PROXY_STATE_FILENAME)
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Raw persisted phase, or null when nothing was ever written.
|
|
94
|
+
* Never throws: a corrupt file must not break the proxy page.
|
|
95
|
+
*/
|
|
96
|
+
export function readProxyServiceState() {
|
|
97
|
+
try {
|
|
98
|
+
const parsed = JSON.parse(readFileSync(proxyStatePath(), 'utf8'))
|
|
99
|
+
if (parsed === null || typeof parsed !== 'object') return null
|
|
100
|
+
if (parsed.phase !== PHASE_RUNNING && parsed.phase !== PHASE_PENDING && parsed.phase !== PHASE_STOPPED) return null
|
|
101
|
+
return parsed
|
|
102
|
+
} catch {
|
|
103
|
+
return null
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function persist() {
|
|
108
|
+
try {
|
|
109
|
+
mkdirSync(dirname(proxyStatePath()), { recursive: true, mode: 0o700 })
|
|
110
|
+
writeFileSync(proxyStatePath(), `${JSON.stringify(phase, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 })
|
|
111
|
+
} catch {
|
|
112
|
+
/* the in-memory phase is still authoritative for this process */
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function snapshotOf() {
|
|
117
|
+
const inMemory = watch !== null
|
|
118
|
+
const source = inMemory ? phase : (readProxyServiceState() ?? phase)
|
|
119
|
+
// In this process the phase is authoritative by definition: the waiter is right
|
|
120
|
+
// here, even if a pid check for our own pid would say whatever it says.
|
|
121
|
+
const ownerAlive = inMemory || (source.owner > 0 ? deps.isAlive(source.owner) === true : false)
|
|
122
|
+
// 待启动 only lives as long as the process doing the waiting.
|
|
123
|
+
const effective = source.phase === PHASE_PENDING && ownerAlive !== true ? PHASE_STOPPED : source.phase
|
|
124
|
+
const waitingSince = typeof source.waitingSince === 'number' ? source.waitingSince : null
|
|
125
|
+
const downSince = typeof source.downSince === 'number' ? source.downSince : null
|
|
126
|
+
return {
|
|
127
|
+
phase: effective,
|
|
128
|
+
since: typeof source.since === 'number' ? source.since : 0,
|
|
129
|
+
cwd: typeof source.cwd === 'string' ? source.cwd : '',
|
|
130
|
+
owner: typeof source.owner === 'number' ? source.owner : 0,
|
|
131
|
+
socksOk: typeof source.socksOk === 'boolean' ? source.socksOk : null,
|
|
132
|
+
socksError: typeof source.socksError === 'string' ? source.socksError : '',
|
|
133
|
+
waitingSince: effective === PHASE_PENDING ? waitingSince : null,
|
|
134
|
+
waitingMs: effective === PHASE_PENDING && waitingSince !== null ? Math.max(0, deps.now() - waitingSince) : 0,
|
|
135
|
+
downSince: effective === PHASE_RUNNING ? downSince : null,
|
|
136
|
+
downMs: effective === PHASE_RUNNING && downSince !== null ? Math.max(0, deps.now() - downSince) : 0,
|
|
137
|
+
stopAfterMs: SOCKS_DOWN_STOP_MS,
|
|
138
|
+
checkedAt: typeof source.checkedAt === 'number' ? source.checkedAt : 0,
|
|
139
|
+
reason: typeof source.reason === 'string' ? source.reason : '',
|
|
140
|
+
bridge: source.bridge ?? null,
|
|
141
|
+
watching: inMemory,
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** Phase + diagnostics for views; safe from any process. */
|
|
146
|
+
export function proxyServiceSnapshot() {
|
|
147
|
+
return snapshotOf()
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function emit() {
|
|
151
|
+
if (listener === null) return
|
|
152
|
+
try {
|
|
153
|
+
listener(snapshotOf())
|
|
154
|
+
} catch {
|
|
155
|
+
/* a broken listener must not stop the probe loop */
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Observe phase transitions (the daemon uses this for idle-exit bookkeeping). */
|
|
160
|
+
export function setProxyPhaseListener(fn) {
|
|
161
|
+
listener = typeof fn === 'function' ? fn : null
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function setPhase(next, patch = {}) {
|
|
165
|
+
const nowMs = deps.now()
|
|
166
|
+
const changed = phase.phase !== next
|
|
167
|
+
phase = Object.assign({}, phase, patch, {
|
|
168
|
+
phase: next,
|
|
169
|
+
owner: process.pid,
|
|
170
|
+
cwd: watch !== null ? watch.cwd : (typeof patch.cwd === 'string' ? patch.cwd : phase.cwd),
|
|
171
|
+
since: changed ? nowMs : phase.since,
|
|
172
|
+
checkedAt: nowMs,
|
|
173
|
+
})
|
|
174
|
+
persist()
|
|
175
|
+
if (changed) emit()
|
|
176
|
+
return phase
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function updatePhase(patch) {
|
|
180
|
+
phase = Object.assign({}, phase, patch, { owner: process.pid, cwd: watch !== null ? watch.cwd : phase.cwd })
|
|
181
|
+
persist()
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function disarm() {
|
|
185
|
+
if (timer !== null) {
|
|
186
|
+
try {
|
|
187
|
+
deps.timers.clearTimeout(timer)
|
|
188
|
+
} catch {
|
|
189
|
+
/* ignore */
|
|
190
|
+
}
|
|
191
|
+
timer = null
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function arm(ms) {
|
|
196
|
+
disarm()
|
|
197
|
+
const handle = deps.timers.setTimeout(() => {
|
|
198
|
+
timer = null
|
|
199
|
+
void tick()
|
|
200
|
+
}, ms)
|
|
201
|
+
timer = handle ?? null
|
|
202
|
+
if (timer !== null && typeof timer.unref === 'function') timer.unref()
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
async function probeOnce(config) {
|
|
206
|
+
try {
|
|
207
|
+
const result = await deps.probe(config.socks)
|
|
208
|
+
return result !== null && typeof result === 'object' ? result : { ok: false, error: '探测没有返回结果' }
|
|
209
|
+
} catch (error) {
|
|
210
|
+
return { ok: false, error: String(error?.message ?? error) }
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
function bridgeSummary(result) {
|
|
215
|
+
if (result === null || typeof result !== 'object') return null
|
|
216
|
+
const started = Array.isArray(result.started) ? result.started : []
|
|
217
|
+
const skipped = Array.isArray(result.skipped) ? result.skipped : []
|
|
218
|
+
return { running: result.running === true, started: started.length, skipped: skipped.length, reason: skipped[0]?.reason ?? '' }
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
async function syncGit(enabled) {
|
|
222
|
+
if (watch === null || typeof watch.syncGit !== 'function') return null
|
|
223
|
+
try {
|
|
224
|
+
return await watch.syncGit({ cwd: watch.cwd, host: watch.gitHost, enabled })
|
|
225
|
+
} catch (error) {
|
|
226
|
+
return { ok: false, error: String(error?.message ?? error) }
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
async function startBridge() {
|
|
231
|
+
const start = watch !== null && typeof watch.startBridge === 'function' ? watch.startBridge : deps.startBridge
|
|
232
|
+
try {
|
|
233
|
+
return await start({ interactive: watch !== null && watch.interactive === true })
|
|
234
|
+
} catch (error) {
|
|
235
|
+
return { started: [], skipped: [{ side: '', reason: String(error?.message ?? error) }], running: false }
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
async function stopBridge() {
|
|
240
|
+
const stop = watch !== null && typeof watch.stopBridge === 'function' ? watch.stopBridge : deps.stopBridge
|
|
241
|
+
try {
|
|
242
|
+
return await stop()
|
|
243
|
+
} catch (error) {
|
|
244
|
+
return { ok: false, error: String(error?.message ?? error) }
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** Spawn engine → bridge → git entry, in that order (a tunnel nobody intercepts). */
|
|
249
|
+
async function launch() {
|
|
250
|
+
const cwd = watch.cwd
|
|
251
|
+
const engine = await deps.startEngine(cwd)
|
|
252
|
+
if (engine === null || typeof engine !== 'object' || engine.ok !== true) {
|
|
253
|
+
setPhase(PHASE_STOPPED, {
|
|
254
|
+
pid: null,
|
|
255
|
+
socksOk: true,
|
|
256
|
+
socksError: '',
|
|
257
|
+
downSince: null,
|
|
258
|
+
waitingSince: null,
|
|
259
|
+
bridge: null,
|
|
260
|
+
reason: engine?.error ?? '代理未能启动',
|
|
261
|
+
})
|
|
262
|
+
disarm()
|
|
263
|
+
watch = null
|
|
264
|
+
emit()
|
|
265
|
+
return { ok: false, phase: PHASE_STOPPED, engine: engine ?? { ok: false }, reason: engine?.error ?? '代理未能启动' }
|
|
266
|
+
}
|
|
267
|
+
const redirector = await startBridge()
|
|
268
|
+
const git = await syncGit(true)
|
|
269
|
+
setPhase(PHASE_RUNNING, {
|
|
270
|
+
pid: typeof engine.pid === 'number' ? engine.pid : null,
|
|
271
|
+
socksOk: true,
|
|
272
|
+
socksError: '',
|
|
273
|
+
downSince: null,
|
|
274
|
+
waitingSince: null,
|
|
275
|
+
bridge: bridgeSummary(redirector),
|
|
276
|
+
reason: '',
|
|
277
|
+
})
|
|
278
|
+
const pendingReason = redirector !== null && redirector.running === false && Array.isArray(redirector.skipped) && redirector.skipped.length > 0
|
|
279
|
+
? '系统层拦截未启动,可在代理页手动启动桥接'
|
|
280
|
+
: ''
|
|
281
|
+
if (pendingReason !== '') updatePhase({ reason: pendingReason })
|
|
282
|
+
arm(RUNNING_PROBE_MS)
|
|
283
|
+
return { ok: true, phase: PHASE_RUNNING, engine, redirector, git }
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/** Stop git entry → bridge → engine (the documented teardown order). */
|
|
287
|
+
async function teardownNetwork() {
|
|
288
|
+
const git = await syncGit(false)
|
|
289
|
+
const redirector = await stopBridge()
|
|
290
|
+
const engine = watch === null ? { ok: true, stopped: false } : await deps.stopEngine(watch.cwd)
|
|
291
|
+
return { engine, redirector, git }
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
async function autoStop(socksError) {
|
|
295
|
+
const wasRunning = phase.phase === PHASE_RUNNING
|
|
296
|
+
const stopped = await teardownNetwork()
|
|
297
|
+
setPhase(PHASE_PENDING, {
|
|
298
|
+
pid: null,
|
|
299
|
+
socksOk: false,
|
|
300
|
+
socksError,
|
|
301
|
+
downSince: null,
|
|
302
|
+
waitingSince: deps.now(),
|
|
303
|
+
bridge: null,
|
|
304
|
+
reason: wasRunning
|
|
305
|
+
? `SOCKS 连续 ${Math.round(SOCKS_DOWN_STOP_MS / 1000)} 秒不通,代理已停止,正在等待恢复`
|
|
306
|
+
: `SOCKS 不通(${socksError}),已进入待启动`,
|
|
307
|
+
})
|
|
308
|
+
arm(WAIT_PROBE_MS)
|
|
309
|
+
return stopped
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/**
|
|
313
|
+
* One probe. Exported so tests drive the state machine without wall-clock waits.
|
|
314
|
+
*/
|
|
315
|
+
export async function proxyLifecycleTick() {
|
|
316
|
+
if (ticking) return snapshotOf()
|
|
317
|
+
if (watch === null) return snapshotOf()
|
|
318
|
+
ticking = true
|
|
319
|
+
try {
|
|
320
|
+
if (phase.phase === PHASE_PENDING) {
|
|
321
|
+
const config = deps.readConfig(watch.cwd)
|
|
322
|
+
const probe = await probeOnce(config)
|
|
323
|
+
updatePhase({ socksOk: probe.ok === true, socksError: probe.ok === true ? '' : (probe.error ?? ''), checkedAt: deps.now() })
|
|
324
|
+
if (probe.ok === true) {
|
|
325
|
+
await launch()
|
|
326
|
+
return snapshotOf()
|
|
327
|
+
}
|
|
328
|
+
arm(WAIT_PROBE_MS)
|
|
329
|
+
return snapshotOf()
|
|
330
|
+
}
|
|
331
|
+
// Running: the engine must still be there, and the upstream must still answer.
|
|
332
|
+
if (deps.readPid(watch.cwd) === null) {
|
|
333
|
+
await syncGit(false)
|
|
334
|
+
await stopBridge()
|
|
335
|
+
setPhase(PHASE_STOPPED, { pid: null, downSince: null, waitingSince: null, bridge: null, reason: '代理引擎已退出,服务已停止' })
|
|
336
|
+
disarm()
|
|
337
|
+
watch = null
|
|
338
|
+
emit()
|
|
339
|
+
return snapshotOf()
|
|
340
|
+
}
|
|
341
|
+
const config = deps.readConfig(watch.cwd)
|
|
342
|
+
const probe = await probeOnce(config)
|
|
343
|
+
if (probe.ok === true) {
|
|
344
|
+
if (phase.downSince !== null) updatePhase({ downSince: null, socksOk: true, socksError: '', checkedAt: deps.now() })
|
|
345
|
+
arm(RUNNING_PROBE_MS)
|
|
346
|
+
return snapshotOf()
|
|
347
|
+
}
|
|
348
|
+
const downSince = typeof phase.downSince === 'number' ? phase.downSince : deps.now()
|
|
349
|
+
updatePhase({ downSince, socksOk: false, socksError: probe.error ?? '', checkedAt: deps.now() })
|
|
350
|
+
if (deps.now() - downSince >= SOCKS_DOWN_STOP_MS) {
|
|
351
|
+
await autoStop(probe.error ?? '')
|
|
352
|
+
return snapshotOf()
|
|
353
|
+
}
|
|
354
|
+
arm(RUNNING_PROBE_MS)
|
|
355
|
+
return snapshotOf()
|
|
356
|
+
} finally {
|
|
357
|
+
ticking = false
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
/**
|
|
362
|
+
* Start the service. Probes SOCKS first; an unreachable upstream parks in
|
|
363
|
+
* `pending` and a watcher retries until it answers.
|
|
364
|
+
*
|
|
365
|
+
* @param options - `{ cwd, gitHost, interactive, syncGit, startBridge, stopBridge }`.
|
|
366
|
+
* `syncGit({ cwd, host, enabled })` is the caller's git wiring (host and daemon
|
|
367
|
+
* own different modules), and the bridge hooks let the daemon serialise them.
|
|
368
|
+
*/
|
|
369
|
+
export async function startProxyService(options = {}) {
|
|
370
|
+
const cwd = typeof options.cwd === 'string' && options.cwd !== '' ? options.cwd : process.cwd()
|
|
371
|
+
watch = {
|
|
372
|
+
cwd,
|
|
373
|
+
gitHost: typeof options.gitHost === 'string' ? options.gitHost : '',
|
|
374
|
+
interactive: options.interactive === true,
|
|
375
|
+
syncGit: typeof options.syncGit === 'function' ? options.syncGit : null,
|
|
376
|
+
startBridge: typeof options.startBridge === 'function' ? options.startBridge : null,
|
|
377
|
+
stopBridge: typeof options.stopBridge === 'function' ? options.stopBridge : null,
|
|
378
|
+
}
|
|
379
|
+
const config = deps.readConfig(cwd)
|
|
380
|
+
const existing = deps.readPid(cwd)
|
|
381
|
+
if (existing !== null) {
|
|
382
|
+
setPhase(PHASE_RUNNING, { pid: existing, reason: '', downSince: null, waitingSince: null })
|
|
383
|
+
arm(RUNNING_PROBE_MS)
|
|
384
|
+
return { ok: true, phase: PHASE_RUNNING, alreadyRunning: true, engine: { ok: true, pid: existing, config }, redirector: null, git: null }
|
|
385
|
+
}
|
|
386
|
+
if (config.socks.host === '' || config.socks.port === 0) {
|
|
387
|
+
// Not a wait: there is nothing to wait FOR. An address the user never set will not
|
|
388
|
+
// appear on its own, so this stays the old hard refusal (the page shows the error
|
|
389
|
+
// next to 保存, where the field lives) instead of a watcher polling forever.
|
|
390
|
+
const error = '未配置上游 SOCKS 地址(.env 的 socks.host / socks.port)'
|
|
391
|
+
setPhase(PHASE_STOPPED, {
|
|
392
|
+
pid: null,
|
|
393
|
+
socksOk: false,
|
|
394
|
+
socksError: error,
|
|
395
|
+
waitingSince: null,
|
|
396
|
+
downSince: null,
|
|
397
|
+
bridge: null,
|
|
398
|
+
reason: error,
|
|
399
|
+
})
|
|
400
|
+
watch = null
|
|
401
|
+
disarm()
|
|
402
|
+
emit()
|
|
403
|
+
return { ok: false, phase: PHASE_STOPPED, error, engine: { ok: false, error, config } }
|
|
404
|
+
}
|
|
405
|
+
const probe = await probeOnce(config)
|
|
406
|
+
if (probe.ok !== true) {
|
|
407
|
+
setPhase(PHASE_PENDING, {
|
|
408
|
+
pid: null,
|
|
409
|
+
socksOk: false,
|
|
410
|
+
socksError: probe.error ?? '',
|
|
411
|
+
waitingSince: deps.now(),
|
|
412
|
+
downSince: null,
|
|
413
|
+
bridge: null,
|
|
414
|
+
reason: `SOCKS ${config.socks.host}:${config.socks.port} 暂时不通,已进入待启动`,
|
|
415
|
+
})
|
|
416
|
+
arm(WAIT_PROBE_MS)
|
|
417
|
+
return {
|
|
418
|
+
ok: true,
|
|
419
|
+
phase: PHASE_PENDING,
|
|
420
|
+
waiting: true,
|
|
421
|
+
reason: `SOCKS ${config.socks.host}:${config.socks.port} 不通(${probe.error ?? '未知原因'}),已进入待启动,连通后会自动启动`,
|
|
422
|
+
engine: { ok: false, config, waitingSocks: true },
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
return await launch()
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
/**
|
|
429
|
+
* Stop the service and cancel any wait. Bridge and git entry follow.
|
|
430
|
+
*/
|
|
431
|
+
export async function stopProxyService(options = {}) {
|
|
432
|
+
const cwd = typeof options.cwd === 'string' && options.cwd !== '' ? options.cwd : (watch !== null ? watch.cwd : process.cwd())
|
|
433
|
+
if (watch === null) {
|
|
434
|
+
watch = {
|
|
435
|
+
cwd,
|
|
436
|
+
gitHost: typeof options.gitHost === 'string' ? options.gitHost : '',
|
|
437
|
+
interactive: false,
|
|
438
|
+
syncGit: typeof options.syncGit === 'function' ? options.syncGit : null,
|
|
439
|
+
startBridge: typeof options.startBridge === 'function' ? options.startBridge : null,
|
|
440
|
+
stopBridge: typeof options.stopBridge === 'function' ? options.stopBridge : null,
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
disarm()
|
|
444
|
+
const stopped = await teardownNetwork()
|
|
445
|
+
watch = null
|
|
446
|
+
const changed = phase.phase !== PHASE_STOPPED
|
|
447
|
+
setPhase(PHASE_STOPPED, { pid: null, socksOk: null, socksError: '', downSince: null, waitingSince: null, bridge: null, reason: '已停止' })
|
|
448
|
+
// setPhase already notifies on a transition; a stop that was already stopped is
|
|
449
|
+
// still worth telling the listener (idle bookkeeping), but only once.
|
|
450
|
+
if (changed !== true) emit()
|
|
451
|
+
return { ok: true, phase: PHASE_STOPPED, engine: stopped.engine, redirector: stopped.redirector, git: stopped.git }
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
/**
|
|
455
|
+
* Drop the wait of a process that is going away: `pending` must not outlive it.
|
|
456
|
+
* Called from the plugin's unload path and the daemon's shutdown.
|
|
457
|
+
*/
|
|
458
|
+
export function releaseProxyLifecycle() {
|
|
459
|
+
disarm()
|
|
460
|
+
const wasPending = phase.phase === PHASE_PENDING
|
|
461
|
+
watch = null
|
|
462
|
+
phase = Object.assign({}, phase, {
|
|
463
|
+
phase: PHASE_STOPPED,
|
|
464
|
+
owner: process.pid,
|
|
465
|
+
since: deps.now(),
|
|
466
|
+
downSince: null,
|
|
467
|
+
waitingSince: null,
|
|
468
|
+
reason: wasPending ? '等待已随进程退出结束' : phase.reason,
|
|
469
|
+
})
|
|
470
|
+
persist()
|
|
471
|
+
if (wasPending) emit()
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
/** Test hook: swap probes/engine/timers, or reset to the real ones. */
|
|
475
|
+
export function configureProxyLifecycle(overrides = {}) {
|
|
476
|
+
deps = Object.assign({}, deps, overrides, {
|
|
477
|
+
timers: Object.assign({}, deps.timers, overrides.timers ?? {}),
|
|
478
|
+
})
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
/** Test hook: forget phase, watcher and timers. */
|
|
482
|
+
export function resetProxyLifecycle() {
|
|
483
|
+
disarm()
|
|
484
|
+
watch = null
|
|
485
|
+
listener = null
|
|
486
|
+
ticking = false
|
|
487
|
+
deps = { ...defaultDeps, timers: { ...defaultDeps.timers } }
|
|
488
|
+
phase = {
|
|
489
|
+
phase: PHASE_STOPPED,
|
|
490
|
+
since: 0,
|
|
491
|
+
owner: 0,
|
|
492
|
+
cwd: '',
|
|
493
|
+
pid: null,
|
|
494
|
+
socksOk: null,
|
|
495
|
+
socksError: '',
|
|
496
|
+
downSince: null,
|
|
497
|
+
waitingSince: null,
|
|
498
|
+
checkedAt: 0,
|
|
499
|
+
reason: '',
|
|
500
|
+
bridge: null,
|
|
501
|
+
}
|
|
502
|
+
}
|
package/lib/proxy.js
CHANGED
|
@@ -1147,6 +1147,56 @@ export function portOpen(port, host = '127.0.0.1') {
|
|
|
1147
1147
|
})
|
|
1148
1148
|
}
|
|
1149
1149
|
|
|
1150
|
+
/**
|
|
1151
|
+
* Is the upstream SOCKS host usable right now?
|
|
1152
|
+
*
|
|
1153
|
+
* A plain TCP connect is not enough: an unrelated service on that port would accept
|
|
1154
|
+
* and then fail every tunnel (the loopback CONNECT proxy itself is exactly such a
|
|
1155
|
+
* service). The probe therefore performs the SOCKS5 greeting (`05 01 00` → `05 00`)
|
|
1156
|
+
* — the same first exchange `connectSocks` needs — and reports what answered: a
|
|
1157
|
+
* version byte other than 5 is "not a SOCKS server", method `0xFF` means the server
|
|
1158
|
+
* wants authentication we cannot supply.
|
|
1159
|
+
*
|
|
1160
|
+
* The engine binds its loopback ports even when the upstream is gone (every tunnel
|
|
1161
|
+
* fails per-connection), which is why the service gates its start on this probe
|
|
1162
|
+
* instead of on the listener being up.
|
|
1163
|
+
*
|
|
1164
|
+
* @param socks - `{ host, port }` from the proxy config.
|
|
1165
|
+
* @param options - `{ timeoutMs }` (default 3000).
|
|
1166
|
+
* @returns `{ ok, host, port, socks, error }` — never throws.
|
|
1167
|
+
*/
|
|
1168
|
+
export function probeSocks(socks, options = {}) {
|
|
1169
|
+
const host = typeof socks?.host === 'string' ? socks.host.trim() : ''
|
|
1170
|
+
const port = Number(socks?.port)
|
|
1171
|
+
if (host === '') return Promise.resolve({ ok: false, host, port: 0, socks: false, error: '上游 SOCKS 主机未配置(.env 的 socks.host)' })
|
|
1172
|
+
if (!Number.isInteger(port) || port <= 0 || port > 65535) return Promise.resolve({ ok: false, host, port: 0, socks: false, error: `上游 SOCKS 端口不合法:${String(socks?.port)}` })
|
|
1173
|
+
const timeout = Number.isInteger(options.timeoutMs) && options.timeoutMs > 0 ? options.timeoutMs : 3000
|
|
1174
|
+
return new Promise((resolvePromise) => {
|
|
1175
|
+
let settled = false
|
|
1176
|
+
let buffer = Buffer.alloc(0)
|
|
1177
|
+
const socket = netConnect({ host, port })
|
|
1178
|
+
const finish = (ok, error, socks5 = true) => {
|
|
1179
|
+
if (settled) return
|
|
1180
|
+
settled = true
|
|
1181
|
+
socket.destroy()
|
|
1182
|
+
resolvePromise({ ok, host, port, socks: socks5, error })
|
|
1183
|
+
}
|
|
1184
|
+
socket.setTimeout(timeout, () => finish(false, `连接超时(${timeout} ms)`, false))
|
|
1185
|
+
socket.once('connect', () => {
|
|
1186
|
+
try { socket.write(Buffer.from([0x05, 0x01, 0x00])) } catch { finish(false, '无法发送 SOCKS5 握手', false) }
|
|
1187
|
+
})
|
|
1188
|
+
socket.on('data', (chunk) => {
|
|
1189
|
+
buffer = Buffer.concat([buffer, chunk])
|
|
1190
|
+
if (buffer.length < 2) return
|
|
1191
|
+
if (buffer[0] !== 0x05) return finish(false, `不是 SOCKS5 服务(版本字节 0x${buffer[0].toString(16)})`, false)
|
|
1192
|
+
if (buffer[1] === 0xff) return finish(false, 'SOCKS5 服务要求认证,当前配置无法通过', true)
|
|
1193
|
+
return finish(true, '')
|
|
1194
|
+
})
|
|
1195
|
+
socket.once('error', (error) => finish(false, String(error?.code ?? error?.message ?? error), false))
|
|
1196
|
+
socket.once('close', () => finish(false, '连接被关闭(SOCKS5 未回应握手)', false))
|
|
1197
|
+
})
|
|
1198
|
+
}
|
|
1199
|
+
|
|
1150
1200
|
/**
|
|
1151
1201
|
* Terminate an engine we ourselves just spawned and that failed to come up.
|
|
1152
1202
|
*
|