bdy 1.7.60-dev → 1.8.3-dev

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.
Files changed (95) hide show
  1. package/package.json +42 -11
  2. package/.eslintrc.yml +0 -23
  3. package/bin/cli.js +0 -5
  4. package/dockerfile +0 -15
  5. package/link.sh +0 -3
  6. package/src/agent/linux.js +0 -127
  7. package/src/agent/manager.js +0 -404
  8. package/src/agent/osx.js +0 -150
  9. package/src/agent/socket/tunnel.js +0 -232
  10. package/src/agent/socket.js +0 -260
  11. package/src/agent/system.js +0 -205
  12. package/src/agent/wait.js +0 -20
  13. package/src/agent/windows.js +0 -168
  14. package/src/agent.js +0 -256
  15. package/src/api/agent.js +0 -95
  16. package/src/api/buddy.js +0 -131
  17. package/src/api/socket.js +0 -148
  18. package/src/cfg.js +0 -239
  19. package/src/command/agent/install.js +0 -116
  20. package/src/command/agent/restart.js +0 -27
  21. package/src/command/agent/run.js +0 -16
  22. package/src/command/agent/start.js +0 -27
  23. package/src/command/agent/status.js +0 -44
  24. package/src/command/agent/stop.js +0 -27
  25. package/src/command/agent/tunnel/http.js +0 -45
  26. package/src/command/agent/tunnel/list.js +0 -26
  27. package/src/command/agent/tunnel/remove.js +0 -29
  28. package/src/command/agent/tunnel/start.js +0 -37
  29. package/src/command/agent/tunnel/status.js +0 -31
  30. package/src/command/agent/tunnel/tcp.js +0 -45
  31. package/src/command/agent/tunnel/tls.js +0 -45
  32. package/src/command/agent/tunnel.js +0 -20
  33. package/src/command/agent/uninstall.js +0 -36
  34. package/src/command/agent/update.js +0 -42
  35. package/src/command/agent/version.js +0 -22
  36. package/src/command/agent.js +0 -26
  37. package/src/command/config/add/http.js +0 -31
  38. package/src/command/config/add/tcp.js +0 -31
  39. package/src/command/config/add/tls.js +0 -31
  40. package/src/command/config/add.js +0 -12
  41. package/src/command/config/get/region.js +0 -12
  42. package/src/command/config/get/timeout.js +0 -12
  43. package/src/command/config/get/token.js +0 -12
  44. package/src/command/config/get/tunnel.js +0 -20
  45. package/src/command/config/get/tunnels.js +0 -12
  46. package/src/command/config/get/whitelist.js +0 -12
  47. package/src/command/config/get.js +0 -18
  48. package/src/command/config/remove/tunnel.js +0 -21
  49. package/src/command/config/remove.js +0 -8
  50. package/src/command/config/set/region.js +0 -18
  51. package/src/command/config/set/timeout.js +0 -21
  52. package/src/command/config/set/token.js +0 -18
  53. package/src/command/config/set/whitelist.js +0 -18
  54. package/src/command/config/set.js +0 -14
  55. package/src/command/config.js +0 -14
  56. package/src/command/http.js +0 -33
  57. package/src/command/pre.js +0 -45
  58. package/src/command/start.js +0 -30
  59. package/src/command/tcp.js +0 -31
  60. package/src/command/tls.js +0 -31
  61. package/src/command/version.js +0 -10
  62. package/src/format.js +0 -171
  63. package/src/index.js +0 -38
  64. package/src/input.js +0 -283
  65. package/src/logger.js +0 -92
  66. package/src/output/interactive/tunnel.js +0 -871
  67. package/src/output/noninteractive/agent/tunnels.js +0 -32
  68. package/src/output/noninteractive/config/tunnel.js +0 -51
  69. package/src/output/noninteractive/config/tunnels.js +0 -19
  70. package/src/output/noninteractive/tunnel.js +0 -79
  71. package/src/output.js +0 -131
  72. package/src/server/cert.js +0 -51
  73. package/src/server/http1.js +0 -79
  74. package/src/server/http2.js +0 -79
  75. package/src/server/sftp.js +0 -474
  76. package/src/server/ssh.js +0 -107
  77. package/src/server/tls.js +0 -41
  78. package/src/ssh/client.js +0 -204
  79. package/src/texts.js +0 -445
  80. package/src/tunnel/agent.js +0 -100
  81. package/src/tunnel/compression.js +0 -32
  82. package/src/tunnel/dns.js +0 -55
  83. package/src/tunnel/html/404.html +0 -129
  84. package/src/tunnel/html/503.html +0 -136
  85. package/src/tunnel/html.js +0 -32
  86. package/src/tunnel/http/log.js +0 -204
  87. package/src/tunnel/http/serve.js +0 -127
  88. package/src/tunnel/http/stream.js +0 -47
  89. package/src/tunnel/http.js +0 -406
  90. package/src/tunnel/identification.js +0 -95
  91. package/src/tunnel/latency.js +0 -69
  92. package/src/tunnel/tcp.js +0 -85
  93. package/src/tunnel.js +0 -713
  94. package/src/utils.js +0 -577
  95. package/unlink.sh +0 -3
package/package.json CHANGED
@@ -1,16 +1,31 @@
1
1
  {
2
2
  "name": "bdy",
3
3
  "preferGlobal": false,
4
- "version": "1.7.60-dev",
4
+ "version": "1.8.3-dev",
5
5
  "type": "commonjs",
6
6
  "license": "MIT",
7
+ "scripts": {
8
+ "lint": "eslint \"*/**\"",
9
+ "lint:types": "tsc --skipLibCheck --noEmit --project tsconfig.json",
10
+ "watch": "tsc --watch --project tsconfig.json"
11
+ },
12
+ "files": [
13
+ "distTs"
14
+ ],
15
+ "bin": {
16
+ "bdy": "distTs/bin/cli.js"
17
+ },
7
18
  "dependencies": {
8
- "socket.io-client": "4.7.5",
9
19
  "@fastify/accept-negotiator": "1.1.0",
20
+ "@fastify/cors": "9.0.1",
21
+ "@puppeteer/browsers": "2.4.0",
10
22
  "@xhmikosr/decompress": "10.0.1",
11
23
  "basic-auth": "2.0.1",
12
- "commander": "12.0.0",
24
+ "chalk": "4.1.2",
25
+ "commander": "12.1.0",
13
26
  "content-disposition": "0.5.4",
27
+ "cross-spawn": "7.0.3",
28
+ "fastify": "4.28.1",
14
29
  "isbinaryfile": "5.0.2",
15
30
  "jsonwebtoken": "9.0.2",
16
31
  "mime-db": "1.52.0",
@@ -20,20 +35,36 @@
20
35
  "node-forge": "1.3.1",
21
36
  "path-is-inside": "1.0.2",
22
37
  "pino": "8.20.0",
38
+ "puppeteer-core": "23.6.0",
23
39
  "range-parser": "1.2.1",
40
+ "socket.io-client": "4.7.5",
24
41
  "ssh2": "1.15.0",
25
42
  "terminal-kit": "3.1.1",
26
- "uuid": "9.0.1",
43
+ "undici": "6.19.2",
44
+ "uuid": "10.0.0",
45
+ "which": "4.0.0",
27
46
  "ws": "8.18.0"
28
47
  },
29
48
  "devDependencies": {
30
- "@rollup/plugin-commonjs": "25.0.8",
49
+ "@eslint/js": "9.13.0",
50
+ "@rollup/plugin-commonjs": "28.0.1",
31
51
  "@rollup/plugin-json": "6.1.0",
32
- "@rollup/plugin-node-resolve": "15.2.3",
33
- "eslint": "8.50.0",
34
- "rollup-plugin-natives": "0.7.8"
35
- },
36
- "bin": {
37
- "bdy": "bin/cli.js"
52
+ "@rollup/plugin-node-resolve": "15.3.0",
53
+ "@rollup/plugin-replace": "6.0.1",
54
+ "@stylistic/eslint-plugin-js": "2.9.0",
55
+ "@types/cross-spawn": "6.0.6",
56
+ "@types/eslint__js": "8.42.3",
57
+ "@types/ssh2": "1.15.1",
58
+ "@types/terminal-kit": "2.5.6",
59
+ "@types/uuid": "10.0.0",
60
+ "@types/which": "3.0.4",
61
+ "eslint": "9.13.0",
62
+ "eslint-config-prettier": "9.1.0",
63
+ "globals": "15.11.0",
64
+ "prettier": "3.3.3",
65
+ "rollup-plugin-natives": "0.7.8",
66
+ "typescript": "5.6.3",
67
+ "typescript-eslint": "8.11.0",
68
+ "rollup": "4.24.2"
38
69
  }
39
70
  }
package/.eslintrc.yml DELETED
@@ -1,23 +0,0 @@
1
- env:
2
- node: true
3
- es2021: true
4
- extends: eslint:recommended
5
- parserOptions:
6
- ecmaVersion: latest
7
- sourceType: commonjs
8
- ignorePatterns:
9
- - dist
10
- rules:
11
- indent:
12
- - error
13
- - 2
14
- linebreak-style:
15
- - error
16
- - unix
17
- quotes:
18
- - error
19
- - single
20
- semi:
21
- - error
22
- - always
23
- eol-last: error
package/bin/cli.js DELETED
@@ -1,5 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- console.log = () => {}; // fix for termkit
4
-
5
- require('../src/index.js');
package/dockerfile DELETED
@@ -1,15 +0,0 @@
1
- FROM ubuntu:22.04
2
- ARG ENV=dev
3
- ARG VERSION=1.4.6
4
- ARG BUILDARCH
5
- ENV IS_IN_DOCKER=1
6
- VOLUME ["/buddy"]
7
- RUN apt-get update && apt-get install -y curl tar
8
- RUN if [ "$BUILDARCH" = "arm64" ]; then \
9
- export ARCH="arm64"; \
10
- else \
11
- export ARCH="x64"; \
12
- fi; \
13
- curl https://es.buddy.works/bdy/$ENV/$VERSION/linux-$ARCH.tar.gz -o bdy.tar.gz && \
14
- tar -zxf bdy.tar.gz -C /usr/local/bin/
15
- ENTRYPOINT ["/usr/local/bin/bdy"]
package/link.sh DELETED
@@ -1,3 +0,0 @@
1
- #!/bin/bash -e
2
-
3
- npm link
@@ -1,127 +0,0 @@
1
- const AgentSystem = require('./system');
2
- const path = require('path');
3
- const { exec } = require('child_process');
4
- const logger = require('../logger');
5
- const { LOG_AGENT_SYSTEM_DIR,
6
- LOG_AGENT_DOWNLOADING_ARCHIVE,
7
- LOG_AGENT_EXTRACTING_ARCHIVE,
8
- LOG_AGENT_SYSTEM_SERVICE_CONFIG,
9
- LOG_AGENT_ENABLING_SYSTEM,
10
- LOG_AGENT_ENABLED,
11
- LOG_AGENT_STOPPING_SYSTEM,
12
- LOG_AGENT_STARTING_SYSTEM
13
- } = require('../texts');
14
-
15
- class AgentLinux extends AgentSystem {
16
- hasAdminRights() {
17
- return new Promise((resolve) => {
18
- resolve(process.getuid() === 0);
19
- });
20
- }
21
-
22
- isSupported() {
23
- return new Promise((resolve) => {
24
- this.systemctl('--version').then(() => {
25
- resolve(['arm64', 'x64'].includes(process.arch));
26
- }).catch(() => {
27
- resolve(false);
28
- });
29
- });
30
- }
31
-
32
- isEnabled() {
33
- return new Promise((resolve) => {
34
- this.systemctl('is-enabled bdy').then(() => {
35
- resolve(true);
36
- }).catch(() => {
37
- resolve(false);
38
- });
39
- });
40
- }
41
-
42
- getBinaryArchive() {
43
- return `linux-${process.arch}.tar.gz`;
44
- }
45
-
46
- getSystemConfigDir() {
47
- return '/etc/bdy';
48
- }
49
-
50
- getSystemConfigPath() {
51
- return path.join(this.getSystemConfigDir(), 'agent.json');
52
- }
53
-
54
- getServicePath() {
55
- return '/etc/systemd/system/bdy.service';
56
- }
57
-
58
- getServiceConfig(id, host, token, port, start, user, debug) {
59
- const cli = this.getSystemBinaryPath();
60
- return `[Unit]
61
- Description=Buddy Tunnel Agent
62
- After=network.target
63
-
64
- [Service]
65
- Environment="DEBUG=${debug ? 1 : 0}"
66
- User=${user || 'root'}
67
- WorkingDirectory=/
68
- ExecStart=${cli} agent run --id="${id}" --host="${host}" --token="${token}" --port=${port} --start=${!!start}
69
- Restart=always
70
- RestartSec=3
71
-
72
- [Install]
73
- WantedBy=multi-user.target`;
74
- }
75
-
76
- async enable(id, host, token, port, start, user, pass, debug) {
77
- try {
78
- logger.info(LOG_AGENT_SYSTEM_DIR);
79
- await this.ensureSystemConfigDir();
80
- logger.info(LOG_AGENT_DOWNLOADING_ARCHIVE);
81
- await this.downloadBinaryArchive();
82
- logger.info(LOG_AGENT_EXTRACTING_ARCHIVE);
83
- await this.extractBinaryArchive();
84
- logger.info(LOG_AGENT_SYSTEM_SERVICE_CONFIG);
85
- await this.saveFile(this.getServicePath(), this.getServiceConfig(id, host, token, port, start, user, debug));
86
- logger.info(LOG_AGENT_ENABLING_SYSTEM);
87
- await this.systemctl('enable --now bdy');
88
- logger.info(LOG_AGENT_ENABLED);
89
- } catch (err) {
90
- logger.error(err);
91
- throw err;
92
- }
93
- }
94
-
95
- async update() {
96
- try {
97
- logger.info(LOG_AGENT_STOPPING_SYSTEM);
98
- await this.systemctl('stop bdy');
99
- logger.info(LOG_AGENT_SYSTEM_DIR);
100
- await this.ensureSystemConfigDir();
101
- logger.info(LOG_AGENT_DOWNLOADING_ARCHIVE);
102
- await this.downloadBinaryArchive();
103
- logger.info(LOG_AGENT_EXTRACTING_ARCHIVE);
104
- await this.extractBinaryArchive();
105
- logger.info(LOG_AGENT_STARTING_SYSTEM);
106
- await this.systemctl('start bdy');
107
- } catch (err) {
108
- logger.error(err);
109
- throw err;
110
- }
111
- }
112
-
113
- async disable() {
114
- return this.systemctl('disable --now bdy');
115
- }
116
-
117
- systemctl(cmd) {
118
- return new Promise((resolve, reject) => {
119
- exec(`systemctl ${cmd}`, (err, stdout, stderr) => {
120
- if (!err) resolve(stdout, stderr);
121
- else reject(err, stderr);
122
- });
123
- });
124
- }
125
- }
126
-
127
- module.exports = AgentLinux;
@@ -1,404 +0,0 @@
1
- const {
2
- ApiErrorAgentNotFound,
3
- AGENT_STATUS_DISABLED,
4
- AGENT_STATUS_ENABLED,
5
- AGENT_STATUS_FETCH_FAILED,
6
- getVersion,
7
- sleep
8
- } = require('../utils.js');
9
- const { WebSocketServer } = require('ws');
10
- const logger = require('../logger.js');
11
- const http = require('http');
12
- const Output = require('../output.js');
13
- const {
14
- AGENT_FETCH_RETRY,
15
- ERR_AGENT_NOT_REGISTERED,
16
- LOG_AGENT_SERVER_STARTED,
17
- LOG_AGENT_STARTED,
18
- LOG_ERROR_STARTING_AGENT_SERVER,
19
- LOG_REQUEST
20
- } = require('../texts.js');
21
- const AgentSocket = require('./socket.js');
22
- const ApiBuddy = require('../api/buddy.js');
23
- const { isOsx,
24
- AGENT_STATUS_INITIALIZING,
25
- isLinux,
26
- isWindows,
27
- TUNNEL_SSH,
28
- createSshHostKey
29
- } = require('../utils');
30
- const AgentOsx = require('./osx');
31
- const { ERR_AGENT_NOT_FOUND,
32
- ERR_SAVING_AGENT_CONFIG
33
- } = require('../texts');
34
- const AgentSystem = require('./system');
35
- const AgentLinux = require('./linux');
36
- const AgentWindows = require('./windows');
37
-
38
- class AgentManagerClass {
39
- constructor() {
40
- this.status = AGENT_STATUS_DISABLED;
41
- this.id = null;
42
- this.host = null;
43
- this.token = null;
44
- this.port = null;
45
- this.shouldStart = null;
46
- this.sshHostKey = null;
47
- this.agent = null;
48
- this.server = null;
49
- this.ws = null;
50
- if (isOsx()) {
51
- this.system = new AgentOsx();
52
- } else if (isLinux()) {
53
- this.system = new AgentLinux();
54
- } else if (isWindows()) {
55
- this.system = new AgentWindows();
56
- } else {
57
- this.system = new AgentSystem();
58
- }
59
- }
60
-
61
- start(id, host, token, port, start) {
62
- this.load(id, host, token, parseInt(port, 10), !!start).then();
63
- }
64
-
65
- async tryFetch() {
66
- try {
67
- this.agent = await ApiBuddy.fetchAgent(this.id, this.host, this.token);
68
- this.agent.manager = this;
69
- this.agent.startRefreshingConfiguration((success) => {
70
- if (success) this.status = AGENT_STATUS_ENABLED;
71
- else this.status = AGENT_STATUS_FETCH_FAILED;
72
- });
73
- if (this.shouldStart) await this.agent.start();
74
- this.status = AGENT_STATUS_ENABLED;
75
- } catch (err) {
76
- if (err instanceof ApiErrorAgentNotFound) {
77
- await this.disableAgentAndExit(ERR_AGENT_NOT_FOUND);
78
- } else {
79
- Output.normal(AGENT_FETCH_RETRY);
80
- this.status = AGENT_STATUS_FETCH_FAILED;
81
- await sleep(3000);
82
- return this.tryFetch();
83
- }
84
- }
85
- }
86
-
87
- serverOutput(res, data) {
88
- res.statusCode = 200;
89
- res.setHeader('content-type', 'application/json');
90
- res.end(JSON.stringify(data));
91
- }
92
-
93
- server404(res) {
94
- res.statusCode = 404;
95
- res.end('Not found');
96
- }
97
-
98
- serverError(res, message) {
99
- res.statusCode = 400;
100
- res.end(JSON.stringify({
101
- message
102
- }));
103
- }
104
-
105
- async processTunnels(res) {
106
- const tunnels = [];
107
- if (this.agent) {
108
- this.agent.tunnels.forEach((tunnel) => {
109
- if (tunnel.type === TUNNEL_SSH) return;
110
- tunnels.push({
111
- id: tunnel.id,
112
- type: tunnel.type,
113
- target: tunnel.target,
114
- domain: tunnel.domain,
115
- subdomain: tunnel.subdomain,
116
- serve: tunnel.serve,
117
- status: tunnel.status,
118
- region: tunnel.region,
119
- sshId: tunnel.sshId,
120
- sshForwardPort: tunnel.sshForwardPort,
121
- regionLatency: tunnel.regionLatency ? tunnel.regionLatency.latency : -1,
122
- targetLatency: tunnel.targetLatency ? tunnel.targetLatency.latency : -1
123
- });
124
- });
125
- }
126
- this.serverOutput(res, {
127
- tunnels
128
- });
129
- }
130
-
131
- async processStatus(res) {
132
- this.serverOutput(res, {
133
- id: this.id,
134
- status: this.status,
135
- version: getVersion(),
136
- started: this.shouldStart,
137
- enabled: this.status === AGENT_STATUS_ENABLED
138
- });
139
- }
140
-
141
- processBody(req) {
142
- return new Promise((resolve, reject) => {
143
- let data = '';
144
- req.setEncoding('utf-8');
145
- req.on('data', (d) => {
146
- data += d;
147
- });
148
- req.on('end', () => {
149
- try {
150
- resolve(JSON.parse(data));
151
- } catch (err) {
152
- reject(err);
153
- }
154
- });
155
- });
156
- }
157
-
158
- async processTunnelStop(req, res) {
159
- if (!this.agent) {
160
- this.serverError(res, 'Agent not enabled');
161
- return;
162
- }
163
- let data;
164
- try {
165
- data = await this.processBody(req);
166
- } catch (err) {
167
- this.serverError(res, 'Wrong input data');
168
- return;
169
- }
170
- const tunnel = this.agent.destroyTunnel(data.id);
171
- if (!tunnel) {
172
- this.serverError(res, 'Tunnel not found');
173
- return;
174
- }
175
- try {
176
- await ApiBuddy.removeTunnel(this.id, tunnel.id, this.host, this.token);
177
- } catch (err) {
178
- this.serverError(res, err.message);
179
- return;
180
- }
181
- this.serverOutput(res, {
182
- success: true
183
- });
184
- }
185
-
186
- async agentRestart() {
187
- let saved = await this.agentStop();
188
- if (!saved) return false;
189
- return await this.agentStart();
190
- }
191
-
192
- async disableAgentAndExit(txt) {
193
- logger.error(txt);
194
- try {
195
- await this.system.disable();
196
- } catch {
197
- // do nothing
198
- }
199
- try {
200
- await ApiBuddy.unregister(this.id, this.host, this.token);
201
- } catch {
202
- // do nothing
203
- }
204
- try {
205
- this.system.clearSystemFiles();
206
- } catch {
207
- // do nothing
208
- }
209
- try {
210
- this.system.clearAgentFiles();
211
- } catch {
212
- // do nothing
213
- }
214
- Output.exitError(txt);
215
- }
216
-
217
- async agentStop() {
218
- const saved = this.resaveAgentConfig(false, true);
219
- if (!saved) return false;
220
- await this.agent.stop();
221
- return true;
222
- }
223
-
224
- async processAgentRestart(req, res) {
225
- if (!this.agent) {
226
- this.serverError(res, 'Agent not enabled');
227
- return;
228
- }
229
- const saved = await this.agentRestart();
230
- if (!saved) {
231
- this.serverError(res, 'Something went wrong');
232
- return;
233
- }
234
- this.serverOutput(res, {
235
- success: true
236
- });
237
- }
238
-
239
- async processAgentStop(req, res) {
240
- if (!this.agent) {
241
- this.serverError(res, 'Agent not enabled');
242
- return;
243
- }
244
- const saved = await this.agentStop();
245
- if (!saved) {
246
- this.serverError(res, 'Something went wrong');
247
- return;
248
- }
249
- this.serverOutput(res, {
250
- success: true
251
- });
252
- }
253
-
254
- async agentStart() {
255
- const saved = this.resaveAgentConfig(true, true);
256
- if (!saved) {
257
- return false;
258
- }
259
- await this.agent.start();
260
- return true;
261
- }
262
-
263
- async processAgentStart(req, res) {
264
- if (!this.agent) {
265
- this.serverError(res, 'Agent not enabled');
266
- return;
267
- }
268
- const saved = await this.agentStart();
269
- if (!saved) {
270
- this.serverError(res, 'Something went wrong');
271
- return;
272
- }
273
- this.serverOutput(res, {
274
- success: true
275
- });
276
- }
277
-
278
- async processTunnelAdd(req, res) {
279
- if (!this.agent) {
280
- this.serverError(res, 'Agent not enabled');
281
- return;
282
- }
283
- let data;
284
- try {
285
- data = await this.processBody(req);
286
- } catch (err) {
287
- this.serverError(res, 'Wrong input data');
288
- return;
289
- }
290
- let tunnel;
291
- try {
292
- tunnel = await ApiBuddy.addTunnel(this.id, this.host, this.token, data, this.sshHostKey);
293
- } catch (err) {
294
- this.serverError(res, err.message);
295
- return;
296
- }
297
- this.agent.addTunnel(tunnel);
298
- this.serverOutput(res, {
299
- id: tunnel.id,
300
- type: tunnel.type,
301
- });
302
- }
303
-
304
- async processRequest(req, res) {
305
- logger.info(LOG_REQUEST(req.url));
306
- if (req.url === '/status') return this.processStatus(res);
307
- if (req.url === '/tunnels') return this.processTunnels(res);
308
- if (req.url === '/tunnel/add') return this.processTunnelAdd(req, res);
309
- if (req.url === '/tunnel/stop') return this.processTunnelStop(req, res);
310
- if (req.url === '/agent/start') return this.processAgentStart(req, res);
311
- if (req.url === '/agent/stop') return this.processAgentStop(req, res);
312
- if (req.url === '/agent/restart') return this.processAgentRestart(req, res);
313
- this.server404(res);
314
- }
315
-
316
- processUpgrade(req, socket, head) {
317
- logger.info(LOG_REQUEST(req.url));
318
- const url = new URL(req.url, 'http://localhost');
319
- const id = url.searchParams.get('id');
320
- if (url.pathname === '/tunnel' && id) {
321
- this.ws.handleUpgrade(req, socket, head, (con) => {
322
- this.ws.emit('connection', con, id);
323
- });
324
- return;
325
- }
326
- socket.destroy();
327
- }
328
-
329
- processWebsocketConnection(con, id) {
330
- if (!this.agent) {
331
- con.close();
332
- return;
333
- }
334
- const tunnel = this.agent.tunnels.find((t) => t.id === id);
335
- if (!tunnel || tunnel.type === TUNNEL_SSH) {
336
- con.close();
337
- return;
338
- }
339
- new AgentSocket(con, tunnel);
340
- }
341
-
342
- createServer() {
343
- this.server = http.createServer((req, res) => this.processRequest(req, res));
344
- this.ws = new WebSocketServer({ noServer: true });
345
- this.ws.on('connection', (con, id) => this.processWebsocketConnection(con, id));
346
- this.server.on('upgrade', (req, socket, head) => this.processUpgrade(req, socket, head));
347
- this.server.listen(this.port, async (err) => {
348
- if (err) {
349
- await this.disableAgentAndExit(LOG_ERROR_STARTING_AGENT_SERVER);
350
- } else {
351
- logger.info(LOG_AGENT_SERVER_STARTED);
352
- }
353
- });
354
- }
355
-
356
- resaveAgentConfig(shouldStart, forceParam = false) {
357
- if (!forceParam) {
358
- try {
359
- // load from config
360
- const json = this.system.loadAgentConfig();
361
- this.shouldStart = !!json.shouldStart;
362
- this.sshHostKey = json.sshHostKey;
363
- } catch {
364
- // save from param
365
- this.shouldStart = shouldStart;
366
- }
367
- if (!this.sshHostKey) this.sshHostKey = createSshHostKey();
368
- } else {
369
- // save from param
370
- this.shouldStart = shouldStart;
371
- }
372
- try {
373
- // resave config
374
- this.system.saveAgentConfig(this.shouldStart, this.sshHostKey);
375
- return true;
376
- } catch {
377
- return false;
378
- }
379
- }
380
-
381
- async load(id, host, token, port, start) {
382
- this.status = AGENT_STATUS_INITIALIZING;
383
- this.id = id;
384
- this.host = host;
385
- this.token = token;
386
- this.port = parseInt(port, 10);
387
- if (!this.id || !this.token || !this.host || !this.port) {
388
- await this.disableAgentAndExit(ERR_AGENT_NOT_REGISTERED);
389
- return;
390
- }
391
- const ok = this.resaveAgentConfig(start);
392
- if (!ok) {
393
- await this.disableAgentAndExit(ERR_SAVING_AGENT_CONFIG);
394
- return;
395
- }
396
- this.createServer();
397
- await this.tryFetch();
398
- logger.info(LOG_AGENT_STARTED);
399
- }
400
- }
401
-
402
- const AgentManager = new AgentManagerClass();
403
-
404
- module.exports = AgentManager;