-
Notifications
You must be signed in to change notification settings - Fork 0
/
reverse-tunnel.ts
51 lines (42 loc) · 1.07 KB
/
reverse-tunnel.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import { Socket } from 'net'
import { Client, ConnectConfig } from 'ssh2'
interface Config extends ConnectConfig {
dstHost: string
dstPort: number
srcHost: string
srcPort: number
host: string
port: number
keepAlive: boolean
agent: string
username: string
}
export function createClient(config: Config, connectedCb: Function, errorCb: Function): Client {
const conn = new Client()
conn.on('ready', () => {
connectedCb(conn)
conn.forwardIn(config.dstHost, config.dstPort, (err, port) => {
if (!err) return conn.emit('forward-in', port)
errorCb(err)
})
})
conn.on('tcp connection', (info, accept, reject) => {
let remote
const srcSocket = new Socket()
srcSocket.on('error', err => {
if (remote === undefined) return reject()
remote.end()
errorCb(err)
})
srcSocket.connect(config.srcPort, config.srcHost, () => {
remote = accept()
srcSocket.pipe(remote).pipe(srcSocket)
})
})
conn.on('error', err => {
conn.end()
errorCb(err)
})
conn.connect(config)
return conn
}