drapcode-utility 1.1.5 → 1.1.7

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.
@@ -0,0 +1,16 @@
1
+ import { AwsConfig } from "./model";
2
+ export declare const processKMSEncryption: (config: AwsConfig, arn: string, plainText: string, context: any) => Promise<{
3
+ status: string;
4
+ data: string;
5
+ message: string;
6
+ }>;
7
+ export declare const processKMSDecryption: (config: AwsConfig, cipherText: string, context: any) => Promise<{
8
+ status: string;
9
+ data: string;
10
+ message: string;
11
+ }>;
12
+ export declare const processKMSGenerateDataKey: (config: AwsConfig, arn: string) => Promise<{
13
+ status: string;
14
+ dataKey: string;
15
+ message: string;
16
+ }>;
@@ -0,0 +1,137 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __generator = (this && this.__generator) || function (thisArg, body) {
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
+ function verb(n) { return function (v) { return step([n, v]); }; }
15
+ function step(op) {
16
+ if (f) throw new TypeError("Generator is already executing.");
17
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
+ if (y = 0, t) op = [op[0] & 2, t.value];
20
+ switch (op[0]) {
21
+ case 0: case 1: t = op; break;
22
+ case 4: _.label++; return { value: op[1], done: false };
23
+ case 5: _.label++; y = op[1]; op = [0]; continue;
24
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
+ default:
26
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
+ if (t[2]) _.ops.pop();
31
+ _.trys.pop(); continue;
32
+ }
33
+ op = body.call(thisArg, _);
34
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
+ }
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.processKMSGenerateDataKey = exports.processKMSDecryption = exports.processKMSEncryption = void 0;
40
+ var client_kms_1 = require("@aws-sdk/client-kms");
41
+ var processKMSEncryption = function (config, arn, plainText, context) { return __awaiter(void 0, void 0, void 0, function () {
42
+ var accessKeyId, secretAccessKey, region, client, input, command, response, cipherText, error_1;
43
+ return __generator(this, function (_a) {
44
+ switch (_a.label) {
45
+ case 0:
46
+ _a.trys.push([0, 2, , 3]);
47
+ accessKeyId = config.accessKeyId, secretAccessKey = config.secretAccessKey, region = config.region;
48
+ client = new client_kms_1.KMSClient({
49
+ region: region,
50
+ credentials: { accessKeyId: accessKeyId, secretAccessKey: secretAccessKey },
51
+ });
52
+ input = {
53
+ KeyId: arn,
54
+ Plaintext: Buffer.from(plainText),
55
+ EncryptionContext: context,
56
+ };
57
+ command = new client_kms_1.EncryptCommand(input);
58
+ return [4 /*yield*/, client.send(command)];
59
+ case 1:
60
+ response = _a.sent();
61
+ cipherText = Buffer.from(response.CiphertextBlob).toString("base64");
62
+ return [2 /*return*/, { status: "SUCCESS", data: cipherText, message: "" }];
63
+ case 2:
64
+ error_1 = _a.sent();
65
+ return [2 /*return*/, {
66
+ status: "FAILED",
67
+ data: "",
68
+ message: error_1.message,
69
+ }];
70
+ case 3: return [2 /*return*/];
71
+ }
72
+ });
73
+ }); };
74
+ exports.processKMSEncryption = processKMSEncryption;
75
+ var processKMSDecryption = function (config, cipherText, context) { return __awaiter(void 0, void 0, void 0, function () {
76
+ var accessKeyId, secretAccessKey, region, client, dcipherText, input, command, response, plainText, error_2;
77
+ return __generator(this, function (_a) {
78
+ switch (_a.label) {
79
+ case 0:
80
+ _a.trys.push([0, 2, , 3]);
81
+ accessKeyId = config.accessKeyId, secretAccessKey = config.secretAccessKey, region = config.region;
82
+ client = new client_kms_1.KMSClient({
83
+ region: region,
84
+ credentials: { accessKeyId: accessKeyId, secretAccessKey: secretAccessKey },
85
+ });
86
+ dcipherText = Buffer.from(cipherText, "base64");
87
+ input = {
88
+ CiphertextBlob: dcipherText,
89
+ EncryptionContext: context,
90
+ };
91
+ command = new client_kms_1.DecryptCommand(input);
92
+ return [4 /*yield*/, client.send(command)];
93
+ case 1:
94
+ response = _a.sent();
95
+ plainText = Buffer.from(response.Plaintext).toString("base64");
96
+ return [2 /*return*/, { status: "SUCCESS", data: plainText, message: "" }];
97
+ case 2:
98
+ error_2 = _a.sent();
99
+ return [2 /*return*/, { status: "FAILED", data: "", message: error_2.message }];
100
+ case 3: return [2 /*return*/];
101
+ }
102
+ });
103
+ }); };
104
+ exports.processKMSDecryption = processKMSDecryption;
105
+ var processKMSGenerateDataKey = function (config, arn) { return __awaiter(void 0, void 0, void 0, function () {
106
+ var accessKeyId, secretAccessKey, region, input, client, command, response, cipherText, error_3;
107
+ return __generator(this, function (_a) {
108
+ switch (_a.label) {
109
+ case 0:
110
+ _a.trys.push([0, 2, , 3]);
111
+ accessKeyId = config.accessKeyId, secretAccessKey = config.secretAccessKey, region = config.region;
112
+ input = {
113
+ KeyId: arn,
114
+ KeySpec: "AES_256",
115
+ };
116
+ client = new client_kms_1.KMSClient({
117
+ region: region,
118
+ credentials: { accessKeyId: accessKeyId, secretAccessKey: secretAccessKey },
119
+ });
120
+ command = new client_kms_1.GenerateDataKeyCommand(input);
121
+ return [4 /*yield*/, client.send(command)];
122
+ case 1:
123
+ response = _a.sent();
124
+ cipherText = Buffer.from(response.CiphertextBlob).toString("base64");
125
+ return [2 /*return*/, { status: "SUCCESS", dataKey: cipherText, message: "" }];
126
+ case 2:
127
+ error_3 = _a.sent();
128
+ return [2 /*return*/, {
129
+ status: "FAILED",
130
+ message: error_3.message,
131
+ dataKey: "",
132
+ }];
133
+ case 3: return [2 /*return*/];
134
+ }
135
+ });
136
+ }); };
137
+ exports.processKMSGenerateDataKey = processKMSGenerateDataKey;
@@ -0,0 +1,2 @@
1
+ export declare const encryptData: (data: string, key: string) => Promise<string>;
2
+ export declare const decryptData: (data: string, key: string) => Promise<string>;
@@ -0,0 +1,99 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __generator = (this && this.__generator) || function (thisArg, body) {
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
+ function verb(n) { return function (v) { return step([n, v]); }; }
15
+ function step(op) {
16
+ if (f) throw new TypeError("Generator is already executing.");
17
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
+ if (y = 0, t) op = [op[0] & 2, t.value];
20
+ switch (op[0]) {
21
+ case 0: case 1: t = op; break;
22
+ case 4: _.label++; return { value: op[1], done: false };
23
+ case 5: _.label++; y = op[1]; op = [0]; continue;
24
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
+ default:
26
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
+ if (t[2]) _.ops.pop();
31
+ _.trys.pop(); continue;
32
+ }
33
+ op = body.call(thisArg, _);
34
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
+ }
37
+ };
38
+ var __importDefault = (this && this.__importDefault) || function (mod) {
39
+ return (mod && mod.__esModule) ? mod : { "default": mod };
40
+ };
41
+ Object.defineProperty(exports, "__esModule", { value: true });
42
+ exports.decryptData = exports.encryptData = void 0;
43
+ var crypto_1 = __importDefault(require("crypto"));
44
+ var defaultAlgorithm = "aes-256-cbc";
45
+ var encryptData = function (data, key) { return __awaiter(void 0, void 0, void 0, function () {
46
+ var iv, keyBuffer, cipher, encryptedDataBuffer, result;
47
+ return __generator(this, function (_a) {
48
+ try {
49
+ iv = Buffer.from("i4mboZDwaNEC38YCzi77lw==", "base64");
50
+ keyBuffer = Buffer.from(key, "base64");
51
+ cipher = crypto_1.default.createCipheriv(defaultAlgorithm, keyBuffer, iv);
52
+ encryptedDataBuffer = cipher.update(data);
53
+ encryptedDataBuffer = Buffer.concat([encryptedDataBuffer, cipher.final()]);
54
+ result = encryptedDataBuffer.toString("base64");
55
+ return [2 /*return*/, handleExtraString(result, true)];
56
+ }
57
+ catch (error) {
58
+ console.log("\n Error: ", error);
59
+ return [2 /*return*/, data];
60
+ }
61
+ return [2 /*return*/];
62
+ });
63
+ }); };
64
+ exports.encryptData = encryptData;
65
+ var decryptData = function (data, key) { return __awaiter(void 0, void 0, void 0, function () {
66
+ var iv, encryptedData, keyBuffer, decipher, decryptedBuffer;
67
+ return __generator(this, function (_a) {
68
+ try {
69
+ data = handleExtraString(data, false);
70
+ iv = Buffer.from("i4mboZDwaNEC38YCzi77lw==", "base64");
71
+ encryptedData = Buffer.from(data, "base64");
72
+ keyBuffer = Buffer.from(key, "base64");
73
+ decipher = crypto_1.default.createDecipheriv(defaultAlgorithm, keyBuffer, iv);
74
+ decryptedBuffer = decipher.update(encryptedData);
75
+ decryptedBuffer = Buffer.concat([decryptedBuffer, decipher.final()]);
76
+ return [2 /*return*/, decryptedBuffer.toString()];
77
+ }
78
+ catch (error) {
79
+ console.log("\n Error: ", error);
80
+ return [2 /*return*/, data];
81
+ }
82
+ return [2 /*return*/];
83
+ });
84
+ }); };
85
+ exports.decryptData = decryptData;
86
+ var handleExtraString = function (key, append) {
87
+ if (append === void 0) { append = true; }
88
+ if (append) {
89
+ var start = crypto_1.default.randomBytes(2).toString("hex");
90
+ var end = crypto_1.default.randomBytes(2).toString("hex");
91
+ key = "".concat(start).concat(key).concat(end);
92
+ return key;
93
+ }
94
+ else {
95
+ key = key.substring(4, key.length);
96
+ key = key.substring(0, key.length - 4);
97
+ return key;
98
+ }
99
+ };
@@ -1,15 +1,48 @@
1
- type AwsConfig = {
2
- accessKeyId: string;
3
- secretAccessKey: string;
4
- region: string;
5
- };
6
- type Encryption = {
7
- encryptionType: string;
8
- algorithm: string;
9
- key: string;
10
- awsConfig: AwsConfig;
11
- };
1
+ import { AwsConfig, Encryption } from "./model";
12
2
  export declare const crypt: (data: any, fields: Array<object>, encryption: Encryption, decrypt: boolean) => Promise<any>;
13
- export declare const createKMSDataKey: (awsConfig: object, KeyId: string) => Promise<any>;
14
- export declare const decryptDataKey: (dataKey: string, awsConfig: object) => Promise<any>;
15
- export {};
3
+ export declare const processItemEncryptDecrypt: (item: any, fields: Array<object>, encryption: Encryption, decrypt: boolean) => Promise<any>;
4
+ export declare const processDataEncryptionDecryption: (data: string, encryption: Encryption, decrypt: boolean) => Promise<string>;
5
+ /**
6
+ * This method is used to generate private KEY for KMS ARN
7
+ * It requires KMS config and ARN
8
+ * @param config AWS config
9
+ * @param arn KMS Key
10
+ * @returns {status: string, dataKey: string, message: ""}
11
+ */
12
+ export declare const createKMSDataKey: (config: AwsConfig, arn: string) => Promise<{
13
+ status: string;
14
+ dataKey: string;
15
+ message: string;
16
+ }>;
17
+ /**
18
+ * This method is used to encrypt plaintext upto 4KB
19
+ * It requires KMS config and ARN
20
+ * @param config AWS Config
21
+ * @param arn KMS Key
22
+ * @param plainText Text to be encrypted
23
+ * @param context Extra setting for extra security
24
+ * @returns {status: string, message: string, cipherText: string}
25
+ */
26
+ export declare const encryptDataWithKMS: (config: AwsConfig, arn: string, plainText: string, context: any) => Promise<{
27
+ status: string;
28
+ data: string;
29
+ message: string;
30
+ }>;
31
+ /**
32
+ * This method is used to decrypt secure text
33
+ * It requires KMS config
34
+ * @param config AWS Config
35
+ * @param cipherText Encrypted Text
36
+ * @param context Extra setting which given for extra security
37
+ * @returns {status: string, message: string, plainText: string}
38
+ */
39
+ export declare const decryptDataWithKMS: (config: AwsConfig, cipherText: string, context: any) => Promise<{
40
+ status: string;
41
+ data: string;
42
+ message: string;
43
+ }>;
44
+ export declare const drapcodeEncryptDecrypt: (data: string, encrypt: boolean) => Promise<{
45
+ status: string;
46
+ data: string;
47
+ message: string;
48
+ }>;
@@ -35,17 +35,12 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
35
35
  if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
36
  }
37
37
  };
38
- var __importDefault = (this && this.__importDefault) || function (mod) {
39
- return (mod && mod.__esModule) ? mod : { "default": mod };
40
- };
41
38
  Object.defineProperty(exports, "__esModule", { value: true });
42
- exports.decryptDataKey = exports.createKMSDataKey = exports.crypt = void 0;
43
- var aws_sdk_1 = require("aws-sdk");
44
- var crypto_1 = __importDefault(require("crypto"));
45
- var prefix = "rec";
46
- var randomCharLen = 8;
39
+ exports.drapcodeEncryptDecrypt = exports.decryptDataWithKMS = exports.encryptDataWithKMS = exports.createKMSDataKey = exports.processDataEncryptionDecryption = exports.processItemEncryptDecrypt = exports.crypt = void 0;
40
+ var crypt_1 = require("./crypt");
41
+ var KMS_1 = require("./KMS");
47
42
  var crypt = function (data, fields, encryption, decrypt) { return __awaiter(void 0, void 0, void 0, function () {
48
- var _a, accessKeyId, secretAccessKey, region, config, key, promises;
43
+ var _a, accessKeyId, secretAccessKey, region, config, plainTextData, promises;
49
44
  return __generator(this, function (_b) {
50
45
  switch (_b.label) {
51
46
  case 0:
@@ -53,26 +48,27 @@ var crypt = function (data, fields, encryption, decrypt) { return __awaiter(void
53
48
  _a = encryption.awsConfig, accessKeyId = _a.accessKeyId, secretAccessKey = _a.secretAccessKey, region = _a.region;
54
49
  config = {
55
50
  region: region,
56
- credentials: {
57
- accessKeyId: accessKeyId,
58
- secretAccessKey: secretAccessKey,
59
- },
51
+ accessKeyId: accessKeyId,
52
+ secretAccessKey: secretAccessKey,
60
53
  };
61
- return [4 /*yield*/, (0, exports.decryptDataKey)(encryption.key, config)];
54
+ return [4 /*yield*/, (0, KMS_1.processKMSDecryption)(config, encryption.dataKey, {})];
62
55
  case 1:
63
- key = _b.sent();
64
- encryption.key = key.toString("base64");
56
+ plainTextData = _b.sent();
57
+ if (plainTextData.status === "FAILED") {
58
+ return [2 /*return*/, plainTextData];
59
+ }
60
+ encryption.dataKey = plainTextData.data;
65
61
  _b.label = 2;
66
62
  case 2:
67
63
  if (!Array.isArray(data)) return [3 /*break*/, 4];
68
64
  promises = data.map(function (item) {
69
- return cryptItem(item, fields, encryption, decrypt);
65
+ return (0, exports.processItemEncryptDecrypt)(item, fields, encryption, decrypt);
70
66
  });
71
67
  return [4 /*yield*/, Promise.all(promises)];
72
68
  case 3:
73
69
  data = _b.sent();
74
70
  return [3 /*break*/, 6];
75
- case 4: return [4 /*yield*/, cryptItem(data, fields, encryption, decrypt)];
71
+ case 4: return [4 /*yield*/, (0, exports.processItemEncryptDecrypt)(data, fields, encryption, decrypt)];
76
72
  case 5:
77
73
  data = _b.sent();
78
74
  _b.label = 6;
@@ -81,177 +77,190 @@ var crypt = function (data, fields, encryption, decrypt) { return __awaiter(void
81
77
  });
82
78
  }); };
83
79
  exports.crypt = crypt;
84
- var cryptItem = function (item, fields, encryption, decrypt) { return __awaiter(void 0, void 0, void 0, function () {
85
- return __generator(this, function (_a) {
86
- if (item && typeof item === "object") {
87
- Object.keys(item).forEach(function (fieldName) { return __awaiter(void 0, void 0, void 0, function () {
88
- var field, _a, _b;
89
- return __generator(this, function (_c) {
90
- switch (_c.label) {
91
- case 0:
92
- field = fields.find(function (field) { return field.fieldName === fieldName; });
93
- if (!(field && field.encrypted)) return [3 /*break*/, 2];
94
- _a = item;
95
- _b = fieldName;
96
- return [4 /*yield*/, cryptData(item[fieldName], encryption, decrypt)];
97
- case 1:
98
- _a[_b] = _c.sent();
99
- _c.label = 2;
100
- case 2: return [2 /*return*/];
101
- }
102
- });
103
- }); });
80
+ var processItemEncryptDecrypt = function (item, fields, encryption, decrypt) { return __awaiter(void 0, void 0, void 0, function () {
81
+ var _loop_1, _i, _a, fieldName;
82
+ return __generator(this, function (_b) {
83
+ switch (_b.label) {
84
+ case 0:
85
+ if (!(item && typeof item === "object")) return [3 /*break*/, 4];
86
+ _loop_1 = function (fieldName) {
87
+ var field, _c, _d;
88
+ return __generator(this, function (_e) {
89
+ switch (_e.label) {
90
+ case 0:
91
+ field = fields.find(function (field) { return field.fieldName === fieldName; });
92
+ if (!(field && field.encrypted)) return [3 /*break*/, 2];
93
+ _c = item;
94
+ _d = fieldName;
95
+ return [4 /*yield*/, (0, exports.processDataEncryptionDecryption)(item[fieldName], encryption, decrypt)];
96
+ case 1:
97
+ _c[_d] = _e.sent();
98
+ _e.label = 2;
99
+ case 2: return [2 /*return*/];
100
+ }
101
+ });
102
+ };
103
+ _i = 0, _a = Object.keys(item);
104
+ _b.label = 1;
105
+ case 1:
106
+ if (!(_i < _a.length)) return [3 /*break*/, 4];
107
+ fieldName = _a[_i];
108
+ return [5 /*yield**/, _loop_1(fieldName)];
109
+ case 2:
110
+ _b.sent();
111
+ _b.label = 3;
112
+ case 3:
113
+ _i++;
114
+ return [3 /*break*/, 1];
115
+ case 4: return [2 /*return*/, item];
104
116
  }
105
- return [2 /*return*/, item];
106
117
  });
107
118
  }); };
108
- var cryptData = function (data, encryption, decrypt) { return __awaiter(void 0, void 0, void 0, function () {
109
- var encryptionType, algorithm, key, _a, _b;
119
+ exports.processItemEncryptDecrypt = processItemEncryptDecrypt;
120
+ var processDataEncryptionDecryption = function (data, encryption, decrypt) { return __awaiter(void 0, void 0, void 0, function () {
121
+ var encryptionType, dataKey, _a, result, _b;
110
122
  return __generator(this, function (_c) {
111
123
  switch (_c.label) {
112
124
  case 0:
113
- encryptionType = encryption.encryptionType, algorithm = encryption.algorithm, key = encryption.key;
125
+ encryptionType = encryption.encryptionType, dataKey = encryption.dataKey;
114
126
  if (!data)
115
127
  return [2 /*return*/, data];
116
128
  _a = encryptionType;
117
129
  switch (_a) {
118
- case "BASE64": return [3 /*break*/, 1];
119
- case "CUSTOM": return [3 /*break*/, 2];
120
- case "KMS": return [3 /*break*/, 3];
130
+ case "KMS": return [3 /*break*/, 1];
121
131
  }
122
- return [3 /*break*/, 8];
123
- case 1: return [2 /*return*/, decrypt ? decryptBase64(data) : encryptBase64(data)];
124
- case 2: return [2 /*return*/, decrypt
125
- ? decryptCustom(data, algorithm, key)
126
- : encryptCustom(data, algorithm, key)];
127
- case 3:
128
- if (!decrypt) return [3 /*break*/, 5];
129
- return [4 /*yield*/, decryptWithKMS(data, algorithm, key)];
130
- case 4:
132
+ return [3 /*break*/, 6];
133
+ case 1:
134
+ if (!decrypt) return [3 /*break*/, 3];
135
+ return [4 /*yield*/, (0, crypt_1.decryptData)(data, dataKey)];
136
+ case 2:
131
137
  _b = _c.sent();
132
- return [3 /*break*/, 7];
133
- case 5: return [4 /*yield*/, encryptWithKMS(data, algorithm, key)];
134
- case 6:
138
+ return [3 /*break*/, 5];
139
+ case 3: return [4 /*yield*/, (0, crypt_1.encryptData)(data, dataKey)];
140
+ case 4:
135
141
  _b = _c.sent();
136
- _c.label = 7;
137
- case 7: return [2 /*return*/, _b];
138
- case 8: return [2 /*return*/, data];
142
+ _c.label = 5;
143
+ case 5:
144
+ result = _b;
145
+ return [2 /*return*/, result];
146
+ case 6: return [2 /*return*/, data];
139
147
  }
140
148
  });
141
149
  }); };
142
- var encryptBase64 = function (data) {
143
- if (data.startsWith(prefix))
144
- return data;
145
- var randomFront = getRandomAlphaNumeric(randomCharLen);
146
- var randomback = getRandomAlphaNumeric(randomCharLen);
147
- var base64Data = btoa(data);
148
- return prefix + randomFront + base64Data + randomback;
149
- };
150
- var decryptBase64 = function (encryptedData) {
151
- if (encryptedData.startsWith(prefix)) {
152
- encryptedData = encryptedData.replace(prefix, "");
153
- encryptedData = encryptedData.substring(randomCharLen, encryptedData.length - randomCharLen);
154
- encryptedData = atob(encryptedData);
155
- }
156
- return encryptedData;
157
- };
158
- var encryptCustom = function (data, alogrithm, key) {
159
- return data;
160
- };
161
- var decryptCustom = function (encryptedData, alogrithm, key) {
162
- return encryptedData;
163
- };
164
- var getRandomAlphaNumeric = function (length) {
165
- return Math.random().toString(36).substr(2, length);
166
- };
167
- var createKMSDataKey = function (awsConfig, KeyId) { return __awaiter(void 0, void 0, void 0, function () {
168
- var kms_1;
150
+ exports.processDataEncryptionDecryption = processDataEncryptionDecryption;
151
+ /**
152
+ * This method is used to generate private KEY for KMS ARN
153
+ * It requires KMS config and ARN
154
+ * @param config AWS config
155
+ * @param arn KMS Key
156
+ * @returns {status: string, dataKey: string, message: ""}
157
+ */
158
+ var createKMSDataKey = function (config, arn) { return __awaiter(void 0, void 0, void 0, function () {
159
+ var dataKeyRes;
169
160
  return __generator(this, function (_a) {
170
- try {
171
- kms_1 = new aws_sdk_1.KMS(awsConfig);
172
- return [2 /*return*/, new Promise(function (resolve, reject) {
173
- var params = {
174
- KeyId: KeyId,
175
- KeySpec: "AES_256",
176
- };
177
- kms_1.generateDataKey(params, function (err, data) {
178
- if (err) {
179
- console.log("\n Error", err);
180
- reject(err);
181
- }
182
- else {
183
- resolve(data);
184
- }
185
- });
186
- })];
187
- }
188
- catch (error) {
189
- console.log("\n Error: ", error);
161
+ switch (_a.label) {
162
+ case 0: return [4 /*yield*/, (0, KMS_1.processKMSGenerateDataKey)(config, arn)];
163
+ case 1:
164
+ dataKeyRes = _a.sent();
165
+ return [2 /*return*/, dataKeyRes];
190
166
  }
191
- return [2 /*return*/];
192
167
  });
193
168
  }); };
194
169
  exports.createKMSDataKey = createKMSDataKey;
195
- var decryptDataKey = function (dataKey, awsConfig) { return __awaiter(void 0, void 0, void 0, function () {
196
- var kms_2, CiphertextBlob_1;
170
+ /**
171
+ * This method is used to encrypt plaintext upto 4KB
172
+ * It requires KMS config and ARN
173
+ * @param config AWS Config
174
+ * @param arn KMS Key
175
+ * @param plainText Text to be encrypted
176
+ * @param context Extra setting for extra security
177
+ * @returns {status: string, message: string, cipherText: string}
178
+ */
179
+ var encryptDataWithKMS = function (config, arn, plainText, context) { return __awaiter(void 0, void 0, void 0, function () {
180
+ var cryptData;
197
181
  return __generator(this, function (_a) {
198
- try {
199
- kms_2 = new aws_sdk_1.KMS(awsConfig);
200
- CiphertextBlob_1 = Buffer.from(dataKey, "base64");
201
- return [2 /*return*/, new Promise(function (resolve, reject) {
202
- var params = { CiphertextBlob: CiphertextBlob_1 };
203
- kms_2.decrypt(params, function (err, data) {
204
- if (err) {
205
- console.log("\n Error", err);
206
- reject(err);
207
- }
208
- else {
209
- resolve(data.Plaintext);
210
- }
211
- });
212
- })];
213
- }
214
- catch (error) {
215
- console.log("\n Error: ", error);
182
+ switch (_a.label) {
183
+ case 0: return [4 /*yield*/, (0, KMS_1.processKMSEncryption)(config, arn, plainText, context)];
184
+ case 1:
185
+ cryptData = _a.sent();
186
+ return [2 /*return*/, cryptData];
216
187
  }
217
- return [2 /*return*/];
218
188
  });
219
189
  }); };
220
- exports.decryptDataKey = decryptDataKey;
221
- var encryptWithKMS = function (data, algorithm, key) { return __awaiter(void 0, void 0, void 0, function () {
222
- var iv, keyBuffer, cipher, encryptedDataBuffer;
190
+ exports.encryptDataWithKMS = encryptDataWithKMS;
191
+ /**
192
+ * This method is used to decrypt secure text
193
+ * It requires KMS config
194
+ * @param config AWS Config
195
+ * @param cipherText Encrypted Text
196
+ * @param context Extra setting which given for extra security
197
+ * @returns {status: string, message: string, plainText: string}
198
+ */
199
+ var decryptDataWithKMS = function (config, cipherText, context) { return __awaiter(void 0, void 0, void 0, function () {
200
+ var plainTextData;
223
201
  return __generator(this, function (_a) {
224
- try {
225
- iv = Buffer.from("i4mboZDwaNEC38YCzi77lw==", "base64");
226
- keyBuffer = Buffer.from(key, "base64");
227
- cipher = crypto_1.default.createCipheriv(algorithm, keyBuffer, iv);
228
- encryptedDataBuffer = cipher.update(data);
229
- encryptedDataBuffer = Buffer.concat([encryptedDataBuffer, cipher.final()]);
230
- return [2 /*return*/, encryptedDataBuffer.toString("base64")];
231
- }
232
- catch (error) {
233
- console.log("\n Error: ", error);
234
- return [2 /*return*/, data];
202
+ switch (_a.label) {
203
+ case 0: return [4 /*yield*/, (0, KMS_1.processKMSDecryption)(config, cipherText, context)];
204
+ case 1:
205
+ plainTextData = _a.sent();
206
+ return [2 /*return*/, plainTextData];
235
207
  }
236
- return [2 /*return*/];
237
208
  });
238
209
  }); };
239
- var decryptWithKMS = function (data, algorithm, key) { return __awaiter(void 0, void 0, void 0, function () {
240
- var iv, encryptedData, keyBuffer, decipher, decryptedBuffer;
210
+ exports.decryptDataWithKMS = decryptDataWithKMS;
211
+ var drapcodeEncryptDecrypt = function (data, encrypt) { return __awaiter(void 0, void 0, void 0, function () {
212
+ var region, accessKey, secretKey, privateDataKey, config, plainTextData, publicKey, response;
241
213
  return __generator(this, function (_a) {
242
- try {
243
- iv = Buffer.from("i4mboZDwaNEC38YCzi77lw==", "base64");
244
- encryptedData = Buffer.from(data, "base64");
245
- keyBuffer = Buffer.from(key, "base64");
246
- decipher = crypto_1.default.createDecipheriv(algorithm, keyBuffer, iv);
247
- decryptedBuffer = decipher.update(encryptedData);
248
- decryptedBuffer = Buffer.concat([decryptedBuffer, decipher.final()]);
249
- return [2 /*return*/, decryptedBuffer.toString()];
250
- }
251
- catch (error) {
252
- console.log("\n Error: ", error);
253
- return [2 /*return*/, data];
214
+ switch (_a.label) {
215
+ case 0:
216
+ region = process.env.AWS_KMS_REGION;
217
+ accessKey = process.env.AWS_KMS_ACCESS_KEY;
218
+ secretKey = process.env.AWS_KMS_SECRET_KEY;
219
+ privateDataKey = process.env.AWS_KMS_PRIVATE_DATA_KEY;
220
+ if (!region)
221
+ return [2 /*return*/, { status: "FAILED", message: "AWS Region is missing", data: "" }];
222
+ if (!accessKey)
223
+ return [2 /*return*/, { status: "FAILED", message: "AWS Access Key is missing", data: "" }];
224
+ if (!secretKey)
225
+ return [2 /*return*/, {
226
+ status: "FAILED",
227
+ message: "AWS Access Secret Key is missing",
228
+ data: "",
229
+ }];
230
+ if (!privateDataKey)
231
+ return [2 /*return*/, {
232
+ status: "FAILED",
233
+ message: "KMS Private Key is missing",
234
+ data: "",
235
+ }];
236
+ console.log("privateDataKey", privateDataKey);
237
+ config = {
238
+ region: region,
239
+ accessKeyId: accessKey,
240
+ secretAccessKey: secretKey,
241
+ };
242
+ return [4 /*yield*/, (0, KMS_1.processKMSDecryption)(config, privateDataKey, {})];
243
+ case 1:
244
+ plainTextData = _a.sent();
245
+ if (plainTextData.status === "FAILED") {
246
+ return [2 /*return*/, plainTextData];
247
+ }
248
+ publicKey = plainTextData.data;
249
+ response = null;
250
+ if (!encrypt) return [3 /*break*/, 3];
251
+ console.log("Encrypting");
252
+ return [4 /*yield*/, (0, crypt_1.encryptData)(data, publicKey)];
253
+ case 2:
254
+ response = _a.sent();
255
+ return [3 /*break*/, 5];
256
+ case 3:
257
+ console.log("Decrypting");
258
+ return [4 /*yield*/, (0, crypt_1.decryptData)(data, publicKey)];
259
+ case 4:
260
+ response = _a.sent();
261
+ _a.label = 5;
262
+ case 5: return [2 /*return*/, { status: "SUCCESS", message: "", data: response }];
254
263
  }
255
- return [2 /*return*/];
256
264
  });
257
265
  }); };
266
+ exports.drapcodeEncryptDecrypt = drapcodeEncryptDecrypt;
@@ -0,0 +1,11 @@
1
+ export type AwsConfig = {
2
+ accessKeyId: string;
3
+ secretAccessKey: string;
4
+ region: string;
5
+ };
6
+ export type Encryption = {
7
+ encryptionType: string;
8
+ algorithm: string;
9
+ dataKey: string;
10
+ awsConfig: AwsConfig;
11
+ };
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
package/build/index.d.ts CHANGED
@@ -6,7 +6,6 @@ export * from "./errors/axios-error";
6
6
  export * from "./middlewares/error-logger";
7
7
  export * from "./middlewares/interceptor-logger";
8
8
  export * from "./middlewares/interceptor-logger-new";
9
- export * from "./middlewares/api-limiter";
10
9
  export * from "./utils/date-util";
11
10
  export * from "./utils/query-parser";
12
11
  export * from "./utils/query-paser-new";
package/build/index.js CHANGED
@@ -22,7 +22,6 @@ __exportStar(require("./errors/axios-error"), exports);
22
22
  __exportStar(require("./middlewares/error-logger"), exports);
23
23
  __exportStar(require("./middlewares/interceptor-logger"), exports);
24
24
  __exportStar(require("./middlewares/interceptor-logger-new"), exports);
25
- __exportStar(require("./middlewares/api-limiter"), exports);
26
25
  __exportStar(require("./utils/date-util"), exports);
27
26
  __exportStar(require("./utils/query-parser"), exports);
28
27
  __exportStar(require("./utils/query-paser-new"), exports);
@@ -6,7 +6,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.interceptLoggerNew = void 0;
7
7
  var drapcode_logger_1 = require("drapcode-logger");
8
8
  var date_util_1 = require("../utils/date-util");
9
- // import { saveRequest } from "./redis/request-log";
10
9
  var fs_1 = __importDefault(require("fs"));
11
10
  var interceptLoggerNew = function (req, res, next) {
12
11
  var todayFilePath = "/tmp/log";
@@ -3,7 +3,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.interceptLogger = void 0;
4
4
  var drapcode_logger_1 = require("drapcode-logger");
5
5
  var date_util_1 = require("../utils/date-util");
6
- // import { saveRequest } from "./redis/request-log";
7
6
  var interceptLogger = function (req, res, next) {
8
7
  var loggerPath = process.env.LOG_FOLDER_PATH || "/tmp/logs";
9
8
  var originalUrl = req.originalUrl, method = req.method, body = req.body, params = req.params, query = req.query, db = req.db, projectName = req.projectName, projectId = req.projectId, ip = req.ip;
@@ -94,7 +94,7 @@ var formatItemDates = function (item, fields, dateFormat, reverse) {
94
94
  var _a;
95
95
  var field = fields.find(function (field) { return field.fieldName === fieldName; });
96
96
  if (field && (field === null || field === void 0 ? void 0 : field.type) === "date") {
97
- if (moment(item[fieldName]).isValid()) {
97
+ if (moment(item[fieldName], dateFormat1_1).isValid()) {
98
98
  item[fieldName] =
99
99
  ((_a = field === null || field === void 0 ? void 0 : field.extraFieldSetting) === null || _a === void 0 ? void 0 : _a.dateDisplayType) === "datetime-local"
100
100
  ? item[fieldName]
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "drapcode-utility",
3
- "version": "1.1.5",
3
+ "version": "1.1.7",
4
4
  "description": "",
5
5
  "main": "build/index.js",
6
6
  "types": "build/index.d.ts",
@@ -14,8 +14,7 @@
14
14
  "keywords": [
15
15
  "drapcode",
16
16
  "constant",
17
- "logger",
18
- "redis"
17
+ "logger"
19
18
  ],
20
19
  "author": "Drapcode",
21
20
  "license": "ISC",
@@ -25,23 +24,18 @@
25
24
  "typescript": "^4.0.2"
26
25
  },
27
26
  "dependencies": {
27
+ "@aws-sdk/client-kms": "^3.540.0",
28
28
  "@types/cookie-session": "^2.0.41",
29
29
  "@types/express": "^4.17.7",
30
- "@types/redis": "^2.8.27",
31
30
  "@types/voca": "^1.4.2",
32
- "aws-sdk": "^2.1324.0",
33
31
  "axios": "^1.1.2",
34
32
  "drapcode-constant": "^1.2.4",
35
33
  "drapcode-logger": "^1.0.4",
36
34
  "drapcode-redis": "^1.0.4",
37
35
  "express": "^4.17.1",
38
- "express-rate-limit": "^5.1.3",
39
- "express-validator": "^6.6.1",
40
36
  "lodash": "^4.17.21",
41
37
  "moment": "^2.29.0",
42
- "redis": "^3.0.2",
43
38
  "stringify-object": "^3.3.0",
44
- "voca": "^1.4.0",
45
- "winston": "^3.8.2"
39
+ "voca": "^1.4.0"
46
40
  }
47
41
  }
@@ -1 +0,0 @@
1
- export declare const apiLimiter: any;
@@ -1,21 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.apiLimiter = void 0;
4
- var rateLimit = require("express-rate-limit");
5
- exports.apiLimiter = rateLimit({
6
- windowMs: 1 * 60 * 1000,
7
- max: 5,
8
- message: "You have crossed your limit. please try after some time",
9
- headers: true,
10
- keyGenerator: function (req, res) {
11
- var subdomains = req.subdomains;
12
- var ip = req.headers["x-forwarded-for"] ||
13
- req.connection.remoteAddress ||
14
- req.socket.remoteAddress ||
15
- (req.connection.socket ? req.connection.socket.remoteAddress : null);
16
- var key = Array.isArray(subdomains) && subdomains.length
17
- ? "".concat(ip, "-").concat(subdomains[1])
18
- : ip;
19
- return key;
20
- },
21
- });