@contentstack/cli-utilities 1.5.1 → 1.5.3

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.
@@ -22,8 +22,10 @@ declare class AuthHandler {
22
22
  private authorisationTypeOAUTHValue;
23
23
  private authorisationTypeAUTHValue;
24
24
  private allAuthConfigItems;
25
+ private logger;
25
26
  set host(contentStackHost: any);
26
27
  constructor();
28
+ initLog(): void;
27
29
  setOAuthBaseURL(): Promise<void>;
28
30
  oauth(): Promise<object>;
29
31
  createHTTPServer(): Promise<object>;
@@ -33,6 +35,13 @@ declare class AuthHandler {
33
35
  unsetConfigData(type?: string): Promise<void>;
34
36
  refreshToken(): Promise<object>;
35
37
  getUserDetails(data: any): Promise<object>;
38
+ oauthLogout(): Promise<object>;
39
+ /**
40
+ * Fetches all authorizations for the Oauth App, returns authorizationUid for current user.
41
+ * @returns authorizationUid for the current user
42
+ */
43
+ getOauthAppAuthorization(): Promise<string | undefined>;
44
+ revokeOauthAppAuthorization(authorizationId: any): Promise<object>;
36
45
  isAuthenticated(): boolean;
37
46
  getAuthorisationType(): Promise<any>;
38
47
  isAuthorisationTypeBasic(): Promise<boolean>;
@@ -2,13 +2,14 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const tslib_1 = require("tslib");
4
4
  const cli_ux_1 = tslib_1.__importDefault(require("./cli-ux"));
5
- const logger_1 = tslib_1.__importDefault(require("./logger"));
6
5
  const http_client_1 = tslib_1.__importDefault(require("./http-client"));
7
6
  const config_handler_1 = tslib_1.__importDefault(require("./config-handler"));
8
7
  const ContentstackManagementSDK = tslib_1.__importStar(require("@contentstack/management"));
8
+ const message_handler_1 = tslib_1.__importDefault(require("./message-handler"));
9
9
  const http = require('http');
10
10
  const url = require('url');
11
11
  const open_1 = tslib_1.__importDefault(require("open"));
12
+ const logger_1 = require("./logger");
12
13
  const crypto = require('crypto');
13
14
  /**
14
15
  * @class
@@ -55,6 +56,9 @@ class AuthHandler {
55
56
  ],
56
57
  };
57
58
  }
59
+ initLog() {
60
+ this.logger = new logger_1.LoggerService(process.cwd(), 'cli-log');
61
+ }
58
62
  async setOAuthBaseURL() {
59
63
  if (config_handler_1.default.get('region')['uiHost']) {
60
64
  this.OAuthBaseURL = config_handler_1.default.get('region')['uiHost'] || '';
@@ -70,6 +74,7 @@ class AuthHandler {
70
74
  */
71
75
  async oauth() {
72
76
  return new Promise((resolve, reject) => {
77
+ this.initLog();
73
78
  this.createHTTPServer()
74
79
  .then(() => {
75
80
  this.openOAuthURL()
@@ -78,12 +83,12 @@ class AuthHandler {
78
83
  resolve({});
79
84
  })
80
85
  .catch((error) => {
81
- logger_1.default.error('OAuth login failed', error.message);
86
+ this.logger.error('OAuth login failed', error.message);
82
87
  reject(error);
83
88
  });
84
89
  })
85
90
  .catch((error) => {
86
- logger_1.default.error('OAuth login failed', error.message);
91
+ this.logger.error('OAuth login failed', error.message);
87
92
  reject(error);
88
93
  });
89
94
  });
@@ -371,6 +376,56 @@ class AuthHandler {
371
376
  }
372
377
  });
373
378
  }
379
+ async oauthLogout() {
380
+ const authorization = await this.getOauthAppAuthorization() || "";
381
+ const response = await this.revokeOauthAppAuthorization(authorization);
382
+ return response || {};
383
+ }
384
+ /**
385
+ * Fetches all authorizations for the Oauth App, returns authorizationUid for current user.
386
+ * @returns authorizationUid for the current user
387
+ */
388
+ async getOauthAppAuthorization() {
389
+ const headers = {
390
+ authorization: `Bearer ${config_handler_1.default.get(this.oauthAccessTokenKeyName)}`,
391
+ organization_uid: config_handler_1.default.get(this.oauthOrgUidKeyName),
392
+ 'Content-type': 'application/json'
393
+ };
394
+ const httpClient = new http_client_1.default().headers(headers);
395
+ await this.setOAuthBaseURL();
396
+ return httpClient
397
+ .get(`${this.OAuthBaseURL}/apps-api/manifests/${this.OAuthAppId}/authorizations`)
398
+ .then(({ data }) => {
399
+ var _a, _b;
400
+ if (((_a = data === null || data === void 0 ? void 0 : data.data) === null || _a === void 0 ? void 0 : _a.length) > 0) {
401
+ const userUid = config_handler_1.default.get(this.oauthUserUidKeyName);
402
+ const currentUserAuthorization = ((_b = data === null || data === void 0 ? void 0 : data.data) === null || _b === void 0 ? void 0 : _b.filter(element => element.user.uid === userUid)) || [];
403
+ if (currentUserAuthorization.length === 0) {
404
+ throw new Error(message_handler_1.default.parse("CLI_AUTH_LOGOUT_NO_AUTHORIZATIONS_USER"));
405
+ }
406
+ return currentUserAuthorization[0].authorization_uid; // filter authorizations by current logged in user
407
+ }
408
+ else {
409
+ throw new Error(message_handler_1.default.parse("CLI_AUTH_LOGOUT_NO_AUTHORIZATIONS"));
410
+ }
411
+ });
412
+ }
413
+ async revokeOauthAppAuthorization(authorizationId) {
414
+ if (authorizationId.length > 1) {
415
+ const headers = {
416
+ authorization: `Bearer ${config_handler_1.default.get(this.oauthAccessTokenKeyName)}`,
417
+ organization_uid: config_handler_1.default.get(this.oauthOrgUidKeyName),
418
+ 'Content-type': 'application/json'
419
+ };
420
+ const httpClient = new http_client_1.default().headers(headers);
421
+ await this.setOAuthBaseURL();
422
+ return httpClient
423
+ .delete(`${this.OAuthBaseURL}/apps-api/manifests/${this.OAuthAppId}/authorizations/${authorizationId}`)
424
+ .then(({ data }) => {
425
+ return data;
426
+ });
427
+ }
428
+ }
374
429
  isAuthenticated() {
375
430
  const authorizationType = config_handler_1.default.get(this.authorisationTypeKeyName);
376
431
  return (authorizationType === this.authorisationTypeOAUTHValue || authorizationType === this.authorisationTypeAUTHValue);
@@ -13,7 +13,7 @@ declare class Config {
13
13
  private getEncryptedConfig;
14
14
  private getDecryptedConfig;
15
15
  get(key: any): string | any;
16
- set(key: any, value: any): Promise<Conf<Record<string, unknown>>>;
16
+ set(key: any, value: any): Conf<Record<string, unknown>>;
17
17
  delete(key: any): Conf<Record<string, unknown>>;
18
18
  clear(): void;
19
19
  }
@@ -19,6 +19,7 @@ const uniqueString = require('unique-string');
19
19
  const oldConfigDirectory = xdgBasedir.config || path.join(os.tmpdir(), uniqueString());
20
20
  const pathPrefix = path.join('configstore', `${CONFIG_NAME}.json`);
21
21
  const oldConfigPath = path.join(oldConfigDirectory, pathPrefix);
22
+ const cwd = process.env.CS_CLI_CONFIG_PATH;
22
23
  class Config {
23
24
  constructor() {
24
25
  this.init();
@@ -73,7 +74,7 @@ class Config {
73
74
  }
74
75
  getObfuscationKey() {
75
76
  const obfuscationKeyName = 'obfuscation_key';
76
- const encConfig = new conf_1.default({ configName: ENC_CONFIG_NAME });
77
+ const encConfig = new conf_1.default({ configName: ENC_CONFIG_NAME, cwd });
77
78
  let obfuscationKey = encConfig === null || encConfig === void 0 ? void 0 : encConfig.get(obfuscationKeyName);
78
79
  if (!obfuscationKey) {
79
80
  encConfig.set(obfuscationKeyName, (0, uuid_1.v4)());
@@ -97,7 +98,7 @@ class Config {
97
98
  try {
98
99
  // NOTE reading current code base encrypted file if exist
99
100
  const encryptionKey = this.getObfuscationKey();
100
- this.config = new conf_1.default({ configName: CONFIG_NAME, encryptionKey });
101
+ this.config = new conf_1.default({ configName: CONFIG_NAME, encryptionKey, cwd });
101
102
  if ((_a = Object.keys(configData || {})) === null || _a === void 0 ? void 0 : _a.length) {
102
103
  this.config.set(configData); // NOTE set config data if passed any
103
104
  }
@@ -110,7 +111,7 @@ class Config {
110
111
  this.getEncryptedConfig(oldConfigData, true);
111
112
  }
112
113
  catch (_error) {
113
- _1.cliux.print(chalk_1.default.red("Error: Config file is corrupted"));
114
+ _1.cliux.print(chalk_1.default.red('Error: Config file is corrupted'));
114
115
  _1.cliux.print(_error);
115
116
  process.exit(1);
116
117
  }
@@ -136,7 +137,7 @@ class Config {
136
137
  getDecryptedConfig(configData) {
137
138
  var _a;
138
139
  try {
139
- this.config = new conf_1.default({ configName: CONFIG_NAME });
140
+ this.config = new conf_1.default({ configName: CONFIG_NAME, cwd });
140
141
  if ((_a = Object.keys(configData || {})) === null || _a === void 0 ? void 0 : _a.length) {
141
142
  this.config.set(configData); // NOTE set config data if passed any
142
143
  }
@@ -145,7 +146,7 @@ class Config {
145
146
  // console.trace(error.message)
146
147
  try {
147
148
  const encryptionKey = this.getObfuscationKey();
148
- let config = new conf_1.default({ configName: CONFIG_NAME, encryptionKey });
149
+ let config = new conf_1.default({ configName: CONFIG_NAME, encryptionKey, cwd });
149
150
  const oldConfigData = this.getConfigDataAndUnlinkConfigFile(config);
150
151
  this.getDecryptedConfig(oldConfigData); // NOTE NOTE reinitialize the config with old data and new decrypted file
151
152
  }
@@ -158,7 +159,7 @@ class Config {
158
159
  }
159
160
  catch (__error) {
160
161
  // console.trace(error.message)
161
- _1.cliux.print(chalk_1.default.red("Error: Config file is corrupted"));
162
+ _1.cliux.print(chalk_1.default.red('Error: Config file is corrupted'));
162
163
  _1.cliux.print(_error);
163
164
  process.exit(1);
164
165
  }
@@ -170,7 +171,7 @@ class Config {
170
171
  var _a;
171
172
  return (_a = this.config) === null || _a === void 0 ? void 0 : _a.get(key);
172
173
  }
173
- async set(key, value) {
174
+ set(key, value) {
174
175
  var _a;
175
176
  (_a = this.config) === null || _a === void 0 ? void 0 : _a.set(key, value);
176
177
  return this.config;
@@ -216,8 +216,8 @@ class FsUtility {
216
216
  if (this.fileExt === 'json') {
217
217
  this.writableStream.write('}');
218
218
  }
219
- this.closeFile(closeIndexer);
220
219
  }
220
+ this.closeFile(closeIndexer);
221
221
  }
222
222
  /**
223
223
  * @method closeFile
package/lib/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { default as logger } from './logger';
1
+ export { LoggerService } from './logger';
2
2
  export { default as cliux } from './cli-ux';
3
3
  export { default as CLIError } from './cli-error';
4
4
  export { default as messageHandler } from './message-handler';
package/lib/index.js CHANGED
@@ -1,9 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.TablePrompt = exports.stdout = exports.stderr = exports.execute = exports.ux = exports.flush = exports.settings = exports.toConfiguredId = exports.toStandardizedId = exports.tsPath = exports.toCached = exports.run = exports.Plugin = exports.Parser = exports.Interfaces = exports.HelpBase = exports.Help = exports.loadHelpClass = exports.Flags = exports.Errors = exports.Config = exports.CommandHelp = exports.Args = exports.Command = exports.flags = exports.args = exports.NodeCrypto = exports.printFlagDeprecation = exports.managementSDKInitiator = exports.managementSDKClient = exports.configHandler = exports.authHandler = exports.messageHandler = exports.CLIError = exports.cliux = exports.logger = void 0;
3
+ exports.TablePrompt = exports.stdout = exports.stderr = exports.execute = exports.ux = exports.flush = exports.settings = exports.toConfiguredId = exports.toStandardizedId = exports.tsPath = exports.toCached = exports.run = exports.Plugin = exports.Parser = exports.Interfaces = exports.HelpBase = exports.Help = exports.loadHelpClass = exports.Flags = exports.Errors = exports.Config = exports.CommandHelp = exports.Args = exports.Command = exports.flags = exports.args = exports.NodeCrypto = exports.printFlagDeprecation = exports.managementSDKInitiator = exports.managementSDKClient = exports.configHandler = exports.authHandler = exports.messageHandler = exports.CLIError = exports.cliux = exports.LoggerService = void 0;
4
4
  const tslib_1 = require("tslib");
5
5
  var logger_1 = require("./logger");
6
- Object.defineProperty(exports, "logger", { enumerable: true, get: function () { return tslib_1.__importDefault(logger_1).default; } });
6
+ Object.defineProperty(exports, "LoggerService", { enumerable: true, get: function () { return logger_1.LoggerService; } });
7
7
  var cli_ux_1 = require("./cli-ux");
8
8
  Object.defineProperty(exports, "cliux", { enumerable: true, get: function () { return tslib_1.__importDefault(cli_ux_1).default; } });
9
9
  var cli_error_1 = require("./cli-error");
package/lib/logger.d.ts CHANGED
@@ -1,10 +1,10 @@
1
1
  import winston from 'winston';
2
- declare class LoggerService {
2
+ export declare class LoggerService {
3
3
  name: string;
4
4
  data: object | null;
5
5
  logger: winston.Logger;
6
6
  static dateFormat(): string;
7
- constructor(name: string);
7
+ constructor(pathToLog: string, name: string);
8
8
  init(context: any): void;
9
9
  set loggerName(name: string);
10
10
  setLogData(data: object): void;
@@ -13,5 +13,3 @@ declare class LoggerService {
13
13
  error(message: string, param?: any): Promise<any>;
14
14
  warn(message: string, param?: any): Promise<any>;
15
15
  }
16
- declare const _default: LoggerService;
17
- export default _default;
package/lib/logger.js CHANGED
@@ -1,20 +1,22 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.LoggerService = void 0;
3
4
  const tslib_1 = require("tslib");
4
5
  const winston_1 = tslib_1.__importDefault(require("winston"));
6
+ const path_1 = tslib_1.__importDefault(require("path"));
5
7
  const message_handler_1 = tslib_1.__importDefault(require("./message-handler"));
6
8
  class LoggerService {
7
9
  static dateFormat() {
8
10
  return new Date(Date.now()).toUTCString();
9
11
  }
10
- constructor(name) {
12
+ constructor(pathToLog, name) {
11
13
  this.data = null;
12
14
  this.name = null;
13
15
  const logger = winston_1.default.createLogger({
14
16
  transports: [
15
17
  // new winston.transports.Console(),
16
18
  new winston_1.default.transports.File({
17
- filename: `./logs/${name}.log`,
19
+ filename: path_1.default.resolve(process.env.CS_CLI_LOG_PATH || `${pathToLog}/logs`, `${name}.log`),
18
20
  }),
19
21
  ],
20
22
  format: winston_1.default.format.combine(winston_1.default.format.colorize(), winston_1.default.format.printf((info) => {
@@ -27,14 +29,14 @@ class LoggerService {
27
29
  }
28
30
  // parse message
29
31
  info.message = message_handler_1.default.parse(info.message);
30
- let message = `${LoggerService.dateFormat()}:${name}:${info.level}:${info.message}`;
32
+ let message = `${LoggerService.dateFormat()} : ${name}: ${info.level} : ${info.message}`;
31
33
  message = info.obj ? message + `:${stringifiedParam}` : message;
32
34
  message = this.data ? message + `:${JSON.stringify(this.data)}` : message;
33
35
  return message;
34
36
  })),
35
- // level: (config.get('logger.level') as string) || 'error',
36
- level: 'error',
37
- silent: true
37
+ // // level: (config.get('logger.level') as string) || 'error',
38
+ // level: 'error',
39
+ // silent: true
38
40
  // silent: config.get('logger.enabled') && process.env.CLI_ENV !== 'TEST' ? false : false,
39
41
  });
40
42
  this.logger = logger;
@@ -89,4 +91,4 @@ class LoggerService {
89
91
  }
90
92
  }
91
93
  }
92
- exports.default = new LoggerService('cli');
94
+ exports.LoggerService = LoggerService;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@contentstack/cli-utilities",
3
- "version": "1.5.1",
3
+ "version": "1.5.3",
4
4
  "description": "Utilities for contentstack projects",
5
5
  "main": "lib/index.js",
6
6
  "types": "lib/index.d.ts",
@@ -32,7 +32,7 @@
32
32
  "author": "contentstack",
33
33
  "license": "MIT",
34
34
  "dependencies": {
35
- "@contentstack/management": "~1.10.0",
35
+ "@contentstack/management": "~1.10.2",
36
36
  "@oclif/core": "^2.9.3",
37
37
  "axios": "1.3.4",
38
38
  "chalk": "^4.0.0",