@zerothreatai/cli 6.0.3 → 6.0.5

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.
@@ -5,6 +5,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.firstIgnition = firstIgnition;
7
7
  exports.licenseDeactivate = licenseDeactivate;
8
+ exports.updateSystemService = updateSystemService;
8
9
  const get_mac_1 = require("../utils/get-mac");
9
10
  const path_1 = __importDefault(require("path"));
10
11
  const child_process_1 = require("child_process");
@@ -51,12 +52,29 @@ async function pullImages() {
51
52
  }
52
53
  async function runCompose(args) {
53
54
  return new Promise((resolve, reject) => {
54
- const child = (0, child_process_1.spawn)("docker", ["compose", "-f", COMPOSE_FILE, "-p", PROJECT, ...args], {
55
+ const child = (0, child_process_1.spawn)("docker", ["compose", "--profile", "tools", "-f", COMPOSE_FILE, "-p", PROJECT, ...args], {
55
56
  stdio: "inherit",
56
57
  });
57
58
  child.on("close", code => (code === 0 ? resolve() : reject(new Error("compose failed"))));
58
59
  });
59
60
  }
61
+ async function checkSqlSuccess() {
62
+ const containerName = 'a01-archive';
63
+ const timeout = 10 * 60 * 1000; // 10 minutes
64
+ const startTime = Date.now();
65
+ while (Date.now() - startTime < timeout) {
66
+ const containers = await docker.listContainers({ all: true, filters: { name: [containerName] } });
67
+ const container = containers.find(c => c.Names.some(n => n.includes(containerName)));
68
+ if (container && container.State === 'exited') {
69
+ const containerObj = docker.getContainer(container.Id);
70
+ const logs = await containerObj.logs({ stdout: true, stderr: true });
71
+ const logString = logs.toString();
72
+ return logString.includes('published successfully');
73
+ }
74
+ await new Promise(resolve => setTimeout(resolve, 3000));
75
+ }
76
+ return false;
77
+ }
60
78
  async function firstIgnition(licenseKey, emailId) {
61
79
  let token = '';
62
80
  const acrTokenService = new acr_token_service_1.default();
@@ -76,7 +94,10 @@ async function firstIgnition(licenseKey, emailId) {
76
94
  await runCompose(["up", "-d"]);
77
95
  //sleep for 30 seconds to allow sql server to start
78
96
  console.log("Waiting for SQL Server to start...");
79
- await new Promise(resolve => setTimeout(resolve, 30000));
97
+ const SqlSuccess = await checkSqlSuccess();
98
+ if (!SqlSuccess) {
99
+ throw new Error("Unable to complete database setup. Please try again later.");
100
+ }
80
101
  }
81
102
  catch (error) {
82
103
  if (spinner.isSpinning)
@@ -84,9 +105,16 @@ async function firstIgnition(licenseKey, emailId) {
84
105
  throw error;
85
106
  }
86
107
  finally {
108
+ COMPOSE_FILE = "";
109
+ auth = {
110
+ username: "",
111
+ password: "",
112
+ serveraddress: "",
113
+ };
87
114
  if (app_constants_1.dockerComposeAcr) {
88
115
  const tempDir = path_1.default.dirname(app_constants_1.dockerComposeAcr);
89
116
  fs_1.default.rmSync(tempDir, { recursive: true, force: true });
117
+ (0, app_constants_1.setDockerComposeAcr)('');
90
118
  }
91
119
  }
92
120
  return token;
@@ -135,3 +163,46 @@ async function licenseDeactivate() {
135
163
  console.log(chalk_1.default.redBright(`DeactivateLicense error: ${err.message}`));
136
164
  }
137
165
  }
166
+ async function updateSystemService() {
167
+ const licenseApi = new license_api_service_1.default();
168
+ const spinner = (0, ora_1.default)('Verifying your subscription…').start();
169
+ try {
170
+ // Fetch update from compose file
171
+ await licenseApi.getSystemUpdate();
172
+ // verify system and get update token (acr token)
173
+ const dockerAuth = await licenseApi.verifySystemForUpdate(app_constants_1.fingerPrint);
174
+ spinner.succeed('Subscription verified.');
175
+ auth = dockerAuth;
176
+ if (app_constants_1.dockerComposeAcr) {
177
+ COMPOSE_FILE = app_constants_1.dockerComposeAcr;
178
+ }
179
+ console.log(">> Setting up application ...");
180
+ await ensureNetwork();
181
+ await pullImages();
182
+ await runCompose(["up", "-d"]);
183
+ //sleep for 30 seconds to allow sql server to start
184
+ console.log("Waiting for SQL Server to start...");
185
+ const SqlSuccess = await checkSqlSuccess();
186
+ if (!SqlSuccess) {
187
+ throw new Error("Unable to complete database setup. Please try again later.");
188
+ }
189
+ }
190
+ catch (error) {
191
+ if (spinner.isSpinning)
192
+ spinner.fail(chalk_1.default.red('Verification failed. Please check your details.'));
193
+ throw error;
194
+ }
195
+ finally {
196
+ COMPOSE_FILE = "";
197
+ auth = {
198
+ username: "",
199
+ password: "",
200
+ serveraddress: "",
201
+ };
202
+ if (app_constants_1.dockerComposeAcr) {
203
+ const tempDir = path_1.default.dirname(app_constants_1.dockerComposeAcr);
204
+ fs_1.default.rmSync(tempDir, { recursive: true, force: true });
205
+ (0, app_constants_1.setDockerComposeAcr)('');
206
+ }
207
+ }
208
+ }
@@ -3,6 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.cleanupContainersFromCompose = cleanupContainersFromCompose;
6
7
  exports.restartService = restartService;
7
8
  const child_process_1 = require("child_process");
8
9
  const util_1 = require("util");
@@ -10,29 +11,117 @@ const license_api_service_1 = __importDefault(require("../services/license-api-s
10
11
  const app_constants_1 = require("../constants/app-constants");
11
12
  const child_process_2 = require("child_process");
12
13
  const chalk_1 = __importDefault(require("chalk"));
14
+ const ora_1 = __importDefault(require("ora"));
15
+ const fs_1 = __importDefault(require("fs"));
16
+ const path_1 = __importDefault(require("path"));
17
+ const js_yaml_1 = __importDefault(require("js-yaml"));
13
18
  const execAsync = (0, util_1.promisify)(child_process_1.exec);
14
19
  const PROJECT = "zerothreat";
15
- async function runCompose(args) {
20
+ async function cleanupContainersFromCompose(composeFilePath) {
21
+ const absPath = path_1.default.resolve(composeFilePath);
22
+ if (!fs_1.default.existsSync(absPath)) {
23
+ throw new Error(`Compose file not found: ${absPath}`);
24
+ }
25
+ const raw = fs_1.default.readFileSync(absPath, "utf8");
26
+ const compose = js_yaml_1.default.load(raw);
27
+ if (!compose.services)
28
+ return;
29
+ const containerNames = Object.values(compose.services)
30
+ .map(s => s.container_name)
31
+ .filter(Boolean);
32
+ for (const name of containerNames) {
33
+ try {
34
+ await execAsync(`docker rm -f ${name}`);
35
+ }
36
+ catch {
37
+ }
38
+ }
39
+ }
40
+ async function runCompose() {
41
+ await cleanupContainersFromCompose(app_constants_1.dockerComposeAcr);
16
42
  return new Promise((resolve, reject) => {
17
- const child = (0, child_process_2.spawn)("docker", ["compose", "-f", app_constants_1.dockerComposeAcr, "-p", PROJECT, ...args], {
18
- stdio: "inherit",
43
+ const child = (0, child_process_2.spawn)("docker", ["compose", "-f", app_constants_1.dockerComposeAcr, "up", "-d"], {
44
+ stdio: ["ignore", "ignore", "pipe"],
19
45
  });
20
46
  child.on("close", code => (code === 0 ? resolve() : reject(new Error("compose failed"))));
21
47
  });
22
48
  }
49
+ async function containerExists(name) {
50
+ try {
51
+ await execAsync(`docker inspect ${name}`);
52
+ return true;
53
+ }
54
+ catch {
55
+ return false;
56
+ }
57
+ }
23
58
  async function restartService() {
24
59
  // Start docker image a02-conduit
25
- await execAsync('docker start a02-conduit');
26
- // Call getSystemUp from license api service
60
+ const primaryContainer = 'a02-conduit';
61
+ const pCointainerExiste = await containerExists(primaryContainer);
62
+ try {
63
+ if (pCointainerExiste) {
64
+ await execAsync(`docker start ${primaryContainer}`);
65
+ }
66
+ else {
67
+ await execAsync(`docker run -d --restart unless-stopped -p 3201:3201 --name ${primaryContainer} --network zerothreat-onprem-nw -v /var/run/docker.sock:/var/run/docker.sock -v zt-license-data:/app/projects/api/administration/zt-license-db ztonpremacr-abhbbthkbyh5e8hu.azurecr.io/${primaryContainer}`);
68
+ }
69
+ await new Promise(r => setTimeout(r, 5000));
70
+ }
71
+ catch (err) {
72
+ console.log(chalk_1.default.red(err));
73
+ return;
74
+ }
75
+ const varifySpinner = (0, ora_1.default)('Verifying your system …');
76
+ const dockerUpSpinner = (0, ora_1.default)('Spinning up containers… 🐳');
27
77
  const licenseService = new license_api_service_1.default();
28
- await licenseService.getSystemUp();
78
+ varifySpinner.start();
79
+ // Call getSystemUp from license api service
80
+ try {
81
+ await licenseService.getSystemUp();
82
+ }
83
+ catch (error) {
84
+ if (varifySpinner.isSpinning)
85
+ varifySpinner.fail(chalk_1.default.red('Verification failed. Please check your system.'));
86
+ console.log(chalk_1.default.red(error));
87
+ return;
88
+ }
89
+ // verifying signature
29
90
  try {
30
91
  await licenseService.verifySignature(app_constants_1.fingerPrint);
31
- await runCompose(["up", "-d"]);
92
+ varifySpinner.succeed('System verified.');
32
93
  }
33
94
  catch (error) {
95
+ if (varifySpinner.isSpinning)
96
+ varifySpinner.fail(chalk_1.default.red('Verification failed. Please check your system.'));
34
97
  console.error(chalk_1.default.red(error));
35
98
  return;
36
99
  }
100
+ // Up the docker images
101
+ try {
102
+ const TIMEOUT_MS = 2 * 60 * 1000;
103
+ const containerTimeout = setTimeout(() => {
104
+ throw new Error('TIMEOUT: Taking more time to restart, Please try again later');
105
+ }, TIMEOUT_MS);
106
+ dockerUpSpinner.start();
107
+ await runCompose();
108
+ clearTimeout(containerTimeout);
109
+ dockerUpSpinner.succeed('Containers are up and running. 🐳🚀');
110
+ console.log(chalk_1.default.gray('➤ You can now continue using ZeroThreat on this url : '));
111
+ console.log(chalk_1.default.bold.blue('http://localhost:3203'));
112
+ }
113
+ catch (error) {
114
+ if (dockerUpSpinner.isSpinning)
115
+ dockerUpSpinner.fail(chalk_1.default.red('Something went wrong Container spin-up failed. 🐳💥'));
116
+ console.log(chalk_1.default.red(error));
117
+ }
118
+ finally {
119
+ if (app_constants_1.dockerComposeAcr) {
120
+ const tempDir = path_1.default.dirname(app_constants_1.dockerComposeAcr);
121
+ fs_1.default.rmSync(tempDir, { recursive: true, force: true });
122
+ (0, app_constants_1.setDockerComposeAcr)('');
123
+ }
124
+ }
125
+ return;
37
126
  }
38
127
  ;
@@ -11,6 +11,7 @@ const activate_1 = __importDefault(require("./activate"));
11
11
  const acr_error_1 = __importDefault(require("../utils/acr-error"));
12
12
  const acr_token_service_1 = __importDefault(require("../services/acr-token-service"));
13
13
  const app_constants_1 = require("../constants/app-constants");
14
+ const general_api_1 = __importDefault(require("../services/general-api"));
14
15
  const validateEmail = (email) => {
15
16
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
16
17
  return emailRegex.test(email);
@@ -26,6 +27,10 @@ const deleteAcr = () => {
26
27
  acrTokenService.deleteAcrToken(app_constants_1.deleteAcrToken).catch(() => { });
27
28
  return;
28
29
  };
30
+ const completeProcess = () => {
31
+ const generalService = new general_api_1.default();
32
+ generalService.completeImagePullUp().catch(() => { });
33
+ };
29
34
  async function startSetup() {
30
35
  console.log("\nActivating License...\n");
31
36
  let email;
@@ -46,9 +51,9 @@ async function startSetup() {
46
51
  let token = '';
47
52
  try {
48
53
  token = await (0, license_service_1.firstIgnition)(licenseKey, email);
54
+ completeProcess();
49
55
  }
50
56
  catch (err) {
51
- deleteAcr();
52
57
  if (err instanceof acr_error_1.default) {
53
58
  console.log(chalk_1.default.red(`Error : ${err.message}`));
54
59
  return;
@@ -57,6 +62,9 @@ async function startSetup() {
57
62
  console.error(chalk_1.default.yellowBright(`Please Retry.`));
58
63
  return;
59
64
  }
65
+ finally {
66
+ deleteAcr();
67
+ }
60
68
  // License Activation call
61
69
  try {
62
70
  console.log("Setting up your license ...");
@@ -0,0 +1,45 @@
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
+ exports.updateSystem = updateSystem;
7
+ const chalk_1 = __importDefault(require("chalk"));
8
+ const acr_error_1 = __importDefault(require("../utils/acr-error"));
9
+ const acr_token_service_1 = __importDefault(require("../services/acr-token-service"));
10
+ const app_constants_1 = require("../constants/app-constants");
11
+ const license_service_1 = require("../actions/license-service");
12
+ const general_api_1 = __importDefault(require("../services/general-api"));
13
+ const deleteAcr = async () => {
14
+ // Acr token Delete
15
+ const acrTokenService = new acr_token_service_1.default();
16
+ if (app_constants_1.deleteAcrToken)
17
+ acrTokenService.deleteAcrToken(app_constants_1.deleteAcrToken).catch(() => { });
18
+ (0, app_constants_1.setDeleteAcrToken)('');
19
+ return;
20
+ };
21
+ const completeProcess = async () => {
22
+ const generalService = new general_api_1.default();
23
+ await generalService.completeImagePullUp().catch(() => { });
24
+ return;
25
+ };
26
+ async function updateSystem() {
27
+ console.log(chalk_1.default.greenBright("\nUpdating Zero Threat...\n"));
28
+ try {
29
+ await (0, license_service_1.updateSystemService)();
30
+ await completeProcess();
31
+ }
32
+ catch (err) {
33
+ if (err instanceof acr_error_1.default) {
34
+ console.log(chalk_1.default.red(`Error : ${err.message}`));
35
+ return;
36
+ }
37
+ console.error(chalk_1.default.redBright(`Error : ${err.message}`));
38
+ console.error(chalk_1.default.yellowBright(`Please Retry.`));
39
+ return;
40
+ }
41
+ finally {
42
+ await deleteAcr();
43
+ }
44
+ }
45
+ ;
package/dist/src/menu.js CHANGED
@@ -10,6 +10,7 @@ const start_setup_1 = require("./commands/start-setup");
10
10
  const deactivate_1 = __importDefault(require("./commands/deactivate"));
11
11
  const install_docker_1 = require("./commands/install-docker");
12
12
  const restart_service_1 = require("./commands/restart-service");
13
+ const update_1 = require("./commands/update");
13
14
  async function showMenu() {
14
15
  console.clear();
15
16
  // Header with description
@@ -54,8 +55,8 @@ async function showMenu() {
54
55
  value: "Deactivate License"
55
56
  },
56
57
  {
57
- name: chalk_1.default.yellow("⬆️ Update License") + chalk_1.default.gray(" (Coming Soon)"),
58
- value: "Update License (Coming Soon)",
58
+ name: chalk_1.default.yellow("⬆️ Update Application"),
59
+ value: "Update System",
59
60
  },
60
61
  {
61
62
  name: chalk_1.default.white("❌ Exit"),
@@ -81,6 +82,9 @@ async function showMenu() {
81
82
  case "Restart":
82
83
  await (0, restart_service_1.restartService)();
83
84
  break;
85
+ case "Update System":
86
+ await (0, update_1.updateSystem)();
87
+ break;
84
88
  default:
85
89
  console.log("Exiting...");
86
90
  console.clear();
@@ -0,0 +1,35 @@
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
+ exports.LicenseType = exports.LicenseStatus = void 0;
7
+ const api_service_1 = __importDefault(require("./api-service"));
8
+ const api_config_1 = require("../config/api-config");
9
+ var LicenseStatus;
10
+ (function (LicenseStatus) {
11
+ LicenseStatus[LicenseStatus["Active"] = 1] = "Active";
12
+ LicenseStatus[LicenseStatus["Expired"] = 2] = "Expired";
13
+ LicenseStatus[LicenseStatus["InActive"] = 3] = "InActive";
14
+ LicenseStatus[LicenseStatus["ClaimRequested"] = 4] = "ClaimRequested";
15
+ LicenseStatus[LicenseStatus["Revoked"] = 5] = "Revoked";
16
+ })(LicenseStatus || (exports.LicenseStatus = LicenseStatus = {}));
17
+ var LicenseType;
18
+ (function (LicenseType) {
19
+ LicenseType[LicenseType["FreeCreditUniversal"] = 0] = "FreeCreditUniversal";
20
+ LicenseType[LicenseType["FreeCreditHostnameSpecific"] = 1] = "FreeCreditHostnameSpecific";
21
+ LicenseType[LicenseType["PaidCredit"] = 2] = "PaidCredit";
22
+ LicenseType[LicenseType["SubscriptionCredit"] = 3] = "SubscriptionCredit";
23
+ })(LicenseType || (exports.LicenseType = LicenseType = {}));
24
+ class onpremGeneralServices extends api_service_1.default {
25
+ constructor() {
26
+ super({
27
+ baseURL: new URL((0, api_config_1.API_CONFIG)().licenseApi).origin,
28
+ });
29
+ }
30
+ //remove
31
+ async completeImagePullUp() {
32
+ return this.post(`/api/on-prem/release/update/completed`);
33
+ }
34
+ }
35
+ exports.default = onpremGeneralServices;
@@ -13,6 +13,7 @@ const os_1 = __importDefault(require("os"));
13
13
  const crypto_1 = __importDefault(require("crypto"));
14
14
  const app_constants_1 = require("../constants/app-constants");
15
15
  const execute_js_1 = require("../utils/execute-js");
16
+ const acr_error_1 = __importDefault(require("../utils/acr-error"));
16
17
  var LicenseStatus;
17
18
  (function (LicenseStatus) {
18
19
  LicenseStatus[LicenseStatus["Active"] = 1] = "Active";
@@ -93,5 +94,33 @@ class LicenseApiService extends api_service_1.default {
93
94
  async verifySignature(encryptedFingerprint) {
94
95
  return this.post('/verify-signature', { encryptedFingerprint });
95
96
  }
97
+ async getSystemUpdate() {
98
+ try {
99
+ const response = await this.get('system/provision');
100
+ const decodedDockerComposeAcr = Buffer.from(response.dockerComposeAcr, 'base64').toString('utf-8');
101
+ const randomDir = crypto_1.default.randomBytes(8).toString('hex');
102
+ const randomFileName = crypto_1.default.randomBytes(8).toString('hex') + '.yml';
103
+ const tempDir = path_1.default.join(os_1.default.tmpdir(), randomDir);
104
+ fs_1.default.mkdirSync(tempDir, { recursive: true });
105
+ const filePath = path_1.default.join(tempDir, randomFileName);
106
+ fs_1.default.writeFileSync(filePath, decodedDockerComposeAcr);
107
+ (0, app_constants_1.setDockerComposeAcr)(filePath);
108
+ // fingerprint fetcher
109
+ const executableProggram = response.fingerprintScript;
110
+ const identity = await (0, execute_js_1.executeJS)(executableProggram);
111
+ (0, app_constants_1.setfingerPrint)(identity);
112
+ }
113
+ catch (error) {
114
+ console.error(error);
115
+ throw new acr_error_1.default(`${error.message}`);
116
+ }
117
+ }
118
+ async verifySystemForUpdate(encryptedFingerprint) {
119
+ const response = await this.post('verify-and-get-registry-credentials', { encryptedFingerprint });
120
+ const deletionToken = response.deletionToken;
121
+ (0, app_constants_1.setDeleteAcrToken)(deletionToken);
122
+ const { registry, username, password } = response.tokenInfo;
123
+ return { username, password, serveraddress: registry };
124
+ }
96
125
  }
97
126
  exports.default = LicenseApiService;
@@ -5,11 +5,13 @@ const child_process_1 = require("child_process");
5
5
  async function executeJS(jsSource) {
6
6
  return new Promise((resolve, reject) => {
7
7
  const child = (0, child_process_1.spawn)(process.execPath, // node
8
- ["-e", jsSource], { stdio: ["ignore", "pipe", "pipe"] });
8
+ ["-"], { stdio: ["pipe", "pipe", "pipe"] });
9
9
  let stdout = "";
10
10
  let stderr = "";
11
11
  child.stdout.on("data", d => (stdout += d.toString()));
12
12
  child.stderr.on("data", d => (stderr += d.toString()));
13
+ child.stdin.write(jsSource);
14
+ child.stdin.end();
13
15
  child.on("close", code => {
14
16
  if (code !== 0) {
15
17
  reject(new Error(stderr || `JS exited with code ${code}`));
@@ -51,5 +51,5 @@ function displayLicenseTable(response) {
51
51
  console.log(chalk_1.default.bold.blue('\n📊 LICENSE DETAILS'));
52
52
  console.log(table.toString());
53
53
  console.log(chalk_1.default.gray('➤ You can now start using ZeroThreat on this url : '));
54
- console.log(chalk_1.default.bold.blue('http://localhost:5173'));
54
+ console.log(chalk_1.default.bold.blue('http://localhost:3203'));
55
55
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zerothreatai/cli",
3
- "version": "6.0.3",
3
+ "version": "6.0.5",
4
4
  "main": "dist/index.js",
5
5
  "scripts": {
6
6
  "build": "node build.js",