· 5 years ago · Jan 11, 2020, 09:28 AM
1const { RelayClient } = require('hypertunnel-tcp-relay').Client
2const parseUrl = require('url-parse')
3const got = require('got')
4
5class Client {
6 constructor (port, opts = {}, options = { ssl: false }) {
7 this.port = port
8 this.host = opts.host || 'localhost'
9 this.server = opts.server || 'https://hypertunnel.ga'
10 this.serverParts = parseUrl(this.server)
11 this.token = opts.token || 'free-server-please-be-nice'
12 this.desiredInternetPort = opts.internetPort
13 this.options = options
14
15 this.deleted = false
16 this.relay = null
17 this.internetPort = null
18 this.relayPort = opts.relayPort
19 this.uri = null
20 this.secret = null
21 this.createdAt = null
22 this.expiresIn = null
23 this.serverBanner = null
24 }
25
26 async create () {
27 const payload = {
28 serverToken: this.token,
29 internetPort: this.desiredInternetPort,
30 ssl: this.options.ssl,
31 relayPort: this.relayPort
32 }
33
34 const { body } = await got(`${this.server}/create`, { json: true, body: payload, throwHttpErrors: false })
35
36 if (body.uri) {
37 this.server = body.uri.split(':')[0];
38 this.serverParts = parseUrl('https://' + this.server);
39 }
40
41 if (!body.success) { throw new Error(body && body.message ? body.message : 'Unexpected response') }
42 this.createdAt = body.createdAt
43 this.internetPort = body.internetPort
44 this.relayPort = body.relayPort
45 this.secret = body.secret
46 this.uri = body.uri
47 this.expiresIn = body.expiresIn
48 this.serverBanner = body.serverBanner
49
50 console.log({
51 host: this.host,
52 port: this.port,
53 relayHost: this.serverParts.hostname,
54 relayPort: this.relayPort
55 });
56
57 this.relay = new RelayClient({
58 host: this.host,
59 port: this.port,
60 relayHost: this.serverParts.hostname,
61 relayPort: this.relayPort
62 }, { secret: this.secret })
63 return this
64 }
65
66 async delete () {
67 if (this.deleted) { return true }
68 const payload = {
69 serverToken: this.token,
70 internetPort: this.internetPort,
71 secret: this.secret
72 }
73 const { body } = await got(`${this.server}/delete`, { json: true, body: payload, throwHttpErrors: false })
74
75 if (!body.success) { throw new Error(body && body.message ? body.message : 'Unexpected response') }
76 this.deleted = true
77 return true
78 }
79
80 async close () {
81 this.relay.end()
82 await this.delete()
83 return true
84 }
85}
86
87(async function() {
88 const client = new Client(10888, {
89 host: 'localhost', // брать из CLI (параметром необязательным --host)
90 server: 'https://proxy.vk.rapps.cloud',
91 token: 'test', // брать из конфига (SECRET_KEY)
92 internetPort: 9988,
93 relayPort: 10888 // брать из CLI (параметром необязательным --port)
94 }, { ssl: false }); // ssl false всегда
95 await client.create()
96}());