@zohocorporation/vault-cli 1.1.2

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 (102) hide show
  1. package/README.md +16 -0
  2. package/out/commands/add/add.const.js +6 -0
  3. package/out/commands/add/add.types.js +2 -0
  4. package/out/commands/add/add.util.js +35 -0
  5. package/out/commands/download/download.const.js +6 -0
  6. package/out/commands/download/download.types.js +2 -0
  7. package/out/commands/download/download.utils.js +35 -0
  8. package/out/commands/generate-password/generate-password.const.js +12 -0
  9. package/out/commands/generate-password/generate-password.types.js +2 -0
  10. package/out/commands/generate-password/generate-password.utils.js +58 -0
  11. package/out/commands/generate-template/generate-template.const.js +7 -0
  12. package/out/commands/generate-template/generate-template.types.js +2 -0
  13. package/out/commands/generate-template/generate-template.util.js +37 -0
  14. package/out/commands/get/get.const.js +8 -0
  15. package/out/commands/get/get.types.js +2 -0
  16. package/out/commands/get/get.utils.js +45 -0
  17. package/out/commands/get-default/get-default.const.js +5 -0
  18. package/out/commands/get-default/get-default.types.js +2 -0
  19. package/out/commands/get-default/get-default.utils.js +33 -0
  20. package/out/commands/list/list.const.js +7 -0
  21. package/out/commands/list/list.types.js +2 -0
  22. package/out/commands/list/list.utils.js +43 -0
  23. package/out/commands/lock/lock.action.js +13 -0
  24. package/out/commands/lock/lock.js +10 -0
  25. package/out/commands/lock/lock.utils.js +52 -0
  26. package/out/commands/login/login.action.js +22 -0
  27. package/out/commands/login/login.const.js +10 -0
  28. package/out/commands/login/login.help.js +12 -0
  29. package/out/commands/login/login.js +17 -0
  30. package/out/commands/login/login.types.js +5 -0
  31. package/out/commands/login/login.utils.js +307 -0
  32. package/out/commands/reset/reset.action.js +28 -0
  33. package/out/commands/reset/reset.help.js +8 -0
  34. package/out/commands/reset/reset.js +14 -0
  35. package/out/commands/reset/reset.utils.js +2 -0
  36. package/out/commands/search/search.action.js +30 -0
  37. package/out/commands/search/search.constants.js +14 -0
  38. package/out/commands/search/search.help.js +6 -0
  39. package/out/commands/search/search.js +26 -0
  40. package/out/commands/search/search.types.js +16 -0
  41. package/out/commands/search/search.utils.js +61 -0
  42. package/out/commands/set-default/set-default.const.js +6 -0
  43. package/out/commands/set-default/set-default.types.js +2 -0
  44. package/out/commands/set-default/set-default.utils.js +39 -0
  45. package/out/commands/unlock/unlock.action.js +23 -0
  46. package/out/commands/unlock/unlock.help.js +2 -0
  47. package/out/commands/unlock/unlock.js +12 -0
  48. package/out/commands/unlock/unlock.type.js +2 -0
  49. package/out/commands/unlock/unlock.utils.js +133 -0
  50. package/out/js/I18n/index.js +80 -0
  51. package/out/js/I18n/resources/CLI_I18N_en.js +173 -0
  52. package/out/js/I18n/resources/CLI_I18N_es.js +3 -0
  53. package/out/js/I18n/resources/CLI_I18N_fr.js +3 -0
  54. package/out/js/I18n/resources/CLI_I18N_nl.js +3 -0
  55. package/out/js/I18n/resources/CLI_I18N_pt.js +3 -0
  56. package/out/js/I18n/resources/CLI_I18N_zh.js +3 -0
  57. package/out/js/crypto/aes.js +225 -0
  58. package/out/js/crypto/index.js +139 -0
  59. package/out/js/crypto/rsa.js +1945 -0
  60. package/out/js/crypto/zohovault.js +671 -0
  61. package/out/js/logger/index.js +10 -0
  62. package/out/old/Add.js +590 -0
  63. package/out/old/Default.js +209 -0
  64. package/out/old/Download.js +69 -0
  65. package/out/old/Generate.js +171 -0
  66. package/out/old/Get.js +225 -0
  67. package/out/old/List.js +197 -0
  68. package/out/old/Login.js +287 -0
  69. package/out/old/Logout.js +21 -0
  70. package/out/old/PasswordGenerator.js +718 -0
  71. package/out/old/PasswordPolicies.js +21 -0
  72. package/out/old/PasswordTypes.js +33 -0
  73. package/out/old/Update.js +682 -0
  74. package/out/old/cmd/addcmd.js +59 -0
  75. package/out/old/cmd/downloadcmd.js +76 -0
  76. package/out/old/cmd/generate-passwordcmd.js +127 -0
  77. package/out/old/cmd/generate-templatecmd.js +59 -0
  78. package/out/old/cmd/get-defaultcmd.js +48 -0
  79. package/out/old/cmd/getcmd.js +57 -0
  80. package/out/old/cmd/listcmd.js +54 -0
  81. package/out/old/cmd/logoutcmd.js +31 -0
  82. package/out/old/cmd/set-default.js +75 -0
  83. package/out/old/cmd/updatecmd.js +44 -0
  84. package/out/old/index.js +580 -0
  85. package/out/util/configuration.util.js +103 -0
  86. package/out/util/consts.util.js +97 -0
  87. package/out/util/dbutils/db.types.js +2 -0
  88. package/out/util/dbutils/db.utils.js +164 -0
  89. package/out/util/dbutils/dbtable.utils.js +19 -0
  90. package/out/util/dev.utils.js +14 -0
  91. package/out/util/encryptionutil/encryption.uitl.js +108 -0
  92. package/out/util/index.util.js +341 -0
  93. package/out/util/keyringutil/keyring.util.js +57 -0
  94. package/out/util/loader/loader.interface.js +2 -0
  95. package/out/util/loader/transfer.loader.js +28 -0
  96. package/out/util/login.util.js +352 -0
  97. package/out/util/passwordtypes.util.js +91 -0
  98. package/out/util/print.util.js +4 -0
  99. package/out/util/search.util.js +359 -0
  100. package/out/util/types.util.js +7 -0
  101. package/out/zv.js +41 -0
  102. package/package.json +96 -0
@@ -0,0 +1,580 @@
1
+ import fs from "node:fs";
2
+ import { Logger } from "../js/logger/index.js";
3
+ import axios from "axios";
4
+ import os from "os";
5
+ import crypto from "crypto";
6
+ import Table from "cli-table3";
7
+ import convert from "xml-js";
8
+ import { highlight } from "cli-highlight";
9
+ import inquirer from "inquirer";
10
+ import yamlConverter from "js-yaml";
11
+ import { I18N } from "../js/I18n/index.js";
12
+ import chalk from "chalk";
13
+ import { CREDENTIALS } from "../util/consts.util.js";
14
+ import { Utilities } from "../util/index.util.js";
15
+ import { LoggerShutdown } from "../js/logger/index.js";
16
+ // Accounts endpoints
17
+ export const urlDeviceCode = "/oauth/v3/device/code", urlDeviceToken = "/oauth/v3/device/token", urlGenerateToken = "/oauth/v2/token";
18
+ //Vault endpoints
19
+ export const urlLogin = "/api/json/login", urlSearchSecrets = "/api/rest/json/v1/secrets/searchSecret", urlSecretTypes = "/api/rest/json/v1/secrettypes", urlOrgKey = "/api/rest/json/v1/user/orgkey", urlSecrets = "/api/rest/json/v1/secrets", urlV2Secrets = "/api/rest/json/v2/secrets", //No I18N
20
+ urlPasswordPolicies = "/api/rest/json/v1/passwordPolicies", urlDownloadFile = "/api/rest/json/v1/secrets/downloadfile", urlOldSecrets = "/api/json/secrets", urlSettingsFori18N = "/api/rest/json/v1/settings", //No I18N
21
+ urlFolder = "/api/rest/json/v1/chambers", //No I18N
22
+ urlLicense = "/api/rest/json/v1/license"; //No I18N
23
+ export const client_id = CREDENTIALS.CLIENT_ID, client_secret = CREDENTIALS.CLIENT_SECRET;
24
+ export const masterKeyFName = "masterKey", credentialsFName = "credentials.json", configurationFName = "configuration.txt";
25
+ export let OS = "linux";
26
+ if (os.platform() === "win32") {
27
+ OS = "windows";
28
+ }
29
+ else if (os.platform() === "darwin") {
30
+ OS = "mac";
31
+ }
32
+ let headers = { "User-Agent": "CLI/1.1.1 (" + OS + ")", "cliaddonversion": "/1.1.1" }; //No I18N
33
+ export const showError = (msg) => {
34
+ console.log(`error: ${msg}`);
35
+ };
36
+ export const validReadablePathCheck = (path) => {
37
+ path = path !== undefined && typeof path === "string" ? path.trim() : "";
38
+ if (path !== "") {
39
+ try {
40
+ fs.accessSync(path, fs.constants.R_OK);
41
+ return true;
42
+ }
43
+ catch (e) {
44
+ Logger.error(e);
45
+ return false;
46
+ }
47
+ }
48
+ else {
49
+ return false;
50
+ }
51
+ };
52
+ export const validPathCheck = (path) => {
53
+ path = path !== undefined && typeof path === "string" ? path.trim() : "";
54
+ if (path === "") {
55
+ return false;
56
+ }
57
+ try {
58
+ if (fs.lstatSync(path).isDirectory()) {
59
+ try {
60
+ fs.accessSync(path, fs.constants.W_OK);
61
+ return true;
62
+ }
63
+ catch (e) {
64
+ console.log(e);
65
+ return false;
66
+ }
67
+ }
68
+ else {
69
+ return false;
70
+ }
71
+ }
72
+ catch (err) {
73
+ Logger.error(err);
74
+ return false;
75
+ }
76
+ };
77
+ const pattern = {
78
+ URL: /^(http(s?)|((s|t)?)ftp|ssh|file|telnet|nfs)\:\/\/[-.\w]*(\/?)([a-zA-Z0-9\-\.\?\,\:\;\'\/\\\+=&%\$#_@!|~]*)?$/,
79
+ secretName: /^[0-9a-zA-Z_\-\.\$@\?\,\:\'\/\!\P{InBasicLatin}\s]+$/,
80
+ XSS: /[<>"+&#%^*\/()\[\]|]/g,
81
+ cleartextpattern: /[<>"&#%^*\/()\[\]|\+\=]/g
82
+ };
83
+ const validateString = (regex, str) => {
84
+ let arrMatch = [];
85
+ let res;
86
+ while ((res = regex.exec(str))) {
87
+ let resStr = "" + res;
88
+ if (arrMatch.indexOf(resStr) === -1) {
89
+ arrMatch.push(resStr);
90
+ }
91
+ }
92
+ // For IE browser '<' char not showing, so fix added
93
+ for (let i = 0; i < arrMatch.length; i++) {
94
+ let resStr = "" + arrMatch[i];
95
+ if (resStr === "<") {
96
+ arrMatch[i] = "&lt;";
97
+ }
98
+ else if (resStr === "&") {
99
+ arrMatch[i] = "&amp;";
100
+ }
101
+ }
102
+ return arrMatch.join(",");
103
+ };
104
+ export const Utilites = {
105
+ getAccountsUrl: (dc) => {
106
+ return Utilities.getAccountsUrl(dc);
107
+ },
108
+ sleep: (millis) => {
109
+ return new Promise(resolve => setTimeout(resolve, millis));
110
+ },
111
+ getVaultUrl: (dc) => {
112
+ return Utilities.getVaultUrl(dc);
113
+ },
114
+ generateRandomToken: (n) => {
115
+ return crypto.randomBytes(n).toString("hex");
116
+ },
117
+ isTrusted: () => {
118
+ const prefix = ".";
119
+ const masterKey = fs.readFileSync(prefix + masterKeyFName, "utf-8");
120
+ if (masterKey === "" || masterKey.split(",").length !== 2) {
121
+ return { status: false };
122
+ }
123
+ else {
124
+ return { status: true, masterKey: masterKey.split(",")[0] };
125
+ }
126
+ },
127
+ writeToFile: (data, filename) => {
128
+ fs.writeFile(filename, data, (err) => {
129
+ if (err !== null) {
130
+ Logger.error(err);
131
+ }
132
+ });
133
+ //fs.createWriteStream(filename).write(data, 'base64')
134
+ },
135
+ groupBy: (objectArray, property) => {
136
+ return objectArray.reduce((acc, obj) => {
137
+ const key = obj[property];
138
+ if (!acc[key]) {
139
+ acc[key] = [];
140
+ }
141
+ // Add object to list for given key's value
142
+ acc[key].push(obj);
143
+ return acc;
144
+ }, {});
145
+ },
146
+ printTable: (arr) => {
147
+ let head = Object.keys(arr[0]);
148
+ let colWidths = [];
149
+ for (let i = 0; i < head.length; i++) {
150
+ colWidths.push(20);
151
+ }
152
+ let table = new Table({
153
+ head,
154
+ style: { "padding-left": 0, "padding-right": 0, head: ['blue', 'bold'], border: ['grey'] }, //No I18N
155
+ colWidths,
156
+ wordWrap: true,
157
+ wrapWords: true
158
+ });
159
+ for (let i = 0; i < arr.length; i++) {
160
+ table.push(Object.values(arr[i]));
161
+ }
162
+ console.log(table.toString());
163
+ },
164
+ printAsXML: (obj, outFile) => {
165
+ // Convert empty strings to empty text content to avoid self-closing tags
166
+ const processObj = (o) => {
167
+ if (typeof o === 'object' && o !== null) {
168
+ for (let key in o) {
169
+ if (o[key] === '') {
170
+ o[key] = { _text: '' };
171
+ }
172
+ else if (typeof o[key] === 'object' && o[key] !== null) {
173
+ processObj(o[key]);
174
+ }
175
+ }
176
+ }
177
+ return o;
178
+ };
179
+ const processedObj = processObj(JSON.parse(JSON.stringify(obj)));
180
+ const options = { compact: true, ignoreComment: true, spaces: 4, textKey: '_text' }; //No I18N
181
+ const xmlOutput = convert.json2xml(processedObj, options);
182
+ if (outFile !== undefined) {
183
+ Utilites.writeToFile(xmlOutput, outFile);
184
+ console.log(chalk.green("File created and stored in location: " + outFile));
185
+ }
186
+ else {
187
+ console.log(highlight(xmlOutput, {
188
+ language: "xml",
189
+ ignoreIllegals: true
190
+ }));
191
+ }
192
+ },
193
+ printAsYML: (obj, outFile) => {
194
+ const yamlOutput = yamlConverter.dump(obj);
195
+ if (outFile !== undefined) {
196
+ Utilites.writeToFile(yamlOutput, outFile);
197
+ console.log(chalk.green("File created and stored in location: " + outFile));
198
+ }
199
+ else {
200
+ console.log(highlight(yamlOutput, {
201
+ language: "yaml",
202
+ ignoreIllegals: true
203
+ }));
204
+ }
205
+ },
206
+ printAsJSON: (obj, outFile) => {
207
+ if (outFile !== undefined) {
208
+ Utilites.writeToFile(JSON.stringify(obj), outFile);
209
+ console.log(chalk.green("File created and stored in location: " + outFile));
210
+ }
211
+ else {
212
+ console.log(highlight(JSON.stringify(obj, null, 4), {
213
+ language: "json",
214
+ ignoreIllegals: true
215
+ }));
216
+ }
217
+ },
218
+ getSharingPrivilege: (level) => {
219
+ if (level === 10) {
220
+ return "MANAGE";
221
+ }
222
+ else if (level === 20) {
223
+ return "AUTOLOGIN";
224
+ }
225
+ else if (level === 30) {
226
+ return "VIEW";
227
+ }
228
+ else {
229
+ return "MODIFY";
230
+ }
231
+ },
232
+ isConfigured: () => {
233
+ try {
234
+ if (fs.existsSync(configurationFName) && fs.existsSync('.' + masterKeyFName)) {
235
+ return true;
236
+ }
237
+ else {
238
+ return false;
239
+ }
240
+ }
241
+ catch (e) {
242
+ Logger.info("Problem while configuring");
243
+ }
244
+ },
245
+ XSSValidatorWithMand: (text) => {
246
+ let i18nText = new I18N();
247
+ text = text.trim();
248
+ if (text === undefined || text === "") {
249
+ return i18nText.getI18nMsg("vault.XSSValidatorWithMand.emptyField");
250
+ }
251
+ const failedChar = validateString(pattern.XSS, text);
252
+ if (failedChar !== "") {
253
+ return i18nText.getI18nMsg("vault.XSSValidatorWithMand.invalidChar") + `${new Array([failedChar]).join(" ")}`;
254
+ }
255
+ return true;
256
+ },
257
+ XSSValidator: (text) => {
258
+ let i18nText = new I18N();
259
+ text = text.trim();
260
+ if (text === "") {
261
+ return true;
262
+ }
263
+ const failedChar = validateString(pattern.XSS, text);
264
+ if (failedChar !== "") {
265
+ return i18nText.getI18nMsg("vault.XSSValidator.invalidChar") + `${new Array([failedChar]).join(" ")}`;
266
+ }
267
+ return true;
268
+ },
269
+ URLValidator: (url) => {
270
+ let i18nText = new I18N();
271
+ url = url.trim();
272
+ if (url !== "" && !pattern.URL.test(url)) {
273
+ return i18nText.getI18nMsg("vault.URLValidator.URL_invalid");
274
+ }
275
+ return true;
276
+ },
277
+ trimText: (text) => {
278
+ return text.trim();
279
+ },
280
+ FileValidator: (path) => {
281
+ let i18nText = new I18N();
282
+ path = path.trim();
283
+ if (path !== "") {
284
+ try {
285
+ fs.accessSync(path, fs.constants.R_OK);
286
+ if (fs.statSync(path).size > 2000000) {
287
+ return "File size must be less than 2MB";
288
+ }
289
+ return true;
290
+ }
291
+ catch (e) {
292
+ Logger.log(e);
293
+ return i18nText.getI18nMsg("vault.FileValidator.filePath_invalid");
294
+ }
295
+ }
296
+ return true;
297
+ },
298
+ mandFileValidator: (path) => {
299
+ let i18nText = new I18N();
300
+ path = path.trim();
301
+ if (path !== "") {
302
+ try {
303
+ fs.accessSync(path, fs.constants.R_OK);
304
+ return true;
305
+ }
306
+ catch (e) {
307
+ Logger.error(e);
308
+ return i18nText.getI18nMsg("vault.mandFileValidator.filePath_invalid");
309
+ }
310
+ }
311
+ else {
312
+ return i18nText.getI18nMsg("vault.mandFileValidator.emptyField");
313
+ }
314
+ },
315
+ mandValidator: (text) => {
316
+ let i18nText = new I18N();
317
+ text = text.trim();
318
+ if (text === "") {
319
+ return i18nText.getI18nMsg("vault.mandValidator.emptyField");
320
+ }
321
+ return true;
322
+ },
323
+ passwordMandValidator: (pass) => {
324
+ let i18nText = new I18N();
325
+ if (pass === "") {
326
+ return i18nText.getI18nMsg("vault.passwordMandValidator.emptyField");
327
+ }
328
+ return true;
329
+ },
330
+ selectionPrompt: async (start, end, message) => {
331
+ let i18nText = new I18N();
332
+ const ans = await inquirer.prompt({
333
+ type: "input",
334
+ name: "sno",
335
+ message: message,
336
+ validate: (val) => {
337
+ if (val >= start && val <= end) {
338
+ return true;
339
+ }
340
+ return (i18nText.getI18nMsg("vault.selectionPrompt.end_invalid")) + end.toString(); //No I18N
341
+ }
342
+ });
343
+ return ans.sno;
344
+ },
345
+ convertFromYAML: (yamlString) => {
346
+ return yamlConverter.load(yamlString);
347
+ },
348
+ convertFromXML: (xmlString) => {
349
+ return convert.xml2js(xmlString, { compact: true, spaces: 4 });
350
+ },
351
+ bytesToHex: (bytes) => {
352
+ return Array.from(new Uint8Array(bytes), Utilites.getHex, this).join("");
353
+ //return Array.from(bytes).map(x => Utilites.getHex(x)).join("");
354
+ },
355
+ getHex(byte) {
356
+ return ("0" + (byte).toString(16)).slice(-2);
357
+ },
358
+ async importPrivateKey(key) {
359
+ const encodingUtil = new JsEncodingUtilImpl();
360
+ const keyBuffer = encodingUtil.base64ToBytes(key);
361
+ const RSA_PARAMS = {
362
+ name: "RSA-OAEP", //No I18N
363
+ hash: "SHA-256" //No I18N
364
+ };
365
+ const privateKey = await crypto.webcrypto.subtle.importKey("pkcs8", keyBuffer, RSA_PARAMS, true, ["decrypt"]); //No I18N
366
+ return privateKey;
367
+ }
368
+ };
369
+ let JsEncodingFormat;
370
+ (function (JsEncodingFormat) {
371
+ JsEncodingFormat["HEX"] = "HEX"; //No I18N
372
+ JsEncodingFormat["BASE64"] = "BASE64"; //No I18N
373
+ JsEncodingFormat["BASE64_URL"] = "BASE64_URL"; //No I18N
374
+ JsEncodingFormat["BYTES"] = "BYTES"; //No I18N
375
+ JsEncodingFormat["ASCII"] = "ASCII"; //No I18N
376
+ })(JsEncodingFormat || (JsEncodingFormat = {}));
377
+ class JsEncodingXToByteUtil {
378
+ textEncoder = new TextEncoder();
379
+ getBytes(input) {
380
+ try {
381
+ if (input.inputBytes) {
382
+ if (input.inputBytes instanceof ArrayBuffer) {
383
+ return new Uint8Array(input.inputBytes);
384
+ }
385
+ return input.inputBytes;
386
+ }
387
+ switch (input.from) {
388
+ case JsEncodingFormat.ASCII:
389
+ return this.textEncoder.encode(input.inputString);
390
+ case JsEncodingFormat.BASE64:
391
+ return base64Util.decodeStringToBytes(input.inputString);
392
+ case JsEncodingFormat.HEX:
393
+ return gg.hexUtil.decodeHexStringToBytes(input.inputString);
394
+ default:
395
+ throw ["NEW_CASE", input];
396
+ }
397
+ }
398
+ catch (e) {
399
+ logError(e, input);
400
+ throw e;
401
+ }
402
+ }
403
+ }
404
+ class Base64Util {
405
+ alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; //No I18N
406
+ base64AlphaValueMap = null;
407
+ encodeBytesToString(bytes) {
408
+ let i = 0;
409
+ let ans = "";
410
+ for (; i + 2 < bytes.length; i += 3) {
411
+ ans += this.mapBase64C1(bytes[i]);
412
+ ans += this.mapBase64C2(bytes[i], bytes[i + 1]);
413
+ ans += this.mapBase64C3(bytes[i + 1], bytes[i + 2]);
414
+ ans += this.mapBase64C4(bytes[i + 2]);
415
+ }
416
+ switch (bytes.length - i) {
417
+ case 2:
418
+ ans += this.mapBase64C1(bytes[i]);
419
+ ans += this.mapBase64C2(bytes[i], bytes[i + 1]);
420
+ ans += this.mapBase64C3(bytes[i + 1], 0);
421
+ ans += "=";
422
+ break;
423
+ case 1:
424
+ ans += this.mapBase64C1(bytes[i]);
425
+ ans += this.mapBase64C2(bytes[i], 0);
426
+ ans += "==";
427
+ break;
428
+ }
429
+ return ans;
430
+ }
431
+ decodeStringToBytes(input) {
432
+ const alphaValue = this.getBase64AlphaValueMap();
433
+ const bytes = [];
434
+ while (input.length % 4 != 0) {
435
+ input += "=";
436
+ }
437
+ let c1 = 0, c2 = 0, c3 = 0, c4 = 0;
438
+ for (let i = 0; i < input.length; i += 4) {
439
+ c1 = alphaValue.get(input[i]);
440
+ c2 = alphaValue.get(input[i + 1]);
441
+ c3 = alphaValue.get(input[i + 2]);
442
+ c4 = alphaValue.get(input[i + 3]);
443
+ bytes.push((c1 << 2) | ((c2 & 48) >> 4));
444
+ bytes.push(((c2 & 15) << 4) | ((c3 & 60) >> 2));
445
+ bytes.push(((c3 & 3) << 6) | c4);
446
+ }
447
+ for (let i = input.length - 1; i >= 0 && input[i] == "="; i--) {
448
+ bytes.pop();
449
+ }
450
+ return new Uint8Array(bytes);
451
+ }
452
+ mapBase64C1(byte) {
453
+ return this.alphabet[(byte & 252) >> 2];
454
+ }
455
+ mapBase64C2(b1, b2) {
456
+ return this.alphabet[((b1 & 3) << 4) | ((b2 & 240) >> 4)];
457
+ }
458
+ mapBase64C3(b1, b2) {
459
+ return this.alphabet[((b1 & 15) << 2) | ((b2 & 192) >> 6)];
460
+ }
461
+ mapBase64C4(byte) {
462
+ return this.alphabet[byte & 63];
463
+ }
464
+ getBase64AlphaValueMap() {
465
+ if (this.base64AlphaValueMap == null) {
466
+ const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; //No I18N
467
+ const map = new Map(Array.from(alphabet, (x, index) => [x, index]));
468
+ map.set("=", 0);
469
+ this.base64AlphaValueMap = map;
470
+ }
471
+ return this.base64AlphaValueMap;
472
+ }
473
+ }
474
+ const base64Util = new Base64Util();
475
+ class JsEncodingByteToXUtil {
476
+ textDecoder = new TextDecoder();
477
+ convertBytes(bytes, input) {
478
+ try {
479
+ switch (input.to) {
480
+ case JsEncodingFormat.BYTES:
481
+ return { outputBytes: bytes };
482
+ case JsEncodingFormat.BASE64:
483
+ return { outputString: base64Util.encodeBytesToString(bytes) };
484
+ case JsEncodingFormat.ASCII:
485
+ return { outputString: this.textDecoder.decode(bytes) };
486
+ case JsEncodingFormat.BASE64_URL:
487
+ return { outputString: this.getBase64Url(base64Util.encodeBytesToString(bytes)) };
488
+ default:
489
+ throw ["NEW_CASE", input];
490
+ }
491
+ }
492
+ catch (e) {
493
+ logError(e, bytes, input);
494
+ throw e;
495
+ }
496
+ }
497
+ getBase64Url(text) {
498
+ return text.replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
499
+ }
500
+ }
501
+ export class JsEncodingUtilImpl {
502
+ xToByteUtil = new JsEncodingXToByteUtil();
503
+ byteToXUtil = new JsEncodingByteToXUtil();
504
+ convert(input) {
505
+ try {
506
+ const bytes = this.xToByteUtil.getBytes(input);
507
+ return this.byteToXUtil.convertBytes(bytes, input);
508
+ }
509
+ catch (e) {
510
+ throw ["FAILED_TO_ENCODE", input, e];
511
+ }
512
+ }
513
+ bytesToBase64(input) {
514
+ return this.convert({ from: JsEncodingFormat.BYTES, to: JsEncodingFormat.BASE64, inputBytes: input }).outputString;
515
+ }
516
+ bytesToBase64Url(input) {
517
+ return this.convert({ from: JsEncodingFormat.BYTES, to: JsEncodingFormat.BASE64_URL, inputBytes: input }).outputString;
518
+ }
519
+ base64ToBytes(input) {
520
+ return this.convert({ from: JsEncodingFormat.BASE64, to: JsEncodingFormat.BYTES, inputString: input }).outputBytes;
521
+ }
522
+ }
523
+ export const setHeaders = (key, val) => {
524
+ headers[key] = val;
525
+ };
526
+ export const _pull = (URL, data, method) => {
527
+ const params = new URLSearchParams();
528
+ let i18nText = new I18N();
529
+ for (const key in data) {
530
+ params.append(key, data[key]);
531
+ }
532
+ switch (method) {
533
+ case "POST":
534
+ return axios.post(URL, params, { headers })
535
+ .catch(function (e) {
536
+ Logger.error(e);
537
+ LoggerShutdown(() => {
538
+ if (e.code === 'ENOTFOUND') {
539
+ console.log(i18nText.getI18nMsg("vault.error.checkConnectivity"));
540
+ }
541
+ else {
542
+ console.log(i18nText.getI18nMsg("vault.server.errorReaching"));
543
+ }
544
+ process.exit(1);
545
+ });
546
+ throw e;
547
+ });
548
+ case "PUT":
549
+ return axios.put(URL, params, { headers })
550
+ .catch(function (e) {
551
+ Logger.error(e);
552
+ LoggerShutdown(() => {
553
+ if (e.code === 'ENOTFOUND') {
554
+ console.log(i18nText.getI18nMsg("vault.error.checkConnectivity"));
555
+ }
556
+ else {
557
+ console.log(i18nText.getI18nMsg("vault.server.errorReaching"));
558
+ }
559
+ process.exit(1);
560
+ });
561
+ throw e;
562
+ });
563
+ default:
564
+ return axios.get(URL, { headers, params: params })
565
+ .catch(function (e) {
566
+ Logger.error(e);
567
+ LoggerShutdown(() => {
568
+ if (e.code === 'ENOTFOUND') {
569
+ console.log(i18nText.getI18nMsg("vault.error.checkConnectivity"));
570
+ }
571
+ else {
572
+ console.log(i18nText.getI18nMsg("vault.server.errorReaching"));
573
+ }
574
+ process.exit(1);
575
+ });
576
+ throw e;
577
+ });
578
+ }
579
+ };
580
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,103 @@
1
+ import { Login } from "./login.util.js";
2
+ import { MODE } from "./consts.util.js";
3
+ import { ACCOUNT_ENDPOINTS, CREDENTIALS, VAULT_ENDPOINTS } from "./consts.util.js";
4
+ import { writeFileSync } from "fs";
5
+ import { _pull } from "./index.util.js";
6
+ import { generateWorkspaceHash, header } from "../commands/login/login.utils.js";
7
+ import { Utilities } from "./index.util.js";
8
+ import { getDecryptedCredentials } from "./dbutils/db.utils.js";
9
+ import { getConfig } from "./dev.utils.js";
10
+ import { insertToDB } from "./dbutils/db.utils.js";
11
+ export class Configuration extends Login {
12
+ constructor(dc) {
13
+ super(undefined, dc);
14
+ }
15
+ setDc(dc) {
16
+ super.setDC(dc);
17
+ }
18
+ setPassPhrase(passphrase) {
19
+ super.setPassPhrase(passphrase);
20
+ }
21
+ // async getConfigFromFile() {
22
+ // const credentialsPath = readFileSync(AME.CONFIGURATION_FILE_NAME, "utf-8");
23
+ // const credentials = JSON.parse(readFileSync(credentialsPath, "utf-8"));
24
+ // this.setDC(credentials.dc);
25
+ // }
26
+ generateLinkForDeviceCode() {
27
+ const scope = "ZohoVault.user.READ,ZohoVault.user.UPDATE,ZohoVault.user.CREATE,ZohoVault.user.DELETE,ZohoVault.secrets.READ,ZohoVault.secrets.UPDATE,ZohoVault.secrets.CREATE,ZohoVault.secrets.DELETE ", //No I18N
28
+ grant_type = "device_request", //No I18N
29
+ access_type = "offline"; //No I18N
30
+ const data = getConfig();
31
+ let { MODE: mode, CLIENT_ID } = data;
32
+ if (mode === MODE.PRODUCTION) {
33
+ CLIENT_ID = CREDENTIALS.CLIENT_ID;
34
+ }
35
+ return _pull(header, Utilities.getAccountsUrl(this.getDC()) + ACCOUNT_ENDPOINTS.URL_DEVICE_CODE, { scope, client_id: CLIENT_ID, grant_type, access_type }, "POST" //No I18N
36
+ );
37
+ }
38
+ generateRefreshToken(code) {
39
+ const grant_type = "device_token"; //No I18N
40
+ const data = getConfig();
41
+ let { MODE: mode, CLIENT_ID, CLIENT_SECRET } = data;
42
+ if (mode === MODE.PRODUCTION) {
43
+ CLIENT_ID = CREDENTIALS.CLIENT_ID;
44
+ CLIENT_SECRET = CREDENTIALS.CLIENT_SECRET;
45
+ }
46
+ return _pull(header, Utilities.getAccountsUrl(this.getDC()) + ACCOUNT_ENDPOINTS.URL_DEVICE_TOKEN, { code, client_id: CLIENT_ID, grant_type, client_secret: CLIENT_SECRET }, "POST" //No I18N
47
+ );
48
+ }
49
+ getUserLanguage() {
50
+ return _pull(header, Utilities.getVaultUrl(this.getDC()) + VAULT_ENDPOINTS.URL_SETTINGS_FOR_I18N, undefined, undefined);
51
+ }
52
+ writeToFile(data, filename) {
53
+ writeFileSync(filename, data);
54
+ }
55
+ // createMasterKeyFile(passphrase: string, masterKey: string, trust: boolean) {
56
+ // this.setPassPhrase(passphrase);
57
+ // let tokenKey = this.getKeyForToken();
58
+ // if (trust) {
59
+ // this.writeToFile(masterKey + "," + tokenKey, '.' + NAME.MASTER_KEY);
60
+ // } else {
61
+ // this.writeToFile(tokenKey, '.' + NAME.MASTER_KEY);
62
+ // }
63
+ // }
64
+ insertToDB(data) {
65
+ insertToDB(data);
66
+ }
67
+ insertMasterKeyToDB(passphrase, masterKey, trust, zuid) {
68
+ return new Promise(async (resolve, reject) => {
69
+ try {
70
+ if (!masterKey) {
71
+ return;
72
+ }
73
+ this.setPassPhrase(passphrase);
74
+ let tokenKey = await this.getKeyForToken();
75
+ const data = await getDecryptedCredentials(generateWorkspaceHash());
76
+ if (!data) {
77
+ return;
78
+ }
79
+ const { credentials } = data;
80
+ if (trust) {
81
+ credentials.masterkey = masterKey + "," + tokenKey;
82
+ data.hasmasterkey = true;
83
+ }
84
+ else {
85
+ credentials.masterkey = tokenKey;
86
+ }
87
+ credentials.orgkey = '';
88
+ if (zuid) {
89
+ data.zuid = zuid;
90
+ }
91
+ this.insertToDB(data);
92
+ resolve(true);
93
+ }
94
+ catch (err) {
95
+ reject(new Error("Error while inserting master key"));
96
+ }
97
+ });
98
+ }
99
+ async hasValidLicense() {
100
+ return _pull(header, Utilities.getVaultUrl(this.getDC()) + VAULT_ENDPOINTS.URL_LICENSE, undefined, undefined);
101
+ }
102
+ }
103
+ //# sourceMappingURL=configuration.util.js.map