dsh-remote 1.2.0 → 1.3.0

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.
@@ -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 (auto-restart on connect when `autoStart: true`), and
12
- // every tunnel is torn down when the pool disconnects — reverse tunnels are
13
- // never auto-restarted (they would re-expose a local port without asking).
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) and `net` (a `node:net`
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
- constructor(pool, { file, net: netModule } = {}) {
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
- /** Called by the pool after a successful connect: restore autoStart tunnels. */
55
- attach(client) {
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
- this.onClose = () => this.stopAll()
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
- if (d.autoStart && d.direction === 'local' && !this.servers.has(d.id)) {
64
- this.start(d).catch(() => {})
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,162 @@ export class ForwardManager {
110
206
  return d
111
207
  }
112
208
 
209
+ /**
210
+ * Patch an existing definition's mutable fields and persist it.
211
+ *
212
+ * Two callers share this: the row's 自动重连 checkbox patches only
213
+ * `autoStart`; the edit form sends the whole definition (direction, ports,
214
+ * target host, owning machine). Fields that are absent stay untouched — the
215
+ * route validates them first, so a typo never reaches this merge.
216
+ *
217
+ * It does NOT start or stop the tunnel. Changing a BIND of a running forward
218
+ * is refused by the route (the live socket would keep the old bind); toggling
219
+ * `autoStart` on a running forward is fine.
220
+ *
221
+ * @param {string} id
222
+ * @param {{autoStart?: boolean, direction?: 'local'|'reverse', listenPort?: number,
223
+ * targetHost?: string, targetPort?: number, machineId?: string|null}} patch
224
+ * @returns {object|null} the updated definition, or null when the id is unknown.
225
+ */
226
+ update(id, { autoStart, direction, listenPort, targetHost, targetPort, machineId } = {}) {
227
+ const d = this.defs.find((x) => x.id === id)
228
+ if (!d) return null
229
+ if (typeof autoStart === 'boolean') {
230
+ d.autoStart = autoStart
231
+ delete d.needsReconsent
232
+ }
233
+ if (direction === 'local' || direction === 'reverse') d.direction = direction
234
+ if (Number.isInteger(listenPort)) d.listenPort = listenPort
235
+ if (typeof targetHost === 'string' && targetHost) d.targetHost = targetHost
236
+ if (Number.isInteger(targetPort)) d.targetPort = targetPort
237
+ if (machineId !== undefined) d.machineId = machineId || null
238
+ this._save()
239
+ return d
240
+ }
241
+
113
242
  remove(id) {
114
- this.stop(id)
243
+ this._bumpStart(id)
244
+ this._teardown(id)
115
245
  const i = this.defs.findIndex((d) => d.id === id)
116
246
  if (i >= 0) { this.defs.splice(i, 1); this._save(); return true }
117
247
  return false
118
248
  }
119
249
 
120
- async start(def) {
250
+ /**
251
+ * Start one forward.
252
+ *
253
+ * Concurrent callers share ONE attempt. That is not a nicety: `attach()`
254
+ * restarts autoStart definitions from inside `pool.connect()`, so a manual
255
+ * "启动" on such a forward used to race its own auto-start pass for the same
256
+ * listen port. The auto pass bound the port, the manual call reported
257
+ * EADDRINUSE, and the UI — which only refreshes on success — left the row on
258
+ * 启动 although the tunnel was up (the second click then short-circuited on
259
+ * `servers.has` and looked like the fix). One attempt per definition removes
260
+ * the race at the source.
261
+ *
262
+ * @param {object} def - a definition or a `list()` row (same `id`).
263
+ * @returns {Promise<{ok: boolean, active?: boolean, error?: string}>}
264
+ */
265
+ /** Invalidate any in-flight attempt for `id` (Stop/Remove/Detach/Disconnect). */
266
+ _bumpStart(id) {
267
+ const next = (this.startGeneration.get(id) || 0) + 1
268
+ this.startGeneration.set(id, next)
269
+ this.starting.delete(id)
270
+ return next
271
+ }
272
+
273
+ _cancelAllStarts() {
274
+ for (const d of this.defs) this._bumpStart(d.id)
275
+ }
276
+
277
+ _isAttemptCurrent(d, seq) {
278
+ return this.startGeneration.get(d.id) === seq && this.defs.includes(d)
279
+ }
280
+
281
+ start(def) {
121
282
  const d = this.defs.find((x) => x.id === def.id) || def
122
- if (this.servers.has(d.id)) return { ok: true, active: true }
123
- let client = await this.pool.connect()
124
- if (!this.client) this.attach(client)
125
- if (this.client !== client) {
126
- // The pool reconnected while we were connecting — retry on the live client.
127
- client = this.client
283
+ // Manual start must respect identity too: starting A's forward while an
284
+ // ephemeral B is connected would tunnel through B. Unknown identity is
285
+ // fail-closed; definitions without a machineId stay startable (legacy).
286
+ // While attached, trust the identity the client was attached with (an
287
+ // explicit attach() argument is more precise than the provider); with no
288
+ // client, fall back to the applied identity. Either way unknown is
289
+ // fail-closed for definitions that carry a machineId.
290
+ const mid = this.client ? this.connectedMachineId : this.currentMachine()
291
+ if (d.machineId && (mid == null || d.machineId !== mid)) {
292
+ return Promise.resolve({ ok: false, error: '该转发属于另一台机器(或当前机器身份未知),请先切换到对应机器' })
293
+ }
294
+ const existing = this.servers.get(d.id)
295
+ if (existing) {
296
+ if (!this.client || existing.client === this.client) return Promise.resolve({ ok: true, active: true })
297
+ // The entry belongs to an old/dead client: never report it as healthy.
298
+ this._teardown(d.id)
128
299
  }
300
+ const inflight = this.starting.get(d.id)
301
+ if (inflight) return inflight
302
+ const seq = this._bumpStart(d.id)
303
+ // Publish the shared attempt BEFORE running it: pool.connect() may call
304
+ // attach() synchronously (fake pools, and the OpenSSH backend's onReady),
305
+ // and attach()'s restore pass calls start() again. Without a placeholder in
306
+ // the map that nested call bumps the generation and cancels the outer one.
307
+ let resolveAttempt
308
+ const attempt = new Promise((resolve) => { resolveAttempt = resolve })
309
+ this.starting.set(d.id, attempt)
310
+ this._startOnce(d, seq).then(
311
+ (r) => {
312
+ if (r && r.ok && this._isAttemptCurrent(d, seq)) this._setLastActive(d, true)
313
+ resolveAttempt(r)
314
+ },
315
+ (err) => resolveAttempt({ ok: false, error: String((err && err.message) || err) }),
316
+ ).finally(() => {
317
+ if (this.starting.get(d.id) === attempt) this.starting.delete(d.id)
318
+ })
319
+ return attempt
320
+ }
321
+
322
+ /** The body of one start attempt; see start() for the concurrency contract. */
323
+ async _startOnce(d, seq) {
324
+ let client
129
325
  try {
130
- if (d.direction === 'reverse') {
131
- await this._startReverse(d, client)
132
- } else {
133
- await this._startLocal(d, client)
134
- }
135
- return { ok: true, active: true }
326
+ client = await this.pool.connect()
136
327
  } catch (err) {
137
328
  return { ok: false, error: String((err && err.message) || err) }
138
329
  }
330
+ // No resource has been created yet. In particular, do NOT teardown by id:
331
+ // a newer attempt may already own the registered listener.
332
+ if (!this._isAttemptCurrent(d, seq)) return { ok: false, error: '已取消' }
333
+ if (this.client && this.client !== client) return { ok: false, error: '启动期间连接已变化' }
334
+ if (!this.client) this.attach(client)
335
+ if (this.client !== client) return { ok: false, error: '启动期间连接已变化' }
336
+ const connSeq = this.connGeneration
337
+ let entry
338
+ try {
339
+ // Resource creation and registration are deliberately separate. Each
340
+ // attempt gets its own entry, so a late stale callback cannot delete a
341
+ // newer attempt's listener merely because both share the definition id.
342
+ entry = d.direction === 'reverse'
343
+ ? await this._startReverse(d, client)
344
+ : await this._startLocal(d, client)
345
+ } catch (err) {
346
+ // A late error from an obsolete attempt is just its own cancellation;
347
+ // it must never tear down a listener installed by a newer attempt.
348
+ if (!this._isAttemptCurrent(d, seq)) return { ok: false, error: '已取消' }
349
+ // A concurrent starter may have won the port between our last check and
350
+ // the bind (attach() starts autoStart defs inside pool.connect()). Only
351
+ // trust that when the same live client/connection owns it.
352
+ if (this.servers.has(d.id) && this.client === client && this.connGeneration === connSeq) {
353
+ return { ok: true, active: true }
354
+ }
355
+ return { ok: false, error: String((err && err.message) || err) }
356
+ }
357
+ if (!this._isAttemptCurrent(d, seq) || this.connGeneration !== connSeq || this.client !== client) {
358
+ // Stop/Remove/disconnect won the race while listen()/forwardIn() was in
359
+ // flight: close ONLY this attempt's late entry, never the current one.
360
+ this._teardownEntry(d, entry)
361
+ return { ok: false, error: this._isAttemptCurrent(d, seq) ? '启动期间连接已变化' : '已取消' }
362
+ }
363
+ this.servers.set(d.id, entry)
364
+ return { ok: true, active: true }
139
365
  }
140
366
 
141
367
  _startLocal(d, client) {
@@ -165,8 +391,7 @@ export class ForwardManager {
165
391
  })
166
392
  server.on('error', (e) => reject(new Error(`本地转发 ${d.listenPort} 启动失败: ${e.message}`)))
167
393
  server.listen(d.listenPort, '127.0.0.1', () => {
168
- this.servers.set(d.id, { kind: 'local', server, sockets: new Set(), client })
169
- resolve()
394
+ resolve({ kind: 'local', server, sockets: new Set(), client })
170
395
  })
171
396
  })
172
397
  }
@@ -183,7 +408,16 @@ export class ForwardManager {
183
408
  targetHost: d.targetHost,
184
409
  targetPort: d.targetPort,
185
410
  }).then((handle) => {
186
- this.servers.set(d.id, { kind: 'reverse-cli', handle, client })
411
+ const entry = { kind: 'reverse-cli', handle, client }
412
+ // The `ssh -R` child can die on its own (remote sshd restarts, network
413
+ // drop). Drop only the entry that still belongs to this handle.
414
+ const child = handle && handle.child
415
+ if (child && typeof child.on === 'function') {
416
+ child.once('close', () => {
417
+ if (this.servers.get(d.id) === entry) this.servers.delete(d.id)
418
+ })
419
+ }
420
+ return entry
187
421
  }).catch((err) => {
188
422
  throw new Error(`远端监听 ${d.listenPort} 失败: ${(err && err.message) || err}`)
189
423
  })
@@ -196,8 +430,7 @@ export class ForwardManager {
196
430
  }
197
431
  client.forwardIn('127.0.0.1', d.listenPort, (err) => {
198
432
  if (err) return reject(new Error(`远端监听 ${d.listenPort} 失败: ${(err && err.message) || err}`))
199
- this.servers.set(d.id, { kind: 'reverse', sockets: new Set(), client })
200
- resolve()
433
+ resolve({ kind: 'reverse', sockets: new Set(), client })
201
434
  })
202
435
  })
203
436
  }
@@ -234,8 +467,31 @@ export class ForwardManager {
234
467
  return { listenPort: 0, targetHost: '127.0.0.1', targetPort: 0 }
235
468
  }
236
469
 
237
- stop(id) {
470
+ /**
471
+ * Stop one listener. `forget` is for the user-initiated stop in the route:
472
+ * it clears the persisted `lastActive`, so 自动重连 will not bring the tunnel
473
+ * back on the next connect. Teardown paths (stopAll/detach/remove) call it
474
+ * without `forget` — a dropped connection is exactly what must be restored.
475
+ */
476
+ stop(id, { forget = false } = {}) {
477
+ this._bumpStart(id)
478
+ if (forget) this._setLastActive(this.defs.find((x) => x.id === id), false)
479
+ this._teardown(id)
480
+ }
481
+
482
+ /** Close one registered listener/handle. Does not touch lastActive or attempts. */
483
+ _teardown(id) {
238
484
  const entry = this.servers.get(id)
485
+ if (!entry) return
486
+ this._teardownEntry(this.defs.find((d) => d.id === id) || this._defFor(entry), entry)
487
+ }
488
+
489
+ /**
490
+ * Close a specific attempt's entry. Removing it from `servers` is conditional
491
+ * on identity: a stale attempt may close its own unregistered resource, but
492
+ * it can never delete a newer attempt's entry with the same definition id.
493
+ */
494
+ _teardownEntry(d, entry) {
239
495
  if (!entry) return
240
496
  try {
241
497
  if (entry.kind === 'local') {
@@ -245,11 +501,17 @@ export class ForwardManager {
245
501
  // The `ssh -R` child IS the tunnel: killing it closes the remote listener.
246
502
  if (entry.handle && typeof entry.handle.close === 'function') entry.handle.close()
247
503
  } else if (entry.client && typeof entry.client.unforwardIn === 'function') {
248
- const d = this._defFor(entry)
249
- entry.client.unforwardIn('127.0.0.1', d.listenPort, () => {})
504
+ const current = this.servers.get(d.id)
505
+ // ssh2 unforwardIn is keyed by client + port, NOT by our entry. If a
506
+ // newer attempt already owns that same remote listener on this client,
507
+ // a stale attempt must not close it. Normal Stop sees current===entry
508
+ // and still unforwards; with no replacement, stale cleanup can proceed.
509
+ if (!current || current === entry || current.client !== entry.client) {
510
+ entry.client.unforwardIn('127.0.0.1', d.listenPort, () => {})
511
+ }
250
512
  }
251
513
  } catch {}
252
- this.servers.delete(id)
514
+ if (this.servers.get(d.id) === entry) this.servers.delete(d.id)
253
515
  }
254
516
 
255
517
  stopAll() {