dsh-remote 0.8.71 → 0.8.73

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/lib/forwards.js CHANGED
@@ -1,258 +1,258 @@
1
- // dsh-remote — SSH port forwarding manager (local & reverse tunnels).
2
- //
3
- // Local forward: listen on 127.0.0.1:<listenPort> → every connection is
4
- // piped through the SSH channel to <targetHost>:<targetPort> on the remote.
5
- // Reverse forward: ask the remote to listen on 127.0.0.1:<listenPort> and pipe
6
- // incoming connections back to <targetHost>:<targetPort> on the LOCAL side
7
- // (ssh2 `forwardIn` + the client `tcpip` event; requires AllowTcpForwarding on
8
- // the remote sshd).
9
- //
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).
14
- import net from 'node:net'
15
- import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'node:fs'
16
- import path from 'node:path'
17
- import { forwardOutChannel } from './pool.js'
18
-
19
- export class ForwardManager {
20
- /** @param {object} pool SshPool (needs .connect() returning the ssh2 client).
21
- * @param {object} [opts] - `file` (persistence) and `net` (a `node:net`
22
- * compatible module, so the listener's connection handler — the path the
23
- * issue #54 crash travelled — can be driven from a unit test without
24
- * binding a real port). */
25
- constructor(pool, { file, net: netModule } = {}) {
26
- this.pool = pool
27
- this.net = netModule || net
28
- this.file = file || null
29
- this.defs = this._load()
30
- this.servers = new Map() // id → { server | remoteListen, sockets:Set, client }
31
- this.client = null
32
- this.onTcpip = null
33
- this.onClose = null
34
- this.attach = this.attach.bind(this)
35
- }
36
-
37
- _load() {
38
- if (!this.file) return []
39
- try {
40
- const j = JSON.parse(readFileSync(this.file, 'utf8'))
41
- if (Array.isArray(j.defs)) return j.defs
42
- } catch {}
43
- return []
44
- }
45
-
46
- _save() {
47
- if (!this.file) return
48
- try {
49
- mkdirSync(path.dirname(this.file), { recursive: true })
50
- writeFileSync(this.file, JSON.stringify({ defs: this.defs }, null, 2))
51
- } catch {}
52
- }
53
-
54
- /** Called by the pool after a successful connect: restore autoStart tunnels. */
55
- attach(client) {
56
- if (this.client === client) return
57
- this.client = client
58
- this.onTcpip = (info, accept, reject) => this._handleTcpip(info, accept, reject)
59
- client.on('tcpip', this.onTcpip)
60
- this.onClose = () => this.stopAll()
61
- client.on('close', this.onClose)
62
- for (const d of this.defs) {
63
- if (d.autoStart && d.direction === 'local' && !this.servers.has(d.id)) {
64
- this.start(d).catch(() => {})
65
- }
66
- }
67
- }
68
-
69
- detach() {
70
- this.stopAll()
71
- if (this.client) {
72
- if (this.onTcpip) this.client.removeListener('tcpip', this.onTcpip)
73
- if (this.onClose) this.client.removeListener('close', this.onClose)
74
- }
75
- this.client = null
76
- this.onTcpip = null
77
- this.onClose = null
78
- }
79
-
80
- list() {
81
- return this.defs.map((d) => ({
82
- id: d.id,
83
- direction: d.direction,
84
- listenPort: d.listenPort,
85
- targetHost: d.targetHost,
86
- targetPort: d.targetPort,
87
- machineId: d.machineId || null,
88
- autoStart: !!d.autoStart,
89
- active: this.servers.has(d.id),
90
- }))
91
- }
92
-
93
- _defId() {
94
- return 'fwd-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 6)
95
- }
96
-
97
- /** Create a forward definition (persisted). Does NOT start it. */
98
- define({ direction = 'local', listenPort, targetHost, targetPort, autoStart = false, machineId } = {}) {
99
- const d = {
100
- id: this._defId(),
101
- direction: direction === 'reverse' ? 'reverse' : 'local',
102
- listenPort: Number(listenPort),
103
- targetHost: String(targetHost || '127.0.0.1'),
104
- targetPort: Number(targetPort),
105
- autoStart: !!autoStart,
106
- machineId: machineId || null,
107
- }
108
- this.defs.push(d)
109
- this._save()
110
- return d
111
- }
112
-
113
- remove(id) {
114
- this.stop(id)
115
- const i = this.defs.findIndex((d) => d.id === id)
116
- if (i >= 0) { this.defs.splice(i, 1); this._save(); return true }
117
- return false
118
- }
119
-
120
- async start(def) {
121
- 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
128
- }
129
- 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 }
136
- } catch (err) {
137
- return { ok: false, error: String((err && err.message) || err) }
138
- }
139
- }
140
-
141
- _startLocal(d, client) {
142
- return new Promise((resolve, reject) => {
143
- const server = this.net.createServer((socket) => {
144
- // ssh2's forwardOut reports a dead connection by THROWING
145
- // (`if (!this._sock || !isWritable(this._sock)) throw new Error('Not
146
- // connected')`) and never calls the callback, so a callback-only error
147
- // path cannot guard this call. Uncaught, the throw escapes net.Server's
148
- // connection handler and kills the whole host process — the exact fatal
149
- // stack of issue #54, found in WebAttach and reachable here too for a
150
- // user-defined local forward. `attach()` does register a `close`
151
- // listener that calls stopAll(), but a request can arrive in the window
152
- // between the connection dying and that event.
153
- forwardOutChannel(client, { dstHost: d.targetHost, dstPort: d.targetPort }).then((channel) => {
154
- socket.pipe(channel)
155
- channel.pipe(socket)
156
- const kill = () => { try { socket.destroy() } catch {}; try { channel.close() } catch {} }
157
- socket.on('error', kill)
158
- channel.on('error', kill)
159
- socket.on('close', kill)
160
- channel.on('close', kill)
161
- }).catch(() => {
162
- // A dead tunnel is a UI state, not a reason to exit.
163
- try { socket.destroy() } catch { /* already gone */ }
164
- })
165
- })
166
- server.on('error', (e) => reject(new Error(`本地转发 ${d.listenPort} 启动失败: ${e.message}`)))
167
- server.listen(d.listenPort, '127.0.0.1', () => {
168
- this.servers.set(d.id, { kind: 'local', server, sockets: new Set(), client })
169
- resolve()
170
- })
171
- })
172
- }
173
-
174
- _startReverse(d, client) {
175
- // The system-OpenSSH backend (issue #51) cannot do ssh2's two-phase
176
- // `forwardIn` + `tcpip`: the `ssh -R` CLI needs the final target as an
177
- // argument, so it exposes `reverseForward()` instead. Prefer it when
178
- // present — otherwise every reverse tunnel would fail on that backend.
179
- if (typeof client.reverseForward === 'function') {
180
- return client.reverseForward({
181
- bindHost: '127.0.0.1',
182
- listenPort: d.listenPort,
183
- targetHost: d.targetHost,
184
- targetPort: d.targetPort,
185
- }).then((handle) => {
186
- this.servers.set(d.id, { kind: 'reverse-cli', handle, client })
187
- }).catch((err) => {
188
- throw new Error(`远端监听 ${d.listenPort} 失败: ${(err && err.message) || err}`)
189
- })
190
- }
191
- return new Promise((resolve, reject) => {
192
- // ssh2 calls the remote TCP listen API `forwardIn` (NOT openssh_forwardIn,
193
- // which in ssh2 >= 1.16 is stream-local only).
194
- if (typeof client.forwardIn !== 'function') {
195
- return reject(new Error('此 ssh2 版本不支持反向转发 (forwardIn)'))
196
- }
197
- client.forwardIn('127.0.0.1', d.listenPort, (err) => {
198
- 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()
201
- })
202
- })
203
- }
204
-
205
- _handleTcpip(info, accept, reject) {
206
- // Only the ssh2 backend reaches here: `ssh -R` handles the remote listener
207
- // and its targets entirely inside the CLI, so a 'reverse-cli' entry never
208
- // produces a 'tcpip' event.
209
- for (const entry of this.servers.values()) {
210
- if (entry.kind === 'reverse' && Number(info.destPort) === Number(this._defFor(entry).listenPort)) {
211
- const channel = accept()
212
- const socket = this.net.connect({ host: this._defFor(entry).targetHost, port: this._defFor(entry).targetPort })
213
- socket.pipe(channel)
214
- channel.pipe(socket)
215
- entry.sockets.add(socket)
216
- const kill = () => {
217
- try { socket.destroy() } catch {}
218
- try { channel.close() } catch {}
219
- entry.sockets.delete(socket)
220
- }
221
- socket.on('error', kill)
222
- channel.on('error', kill)
223
- socket.on('close', kill)
224
- return
225
- }
226
- }
227
- reject()
228
- }
229
-
230
- _defFor(entry) {
231
- for (const d of this.defs) {
232
- if (this.servers.has(d.id) && this.servers.get(d.id) === entry) return d
233
- }
234
- return { listenPort: 0, targetHost: '127.0.0.1', targetPort: 0 }
235
- }
236
-
237
- stop(id) {
238
- const entry = this.servers.get(id)
239
- if (!entry) return
240
- try {
241
- if (entry.kind === 'local') {
242
- entry.server.close()
243
- for (const s of entry.sockets) { try { s.destroy() } catch {} }
244
- } else if (entry.kind === 'reverse-cli') {
245
- // The `ssh -R` child IS the tunnel: killing it closes the remote listener.
246
- if (entry.handle && typeof entry.handle.close === 'function') entry.handle.close()
247
- } 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, () => {})
250
- }
251
- } catch {}
252
- this.servers.delete(id)
253
- }
254
-
255
- stopAll() {
256
- for (const id of [...this.servers.keys()]) this.stop(id)
257
- }
258
- }
1
+ // dsh-remote — SSH port forwarding manager (local & reverse tunnels).
2
+ //
3
+ // Local forward: listen on 127.0.0.1:<listenPort> → every connection is
4
+ // piped through the SSH channel to <targetHost>:<targetPort> on the remote.
5
+ // Reverse forward: ask the remote to listen on 127.0.0.1:<listenPort> and pipe
6
+ // incoming connections back to <targetHost>:<targetPort> on the LOCAL side
7
+ // (ssh2 `forwardIn` + the client `tcpip` event; requires AllowTcpForwarding on
8
+ // the remote sshd).
9
+ //
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).
14
+ import net from 'node:net'
15
+ import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'node:fs'
16
+ import path from 'node:path'
17
+ import { forwardOutChannel } from './pool.js'
18
+
19
+ export class ForwardManager {
20
+ /** @param {object} pool SshPool (needs .connect() returning the ssh2 client).
21
+ * @param {object} [opts] - `file` (persistence) and `net` (a `node:net`
22
+ * compatible module, so the listener's connection handler — the path the
23
+ * issue #54 crash travelled — can be driven from a unit test without
24
+ * binding a real port). */
25
+ constructor(pool, { file, net: netModule } = {}) {
26
+ this.pool = pool
27
+ this.net = netModule || net
28
+ this.file = file || null
29
+ this.defs = this._load()
30
+ this.servers = new Map() // id → { server | remoteListen, sockets:Set, client }
31
+ this.client = null
32
+ this.onTcpip = null
33
+ this.onClose = null
34
+ this.attach = this.attach.bind(this)
35
+ }
36
+
37
+ _load() {
38
+ if (!this.file) return []
39
+ try {
40
+ const j = JSON.parse(readFileSync(this.file, 'utf8'))
41
+ if (Array.isArray(j.defs)) return j.defs
42
+ } catch {}
43
+ return []
44
+ }
45
+
46
+ _save() {
47
+ if (!this.file) return
48
+ try {
49
+ mkdirSync(path.dirname(this.file), { recursive: true })
50
+ writeFileSync(this.file, JSON.stringify({ defs: this.defs }, null, 2))
51
+ } catch {}
52
+ }
53
+
54
+ /** Called by the pool after a successful connect: restore autoStart tunnels. */
55
+ attach(client) {
56
+ if (this.client === client) return
57
+ this.client = client
58
+ this.onTcpip = (info, accept, reject) => this._handleTcpip(info, accept, reject)
59
+ client.on('tcpip', this.onTcpip)
60
+ this.onClose = () => this.stopAll()
61
+ client.on('close', this.onClose)
62
+ for (const d of this.defs) {
63
+ if (d.autoStart && d.direction === 'local' && !this.servers.has(d.id)) {
64
+ this.start(d).catch(() => {})
65
+ }
66
+ }
67
+ }
68
+
69
+ detach() {
70
+ this.stopAll()
71
+ if (this.client) {
72
+ if (this.onTcpip) this.client.removeListener('tcpip', this.onTcpip)
73
+ if (this.onClose) this.client.removeListener('close', this.onClose)
74
+ }
75
+ this.client = null
76
+ this.onTcpip = null
77
+ this.onClose = null
78
+ }
79
+
80
+ list() {
81
+ return this.defs.map((d) => ({
82
+ id: d.id,
83
+ direction: d.direction,
84
+ listenPort: d.listenPort,
85
+ targetHost: d.targetHost,
86
+ targetPort: d.targetPort,
87
+ machineId: d.machineId || null,
88
+ autoStart: !!d.autoStart,
89
+ active: this.servers.has(d.id),
90
+ }))
91
+ }
92
+
93
+ _defId() {
94
+ return 'fwd-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 6)
95
+ }
96
+
97
+ /** Create a forward definition (persisted). Does NOT start it. */
98
+ define({ direction = 'local', listenPort, targetHost, targetPort, autoStart = false, machineId } = {}) {
99
+ const d = {
100
+ id: this._defId(),
101
+ direction: direction === 'reverse' ? 'reverse' : 'local',
102
+ listenPort: Number(listenPort),
103
+ targetHost: String(targetHost || '127.0.0.1'),
104
+ targetPort: Number(targetPort),
105
+ autoStart: !!autoStart,
106
+ machineId: machineId || null,
107
+ }
108
+ this.defs.push(d)
109
+ this._save()
110
+ return d
111
+ }
112
+
113
+ remove(id) {
114
+ this.stop(id)
115
+ const i = this.defs.findIndex((d) => d.id === id)
116
+ if (i >= 0) { this.defs.splice(i, 1); this._save(); return true }
117
+ return false
118
+ }
119
+
120
+ async start(def) {
121
+ 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
128
+ }
129
+ 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 }
136
+ } catch (err) {
137
+ return { ok: false, error: String((err && err.message) || err) }
138
+ }
139
+ }
140
+
141
+ _startLocal(d, client) {
142
+ return new Promise((resolve, reject) => {
143
+ const server = this.net.createServer((socket) => {
144
+ // ssh2's forwardOut reports a dead connection by THROWING
145
+ // (`if (!this._sock || !isWritable(this._sock)) throw new Error('Not
146
+ // connected')`) and never calls the callback, so a callback-only error
147
+ // path cannot guard this call. Uncaught, the throw escapes net.Server's
148
+ // connection handler and kills the whole host process — the exact fatal
149
+ // stack of issue #54, found in WebAttach and reachable here too for a
150
+ // user-defined local forward. `attach()` does register a `close`
151
+ // listener that calls stopAll(), but a request can arrive in the window
152
+ // between the connection dying and that event.
153
+ forwardOutChannel(client, { dstHost: d.targetHost, dstPort: d.targetPort }).then((channel) => {
154
+ socket.pipe(channel)
155
+ channel.pipe(socket)
156
+ const kill = () => { try { socket.destroy() } catch {}; try { channel.close() } catch {} }
157
+ socket.on('error', kill)
158
+ channel.on('error', kill)
159
+ socket.on('close', kill)
160
+ channel.on('close', kill)
161
+ }).catch(() => {
162
+ // A dead tunnel is a UI state, not a reason to exit.
163
+ try { socket.destroy() } catch { /* already gone */ }
164
+ })
165
+ })
166
+ server.on('error', (e) => reject(new Error(`本地转发 ${d.listenPort} 启动失败: ${e.message}`)))
167
+ server.listen(d.listenPort, '127.0.0.1', () => {
168
+ this.servers.set(d.id, { kind: 'local', server, sockets: new Set(), client })
169
+ resolve()
170
+ })
171
+ })
172
+ }
173
+
174
+ _startReverse(d, client) {
175
+ // The system-OpenSSH backend (issue #51) cannot do ssh2's two-phase
176
+ // `forwardIn` + `tcpip`: the `ssh -R` CLI needs the final target as an
177
+ // argument, so it exposes `reverseForward()` instead. Prefer it when
178
+ // present — otherwise every reverse tunnel would fail on that backend.
179
+ if (typeof client.reverseForward === 'function') {
180
+ return client.reverseForward({
181
+ bindHost: '127.0.0.1',
182
+ listenPort: d.listenPort,
183
+ targetHost: d.targetHost,
184
+ targetPort: d.targetPort,
185
+ }).then((handle) => {
186
+ this.servers.set(d.id, { kind: 'reverse-cli', handle, client })
187
+ }).catch((err) => {
188
+ throw new Error(`远端监听 ${d.listenPort} 失败: ${(err && err.message) || err}`)
189
+ })
190
+ }
191
+ return new Promise((resolve, reject) => {
192
+ // ssh2 calls the remote TCP listen API `forwardIn` (NOT openssh_forwardIn,
193
+ // which in ssh2 >= 1.16 is stream-local only).
194
+ if (typeof client.forwardIn !== 'function') {
195
+ return reject(new Error('此 ssh2 版本不支持反向转发 (forwardIn)'))
196
+ }
197
+ client.forwardIn('127.0.0.1', d.listenPort, (err) => {
198
+ 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()
201
+ })
202
+ })
203
+ }
204
+
205
+ _handleTcpip(info, accept, reject) {
206
+ // Only the ssh2 backend reaches here: `ssh -R` handles the remote listener
207
+ // and its targets entirely inside the CLI, so a 'reverse-cli' entry never
208
+ // produces a 'tcpip' event.
209
+ for (const entry of this.servers.values()) {
210
+ if (entry.kind === 'reverse' && Number(info.destPort) === Number(this._defFor(entry).listenPort)) {
211
+ const channel = accept()
212
+ const socket = this.net.connect({ host: this._defFor(entry).targetHost, port: this._defFor(entry).targetPort })
213
+ socket.pipe(channel)
214
+ channel.pipe(socket)
215
+ entry.sockets.add(socket)
216
+ const kill = () => {
217
+ try { socket.destroy() } catch {}
218
+ try { channel.close() } catch {}
219
+ entry.sockets.delete(socket)
220
+ }
221
+ socket.on('error', kill)
222
+ channel.on('error', kill)
223
+ socket.on('close', kill)
224
+ return
225
+ }
226
+ }
227
+ reject()
228
+ }
229
+
230
+ _defFor(entry) {
231
+ for (const d of this.defs) {
232
+ if (this.servers.has(d.id) && this.servers.get(d.id) === entry) return d
233
+ }
234
+ return { listenPort: 0, targetHost: '127.0.0.1', targetPort: 0 }
235
+ }
236
+
237
+ stop(id) {
238
+ const entry = this.servers.get(id)
239
+ if (!entry) return
240
+ try {
241
+ if (entry.kind === 'local') {
242
+ entry.server.close()
243
+ for (const s of entry.sockets) { try { s.destroy() } catch {} }
244
+ } else if (entry.kind === 'reverse-cli') {
245
+ // The `ssh -R` child IS the tunnel: killing it closes the remote listener.
246
+ if (entry.handle && typeof entry.handle.close === 'function') entry.handle.close()
247
+ } 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, () => {})
250
+ }
251
+ } catch {}
252
+ this.servers.delete(id)
253
+ }
254
+
255
+ stopAll() {
256
+ for (const id of [...this.servers.keys()]) this.stop(id)
257
+ }
258
+ }