dsh-remote 1.2.0 → 1.2.1
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.en.md +10 -2
- package/README.md +10 -2
- package/lib/binding.js +26 -2
- package/lib/boot.js +4 -31
- package/lib/client.js +408 -66
- package/lib/connect-summary.js +52 -0
- package/lib/forwards.js +285 -35
- package/lib/index.js +20 -4615
- package/lib/main.js +4660 -0
- package/lib/openssh.js +59 -8
- package/lib/routes-forwards.js +24 -4
- package/lib/self-heal.js +58 -5
- package/lib/sshconfig.js +6 -0
- package/lib/update.js +95 -33
- package/lib/vendor/jsdiff/SOURCE.md +1 -1
- package/lib/vendor/jsdiff/diff/base.js +1 -1
- package/lib/vendor/jsdiff/diff/line.js +1 -1
- package/lib/vendor/jsdiff/patch/create.js +147 -18
- package/lib/vendor/jsdiff/util/params.js +1 -1
- package/package.json +4 -4
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
// The sentence `rw_connect` prints after it reaches a machine.
|
|
2
|
+
//
|
|
3
|
+
// Two identities are in play, and confusing them is what makes a working
|
|
4
|
+
// connection look broken (issue #51, #153):
|
|
5
|
+
//
|
|
6
|
+
// • the DIAL identity — what the transport was actually told. On the
|
|
7
|
+
// system-OpenSSH backend an ssh-config alias is handed to `ssh` VERBATIM:
|
|
8
|
+
// the plugin emits no `-l`/`-p` (that is precisely what keeps the
|
|
9
|
+
// `Host` block matching), so the dial identity carries no user and the
|
|
10
|
+
// fallback port 22, while the file supplies both.
|
|
11
|
+
// • the MACHINE identity — what `ssh <alias>` really reaches: the HostName,
|
|
12
|
+
// User and Port ~/.ssh/config resolves for that alias.
|
|
13
|
+
//
|
|
14
|
+
// Reporting the dial identity produced "Connected to devbox as ." for a machine
|
|
15
|
+
// that connects perfectly as yangruitao@10.37.111.244. A sentence that reads
|
|
16
|
+
// like a missing username sends the agent — and the person reading it — looking
|
|
17
|
+
// for a configuration error that does not exist. Describe the MACHINE here; the
|
|
18
|
+
// dial identity stays where it belongs, in the audit log of the transport
|
|
19
|
+
// (`connect <dialUser>@<dialHost>:<dialPort>`, which `audit()` keeps).
|
|
20
|
+
//
|
|
21
|
+
// Kept as a pure function so the rule is testable without a live SSH server: an
|
|
22
|
+
// alias connect cannot be faked against the real `ssh` binary in CI (ssh reads
|
|
23
|
+
// the developer's own ~/.ssh/config, not the plugin's reader).
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* @param {object} input
|
|
27
|
+
* @param {string} [input.alias] - the ~/.ssh/config alias the registry stores ('' for a literal machine).
|
|
28
|
+
* @param {boolean} [input.aliasNative] - true when the alias itself was dialed (system-OpenSSH backend).
|
|
29
|
+
* @param {{host?: string, port?: number, username?: string}|null} [input.resolved] - what the file resolves the alias to.
|
|
30
|
+
* @param {string} [input.dialHost] - host the transport was given.
|
|
31
|
+
* @param {string} [input.dialUser] - user the transport was given ('' for an alias-native dial).
|
|
32
|
+
* @param {number} [input.dialPort] - port the transport was given (fallback 22 for an alias-native dial).
|
|
33
|
+
* @param {string[]} [input.warnings] - ~/.ssh/config directives the plugin could not honour.
|
|
34
|
+
* @returns {string} one paragraph: "Connected to <machine> as <user>." plus the alias note.
|
|
35
|
+
*/
|
|
36
|
+
export function describeConnect({ alias = '', aliasNative = false, resolved = null, dialHost = '', dialUser = '', dialPort = 22, warnings = [] } = {}) {
|
|
37
|
+
const name = String(alias || '')
|
|
38
|
+
// The alias is what the user (and `ssh`) calls this machine, so an
|
|
39
|
+
// alias-native dial is reported as the ALIAS, not as the address the file
|
|
40
|
+
// happens to resolve it to today.
|
|
41
|
+
const machineHost = aliasNative && name ? name : String(dialHost || '')
|
|
42
|
+
const user = String((aliasNative && resolved && resolved.username) || (!aliasNative && dialUser) || '')
|
|
43
|
+
const endpoint = {
|
|
44
|
+
host: String((aliasNative && resolved && resolved.host) || dialHost || ''),
|
|
45
|
+
port: Number(aliasNative && resolved && resolved.port) || Number(dialPort) || 22,
|
|
46
|
+
}
|
|
47
|
+
const note = (Array.isArray(warnings) ? warnings : []).filter(Boolean)
|
|
48
|
+
const via = name
|
|
49
|
+
? `\n(ssh-config alias "${name}" → ${user ? user + '@' : ''}${endpoint.host}:${endpoint.port}` + (note.length ? `; ${note.join(' ')}` : '') + ')'
|
|
50
|
+
: ''
|
|
51
|
+
return `Connected to ${machineHost}${user ? ` as ${user}` : ''}.${via}`
|
|
52
|
+
}
|
package/lib/forwards.js
CHANGED
|
@@ -8,9 +8,10 @@
|
|
|
8
8
|
// the remote sshd).
|
|
9
9
|
//
|
|
10
10
|
// Definitions persist in forwards.json; forwards become active only while the
|
|
11
|
-
// SSH connection is up
|
|
12
|
-
//
|
|
13
|
-
//
|
|
11
|
+
// SSH connection is up, and definitions marked autoStart + lastActive are
|
|
12
|
+
// restored when their machine reconnects. Reverse tunnels are restored too,
|
|
13
|
+
// but the UI warns before the flag can be set for one: an auto-restored reverse
|
|
14
|
+
// tunnel re-opens a listening port on the REMOTE without a fresh click.
|
|
14
15
|
import net from 'node:net'
|
|
15
16
|
import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'node:fs'
|
|
16
17
|
import path from 'node:path'
|
|
@@ -18,16 +19,27 @@ import { forwardOutChannel } from './pool.js'
|
|
|
18
19
|
|
|
19
20
|
export class ForwardManager {
|
|
20
21
|
/** @param {object} pool SshPool (needs .connect() returning the ssh2 client).
|
|
21
|
-
* @param {object} [opts] - `file` (persistence)
|
|
22
|
+
* @param {object} [opts] - `file` (persistence), `net` (a `node:net`
|
|
22
23
|
* compatible module, so the listener's connection handler — the path the
|
|
23
24
|
* issue #54 crash travelled — can be driven from a unit test without
|
|
24
|
-
* binding a real port)
|
|
25
|
-
|
|
25
|
+
* binding a real port), and `currentMachine` (returns the id of the
|
|
26
|
+
* machine the pool is connected to; used to scope `autoStart` restores).
|
|
27
|
+
*/
|
|
28
|
+
constructor(pool, { file, net: netModule, currentMachine } = {}) {
|
|
26
29
|
this.pool = pool
|
|
27
30
|
this.net = netModule || net
|
|
28
31
|
this.file = file || null
|
|
29
32
|
this.defs = this._load()
|
|
33
|
+
this._migrateLegacy()
|
|
30
34
|
this.servers = new Map() // id → { server | remoteListen, sockets:Set, client }
|
|
35
|
+
this.starting = new Map() // id → in-flight start promise (see start())
|
|
36
|
+
/** id → attempt counter; bumping it invalidates a late start result. */
|
|
37
|
+
this.startGeneration = new Map()
|
|
38
|
+
/** Bumped whenever the live client changes; a start binds to one client. */
|
|
39
|
+
this.connGeneration = 0
|
|
40
|
+
/** Id of the machine the live client belongs to (null when unknown). */
|
|
41
|
+
this.currentMachine = typeof currentMachine === 'function' ? currentMachine : () => null
|
|
42
|
+
this.connectedMachineId = null
|
|
31
43
|
this.client = null
|
|
32
44
|
this.onTcpip = null
|
|
33
45
|
this.onClose = null
|
|
@@ -43,6 +55,28 @@ export class ForwardManager {
|
|
|
43
55
|
return []
|
|
44
56
|
}
|
|
45
57
|
|
|
58
|
+
/**
|
|
59
|
+
* Upgrade older forwards.json files. Before auto-reconnect persisted a
|
|
60
|
+
* "was running" flag, `autoStart: true` meant "start it on every connect".
|
|
61
|
+
* Silently re-interpreting that as "restore only if it was running" would
|
|
62
|
+
* stop previously-working tunnels without telling anyone — and an old
|
|
63
|
+
* reverse entry never saw the remote-listener warning. Disable both, mark
|
|
64
|
+
* them for re-consent, and let the row badge ask the user to opt in again.
|
|
65
|
+
*/
|
|
66
|
+
_migrateLegacy() {
|
|
67
|
+
let changed = false
|
|
68
|
+
for (const d of this.defs) {
|
|
69
|
+
if (Object.prototype.hasOwnProperty.call(d, 'lastActive')) continue
|
|
70
|
+
changed = true
|
|
71
|
+
d.lastActive = false
|
|
72
|
+
if (d.autoStart) {
|
|
73
|
+
d.autoStart = false
|
|
74
|
+
d.needsReconsent = true
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
if (changed) this._save()
|
|
78
|
+
}
|
|
79
|
+
|
|
46
80
|
_save() {
|
|
47
81
|
if (!this.file) return
|
|
48
82
|
try {
|
|
@@ -51,28 +85,85 @@ export class ForwardManager {
|
|
|
51
85
|
} catch {}
|
|
52
86
|
}
|
|
53
87
|
|
|
54
|
-
/**
|
|
55
|
-
|
|
88
|
+
/**
|
|
89
|
+
* Called by the pool after a successful connect: restore the tunnels that
|
|
90
|
+
* were already running the last time this machine was connected.
|
|
91
|
+
*
|
|
92
|
+
* `autoStart` is labelled 自动重连 — RESTORE, not "start every checked
|
|
93
|
+
* definition on any connect". The old loop started them all, so on a fresh
|
|
94
|
+
* session clicking one forward established the connection and silently lit
|
|
95
|
+
* up every other autoStart row; and because it ignored `machineId`, a
|
|
96
|
+
* connection to machine B could even start machine A's forwards through B.
|
|
97
|
+
*
|
|
98
|
+
* The flag that remembers "was running" is `lastActive`, persisted in
|
|
99
|
+
* forwards.json, so the restore also survives a dsh-web restart. The plugin's
|
|
100
|
+
* boot-time reconnect of the current machine (index.js) is what makes that
|
|
101
|
+
* happen without the user clicking anything.
|
|
102
|
+
*
|
|
103
|
+
* @param {object} client - the live ssh2 client / OpenSshConnection.
|
|
104
|
+
* @param {string} [machineId] - machine the client belongs to; defaults to
|
|
105
|
+
* the manager's `currentMachine()` provider.
|
|
106
|
+
*/
|
|
107
|
+
attach(client, machineId) {
|
|
56
108
|
if (this.client === client) return
|
|
109
|
+
const mid = machineId !== undefined ? (machineId || null) : (this.currentMachine() || null)
|
|
110
|
+
this.connGeneration += 1
|
|
57
111
|
this.client = client
|
|
112
|
+
this.connectedMachineId = mid
|
|
58
113
|
this.onTcpip = (info, accept, reject) => this._handleTcpip(info, accept, reject)
|
|
59
114
|
client.on('tcpip', this.onTcpip)
|
|
60
|
-
|
|
115
|
+
// A socket can die WITHOUT the pool calling detach() first (network drop,
|
|
116
|
+
// keepalive timeout): drop the dead handle so the next start() attaches the
|
|
117
|
+
// NEW client instead of reusing this one. `lastActive` already persisted,
|
|
118
|
+
// so the next attach() still knows what to restore.
|
|
119
|
+
this.onClose = () => {
|
|
120
|
+
this._cancelAllStarts()
|
|
121
|
+
this.stopAll()
|
|
122
|
+
this.connGeneration += 1
|
|
123
|
+
this.client = null
|
|
124
|
+
this.connectedMachineId = null
|
|
125
|
+
this.onTcpip = null
|
|
126
|
+
this.onClose = null
|
|
127
|
+
}
|
|
61
128
|
client.on('close', this.onClose)
|
|
129
|
+
// Unknown identity is fail-closed: a null provider must never match a
|
|
130
|
+
// definition whose machineId is also null (that would restore machine A's
|
|
131
|
+
// tunnel after an ephemeral switch to B).
|
|
132
|
+
if (mid == null) return
|
|
62
133
|
for (const d of this.defs) {
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
134
|
+
// Both directions: a reverse tunnel is only restored when the user
|
|
135
|
+
// explicitly set autoStart (the UI shows the remote-listener warning
|
|
136
|
+
// before that flag can be enabled), plus it was running lastActive.
|
|
137
|
+
if (!d.autoStart || !d.lastActive) continue
|
|
138
|
+
if (!d.machineId || d.machineId !== mid || this.servers.has(d.id)) continue
|
|
139
|
+
this.start(d).catch(() => {})
|
|
66
140
|
}
|
|
67
141
|
}
|
|
68
142
|
|
|
143
|
+
/** Persist "this forward was running" so a later attach() (or a restart) can restore it. */
|
|
144
|
+
_setLastActive(d, value) {
|
|
145
|
+
if (!d || d.lastActive === value) return
|
|
146
|
+
d.lastActive = value
|
|
147
|
+
this._save()
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** True when the given/current machine has a persisted forward to restore on connect. */
|
|
151
|
+
hasPendingRestore(machineId) {
|
|
152
|
+
const mid = machineId !== undefined ? (machineId || null) : (this.currentMachine() || null)
|
|
153
|
+
if (mid == null) return false
|
|
154
|
+
return this.defs.some((d) => d.autoStart && d.lastActive && d.machineId && d.machineId === mid)
|
|
155
|
+
}
|
|
156
|
+
|
|
69
157
|
detach() {
|
|
158
|
+
this._cancelAllStarts()
|
|
70
159
|
this.stopAll()
|
|
160
|
+
this.connGeneration += 1
|
|
71
161
|
if (this.client) {
|
|
72
162
|
if (this.onTcpip) this.client.removeListener('tcpip', this.onTcpip)
|
|
73
163
|
if (this.onClose) this.client.removeListener('close', this.onClose)
|
|
74
164
|
}
|
|
75
165
|
this.client = null
|
|
166
|
+
this.connectedMachineId = null
|
|
76
167
|
this.onTcpip = null
|
|
77
168
|
this.onClose = null
|
|
78
169
|
}
|
|
@@ -86,6 +177,8 @@ export class ForwardManager {
|
|
|
86
177
|
targetPort: d.targetPort,
|
|
87
178
|
machineId: d.machineId || null,
|
|
88
179
|
autoStart: !!d.autoStart,
|
|
180
|
+
lastActive: !!d.lastActive,
|
|
181
|
+
needsReconsent: !!d.needsReconsent,
|
|
89
182
|
active: this.servers.has(d.id),
|
|
90
183
|
}))
|
|
91
184
|
}
|
|
@@ -103,6 +196,9 @@ export class ForwardManager {
|
|
|
103
196
|
targetHost: String(targetHost || '127.0.0.1'),
|
|
104
197
|
targetPort: Number(targetPort),
|
|
105
198
|
autoStart: !!autoStart,
|
|
199
|
+
// Persisted across process restarts: attach() restores autoStart defs
|
|
200
|
+
// that were running the last time their machine was connected.
|
|
201
|
+
lastActive: false,
|
|
106
202
|
machineId: machineId || null,
|
|
107
203
|
}
|
|
108
204
|
this.defs.push(d)
|
|
@@ -110,32 +206,150 @@ export class ForwardManager {
|
|
|
110
206
|
return d
|
|
111
207
|
}
|
|
112
208
|
|
|
209
|
+
/**
|
|
210
|
+
* Patch an existing definition's mutable fields and persist it. Today that is
|
|
211
|
+
* just `autoStart` (the 自动重连 checkbox in the list). It does NOT start or
|
|
212
|
+
* stop the tunnel: the flag only decides whether a RUNNING forward is
|
|
213
|
+
* restored after its machine's connection drops.
|
|
214
|
+
*
|
|
215
|
+
* @param {string} id
|
|
216
|
+
* @param {{autoStart?: boolean}} patch
|
|
217
|
+
* @returns {object|null} the updated definition, or null when the id is unknown.
|
|
218
|
+
*/
|
|
219
|
+
update(id, { autoStart } = {}) {
|
|
220
|
+
const d = this.defs.find((x) => x.id === id)
|
|
221
|
+
if (!d) return null
|
|
222
|
+
if (typeof autoStart === 'boolean') {
|
|
223
|
+
d.autoStart = autoStart
|
|
224
|
+
delete d.needsReconsent
|
|
225
|
+
}
|
|
226
|
+
this._save()
|
|
227
|
+
return d
|
|
228
|
+
}
|
|
229
|
+
|
|
113
230
|
remove(id) {
|
|
114
|
-
this.
|
|
231
|
+
this._bumpStart(id)
|
|
232
|
+
this._teardown(id)
|
|
115
233
|
const i = this.defs.findIndex((d) => d.id === id)
|
|
116
234
|
if (i >= 0) { this.defs.splice(i, 1); this._save(); return true }
|
|
117
235
|
return false
|
|
118
236
|
}
|
|
119
237
|
|
|
120
|
-
|
|
238
|
+
/**
|
|
239
|
+
* Start one forward.
|
|
240
|
+
*
|
|
241
|
+
* Concurrent callers share ONE attempt. That is not a nicety: `attach()`
|
|
242
|
+
* restarts autoStart definitions from inside `pool.connect()`, so a manual
|
|
243
|
+
* "启动" on such a forward used to race its own auto-start pass for the same
|
|
244
|
+
* listen port. The auto pass bound the port, the manual call reported
|
|
245
|
+
* EADDRINUSE, and the UI — which only refreshes on success — left the row on
|
|
246
|
+
* 启动 although the tunnel was up (the second click then short-circuited on
|
|
247
|
+
* `servers.has` and looked like the fix). One attempt per definition removes
|
|
248
|
+
* the race at the source.
|
|
249
|
+
*
|
|
250
|
+
* @param {object} def - a definition or a `list()` row (same `id`).
|
|
251
|
+
* @returns {Promise<{ok: boolean, active?: boolean, error?: string}>}
|
|
252
|
+
*/
|
|
253
|
+
/** Invalidate any in-flight attempt for `id` (Stop/Remove/Detach/Disconnect). */
|
|
254
|
+
_bumpStart(id) {
|
|
255
|
+
const next = (this.startGeneration.get(id) || 0) + 1
|
|
256
|
+
this.startGeneration.set(id, next)
|
|
257
|
+
this.starting.delete(id)
|
|
258
|
+
return next
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
_cancelAllStarts() {
|
|
262
|
+
for (const d of this.defs) this._bumpStart(d.id)
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
_isAttemptCurrent(d, seq) {
|
|
266
|
+
return this.startGeneration.get(d.id) === seq && this.defs.includes(d)
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
start(def) {
|
|
121
270
|
const d = this.defs.find((x) => x.id === def.id) || def
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
271
|
+
// Manual start must respect identity too: starting A's forward while an
|
|
272
|
+
// ephemeral B is connected would tunnel through B. Unknown identity is
|
|
273
|
+
// fail-closed; definitions without a machineId stay startable (legacy).
|
|
274
|
+
// While attached, trust the identity the client was attached with (an
|
|
275
|
+
// explicit attach() argument is more precise than the provider); with no
|
|
276
|
+
// client, fall back to the applied identity. Either way unknown is
|
|
277
|
+
// fail-closed for definitions that carry a machineId.
|
|
278
|
+
const mid = this.client ? this.connectedMachineId : this.currentMachine()
|
|
279
|
+
if (d.machineId && (mid == null || d.machineId !== mid)) {
|
|
280
|
+
return Promise.resolve({ ok: false, error: '该转发属于另一台机器(或当前机器身份未知),请先切换到对应机器' })
|
|
281
|
+
}
|
|
282
|
+
const existing = this.servers.get(d.id)
|
|
283
|
+
if (existing) {
|
|
284
|
+
if (!this.client || existing.client === this.client) return Promise.resolve({ ok: true, active: true })
|
|
285
|
+
// The entry belongs to an old/dead client: never report it as healthy.
|
|
286
|
+
this._teardown(d.id)
|
|
128
287
|
}
|
|
288
|
+
const inflight = this.starting.get(d.id)
|
|
289
|
+
if (inflight) return inflight
|
|
290
|
+
const seq = this._bumpStart(d.id)
|
|
291
|
+
// Publish the shared attempt BEFORE running it: pool.connect() may call
|
|
292
|
+
// attach() synchronously (fake pools, and the OpenSSH backend's onReady),
|
|
293
|
+
// and attach()'s restore pass calls start() again. Without a placeholder in
|
|
294
|
+
// the map that nested call bumps the generation and cancels the outer one.
|
|
295
|
+
let resolveAttempt
|
|
296
|
+
const attempt = new Promise((resolve) => { resolveAttempt = resolve })
|
|
297
|
+
this.starting.set(d.id, attempt)
|
|
298
|
+
this._startOnce(d, seq).then(
|
|
299
|
+
(r) => {
|
|
300
|
+
if (r && r.ok && this._isAttemptCurrent(d, seq)) this._setLastActive(d, true)
|
|
301
|
+
resolveAttempt(r)
|
|
302
|
+
},
|
|
303
|
+
(err) => resolveAttempt({ ok: false, error: String((err && err.message) || err) }),
|
|
304
|
+
).finally(() => {
|
|
305
|
+
if (this.starting.get(d.id) === attempt) this.starting.delete(d.id)
|
|
306
|
+
})
|
|
307
|
+
return attempt
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/** The body of one start attempt; see start() for the concurrency contract. */
|
|
311
|
+
async _startOnce(d, seq) {
|
|
312
|
+
let client
|
|
129
313
|
try {
|
|
130
|
-
|
|
131
|
-
await this._startReverse(d, client)
|
|
132
|
-
} else {
|
|
133
|
-
await this._startLocal(d, client)
|
|
134
|
-
}
|
|
135
|
-
return { ok: true, active: true }
|
|
314
|
+
client = await this.pool.connect()
|
|
136
315
|
} catch (err) {
|
|
137
316
|
return { ok: false, error: String((err && err.message) || err) }
|
|
138
317
|
}
|
|
318
|
+
// No resource has been created yet. In particular, do NOT teardown by id:
|
|
319
|
+
// a newer attempt may already own the registered listener.
|
|
320
|
+
if (!this._isAttemptCurrent(d, seq)) return { ok: false, error: '已取消' }
|
|
321
|
+
if (this.client && this.client !== client) return { ok: false, error: '启动期间连接已变化' }
|
|
322
|
+
if (!this.client) this.attach(client)
|
|
323
|
+
if (this.client !== client) return { ok: false, error: '启动期间连接已变化' }
|
|
324
|
+
const connSeq = this.connGeneration
|
|
325
|
+
let entry
|
|
326
|
+
try {
|
|
327
|
+
// Resource creation and registration are deliberately separate. Each
|
|
328
|
+
// attempt gets its own entry, so a late stale callback cannot delete a
|
|
329
|
+
// newer attempt's listener merely because both share the definition id.
|
|
330
|
+
entry = d.direction === 'reverse'
|
|
331
|
+
? await this._startReverse(d, client)
|
|
332
|
+
: await this._startLocal(d, client)
|
|
333
|
+
} catch (err) {
|
|
334
|
+
// A late error from an obsolete attempt is just its own cancellation;
|
|
335
|
+
// it must never tear down a listener installed by a newer attempt.
|
|
336
|
+
if (!this._isAttemptCurrent(d, seq)) return { ok: false, error: '已取消' }
|
|
337
|
+
// A concurrent starter may have won the port between our last check and
|
|
338
|
+
// the bind (attach() starts autoStart defs inside pool.connect()). Only
|
|
339
|
+
// trust that when the same live client/connection owns it.
|
|
340
|
+
if (this.servers.has(d.id) && this.client === client && this.connGeneration === connSeq) {
|
|
341
|
+
return { ok: true, active: true }
|
|
342
|
+
}
|
|
343
|
+
return { ok: false, error: String((err && err.message) || err) }
|
|
344
|
+
}
|
|
345
|
+
if (!this._isAttemptCurrent(d, seq) || this.connGeneration !== connSeq || this.client !== client) {
|
|
346
|
+
// Stop/Remove/disconnect won the race while listen()/forwardIn() was in
|
|
347
|
+
// flight: close ONLY this attempt's late entry, never the current one.
|
|
348
|
+
this._teardownEntry(d, entry)
|
|
349
|
+
return { ok: false, error: this._isAttemptCurrent(d, seq) ? '启动期间连接已变化' : '已取消' }
|
|
350
|
+
}
|
|
351
|
+
this.servers.set(d.id, entry)
|
|
352
|
+
return { ok: true, active: true }
|
|
139
353
|
}
|
|
140
354
|
|
|
141
355
|
_startLocal(d, client) {
|
|
@@ -165,8 +379,7 @@ export class ForwardManager {
|
|
|
165
379
|
})
|
|
166
380
|
server.on('error', (e) => reject(new Error(`本地转发 ${d.listenPort} 启动失败: ${e.message}`)))
|
|
167
381
|
server.listen(d.listenPort, '127.0.0.1', () => {
|
|
168
|
-
|
|
169
|
-
resolve()
|
|
382
|
+
resolve({ kind: 'local', server, sockets: new Set(), client })
|
|
170
383
|
})
|
|
171
384
|
})
|
|
172
385
|
}
|
|
@@ -183,7 +396,16 @@ export class ForwardManager {
|
|
|
183
396
|
targetHost: d.targetHost,
|
|
184
397
|
targetPort: d.targetPort,
|
|
185
398
|
}).then((handle) => {
|
|
186
|
-
|
|
399
|
+
const entry = { kind: 'reverse-cli', handle, client }
|
|
400
|
+
// The `ssh -R` child can die on its own (remote sshd restarts, network
|
|
401
|
+
// drop). Drop only the entry that still belongs to this handle.
|
|
402
|
+
const child = handle && handle.child
|
|
403
|
+
if (child && typeof child.on === 'function') {
|
|
404
|
+
child.once('close', () => {
|
|
405
|
+
if (this.servers.get(d.id) === entry) this.servers.delete(d.id)
|
|
406
|
+
})
|
|
407
|
+
}
|
|
408
|
+
return entry
|
|
187
409
|
}).catch((err) => {
|
|
188
410
|
throw new Error(`远端监听 ${d.listenPort} 失败: ${(err && err.message) || err}`)
|
|
189
411
|
})
|
|
@@ -196,8 +418,7 @@ export class ForwardManager {
|
|
|
196
418
|
}
|
|
197
419
|
client.forwardIn('127.0.0.1', d.listenPort, (err) => {
|
|
198
420
|
if (err) return reject(new Error(`远端监听 ${d.listenPort} 失败: ${(err && err.message) || err}`))
|
|
199
|
-
|
|
200
|
-
resolve()
|
|
421
|
+
resolve({ kind: 'reverse', sockets: new Set(), client })
|
|
201
422
|
})
|
|
202
423
|
})
|
|
203
424
|
}
|
|
@@ -234,8 +455,31 @@ export class ForwardManager {
|
|
|
234
455
|
return { listenPort: 0, targetHost: '127.0.0.1', targetPort: 0 }
|
|
235
456
|
}
|
|
236
457
|
|
|
237
|
-
|
|
458
|
+
/**
|
|
459
|
+
* Stop one listener. `forget` is for the user-initiated stop in the route:
|
|
460
|
+
* it clears the persisted `lastActive`, so 自动重连 will not bring the tunnel
|
|
461
|
+
* back on the next connect. Teardown paths (stopAll/detach/remove) call it
|
|
462
|
+
* without `forget` — a dropped connection is exactly what must be restored.
|
|
463
|
+
*/
|
|
464
|
+
stop(id, { forget = false } = {}) {
|
|
465
|
+
this._bumpStart(id)
|
|
466
|
+
if (forget) this._setLastActive(this.defs.find((x) => x.id === id), false)
|
|
467
|
+
this._teardown(id)
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
/** Close one registered listener/handle. Does not touch lastActive or attempts. */
|
|
471
|
+
_teardown(id) {
|
|
238
472
|
const entry = this.servers.get(id)
|
|
473
|
+
if (!entry) return
|
|
474
|
+
this._teardownEntry(this.defs.find((d) => d.id === id) || this._defFor(entry), entry)
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
/**
|
|
478
|
+
* Close a specific attempt's entry. Removing it from `servers` is conditional
|
|
479
|
+
* on identity: a stale attempt may close its own unregistered resource, but
|
|
480
|
+
* it can never delete a newer attempt's entry with the same definition id.
|
|
481
|
+
*/
|
|
482
|
+
_teardownEntry(d, entry) {
|
|
239
483
|
if (!entry) return
|
|
240
484
|
try {
|
|
241
485
|
if (entry.kind === 'local') {
|
|
@@ -245,11 +489,17 @@ export class ForwardManager {
|
|
|
245
489
|
// The `ssh -R` child IS the tunnel: killing it closes the remote listener.
|
|
246
490
|
if (entry.handle && typeof entry.handle.close === 'function') entry.handle.close()
|
|
247
491
|
} else if (entry.client && typeof entry.client.unforwardIn === 'function') {
|
|
248
|
-
const
|
|
249
|
-
|
|
492
|
+
const current = this.servers.get(d.id)
|
|
493
|
+
// ssh2 unforwardIn is keyed by client + port, NOT by our entry. If a
|
|
494
|
+
// newer attempt already owns that same remote listener on this client,
|
|
495
|
+
// a stale attempt must not close it. Normal Stop sees current===entry
|
|
496
|
+
// and still unforwards; with no replacement, stale cleanup can proceed.
|
|
497
|
+
if (!current || current === entry || current.client !== entry.client) {
|
|
498
|
+
entry.client.unforwardIn('127.0.0.1', d.listenPort, () => {})
|
|
499
|
+
}
|
|
250
500
|
}
|
|
251
501
|
} catch {}
|
|
252
|
-
this.servers.delete(id)
|
|
502
|
+
if (this.servers.get(d.id) === entry) this.servers.delete(d.id)
|
|
253
503
|
}
|
|
254
504
|
|
|
255
505
|
stopAll() {
|