fiberx-backend-toolkit 0.0.34 → 0.0.36

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.
@@ -18,3 +18,4 @@ export declare const REQUEST_RATE_LIMITTER_OPTIONS: {
18
18
  max_requests: number;
19
19
  message: string;
20
20
  };
21
+ export declare const ALPHABET_CORPUS: string[];
@@ -3,7 +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.REQUEST_RATE_LIMITTER_OPTIONS = exports.CORS_MAX_AGE_IN_MICRO_SECONDS = exports.CORS_MAX_AGE_IN_SECONDS = exports.CORS_ALLOWED_HEADERS = exports.CORS_ALLOWED_METHODS = exports.REQUEST_ID_COOKIE_MAX_AGE = exports.SEQUELIZE_SEEDER_META_TABLE_NAME = exports.SEQUELIZE_META_TABLE_NAME = exports.SEEDERS_DIR = exports.MIGRATIONS_DIR = exports.MODELS_DIR = exports.SCHEMA_SNAPSHOTS_DIR = exports.SCHEMAS_DIR = exports.ENV_VAR_DIR = exports.LOG_DIR = exports.BASE_DIR = void 0;
6
+ exports.ALPHABET_CORPUS = exports.REQUEST_RATE_LIMITTER_OPTIONS = exports.CORS_MAX_AGE_IN_MICRO_SECONDS = exports.CORS_MAX_AGE_IN_SECONDS = exports.CORS_ALLOWED_HEADERS = exports.CORS_ALLOWED_METHODS = exports.REQUEST_ID_COOKIE_MAX_AGE = exports.SEQUELIZE_SEEDER_META_TABLE_NAME = exports.SEQUELIZE_META_TABLE_NAME = exports.SEEDERS_DIR = exports.MIGRATIONS_DIR = exports.MODELS_DIR = exports.SCHEMA_SNAPSHOTS_DIR = exports.SCHEMAS_DIR = exports.ENV_VAR_DIR = exports.LOG_DIR = exports.BASE_DIR = void 0;
7
7
  const path_1 = __importDefault(require("path"));
8
8
  // Database constants
9
9
  exports.BASE_DIR = process.cwd();
@@ -28,3 +28,4 @@ exports.REQUEST_RATE_LIMITTER_OPTIONS = {
28
28
  max_requests: 50,
29
29
  message: "⏳ Too many requests from this IP, please try again later"
30
30
  };
31
+ exports.ALPHABET_CORPUS = ["6", ";", "s", "[", "w", "*", "n", "K", "h", "U", "#", "P", "T", "&", "M", "2", "}", "x", ")", "{", "|", "i", "%", "m", ":", "E", "q", "?", "0", "@", "1", "v", "A", "W", "<", "y", "Y", "4", "5", ".", "e", "G", ",", "D", "7", "I", "j", ">", "g", "t", "k", "c", "V", "9", "J", "L", "u", "H", "b", "Z", "+", '"', "'", "a", "f"];
@@ -3,3 +3,4 @@ export * from "./migration_type";
3
3
  export * from "./util_type";
4
4
  export * from "./middle_ware_type";
5
5
  export * from "./database_type";
6
+ export * from "./module_type";
@@ -19,3 +19,4 @@ __exportStar(require("./migration_type"), exports);
19
19
  __exportStar(require("./util_type"), exports);
20
20
  __exportStar(require("./middle_ware_type"), exports);
21
21
  __exportStar(require("./database_type"), exports);
22
+ __exportStar(require("./module_type"), exports);
@@ -0,0 +1,12 @@
1
+ export interface ServiceMethodRetrunInterface<T> {
2
+ status: boolean;
3
+ msg: string;
4
+ data?: T;
5
+ status_code?: number;
6
+ }
7
+ export interface ValidatorMethodReturnInterface<T> {
8
+ v_state: boolean;
9
+ v_msg: string;
10
+ v_data?: T;
11
+ v_code?: number;
12
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,27 @@
1
+ declare class EncryptorDecryptorUtil {
2
+ readonly name = "encrypt_decrypt_util";
3
+ private static instance;
4
+ readonly encrypt_secret_key?: string;
5
+ readonly corpus_shift_key: number;
6
+ readonly corpus: string[];
7
+ private algorithm;
8
+ private iv_length;
9
+ private jwt_secret_key?;
10
+ private logger;
11
+ private env_manger;
12
+ private constructor();
13
+ private verifyJWT;
14
+ static getInstance(encrypt_secret_key?: string): EncryptorDecryptorUtil;
15
+ static generateEncryptSecretKey(): string;
16
+ setEncryptSecretKey(key?: string): string;
17
+ encryptV1<T>(data: T): string;
18
+ decryptV1<T>(encrypted_data: string): T;
19
+ encryptV2<T>(data: T): string;
20
+ decryptV2<T>(encrypted_data: string): T | string;
21
+ compressPayload<T = string>(payload: T): string;
22
+ decompressPayload<T = string>(compressed_base64: string): T;
23
+ dataToTimedEncryptedString<T = string>(data: T, time_in_mins?: number): string;
24
+ timedEncryptedStringToData<T>(encrypted_string: string, ignore_expiration?: boolean): T | string | boolean;
25
+ hashString(input: string, algorithm?: string): string;
26
+ }
27
+ export default EncryptorDecryptorUtil;
@@ -0,0 +1,226 @@
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
+ const crypto_1 = __importDefault(require("crypto"));
7
+ const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
8
+ const zlib_1 = __importDefault(require("zlib"));
9
+ const logger_util_1 = __importDefault(require("./logger_util"));
10
+ const env_manager_util_1 = __importDefault(require("./env_manager_util"));
11
+ const constants_1 = require("../config/constants");
12
+ class EncryptorDecryptorUtil {
13
+ name = "encrypt_decrypt_util";
14
+ static instance;
15
+ encrypt_secret_key;
16
+ corpus_shift_key;
17
+ corpus = constants_1.ALPHABET_CORPUS;
18
+ algorithm = "aes-256-cbc";
19
+ iv_length = 16;
20
+ jwt_secret_key;
21
+ logger = new logger_util_1.default(this.name);
22
+ env_manger = env_manager_util_1.default.getInstance();
23
+ constructor(encrypt_secret_key) {
24
+ this.encrypt_secret_key = this.setEncryptSecretKey(encrypt_secret_key);
25
+ this.corpus_shift_key = this.env_manger.getEnvVar("CORPUS_SHIFT_KEY", 4) || 4;
26
+ this.jwt_secret_key = this.env_manger.getEnvVar("JWT_SECRET_KEY", "");
27
+ if (!this.encrypt_secret_key ||
28
+ !this.jwt_secret_key) {
29
+ const msg = `Secret Key Variables are missing please set in envrionment variable`;
30
+ const data = { encrypt_secret_key: this.encrypt_secret_key, jwt_secret_key: this.jwt_secret_key };
31
+ this.logger.error(msg, { data });
32
+ throw new Error(msg);
33
+ }
34
+ }
35
+ verifyJWT(jwt_string, secret_key, ignore_expiration = false) {
36
+ try {
37
+ const jwt_data = jsonwebtoken_1.default.verify(jwt_string, secret_key, { ignoreExpiration: ignore_expiration });
38
+ return jwt_data;
39
+ }
40
+ catch (error) {
41
+ this.logger.error(`[${this.name}] JWT string has expired`, { jwt_string, ignore_expiration });
42
+ return null;
43
+ }
44
+ }
45
+ // ✅ Global access point
46
+ static getInstance(encrypt_secret_key) {
47
+ if (!EncryptorDecryptorUtil.instance) {
48
+ EncryptorDecryptorUtil.instance = new EncryptorDecryptorUtil(encrypt_secret_key);
49
+ }
50
+ return EncryptorDecryptorUtil.instance;
51
+ }
52
+ // ==============================
53
+ // AES-256 (V1)
54
+ // ==============================
55
+ // Method to generate Encrypt Secret Key
56
+ static generateEncryptSecretKey() {
57
+ return crypto_1.default.randomBytes(32).toString("hex");
58
+ }
59
+ // Method to set encrypt secret key
60
+ setEncryptSecretKey(key) {
61
+ const secret_key = key || this.env_manger.getEnvVar("ENCRYPT_SECRET_KEY", "");
62
+ if (!secret_key || Buffer.from(secret_key, "hex").length !== 32) {
63
+ throw new Error("Invalid encryption key check it is set in environment file and the length is correct. Expected 32 bytes (64 hex characters).");
64
+ }
65
+ return secret_key;
66
+ }
67
+ // Method to convert data type T to encrypted string s using encryption method V1
68
+ encryptV1(data) {
69
+ if (!this.encrypt_secret_key) {
70
+ throw new Error("Encryption key not set. Use setEncryptionV1Key() first.");
71
+ }
72
+ const iv = crypto_1.default.randomBytes(this.iv_length);
73
+ const iv_base_64 = iv.toString("base64");
74
+ const buffer_data = Buffer.from(this.encrypt_secret_key, "hex");
75
+ const cipher = crypto_1.default.createCipheriv(this.algorithm, buffer_data, iv);
76
+ const stringified_data = typeof data === "string" ? data : JSON.stringify(data);
77
+ let encrypted = cipher.update(stringified_data, "utf-8", "base64");
78
+ encrypted += cipher.final("base64");
79
+ return `${iv_base_64}:${encrypted}`;
80
+ }
81
+ // Method to convert encrypted string data s to data type T using decryption method v1
82
+ decryptV1(encrypted_data) {
83
+ try {
84
+ if (!this.encrypt_secret_key) {
85
+ throw new Error("Encryption key not set. Use setEncryptionV1Key() first.");
86
+ }
87
+ const [iv_base_64, encrypted] = encrypted_data.split(":");
88
+ const iv = Buffer.from(iv_base_64, "base64");
89
+ const buffer_data = Buffer.from(this.encrypt_secret_key, "hex");
90
+ const decipher = crypto_1.default.createDecipheriv(this.algorithm, buffer_data, iv);
91
+ let decrypted = decipher.update(encrypted, "base64", "utf-8");
92
+ decrypted += decipher.final("utf-8");
93
+ try {
94
+ return JSON.parse(decrypted);
95
+ }
96
+ catch {
97
+ return decrypted;
98
+ }
99
+ }
100
+ catch (error) {
101
+ throw error;
102
+ }
103
+ }
104
+ // ==============================
105
+ // Shift Cipher (V2)
106
+ // ==============================
107
+ // Method to convert data type T to encrypted string s using encryption method v2
108
+ encryptV2(data) {
109
+ if (!this.corpus || !this.corpus_shift_key) {
110
+ throw new Error("Environment not initialized.");
111
+ }
112
+ const input_data = typeof data === "string" ? data : JSON.stringify(data);
113
+ const array_input_data = input_data.split("");
114
+ let encrypted_data = "";
115
+ for (const char of array_input_data) {
116
+ const index = this.corpus.indexOf(char);
117
+ if (index !== -1) {
118
+ const new_index = (index + this.corpus_shift_key) % this.corpus.length;
119
+ encrypted_data += this.corpus[new_index];
120
+ }
121
+ else {
122
+ encrypted_data += char;
123
+ }
124
+ }
125
+ return encrypted_data;
126
+ }
127
+ // Method to convert encrypted string data s to data type T using decryption method v1
128
+ decryptV2(encrypted_data) {
129
+ try {
130
+ if (!this.corpus || !this.corpus_shift_key) {
131
+ throw new Error("Environment not initialized.");
132
+ }
133
+ const array_input_data = encrypted_data.split("");
134
+ let decrypted_data = "";
135
+ for (const char of array_input_data) {
136
+ const index = this.corpus.indexOf(char);
137
+ if (index !== -1) {
138
+ const calc_shift = (index - this.corpus_shift_key);
139
+ const new_index = calc_shift < 0 ? (this.corpus.length + calc_shift) : calc_shift;
140
+ decrypted_data += this.corpus[new_index];
141
+ }
142
+ else {
143
+ decrypted_data += char; // keep characters not in corpus
144
+ }
145
+ }
146
+ try {
147
+ return JSON.parse(decrypted_data);
148
+ }
149
+ catch {
150
+ return decrypted_data;
151
+ }
152
+ }
153
+ catch (error) {
154
+ throw error;
155
+ }
156
+ }
157
+ // ==============================
158
+ // Compression
159
+ // ==============================
160
+ // Method to help compress a data payload
161
+ compressPayload(payload) {
162
+ const stringified_data = typeof payload === "string" ? payload : JSON.stringify(payload);
163
+ const buffer = Buffer.from(stringified_data);
164
+ const compression_config = { level: 9, strategy: zlib_1.default.constants.Z_DEFAULT_STRATEGY };
165
+ const compressed = zlib_1.default.deflateSync(buffer, compression_config);
166
+ return compressed.toString("base64");
167
+ }
168
+ // Method to decompress payload
169
+ decompressPayload(compressed_base64) {
170
+ const buffer = Buffer.from(compressed_base64, "base64");
171
+ const json_string = zlib_1.default.inflateSync(buffer).toString();
172
+ try {
173
+ return JSON.parse(json_string);
174
+ }
175
+ catch (error) {
176
+ return json_string;
177
+ }
178
+ }
179
+ // ==============================
180
+ // JWT + Compression
181
+ // ==============================
182
+ // Method to convert a data payload to a time encrypted string
183
+ dataToTimedEncryptedString(data, time_in_mins = 60) {
184
+ const encoded_data = this.compressPayload(this.encryptV2(data));
185
+ if (!this.jwt_secret_key) {
186
+ throw new Error("No secret key provided");
187
+ }
188
+ const json_web_config = { expiresIn: time_in_mins * 60 };
189
+ const jwt_token = jsonwebtoken_1.default.sign({ encoded_data }, this.jwt_secret_key, json_web_config);
190
+ return this.compressPayload(jwt_token);
191
+ }
192
+ // Method to convert times encrypted string data s to data payload T
193
+ timedEncryptedStringToData(encrypted_string, ignore_expiration = false) {
194
+ try {
195
+ if (!this.jwt_secret_key) {
196
+ throw new Error("No secret key provided");
197
+ }
198
+ const uncompressed_string = this.decompressPayload(encrypted_string);
199
+ if (!uncompressed_string) {
200
+ return false;
201
+ }
202
+ const jwt_data = this.verifyJWT(uncompressed_string, this.jwt_secret_key, ignore_expiration);
203
+ if (!jwt_data) {
204
+ return false;
205
+ }
206
+ const decompressed_data = this.decompressPayload(jwt_data?.encoded_data);
207
+ if (!decompressed_data) {
208
+ return false;
209
+ }
210
+ const decoded_data = this.decryptV2(decompressed_data);
211
+ return decoded_data || false;
212
+ }
213
+ catch (error) {
214
+ this.logger.error(`[${this.name}] Failed to convert encrypted string to data`, { encrypted_string, error });
215
+ return false;
216
+ }
217
+ }
218
+ // ==============================
219
+ // Hash
220
+ // ==============================
221
+ // Method to hash a string
222
+ hashString(input, algorithm = "sha256") {
223
+ return crypto_1.default.createHash(algorithm).update(input).digest("hex");
224
+ }
225
+ }
226
+ exports.default = EncryptorDecryptorUtil;
@@ -7,4 +7,5 @@ import ServerUtil from "./server_util";
7
7
  import SafeExecuteUtil from "./safe_execute_util";
8
8
  import InMemoryCache from "./cache_util";
9
9
  import UUIDGeneratorUtil from "./uuid_gen_util";
10
- export { LoggerUtil, InputTransformerUtil, InputValidatorUtil, EnvManagerUtil, SqlFormatterUtil, ServerUtil, SafeExecuteUtil, InMemoryCache, UUIDGeneratorUtil };
10
+ import EncryptorDecryptorUtil from "./encryptor_decryptor_util";
11
+ export { LoggerUtil, InputTransformerUtil, InputValidatorUtil, EnvManagerUtil, SqlFormatterUtil, ServerUtil, SafeExecuteUtil, InMemoryCache, UUIDGeneratorUtil, EncryptorDecryptorUtil };
@@ -3,7 +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.UUIDGeneratorUtil = exports.InMemoryCache = exports.SafeExecuteUtil = exports.ServerUtil = exports.SqlFormatterUtil = exports.EnvManagerUtil = exports.InputValidatorUtil = exports.InputTransformerUtil = exports.LoggerUtil = void 0;
6
+ exports.EncryptorDecryptorUtil = exports.UUIDGeneratorUtil = exports.InMemoryCache = exports.SafeExecuteUtil = exports.ServerUtil = exports.SqlFormatterUtil = exports.EnvManagerUtil = exports.InputValidatorUtil = exports.InputTransformerUtil = exports.LoggerUtil = void 0;
7
7
  const logger_util_1 = __importDefault(require("./logger_util"));
8
8
  exports.LoggerUtil = logger_util_1.default;
9
9
  const input_transformer_util_1 = __importDefault(require("./input_transformer_util"));
@@ -22,3 +22,5 @@ const cache_util_1 = __importDefault(require("./cache_util"));
22
22
  exports.InMemoryCache = cache_util_1.default;
23
23
  const uuid_gen_util_1 = __importDefault(require("./uuid_gen_util"));
24
24
  exports.UUIDGeneratorUtil = uuid_gen_util_1.default;
25
+ const encryptor_decryptor_util_1 = __importDefault(require("./encryptor_decryptor_util"));
26
+ exports.EncryptorDecryptorUtil = encryptor_decryptor_util_1.default;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fiberx-backend-toolkit",
3
- "version": "0.0.34",
3
+ "version": "0.0.36",
4
4
  "description": "A TypeScript backend toolkit providing shared domain logic, infrastructure helpers, and utilities for FiberX server-side applications and services.",
5
5
  "type": "commonjs",
6
6
  "main": "./dist/index.js",