-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
171 lines (158 loc) · 5.22 KB
/
index.js
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
'use strict'
const { socksAuthMessages } = require('./lib/socks-messages')
const xsenv = require('@sap/xsenv')
const https = require('https')
const { SocksClient } = require('socks')
const net = require('net')
const log = console.log // eslint-disable-line no-console
class ConnectivitySocks {
#jwtCache
#socket
#connectivityCredentials
constructor() {
xsenv.loadEnv()
this.#connectivityCredentials = xsenv.cfServiceCredentials('connectivity')
if (!this.#connectivityCredentials) {
throw Error(
'No connectivity credentials provided (local: not supported, SAP BTP: check binding)'
)
}
this.#jwtCache = {
expiration: 0,
jwt: undefined,
}
this.#createSocket()
}
async #connectivityToken() {
return new Promise((resolve, reject) => {
log('Renewing the new connectivity access token')
https
.get(
`${
this.#connectivityCredentials.token_service_url
}/oauth/token?grant_type=client_credentials&response_type=token`,
{
headers: {
Authorization: `Basic ${Buffer.from(
`${this.#connectivityCredentials.clientid}:${
this.#connectivityCredentials.clientsecret
}`
).toString('base64')}`,
},
},
(res) => {
const data = []
res.on('data', (chunk) => data.push(chunk))
res.on('end', () => {
let r = JSON.parse(data.join(''))
this.#jwtCache.expiration =
Date.now() + (r.expires_in - 60) * 1000
this.#jwtCache.jwt = r.access_token
resolve(r.access_token)
})
}
)
.on('error', (err) => {
reject('Error while getting connectivity JWT: ' + err.message)
})
})
}
async #generateSocksClientOptions() {
let jwt =
Date.now() > this.#jwtCache.expiration
? await this.#connectivityToken()
: this.#jwtCache.jwt
let logAuthMessage = function (authStatusByte) {
if (socksAuthMessages.length < authStatusByte - 1) {
log('ERROR: Unknown SOCKS5 auth flow error.')
} else {
log(socksAuthMessages[authStatusByte])
}
}
let sLocationBase64 = process.env.PG_CONNECTIVITY_LOCATION_ID
? Buffer.from(process.env.PG_CONNECTIVITY_LOCATION_ID).toString('base64')
: ''
let iJWTLength = Buffer.byteLength(jwt, 'utf8')
let iLocationLength = Buffer.byteLength(sLocationBase64, 'utf8')
let xJWTLengthBuffer = Buffer.alloc(4)
xJWTLengthBuffer.writeInt32BE(iJWTLength)
let xLocationLengthBuffer = Buffer.alloc(1)
xLocationLengthBuffer.writeInt8(iLocationLength)
return {
proxy: {
host: this.#connectivityCredentials.onpremise_proxy_host,
port: parseInt(
this.#connectivityCredentials.onpremise_socks5_proxy_port
),
type: 5,
custom_auth_method: 0x80,
custom_auth_request_handler: async () => {
return Buffer.concat([
Buffer.from([0x01]), // Authentication method version - currently 1
xJWTLengthBuffer, // Length of the JWT
Buffer.from(jwt), // The actual value of the JWT in its encoded form
xLocationLengthBuffer, // Length of the Cloud Connector location ID (0 if no Cloud Connector location ID is used)
Buffer.from(sLocationBase64), // The value of the Cloud Connector location ID in base64-encoded form
])
},
custom_auth_response_size: 2,
custom_auth_response_handler: async (data) => {
logAuthMessage(data[1])
if (data[1] === 0x00) {
return true
} else {
return false
}
},
},
command: 'connect',
destination: {
host: process.env.PG_HOST,
port: parseInt(process.env.PG_PORT),
},
}
}
async #createSocket() {
this.#socket = new net.Socket()
this.#socket.setKeepAlive(true, 60 * 60 * 1000) // TODO: no effect because BTP ends first
this.#socket.setTimeout(60 * 60 * 1000) // TODO: no effect because BTP ends first
let connectSocksSocket = () => {
this.#socket.connect(
this.#connectivityCredentials.onpremise_socks5_proxy_port,
this.#connectivityCredentials.onpremise_proxy_host,
async () => {
let options = await this.#generateSocksClientOptions()
let socksClient = new SocksClient(options)
socksClient.connect(this.#socket)
}
)
}
this.#socket.on('close', () => {
log('Connection closed, reconnecting...')
connectSocksSocket()
})
this.#socket.on('error', (e) => {
log('Socket error: ', e.code)
})
this.#socket.on('end', () => {
log('Socket ended by BTP')
})
this.#socket.on('ready', () => {
log('Socket ready')
})
this.#socket.on('timeout', () => {
log('Socket timeout due to inactivity')
})
this.#socket.on('connect', () => {
log('Socket connected')
})
connectSocksSocket()
}
/**
* Creates a SOCKS5 connection to the SAP BTP Connectivity service
*/
getSocket() {
return this.#socket
}
}
module.exports.ConnectivitySocks = ConnectivitySocks