-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.ts
77 lines (72 loc) · 2.14 KB
/
client.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import fetch from 'node-fetch'
import { createClient } from './reverse-tunnel'
import { createServer } from 'http'
const { USER, SSH_AUTH_SOCK } = process.env
interface ClientController {
close: () => void
}
export function tunnelPort(
localPort: number,
subdomain: string,
tunnelDomain: string,
sshPort: number,
): Promise<ClientController> {
if (localPort === undefined) throw new Error('No port given')
if (subdomain === undefined) throw new Error('No subdomain given')
const protocol = tunnelDomain === 'localhost' ? 'http' : 'https'
const url = `${protocol}://${tunnelDomain}?subdomain=${subdomain}`
return fetch(url, { method: 'post' })
.then(res => res.json())
.then(res => {
const { port, error } = res
if (error) throw error
return port
})
.then(dstPort => {
const promise = new Promise<ClientController>((resolve, reject) => {
const client = createClient(
{
host: tunnelDomain,
port: Number(sshPort),
dstHost: 'localhost',
dstPort: dstPort,
srcHost: 'localhost',
srcPort: localPort,
keepAlive: true,
agent: SSH_AUTH_SOCK,
username: USER,
},
resolve,
reject,
)
return client
})
return promise
})
}
const {
SUBDOMAIN = 'maronn',
SERVER_PORT = 2005,
TUNNEL_DOMAIN = 'internal.accurat.io',
SSH_PORT = 2222,
ONLY_TUNNEL = null,
} = process.env
function run() {
tunnelPort(Number(SERVER_PORT), SUBDOMAIN, TUNNEL_DOMAIN, Number(SSH_PORT))
.then(client => {
const protocol = TUNNEL_DOMAIN === 'localhost' ? 'http' : 'https'
const url = `${protocol}://${SUBDOMAIN}.${TUNNEL_DOMAIN}`
console.log(`Tunnel opened between port ${SERVER_PORT} and ${url}`)
})
.catch(err => {
console.error('err', err.message)
})
if (ONLY_TUNNEL) return
createServer((req, res) => {
res.statusCode = 200
res.end(`Maronn, everything works here at ${SUBDOMAIN}!`)
}).listen(SERVER_PORT, () => {
console.log(`HTTP Server running on ${SERVER_PORT}`)
})
}
if (require.main === module) run()