biz-a-cli 2.3.60 → 2.3.62

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,6 +1,7 @@
1
1
  import { apiRequestListener, RECONNECT_SOCKET_DELAY } from './hubEvent.js'
2
2
  import { deploymentListenerForVSCode } from './deployEvent.js'
3
3
  import { Tunnel as QuickTunnel } from 'cloudflared'
4
+ import { Server as ioServer } from 'socket.io'
4
5
 
5
6
  export const CLIENT_ROOM = 'clientRoom'
6
7
 
@@ -46,25 +47,40 @@ export async function localhostTunnel(port, notifier){
46
47
 
47
48
  export function directHubEvent(serverSocket, argv){
48
49
  serverSocket.on('connection', (clientSocket) => {
50
+
51
+ const setConnectListeners = (sock)=>{
52
+ // shall not log in production mode
53
+ if (process.env.NODE_ENV !== 'production') {
54
+ const id = `<${sock.handshake?.query?.isClient ? `Client` : sock.handshake?.query?.isDeploy ? 'Deployer' : 'Anonymous'}> ${sock.id}`;
55
+ console.log(id, `connected`)
56
+ sock.on('disconnect', (reason)=>{
57
+ console.log(id, `disconnected. Reason : ${reason}`)
58
+ })
59
+ };
60
+ };
61
+
49
62
  if (clientSocket.handshake.query.isClient) {
50
- clientSocket.join(CLIENT_ROOM);
63
+ setConnectListeners(clientSocket);
51
64
  apiRequestListener(clientSocket, argv);
65
+ clientSocket.join(CLIENT_ROOM);
52
66
  }
53
67
  else if (clientSocket.handshake.query.isDeploy) {
68
+ setConnectListeners(clientSocket);
54
69
  deploymentListenerForVSCode(clientSocket, argv)
70
+ } else {
71
+ clientSocket.disconnect();
55
72
  }
56
-
57
- // shall not log in production mode
58
- if (process.env.NODE_ENV !== 'production') {
59
- const id = `<${clientSocket.handshake?.query?.isClient ? `Client` : clientSocket.handshake?.query?.isDeploy ? 'Deployer' : 'Anonymous'}> ${clientSocket.id}`;
60
- clientSocket.on('disconnect', (reason)=>{
61
- console.log(id, `disconnected. Reason : ${reason}`)
62
- })
63
- console.log(id, `connected`)
64
- };
65
73
  })
66
74
  }
67
75
 
68
- export function getSocketCORSOrigin(cliIpAddress){
69
- return ['https://biz-a.id', 'https://test.biz-a.id', /\.biz-a\.id$/, 'vscode-file://vscode-app', /\.vscode-cdn\.net$/].concat((process.env.NODE_ENV === 'production') ? [] : [`http://${cliIpAddress}:4200`, 'http://localhost:4200'])
70
- }
76
+ export function createSocketServer(httpServer, cliIpAddress='127.0.0.1'){
77
+ return new ioServer(
78
+ httpServer,
79
+ {
80
+ cors: {origin: ['https://biz-a.id', 'https://test.biz-a.id', /\.biz-a\.id$/, 'vscode-file://vscode-app', /\.vscode-cdn\.net$/].concat((process.env.NODE_ENV === 'production') ? [] : [`http://${cliIpAddress}:4200`, 'http://localhost:4200'])},
81
+ maxHttpBufferSize: 1e8, // 100 MB
82
+ pingInterval: 35000, // default = 25000
83
+ pingTimeout: 30000 // default = 20000
84
+ }
85
+ );
86
+ };
package/bin/hub.js CHANGED
@@ -1,12 +1,15 @@
1
1
  #!/usr/bin/env node
2
2
 
3
+ if (!process.env.NODE_ENV) {
4
+ process.env.NODE_ENV = 'production';
5
+ };
6
+
3
7
  import yargs from 'yargs';
4
8
  import { io as ioClient } from "socket.io-client";
5
9
  import { streamEvent, hubEvent, RECONNECT_SOCKET_DELAY } from './hubEvent.js'
6
10
  import { createLogger, transports, format } from "winston";
7
- import { Server as ioServer } from 'socket.io'
8
11
  import os from 'node:os'
9
- import { directHubEvent, localhostTunnel, getSocketCORSOrigin }from './directHubEvent.js'
12
+ import { directHubEvent, localhostTunnel, createSocketServer }from './directHubEvent.js'
10
13
  import { env } from "../envs/env.js"
11
14
 
12
15
  const logger = createLogger({
@@ -87,7 +90,8 @@ const argv = yargs(process.argv.slice(2))
87
90
  type: 'number',
88
91
  demandOption: false
89
92
  })
90
- .options('hub', {
93
+ .options('hs', {
94
+ alias: 'hubServer',
91
95
  default: `${env.BIZA_HUB_SERVER_LINK}`,
92
96
  describe: 'BizA hub',
93
97
  type: 'string',
@@ -129,6 +133,10 @@ app.set('args', argv);
129
133
 
130
134
  app.use('/cb', runCliScript);
131
135
 
136
+ app.use('/status', (req, res)=>{
137
+ res.status(200).json(argv.cliAddress());
138
+ });
139
+
132
140
  // create HTTP(s) Server
133
141
  const keyFile = path.join(import.meta.dirname, "../cert/key.pem")
134
142
  const certFile = path.join(import.meta.dirname, "../cert/cert.pem")
@@ -148,8 +156,8 @@ server.listen(argv.serverport, () => {
148
156
  await streamEvent(ioClient(argv['server'], {query: {isSockStream: true }}), argv); // as socket client to BizA SERVER
149
157
 
150
158
  // as socket client to BizA HUB
151
- if (argv.hub) {
152
- hubEvent(ioClient(argv['hub'], { reconnectionDelay: RECONNECT_SOCKET_DELAY, reconnectionDelayMax: RECONNECT_SOCKET_DELAY, query: {isCLI: true, room: argv['subdomain']} }), argv, (url)=>{
159
+ if (argv.hubServer) {
160
+ hubEvent(ioClient(argv['hubServer'], { reconnectionDelay: RECONNECT_SOCKET_DELAY, reconnectionDelayMax: RECONNECT_SOCKET_DELAY, query: {isCLI: true, room: argv['subdomain']} }), argv, (url)=>{
153
161
  if (url!==argv.connectedHubUrl) {
154
162
  argv.connectedHubUrl = url
155
163
  }
@@ -157,7 +165,8 @@ if (argv.hub) {
157
165
  }
158
166
 
159
167
  // as socket server for BizA Client and BizA devTools
160
- directHubEvent(new ioServer(server, {cors: {origin: getSocketCORSOrigin(argv.cliAddress().ip)}}), argv);
168
+ directHubEvent(createSocketServer(server, argv.cliAddress().ip), argv);
169
+
161
170
  if (argv.publish==true) {
162
171
  localhostTunnel(argv.serverport, (url)=>{ // publish CLI
163
172
  if (url!==argv.connectedPublicUrl) {
package/bin/hubEvent.js CHANGED
@@ -134,8 +134,8 @@ export const hubEvent = (socket, argv, notifier)=>{
134
134
  let id
135
135
  socket.on('connect', ()=>{
136
136
  id = socket.id
137
- notifier(argv['hub'])
138
- console.log(`${new Date()}: ${getIdText(id)}connected to BizA Hub at ${argv['hub']} using sub domain "${argv['subdomain']}"`)
137
+ notifier(argv['hubServer'])
138
+ console.log(`${new Date()}: ${getIdText(id)}connected to BizA Hub at ${argv['hubServer']} using sub domain "${argv['subdomain']}"`)
139
139
  })
140
140
  socket.on('disconnect', (reason)=>{
141
141
  notifier('')
@@ -164,7 +164,6 @@ export const hubEvent = (socket, argv, notifier)=>{
164
164
 
165
165
  export const apiRequestListener = (socket, argv)=>{
166
166
  socket.on('apiRequest', (reqData, resCB)=>{
167
-
168
167
  let apiAddress = `${argv['secure']==true ? 'https://' : 'http://'}${argv['hostname']}:${argv['port']}`
169
168
  let reqBody = reqData.body
170
169
  try{
@@ -176,14 +175,23 @@ export const apiRequestListener = (socket, argv)=>{
176
175
  }
177
176
  } catch (error) {}
178
177
 
179
- const socketResponse = (resp)=>{return {
180
- status: resp.status,
181
- statusText: resp.statusText,
182
- headers: resp.headers,
183
- body: resp.data,
184
- url: apiAddress + resp.config.url
185
- }}
186
-
178
+ const socketResponse = (resp)=>{
179
+ const cliAddress = argv.cliAddress();
180
+ let cliAddressHeaders = {};
181
+ if (cliAddress.publicUrl) {
182
+ cliAddressHeaders['biza-cli-address'] = cliAddress.publicUrl;
183
+ };
184
+ if (cliAddress.hubUrl) {
185
+ cliAddressHeaders['biza-hub-address'] = cliAddress.hubUrl;
186
+ };
187
+ return {
188
+ status: resp.status,
189
+ statusText: resp.statusText,
190
+ headers: {...resp.headers, ...cliAddressHeaders},
191
+ body: resp.data,
192
+ url: apiAddress + resp.config.url
193
+ };
194
+ };
187
195
  if (argv['subdomain'].localeCompare(reqData.subDomain)==0) {
188
196
  axios.request({
189
197
  timeout : (reqData.timeout || IDLE_SOCKET_TIMEOUT_MILLISECONDS),
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "biz-a-cli",
3
3
  "nameDev": "biz-a-cli-dev",
4
- "version": "2.3.60",
4
+ "version": "2.3.62",
5
5
  "versionDev": "0.0.34",
6
6
  "description": "",
7
7
  "main": "bin/index.js",
@@ -14,7 +14,7 @@
14
14
  "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js --watch a",
15
15
  "testOnce": "node --experimental-vm-modules node_modules/jest/bin/jest.js",
16
16
  "dev": "node --watch server.js",
17
- "hub": "set NODE_ENV=production && node --experimental-vm-modules bin/hub.js"
17
+ "hub": "set NODE_ENV=dev&& node --experimental-vm-modules bin/hub.js"
18
18
  },
19
19
  "author": "Imamatek",
20
20
  "license": "ISC",
@@ -3,7 +3,7 @@ import { getAppData, onScriptChangeFromVsCode, onScriptChangeFromHubServer} from
3
3
  import { io as ioClient, Socket, Manager } from "socket.io-client";
4
4
  import { expect, jest } from '@jest/globals';
5
5
  import axios from "axios";
6
- import { directHubEvent, getSocketCORSOrigin, CLIENT_ROOM } from '../bin/directHubEvent.js'
6
+ import { directHubEvent, CLIENT_ROOM } from '../bin/directHubEvent.js'
7
7
  import { createDecipheriv } from 'node:crypto'
8
8
  import { hubEvent } from '../bin/hubEvent.js';
9
9
 
@@ -38,18 +38,6 @@ describe('Deployment', () => {
38
38
  jest.restoreAllMocks()
39
39
  })
40
40
 
41
- it('shall allow origins', ()=>{
42
- expect(getSocketCORSOrigin(hostname)).toStrictEqual([
43
- 'https://biz-a.id',
44
- 'https://test.biz-a.id',
45
- /\.biz-a\.id$/,
46
- 'vscode-file://vscode-app',
47
- /\.vscode-cdn\.net$/,
48
- `http://${hostname}:4200`,
49
- 'http://localhost:4200'
50
- ])
51
- })
52
-
53
41
  it('shall get app list from database', async ()=>{
54
42
  // Failed : check for error message
55
43
  const requestSpy = jest.spyOn(axios, 'request').mockResolvedValueOnce({
@@ -174,7 +162,7 @@ describe('Deployment', () => {
174
162
  jest.spyOn(console, 'log').mockImplementation()
175
163
 
176
164
  vsCodeToCLISock = await toPromise((resolve)=>{
177
- const sock = ioClient(`http://${hostname}:${port}`).on('connect', async ()=>{
165
+ const sock = ioClient(`http://${hostname}:${port}`, {query: {isDeploy: true}}).on('connect', async ()=>{
178
166
  serverSideSock = (await cliSocketServer.fetchSockets()).find((s)=>s.id==sock.id)
179
167
 
180
168
  // if using socket.broadcast.emit()
package/tests/hub.test.js CHANGED
@@ -9,7 +9,7 @@ import tls from 'node:tls'
9
9
  import ss from 'socket.io-stream'
10
10
  import { Writable, pipeline } from 'node:stream'
11
11
  import { text } from 'node:stream/consumers'
12
- import { directHubEvent } from '../bin/directHubEvent.js'
12
+ import { directHubEvent, createSocketServer } from '../bin/directHubEvent.js'
13
13
 
14
14
  let socketsBySubdomain = {};
15
15
 
@@ -154,7 +154,7 @@ describe('Hub event tests', () => {
154
154
  port: 212,
155
155
  serverport: 3002,
156
156
  cliAddress: ()=>{return {ip: '59.60.1.22', port: '3002', address: `59.60.1.22:3002`, publicUrl: 'https://some.public.url', hubUrl: 'https://some.hub.url'}},
157
- hub: 'https://some.hub.url'
157
+ hubServer: 'https://some.hub.url'
158
158
  })
159
159
 
160
160
  mockAPIServer = net.createServer((clientSocket)=>{
@@ -234,8 +234,7 @@ describe('Hub event tests', () => {
234
234
 
235
235
  beforeAll(()=>{
236
236
  cliSocketServer = new ioServer(9999)// mocking of CLI socket server
237
- directHubEvent(cliSocketServer, {subdomain, hostname: apiAddress, port, secure: false})
238
-
237
+ directHubEvent(cliSocketServer, {subdomain, hostname: apiAddress, port, secure: false, cliAddress: ()=>{return {ip: '59.60.1.22', port: '3002', address: `59.60.1.22:3002`, publicUrl: 'https://some.public.url', hubUrl: 'https://some.hub.url'}}});
239
238
  clientToCliSocket = ioClient('http://localhost:9999', {query: {isClient:true}})
240
239
  })
241
240
 
@@ -260,14 +259,16 @@ describe('Hub event tests', () => {
260
259
  clientToCliSocket.emit(
261
260
  'apiRequest'
262
261
  , {subDomain: subdomain, method: 'POST', path: '/test', headers: {'req-header': 'aa'}, body: 'body of request', responseType: 'json'}
263
- , (err, res)=>{resolve([err, res])}
262
+ , (err, res)=>{
263
+ resolve([err, res])
264
+ }
264
265
  )
265
266
  })
266
267
 
267
268
  expect(response).toStrictEqual({
268
269
  status: 200,
269
270
  statusText: 'Success',
270
- headers: {'res-header': 'aa'},
271
+ headers: {'res-header': 'aa', "biza-cli-address": "https://some.public.url", "biza-hub-address": "https://some.hub.url"},
271
272
  body: 'body of response',
272
273
  url: `http://${apiAddress}:${port}/test`
273
274
  })
@@ -363,7 +364,7 @@ describe('Hub event tests', () => {
363
364
  port,
364
365
  serverport: 3002,
365
366
  cliAddress: ()=>{return {ip: '59.60.1.22', port: '3002', address: `59.60.1.22:3002`, publicUrl: 'https://some.tunnel.url'}},
366
- hub: 'https://some.hub.url'
367
+ hubServer: 'https://some.hub.url'
367
368
  },
368
369
  (hubUrl)=>{
369
370
  expect(hubUrl).toBe('https://some.hub.url')
@@ -398,7 +399,7 @@ describe('Hub event tests', () => {
398
399
  expect(result.response).toStrictEqual({
399
400
  status: 200,
400
401
  statusText: 'Success',
401
- headers: {'res-header': 'aa'},
402
+ headers: {'res-header': 'aa', "biza-cli-address": "https://some.tunnel.url"},
402
403
  body: 'body of response',
403
404
  url: `http://127.0.0.1:${port}/test`
404
405
  })
@@ -420,7 +421,7 @@ describe('Hub event tests', () => {
420
421
  expect(result.response).toStrictEqual({
421
422
  status: 200,
422
423
  statusText: 'Success',
423
- headers: {'res-header': 'aa'},
424
+ headers: {'res-header': 'aa', 'biza-cli-address': 'https://some.tunnel.url'},
424
425
  body: 'body of response',
425
426
  url: 'http://apiHost:apiPort/test'
426
427
  })
@@ -442,7 +443,7 @@ describe('Hub event tests', () => {
442
443
  expect(result.response).toStrictEqual({
443
444
  status: 200,
444
445
  statusText: 'Success',
445
- headers: {'res-header': 'aa'},
446
+ headers: {'res-header': 'aa', 'biza-cli-address': 'https://some.tunnel.url'},
446
447
  body: 'body of response',
447
448
  url: 'http://apiHost:apiPort/test'
448
449
  })
@@ -467,4 +468,27 @@ describe('Hub event tests', () => {
467
468
  }
468
469
  })
469
470
 
471
+ test('shall create socket server with correct options', ()=>{
472
+ const sockHttpServer = createServer();
473
+ const sockServer = createSocketServer(sockHttpServer, '1.2.3.4');
474
+ try {
475
+ const opts = sockServer.opts;
476
+ expect(opts.cors.origin).toStrictEqual([
477
+ 'https://biz-a.id',
478
+ 'https://test.biz-a.id',
479
+ /\.biz-a\.id$/,
480
+ 'vscode-file://vscode-app',
481
+ /\.vscode-cdn\.net$/,
482
+ 'http://1.2.3.4:4200',
483
+ 'http://localhost:4200'
484
+ ]);
485
+ expect(opts.maxHttpBufferSize).toBe(1e8);
486
+ expect(opts.pingInterval).toBe(35000);
487
+ expect(opts.pingTimeout).toBe(30000);
488
+ } finally {
489
+ sockServer.close();
490
+ sockHttpServer.close();
491
+ };
492
+ });
493
+
470
494
  })
package/constanta.js DELETED
@@ -1,8 +0,0 @@
1
- export const ECODE = {
2
- API: 'EAPI',
3
- FULL: 'full'
4
- }
5
- export const MSG = {
6
- E_USER_PASS_IN_API: 'Username or password is not valid. Check database no:1 in API',
7
- E_LICENSE_FULL: 'The license is full.',
8
- }