bdy 1.13.0-dev → 1.13.0-master

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.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "bdy",
3
3
  "preferGlobal": false,
4
- "version": "1.13.0-dev",
4
+ "version": "1.13.0-master",
5
5
  "type": "commonjs",
6
6
  "license": "MIT",
7
7
  "scripts": {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "bdy",
3
3
  "preferGlobal": false,
4
- "version": "1.13.0-dev",
4
+ "version": "1.13.0-master",
5
5
  "type": "commonjs",
6
6
  "license": "MIT",
7
7
  "scripts": {
@@ -1,302 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- const events_1 = __importDefault(require("events"));
7
- const logger_js_1 = __importDefault(require("./logger.js"));
8
- const texts_js_1 = require("./texts.js");
9
- const utils_js_1 = require("./utils.js");
10
- const tunnel_js_1 = __importDefault(require("./tunnel.js"));
11
- const output_js_1 = __importDefault(require("./output.js"));
12
- const socket_1 = __importDefault(require("./api/socket"));
13
- class Agent extends events_1.default {
14
- constructor(id, host, token, service, target, api, disabled) {
15
- super();
16
- this.id = id;
17
- this.host = host;
18
- this.token = token;
19
- this.service = service;
20
- this.target = target;
21
- this.disabled = disabled;
22
- this.tunnels = [];
23
- this.tunnelsUpdating = false;
24
- this.started = false;
25
- this.api = api;
26
- this.manager = null;
27
- this.onRefresh = null;
28
- this.socket = new socket_1.default(host, id, token);
29
- this.socket.on(utils_js_1.SOCKET_IO_EVENT_FETCH_SUCCESS, (data) => this._onSocketFetch(data));
30
- this.socket.on(utils_js_1.SOCKET_IO_EVENT_FETCH_FAILED, (err) => this._onSocketFetchFailed(err));
31
- this.socket.on(utils_js_1.SOCKET_IO_EVENT_CONNECTED, () => this._onSocketConnected());
32
- this.socket.on(utils_js_1.SOCKET_IO_EVENT_DISCONNECTED, () => this._onSocketDisconnected());
33
- this.socket.on(utils_js_1.SOCKET_IO_EVENT_TUNNEL, (tunnel, action) => this._onSocketTunnel(tunnel, action));
34
- this.socket.on(utils_js_1.SOCKET_IO_EVENT_AGENT, (agent, action) => this._onSocketAgent(agent, action));
35
- }
36
- destroy() {
37
- if (this.socket) {
38
- this.socket.removeAllListeners();
39
- this.socket.destroy();
40
- this.socket = null;
41
- }
42
- this.manager = null;
43
- this.onRefresh = null;
44
- this.api = null;
45
- // musza byc manualnie wczesniej zniszczone to tylko czysci obiekt
46
- this.tunnels = null;
47
- }
48
- _onSocketTunnel(data, action) {
49
- if (action === 'DEL') {
50
- this.destroyTunnel(data.id);
51
- if (!this.service && this.tunnels.length <= 0)
52
- output_js_1.default.exitError(texts_js_1.ERR_TUNNEL_REMOVED);
53
- }
54
- else {
55
- logger_js_1.default.debug('Socket fetch tunnel after sync push');
56
- this.socket.fetch(this.started, null, null, false, []);
57
- }
58
- }
59
- async _onSocketAgent(data, action) {
60
- if (action === 'DEL') {
61
- if (this.manager) {
62
- return this.manager.disableAgentAndExit(texts_js_1.ERR_AGENT_REMOVED);
63
- }
64
- output_js_1.default.exitError(texts_js_1.ERR_AGENT_REMOVED);
65
- }
66
- else {
67
- this.target = !!data.target;
68
- this.disabled = !!data.disabled;
69
- if (data.disabled === this.started) {
70
- await this.makeAction(data.disabled ? utils_js_1.AGENT_ACTION_STOP : utils_js_1.AGENT_ACTION_START);
71
- }
72
- else if (data.action) {
73
- try {
74
- await this.makeAction(data.action);
75
- }
76
- catch (err) {
77
- logger_js_1.default.error('Agent sync error');
78
- logger_js_1.default.error(err);
79
- }
80
- }
81
- }
82
- }
83
- _onSocketConnected() {
84
- if (this.onRefresh)
85
- this.onRefresh(true);
86
- }
87
- _onSocketDisconnected() {
88
- if (this.onRefresh)
89
- this.onRefresh(false);
90
- }
91
- async _onSocketFetch(data) {
92
- try {
93
- if (data.agent.action)
94
- await this.makeAction(data.agent.action);
95
- this.refreshTunnels(data.tunnels || []);
96
- }
97
- catch (err) {
98
- logger_js_1.default.error('Fetch error');
99
- logger_js_1.default.error(err);
100
- }
101
- }
102
- _onSocketFetchFailed(err) {
103
- if (err instanceof utils_js_1.ApiErrorAgentNotFound) {
104
- if (this.manager) {
105
- return this.manager.disableAgentAndExit(texts_js_1.ERR_AGENT_REMOVED);
106
- }
107
- output_js_1.default.exitError(texts_js_1.ERR_AGENT_REMOVED);
108
- }
109
- else {
110
- logger_js_1.default.error(texts_js_1.LOG_ERROR_WHILE_REFRESHING_AGENT);
111
- logger_js_1.default.error(err);
112
- }
113
- }
114
- startRefreshingConfiguration(onRefresh) {
115
- this.onRefresh = onRefresh;
116
- if (this.onRefresh)
117
- this.onRefresh(this.socket.connected);
118
- this.refreshIn15();
119
- }
120
- async start() {
121
- this.started = true;
122
- this.tunnels.forEach((t) => {
123
- t.start();
124
- });
125
- this.socket.fetch(this.started, '', null, true, this.getTunnelsUpdate());
126
- }
127
- async enable() {
128
- this.disabled = false;
129
- this.started = true;
130
- this.tunnels.forEach((t) => {
131
- t.start();
132
- });
133
- this.socket.fetch(this.started, '', false, true, this.getTunnelsUpdate());
134
- }
135
- async stop(clearAction = true) {
136
- this.started = false;
137
- this.tunnels.forEach((t) => {
138
- t.stop();
139
- });
140
- this.socket.fetch(this.started, clearAction ? '' : null, null, false, this.getTunnelsUpdate());
141
- }
142
- async disable() {
143
- this.disabled = true;
144
- this.started = false;
145
- this.tunnels.forEach((t) => {
146
- t.stop();
147
- });
148
- this.socket.fetch(this.started, '', true, false, this.getTunnelsUpdate());
149
- }
150
- async restart() {
151
- await this.stop(false);
152
- await (0, utils_js_1.sleep)(100);
153
- await this.start();
154
- }
155
- async delete() {
156
- try {
157
- await this.api.unregister(this.id, this.host, this.token);
158
- }
159
- catch {
160
- // do nothing
161
- }
162
- process.exit(0);
163
- }
164
- refreshIn15(fetch = true, counter = 1) {
165
- setTimeout(async () => {
166
- try {
167
- if (fetch || counter >= 3) {
168
- counter = 0;
169
- this.socket.fetch(this.started, null, null, false, this.getTunnelsUpdate());
170
- }
171
- else {
172
- this.update();
173
- }
174
- }
175
- catch {
176
- // do nothing
177
- }
178
- this.refreshIn15(false, counter + 1);
179
- }, 15000);
180
- }
181
- httpRequest(tunnelId, logRequest) {
182
- this.socket.request(tunnelId, logRequest);
183
- }
184
- update(force = false) {
185
- this.socket.update(this.started, this.getTunnelsUpdate(), force);
186
- }
187
- async makeAction(action) {
188
- if (action === utils_js_1.AGENT_ACTION_STOP) {
189
- if (this.manager) {
190
- return this.manager.agentStop();
191
- }
192
- return this.stop();
193
- }
194
- if (action === utils_js_1.AGENT_ACTION_START) {
195
- if (this.manager) {
196
- return this.manager.agentStart();
197
- }
198
- return this.start();
199
- }
200
- if (action === utils_js_1.AGENT_ACTION_RESTART) {
201
- if (this.manager) {
202
- return this.manager.agentRestart();
203
- }
204
- return this.restart();
205
- }
206
- if (action === utils_js_1.AGENT_ACTION_DELETE) {
207
- if (this.manager) {
208
- return this.manager.disableAgentAndExit(texts_js_1.ERR_AGENT_REMOVED);
209
- }
210
- return this.delete();
211
- }
212
- }
213
- refreshTunnels(tunnels) {
214
- if (this.tunnelsUpdating)
215
- return;
216
- this.tunnelsUpdating = true;
217
- let hasTunnels = false;
218
- let haveTunnels = false;
219
- try {
220
- const tt = [...this.tunnels];
221
- hasTunnels = tt.length > 0;
222
- haveTunnels = tunnels.length > 0;
223
- if (hasTunnels) {
224
- tt.forEach((tunnel) => {
225
- if (!tunnels.find((t) => t.id === tunnel.id)) {
226
- this.destroyTunnel(tunnel.id);
227
- }
228
- });
229
- }
230
- if (haveTunnels) {
231
- tunnels.forEach((data) => {
232
- let sshHostKey;
233
- if (this.manager)
234
- sshHostKey = this.manager.sshHostKey;
235
- const tunnel = tt.find((tunnel) => data.id === tunnel.id);
236
- if (!tunnel) {
237
- this.addTunnel(new tunnel_js_1.default({
238
- ...data,
239
- sshHostKey,
240
- agent: {
241
- id: this.id,
242
- host: this.host,
243
- token: this.token
244
- },
245
- }));
246
- }
247
- else if (tunnel.hasChanged(data)) {
248
- tunnel.recreate(data);
249
- }
250
- });
251
- }
252
- }
253
- catch {
254
- // do nothing
255
- }
256
- this.tunnelsUpdating = false;
257
- if (!this.service && hasTunnels && !haveTunnels) {
258
- output_js_1.default.exitError(texts_js_1.ERR_TUNNEL_REMOVED);
259
- }
260
- }
261
- getTunnelsUpdate() {
262
- const update = [];
263
- this.tunnels.forEach((t) => {
264
- update.push({
265
- id: t.id,
266
- active: t.status === utils_js_1.TUNNEL_OPEN,
267
- regionLatency: t.regionLatency ? t.regionLatency.latency : -1,
268
- targetLatency: t.targetLatency ? t.targetLatency.latency : -1,
269
- totalConnections: t.totalConnections,
270
- currentConnections: Object.keys(t.connections).length,
271
- httpIdentified: t.identify ? t.identify.type : '',
272
- });
273
- });
274
- return update;
275
- }
276
- addTunnel(tunnel) {
277
- this.tunnels.push(tunnel);
278
- if (this.started)
279
- tunnel.start();
280
- tunnel.on(utils_js_1.TUNNEL_EVENT_OPEN, () => this.update(true));
281
- tunnel.on(utils_js_1.TUNNEL_EVENT_CLOSED, () => this.update());
282
- tunnel.on(utils_js_1.TUNNEL_EVENT_TCP_OPEN, () => this.update());
283
- tunnel.on(utils_js_1.TUNNEL_EVENT_TCP_CLOSED, () => this.update());
284
- tunnel.on(utils_js_1.TUNNEL_EVENT_TLS_OPEN, () => this.update());
285
- tunnel.on(utils_js_1.TUNNEL_EVENT_TLS_CLOSED, () => this.update());
286
- tunnel.on(utils_js_1.TUNNEL_EVENT_HTTP_IDENTIFIED, () => this.update());
287
- tunnel.on(utils_js_1.TUNNEL_EVENT_HTTP_OPEN, () => this.update());
288
- tunnel.on(utils_js_1.TUNNEL_EVENT_HTTP_CLOSED, () => this.update());
289
- tunnel.on(utils_js_1.TUNNEL_EVENT_STOPPED, () => this.update());
290
- tunnel.on(utils_js_1.TUNNEL_EVENT_HTTP_REQUEST, (t, logRequest) => this.httpRequest(t.id, logRequest));
291
- }
292
- destroyTunnel(id) {
293
- let tunnel = this.tunnels.find((t) => t.id === id);
294
- if (!tunnel)
295
- return null;
296
- this.tunnels = this.tunnels.filter((t) => t.id !== tunnel.id);
297
- tunnel.stop();
298
- tunnel.removeAllListeners();
299
- return tunnel;
300
- }
301
- }
302
- exports.default = Agent;
@@ -1,99 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- const logger_js_1 = __importDefault(require("../logger.js"));
7
- const texts_js_1 = require("../texts.js");
8
- const ws_1 = require("ws");
9
- const TIMEOUT = 120000;
10
- const openSocket = (port, path) => {
11
- return new Promise((resolve, reject) => {
12
- const ws = new ws_1.WebSocket(`ws://localhost:${port}${path}`);
13
- ws.on('error', () => {
14
- reject(new Error(texts_js_1.ERR_FAILED_TO_CONNECT_TO_AGENT));
15
- });
16
- ws.on('open', () => {
17
- resolve(ws);
18
- });
19
- });
20
- };
21
- const makeRequest = async (port, path, body) => {
22
- const c = new AbortController();
23
- setTimeout(() => {
24
- c.abort();
25
- }, TIMEOUT);
26
- const response = await fetch(`http://localhost:${port}${path}`, {
27
- body: body ? JSON.stringify(body) : null,
28
- headers: { 'Content-Type': 'application/json' },
29
- method: 'POST',
30
- signal: c.signal,
31
- });
32
- if (response.status === 404) {
33
- throw new Error(texts_js_1.ERR_NOT_FOUND);
34
- }
35
- if (response.status === 400) {
36
- const data = await response.json();
37
- throw new Error(data.message);
38
- }
39
- if (response.status !== 200) {
40
- throw new Error(texts_js_1.ERR_SWW);
41
- }
42
- let data;
43
- try {
44
- data = await response.json();
45
- }
46
- catch (err) {
47
- logger_js_1.default.error(texts_js_1.LOG_ERROR);
48
- logger_js_1.default.error(err);
49
- throw new Error(texts_js_1.ERR_FAILED_TO_CONNECT_TO_AGENT);
50
- }
51
- return data;
52
- };
53
- class ApiAgent {
54
- constructor(port) {
55
- this.port = port;
56
- }
57
- async fetchStatus() {
58
- return makeRequest(this.port, '/status');
59
- }
60
- async addTunnel(data) {
61
- return makeRequest(this.port, '/tunnel/add', data);
62
- }
63
- async fetchTunnels() {
64
- return makeRequest(this.port, '/tunnels');
65
- }
66
- async fetchAgentTarget() {
67
- return makeRequest(this.port, '/target');
68
- }
69
- async enableAgentTarget() {
70
- return makeRequest(this.port, '/target/enable');
71
- }
72
- async disableAgentTarget() {
73
- return makeRequest(this.port, '/target/disable');
74
- }
75
- async stopTunnel(id) {
76
- return makeRequest(this.port, '/tunnel/stop', {
77
- id,
78
- });
79
- }
80
- async startAgent() {
81
- return makeRequest(this.port, '/agent/start');
82
- }
83
- async disableAgent() {
84
- return makeRequest(this.port, '/agent/disable');
85
- }
86
- async enableAgent() {
87
- return makeRequest(this.port, '/agent/enable');
88
- }
89
- async restartAgent() {
90
- return makeRequest(this.port, '/agent/restart');
91
- }
92
- async stopAgent() {
93
- return makeRequest(this.port, '/agent/stop');
94
- }
95
- async socketTunnel(id) {
96
- return openSocket(this.port, `/tunnel?id=${encodeURIComponent(id)}`);
97
- }
98
- }
99
- exports.default = ApiAgent;
@@ -1,139 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- const https_1 = require("https");
7
- const tunnel_js_1 = __importDefault(require("../tunnel.js"));
8
- const logger_js_1 = __importDefault(require("../logger.js"));
9
- const agent_js_1 = __importDefault(require("../agent.js"));
10
- const utils_1 = require("../utils");
11
- const texts_js_1 = require("../texts.js");
12
- const TIMEOUT = 120000;
13
- const nodeFetch = (url, opts) => {
14
- return new Promise((resolve, reject) => {
15
- import('node-fetch')
16
- .then(({ default: fetch }) => {
17
- fetch(url, opts).then(resolve).catch(reject);
18
- })
19
- .catch(reject);
20
- });
21
- };
22
- const makeRequest = async (host, path, body, method = 'POST', respAsJson = true, timeout = TIMEOUT) => {
23
- let data;
24
- try {
25
- const c = new AbortController();
26
- setTimeout(() => {
27
- c.abort();
28
- }, timeout);
29
- const response = await nodeFetch(`${host}${path}`, {
30
- body: body ? JSON.stringify(body) : null,
31
- headers: body ? { 'Content-Type': 'application/json' } : null,
32
- method,
33
- signal: c.signal,
34
- agent: new https_1.Agent({
35
- rejectUnauthorized: false,
36
- }),
37
- });
38
- if (respAsJson)
39
- data = await response.json();
40
- else
41
- data = await response.text();
42
- }
43
- catch {
44
- throw new utils_1.ApiErrorFailedToConnect(host);
45
- }
46
- if (respAsJson) {
47
- if (data.code !== 200) {
48
- throw (0, utils_1.apiErrorCodeToClass)(data.result.code, host);
49
- }
50
- return data.result;
51
- }
52
- else {
53
- return data;
54
- }
55
- };
56
- class ApiBuddyClass {
57
- async register(service, target, host, token, onDefaultRegion) {
58
- const version = (0, utils_1.getVersion)();
59
- const hostname = (0, utils_1.getHostname)();
60
- const platform = (0, utils_1.getPlatform)();
61
- logger_js_1.default.info(texts_js_1.LOG_REGISTERING_AGENT);
62
- const r = await makeRequest(host, '/tunnel/agent/add', {
63
- token,
64
- version,
65
- hostname,
66
- platform,
67
- service,
68
- target,
69
- });
70
- logger_js_1.default.info((0, texts_js_1.LOG_AGENT_REGISTERED)(r.id));
71
- logger_js_1.default.info((0, texts_js_1.LOG_REGION_DETECTED)(r.region));
72
- if (onDefaultRegion)
73
- onDefaultRegion(r.region);
74
- return new agent_js_1.default(r.id, host, r.token, service, target, this, false);
75
- }
76
- async unregister(id, host, token) {
77
- logger_js_1.default.info(texts_js_1.LOG_UNREGISTERING_AGENT);
78
- await makeRequest(host, '/tunnel/agent/remove', {
79
- token,
80
- id,
81
- });
82
- return true;
83
- }
84
- async fetchAgent(id, host, token) {
85
- logger_js_1.default.info(texts_js_1.LOG_GETTING_AGENT);
86
- const r = await makeRequest(host, '/tunnel/agent/fetch', {
87
- token,
88
- id,
89
- });
90
- return new agent_js_1.default(r.id, host, token, !!r.service, !!r.target, this, !!r.disabled);
91
- }
92
- async fetchAgentKeys(id, host, token) {
93
- return await makeRequest(host, '/tunnel/agent/fetch/keys', {
94
- token,
95
- id,
96
- });
97
- }
98
- async disableTarget(agentId, host, token) {
99
- logger_js_1.default.info(texts_js_1.LOG_DISABLING_AGENT_TARGET);
100
- await makeRequest(host, '/tunnel/agent/target/disable', {
101
- agentId,
102
- token,
103
- });
104
- }
105
- async enableTarget(agentId, host, token) {
106
- logger_js_1.default.info(texts_js_1.LOG_ENABLING_AGENT_TARGET);
107
- await makeRequest(host, '/tunnel/agent/target/enable', {
108
- agentId,
109
- token,
110
- });
111
- }
112
- async addTunnel(agentId, host, token, prepared, sshHostKey) {
113
- logger_js_1.default.info(texts_js_1.LOG_REGISTERING_TUNNEL);
114
- const config = await makeRequest(host, '/tunnel/add', {
115
- ...prepared,
116
- token,
117
- agentId,
118
- });
119
- logger_js_1.default.info((0, texts_js_1.LOG_TUNNEL_REGISTERED)(config.id));
120
- return new tunnel_js_1.default({
121
- ...config,
122
- sshHostKey,
123
- agent: { id: agentId, host, token },
124
- });
125
- }
126
- async removeTunnel(agentId, tunnelId, host, token) {
127
- logger_js_1.default.info(texts_js_1.LOG_REMOVING_TUNNEL);
128
- await makeRequest(host, '/tunnel/remove', {
129
- agentId,
130
- tunnelId,
131
- token,
132
- });
133
- }
134
- async fetchMyIp() {
135
- return makeRequest('https://es.buddy.works', '/ip', null, 'GET', false);
136
- }
137
- }
138
- const ApiBuddy = new ApiBuddyClass();
139
- exports.default = ApiBuddy;