@catbee/utils 1.1.0 → 2.0.0-next.0

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 (121) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +27 -27
  3. package/array/array.utils.d.ts +191 -0
  4. package/array/index.cjs +246 -0
  5. package/array/index.d.ts +25 -0
  6. package/array/index.mjs +228 -0
  7. package/async/async.utils.d.ts +296 -0
  8. package/async/index.cjs +428 -0
  9. package/async/index.d.ts +25 -0
  10. package/async/index.mjs +407 -0
  11. package/cache/cache.utils.d.ts +176 -0
  12. package/cache/index.cjs +292 -0
  13. package/cache/index.d.ts +25 -0
  14. package/cache/index.mjs +290 -0
  15. package/config/config.d.ts +57 -0
  16. package/config/index.cjs +136 -0
  17. package/config/index.d.ts +26 -0
  18. package/config/index.mjs +131 -0
  19. package/context-store/context-store.utils.d.ts +212 -0
  20. package/context-store/index.cjs +267 -0
  21. package/context-store/index.d.ts +25 -0
  22. package/context-store/index.mjs +261 -0
  23. package/crypto/crypto.utils.d.ts +183 -0
  24. package/crypto/index.cjs +182 -0
  25. package/crypto/index.d.ts +25 -0
  26. package/crypto/index.mjs +166 -0
  27. package/date/date.utils.d.ts +190 -0
  28. package/date/index.cjs +295 -0
  29. package/date/index.d.ts +25 -0
  30. package/date/index.mjs +283 -0
  31. package/decorators/decorators.utils.d.ts +705 -0
  32. package/decorators/index.cjs +913 -0
  33. package/decorators/index.d.ts +25 -0
  34. package/decorators/index.mjs +872 -0
  35. package/dir/dir.utils.d.ts +216 -0
  36. package/dir/index.cjs +416 -0
  37. package/dir/index.d.ts +25 -0
  38. package/dir/index.mjs +389 -0
  39. package/env/env.utils.d.ts +400 -0
  40. package/env/index.cjs +761 -0
  41. package/env/index.d.ts +25 -0
  42. package/env/index.mjs +758 -0
  43. package/exception/exception.utils.d.ts +253 -0
  44. package/exception/index.cjs +362 -0
  45. package/exception/index.d.ts +25 -0
  46. package/exception/index.mjs +338 -0
  47. package/fs/fs.utils.d.ts +196 -0
  48. package/fs/index.cjs +253 -0
  49. package/fs/index.d.ts +25 -0
  50. package/fs/index.mjs +228 -0
  51. package/http-status-codes/http-status-codes.d.ts +289 -0
  52. package/http-status-codes/index.cjs +96 -0
  53. package/http-status-codes/index.d.ts +25 -0
  54. package/http-status-codes/index.mjs +94 -0
  55. package/id/id.utils.d.ts +59 -0
  56. package/id/index.cjs +62 -0
  57. package/id/index.d.ts +25 -0
  58. package/id/index.mjs +56 -0
  59. package/index.cjs +218 -0
  60. package/index.d.ts +51 -0
  61. package/index.mjs +51 -0
  62. package/logger/index.cjs +334 -0
  63. package/logger/index.d.ts +25 -0
  64. package/logger/index.mjs +313 -0
  65. package/logger/logger.utils.d.ts +210 -0
  66. package/middleware/index.cjs +177 -0
  67. package/middleware/index.d.ts +25 -0
  68. package/middleware/index.mjs +170 -0
  69. package/middleware/middleware.utils.d.ts +123 -0
  70. package/obj/index.cjs +317 -0
  71. package/obj/index.d.ts +25 -0
  72. package/obj/index.mjs +301 -0
  73. package/obj/obj.utils.d.ts +156 -0
  74. package/package.json +171 -19
  75. package/performance/index.cjs +231 -0
  76. package/performance/index.d.ts +25 -0
  77. package/performance/index.mjs +225 -0
  78. package/performance/performance.utils.d.ts +159 -0
  79. package/request/index.cjs +202 -0
  80. package/request/index.d.ts +26 -0
  81. package/request/index.mjs +194 -0
  82. package/request/request.utils.d.ts +109 -0
  83. package/response/index.cjs +234 -0
  84. package/response/index.d.ts +26 -0
  85. package/response/index.mjs +222 -0
  86. package/response/response.utils.d.ts +186 -0
  87. package/server/index.cjs +1627 -0
  88. package/server/index.d.ts +28 -0
  89. package/server/index.mjs +1617 -0
  90. package/server/server.builder.d.ts +531 -0
  91. package/server/server.d.ts +303 -0
  92. package/stream/index.cjs +151 -0
  93. package/stream/index.d.ts +25 -0
  94. package/stream/index.mjs +144 -0
  95. package/stream/stream.utils.d.ts +111 -0
  96. package/string/index.cjs +109 -0
  97. package/string/index.d.ts +25 -0
  98. package/string/index.mjs +95 -0
  99. package/string/string.utils.d.ts +124 -0
  100. package/type/index.cjs +129 -0
  101. package/type/index.d.ts +25 -0
  102. package/type/index.mjs +119 -0
  103. package/type/type.utils.d.ts +129 -0
  104. package/types/api-response.d.ts +175 -0
  105. package/types/common.d.ts +148 -0
  106. package/types/config.d.ts +88 -0
  107. package/types/index.cjs +34 -0
  108. package/types/index.d.ts +28 -0
  109. package/types/index.mjs +32 -0
  110. package/types/server.d.ts +291 -0
  111. package/url/index.cjs +201 -0
  112. package/url/index.d.ts +25 -0
  113. package/url/index.mjs +189 -0
  114. package/url/url.utils.d.ts +164 -0
  115. package/validate/index.cjs +212 -0
  116. package/validate/index.d.ts +25 -0
  117. package/validate/index.mjs +188 -0
  118. package/validate/validate.utils.d.ts +200 -0
  119. package/build/index.cjs +0 -7694
  120. package/build/index.d.ts +0 -5792
  121. package/build/index.mjs +0 -7386
@@ -0,0 +1,183 @@
1
+ /*
2
+ * The MIT License
3
+ *
4
+ * Copyright (c) 2025 Catbee Technologies. https://catbee.in/license
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in all
14
+ * copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ * SOFTWARE.
23
+ */
24
+
25
+ import { BinaryToTextEncoding, CipherGCMTypes } from 'crypto';
26
+ export type BufferEncoding = 'ascii' | 'utf8' | 'utf-8' | 'utf16le' | 'utf-16le' | 'ucs2' | 'ucs-2' | 'base64' | 'base64url' | 'latin1' | 'binary' | 'hex';
27
+ /**
28
+ * Generates an HMAC digest using the specified algorithm and secret key.
29
+ *
30
+ * @param {string} algorithm - The hashing algorithm (e.g., 'sha256', 'sha1').
31
+ * @param {string} input - The string to hash.
32
+ * @param {string} secret - The secret key for HMAC.
33
+ * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding ('hex', 'base64', etc).
34
+ * @returns {string} HMAC digest as a string.
35
+ */
36
+ export declare function hmac(algorithm: string, input: string, secret: string, encoding?: BinaryToTextEncoding): string;
37
+ /**
38
+ * Generates a hash digest using the specified algorithm.
39
+ *
40
+ * @param {string} algorithm - The hashing algorithm (e.g., 'sha256', 'md5').
41
+ * @param {string} input - The string to hash.
42
+ * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding ('hex', 'base64', etc).
43
+ * @returns {string} Hash digest as a string.
44
+ */
45
+ export declare function hash(algorithm: string, input: string, encoding?: BinaryToTextEncoding): string;
46
+ /**
47
+ * Generates an HMAC-SHA256 digest.
48
+ *
49
+ * @param {string} input - The string to hash.
50
+ * @param {string} secret - The secret key.
51
+ * @returns {string} SHA-256 HMAC digest as a string.
52
+ */
53
+ export declare function sha256Hmac(input: string, secret: string): string;
54
+ /**
55
+ * Generates a SHA1 hash digest.
56
+ *
57
+ * @param {string} input - The string to hash.
58
+ * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.
59
+ * @returns {string} SHA-1 hash as a string.
60
+ */
61
+ export declare function sha1(input: string, encoding?: BinaryToTextEncoding): string;
62
+ /**
63
+ * Generates a SHA256 hash digest.
64
+ *
65
+ * @param {string} input - The string to hash.
66
+ * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.
67
+ * @returns {string} SHA-256 hash as a string.
68
+ */
69
+ export declare function sha256(input: string, encoding?: BinaryToTextEncoding): string;
70
+ /**
71
+ * Generates an MD5 hash digest.
72
+ *
73
+ * @param {string} input - The string to hash.
74
+ * @returns {string} MD5 hash as a string.
75
+ */
76
+ export declare function md5(input: string): string;
77
+ /**
78
+ * Generates a cryptographically strong random string by hashing a random UUID with SHA-256.
79
+ *
80
+ * @returns {string} Random string hashed with SHA-256 (hex encoding).
81
+ */
82
+ export declare function randomString(): string;
83
+ /**
84
+ * Generates a secure random buffer of specified byte length.
85
+ *
86
+ * @param {number} [byteLength=32] - Number of random bytes to generate.
87
+ * @returns {Buffer} Buffer containing random bytes.
88
+ */
89
+ export declare function generateRandomBytes(byteLength?: number): Buffer;
90
+ /**
91
+ * Generates a secure random string of specified byte length with specified encoding.
92
+ *
93
+ * @param {number} [byteLength=32] - Number of random bytes to generate.
94
+ * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.
95
+ * @returns {string} Random string in specified encoding.
96
+ */
97
+ export declare function generateRandomBytesAsString(byteLength?: number, encoding?: BinaryToTextEncoding): string;
98
+ /**
99
+ * Generates a secure API key with a specified format.
100
+ *
101
+ * @param {string} [prefix=''] - Optional prefix for the key.
102
+ * @param {number} [byteLength=24] - Number of random bytes to generate.
103
+ * @returns {string} Formatted API key.
104
+ */
105
+ export declare function generateApiKey(prefix?: string, byteLength?: number): string;
106
+ /**
107
+ * Compares two strings, arrays, or buffers in constant time to prevent timing attacks.
108
+ *
109
+ * @param {string | Buffer | Uint8Array} a - First value to compare
110
+ * @param {string | Buffer | Uint8Array} b - Second value to compare
111
+ * @returns {boolean} True if values are equal
112
+ */
113
+ export declare function safeCompare(a: string | Buffer | Uint8Array, b: string | Buffer | Uint8Array): boolean;
114
+ /**
115
+ * Interface for encryption options
116
+ */
117
+ export interface EncryptionOptions {
118
+ /** Algorithm to use (default: aes-256-gcm) */
119
+ algorithm?: CipherGCMTypes;
120
+ /** Input encoding for plaintext if string (default: utf8) */
121
+ inputEncoding?: BufferEncoding;
122
+ /** Output encoding for ciphertext (default: hex) */
123
+ outputEncoding?: BinaryToTextEncoding;
124
+ }
125
+ /**
126
+ * Interface for decryption options
127
+ */
128
+ export interface DecryptionOptions {
129
+ /** Algorithm to use (default: aes-256-gcm) */
130
+ algorithm?: CipherGCMTypes;
131
+ /** Input encoding for ciphertext if string (default: hex) */
132
+ inputEncoding?: BinaryToTextEncoding;
133
+ /** Output encoding for plaintext (default: utf8) */
134
+ outputEncoding?: BufferEncoding;
135
+ }
136
+ /**
137
+ * Result of encryption operation including all data needed for decryption
138
+ */
139
+ export interface EncryptionResult {
140
+ /** Encrypted data (string or Buffer based on options) */
141
+ ciphertext: string | Buffer;
142
+ /** Initialization vector */
143
+ iv: Buffer;
144
+ /** Authentication tag (for GCM mode) */
145
+ authTag?: Buffer;
146
+ /** Algorithm used */
147
+ algorithm: string;
148
+ }
149
+ /**
150
+ * Encrypts data using a symmetric key with secure defaults (AES-256-GCM).
151
+ *
152
+ * @param {string | Buffer} data - Data to encrypt
153
+ * @param {string | Buffer} key - Encryption key or passphrase
154
+ * @param {EncryptionOptions} [options] - Encryption options
155
+ * @returns {Promise<EncryptionResult>} Encrypted data with metadata
156
+ */
157
+ export declare function encrypt(data: string | Buffer, key: string | Buffer, options?: EncryptionOptions): Promise<EncryptionResult>;
158
+ /**
159
+ * Decrypts data that was encrypted with the encrypt function.
160
+ *
161
+ * @param {EncryptionResult} encryptedData - The encrypted data and metadata
162
+ * @param {string | Buffer} key - Decryption key or passphrase
163
+ * @param {DecryptionOptions} [options] - Decryption options
164
+ * @returns {Promise<string | Buffer>} Decrypted data
165
+ */
166
+ export declare function decrypt(encryptedData: EncryptionResult, key: string | Buffer, options?: DecryptionOptions): Promise<string | Buffer>;
167
+ /**
168
+ * Creates a signed token with an expiration time and payload.
169
+ *
170
+ * @param {object} payload - Data to include in the token
171
+ * @param {string} secret - Secret key for signing
172
+ * @param {number} [expiresInSeconds=3600] - Token expiration in seconds
173
+ * @returns {string} Signed token string
174
+ */
175
+ export declare function createSignedToken(payload: Record<string, any>, secret: string, expiresInSeconds?: number): string;
176
+ /**
177
+ * Verifies and decodes a signed token.
178
+ *
179
+ * @param {string} token - The token to verify
180
+ * @param {string} secret - Secret key for verification
181
+ * @returns {object | null} Decoded payload if valid, null if invalid
182
+ */
183
+ export declare function verifySignedToken(token: string, secret: string): Record<string, any> | null;
@@ -0,0 +1,182 @@
1
+ /*
2
+ * The MIT License
3
+ *
4
+ * Copyright (c) 2025 Catbee Technologies. https://catbee.in/license
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in all
14
+ * copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ * SOFTWARE.
23
+ */
24
+
25
+ 'use strict';
26
+
27
+ var crypto = require('crypto');
28
+ var util = require('util');
29
+ var id = require('@catbee/utils/id');
30
+
31
+ var __defProp = Object.defineProperty;
32
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
33
+ function hmac(algorithm, input, secret, encoding = "hex") {
34
+ return crypto.createHmac(algorithm, secret).update(input).digest(encoding);
35
+ }
36
+ __name(hmac, "hmac");
37
+ function hash(algorithm, input, encoding = "hex") {
38
+ return crypto.createHash(algorithm).update(input).digest(encoding);
39
+ }
40
+ __name(hash, "hash");
41
+ function sha256Hmac(input, secret) {
42
+ return hmac("sha256", input, secret);
43
+ }
44
+ __name(sha256Hmac, "sha256Hmac");
45
+ function sha1(input, encoding = "hex") {
46
+ return hash("sha1", input, encoding);
47
+ }
48
+ __name(sha1, "sha1");
49
+ function sha256(input, encoding = "hex") {
50
+ return hash("sha256", input, encoding);
51
+ }
52
+ __name(sha256, "sha256");
53
+ function md5(input) {
54
+ return hash("md5", input);
55
+ }
56
+ __name(md5, "md5");
57
+ function randomString() {
58
+ return sha256(id.uuid());
59
+ }
60
+ __name(randomString, "randomString");
61
+ function generateRandomBytes(byteLength = 32) {
62
+ return crypto.randomBytes(byteLength);
63
+ }
64
+ __name(generateRandomBytes, "generateRandomBytes");
65
+ function generateRandomBytesAsString(byteLength = 32, encoding = "hex") {
66
+ return crypto.randomBytes(byteLength).toString(encoding);
67
+ }
68
+ __name(generateRandomBytesAsString, "generateRandomBytesAsString");
69
+ function generateApiKey(prefix = "", byteLength = 24) {
70
+ const randomString2 = generateRandomBytesAsString(byteLength, "base64");
71
+ const key = randomString2.replace(/[+/=]/g, "").substring(0, 32);
72
+ return prefix ? `${prefix}_${key}` : key;
73
+ }
74
+ __name(generateApiKey, "generateApiKey");
75
+ function safeCompare(a, b) {
76
+ if (typeof a === "string" && typeof b === "string") {
77
+ const bufA = Buffer.from(a);
78
+ const bufB = Buffer.from(b);
79
+ if (bufA.length !== bufB.length) return false;
80
+ return crypto.timingSafeEqual(bufA, bufB);
81
+ } else if ((a instanceof Buffer || a instanceof Uint8Array) && (b instanceof Buffer || b instanceof Uint8Array)) {
82
+ if (a.length !== b.length) return false;
83
+ return crypto.timingSafeEqual(a instanceof Buffer ? a : Buffer.from(a), b instanceof Buffer ? b : Buffer.from(b));
84
+ }
85
+ throw new Error("Cannot compare: inputs must be strings, Buffers, or Uint8Arrays");
86
+ }
87
+ __name(safeCompare, "safeCompare");
88
+ var scryptAsync = util.promisify(crypto.scrypt);
89
+ async function encrypt(data, key, options = {}) {
90
+ const algorithm = options.algorithm || "aes-256-gcm";
91
+ const inputEncoding = options.inputEncoding || "utf8";
92
+ const outputEncoding = options.outputEncoding || "hex";
93
+ const iv = crypto.randomBytes(16);
94
+ const derivedKey = typeof key === "string" ? await scryptAsync(key, iv.slice(0, 8), 32) : key;
95
+ const cipher = crypto.createCipheriv(algorithm, derivedKey, iv);
96
+ let ciphertext;
97
+ if (typeof data === "string") {
98
+ ciphertext = cipher.update(data, inputEncoding, outputEncoding);
99
+ ciphertext += cipher.final(outputEncoding);
100
+ } else {
101
+ const encrypted = Buffer.concat([
102
+ cipher.update(data),
103
+ cipher.final()
104
+ ]);
105
+ ciphertext = encrypted.toString(outputEncoding) ;
106
+ }
107
+ const authTag = algorithm.includes("gcm") ? cipher.getAuthTag() : void 0;
108
+ return {
109
+ ciphertext,
110
+ iv,
111
+ authTag,
112
+ algorithm
113
+ };
114
+ }
115
+ __name(encrypt, "encrypt");
116
+ async function decrypt(encryptedData, key, options = {}) {
117
+ const algorithm = options.algorithm || encryptedData.algorithm || "aes-256-gcm";
118
+ const inputEncoding = options.inputEncoding || "hex";
119
+ const outputEncoding = options.outputEncoding || "utf8";
120
+ const derivedKey = typeof key === "string" ? await scryptAsync(key, encryptedData.iv.slice(0, 8), 32) : key;
121
+ const decipher = crypto.createDecipheriv(algorithm, derivedKey, encryptedData.iv);
122
+ if (encryptedData.authTag && algorithm.includes("gcm")) {
123
+ decipher.setAuthTag(encryptedData.authTag);
124
+ }
125
+ let decrypted;
126
+ if (typeof encryptedData.ciphertext === "string") {
127
+ decrypted = decipher.update(encryptedData.ciphertext, inputEncoding, outputEncoding);
128
+ decrypted += decipher.final(outputEncoding);
129
+ } else {
130
+ const result = Buffer.concat([
131
+ decipher.update(encryptedData.ciphertext),
132
+ decipher.final()
133
+ ]);
134
+ decrypted = result.toString(outputEncoding) ;
135
+ }
136
+ return decrypted;
137
+ }
138
+ __name(decrypt, "decrypt");
139
+ function createSignedToken(payload, secret, expiresInSeconds = 3600) {
140
+ const tokenPayload = {
141
+ ...payload,
142
+ exp: Math.floor(Date.now() / 1e3) + expiresInSeconds
143
+ };
144
+ const payloadStr = JSON.stringify(tokenPayload);
145
+ const base64Payload = Buffer.from(payloadStr).toString("base64url");
146
+ const signature = hmac("sha256", base64Payload, secret, "base64url");
147
+ return `${base64Payload}.${signature}`;
148
+ }
149
+ __name(createSignedToken, "createSignedToken");
150
+ function verifySignedToken(token, secret) {
151
+ try {
152
+ const [payloadB64, signature] = token.split(".");
153
+ if (!payloadB64 || !signature) return null;
154
+ const expectedSignature = hmac("sha256", payloadB64, secret, "base64url");
155
+ if (!safeCompare(signature, expectedSignature)) return null;
156
+ const payloadStr = Buffer.from(payloadB64, "base64url").toString("utf8");
157
+ const payload = JSON.parse(payloadStr);
158
+ if (payload.exp && payload.exp < Math.floor(Date.now() / 1e3)) {
159
+ return null;
160
+ }
161
+ return payload;
162
+ } catch {
163
+ return null;
164
+ }
165
+ }
166
+ __name(verifySignedToken, "verifySignedToken");
167
+
168
+ exports.createSignedToken = createSignedToken;
169
+ exports.decrypt = decrypt;
170
+ exports.encrypt = encrypt;
171
+ exports.generateApiKey = generateApiKey;
172
+ exports.generateRandomBytes = generateRandomBytes;
173
+ exports.generateRandomBytesAsString = generateRandomBytesAsString;
174
+ exports.hash = hash;
175
+ exports.hmac = hmac;
176
+ exports.md5 = md5;
177
+ exports.randomString = randomString;
178
+ exports.safeCompare = safeCompare;
179
+ exports.sha1 = sha1;
180
+ exports.sha256 = sha256;
181
+ exports.sha256Hmac = sha256Hmac;
182
+ exports.verifySignedToken = verifySignedToken;
@@ -0,0 +1,25 @@
1
+ /*
2
+ * The MIT License
3
+ *
4
+ * Copyright (c) 2025 Catbee Technologies. https://catbee.in/license
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in all
14
+ * copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ * SOFTWARE.
23
+ */
24
+
25
+ export * from './crypto.utils';
@@ -0,0 +1,166 @@
1
+ /*
2
+ * The MIT License
3
+ *
4
+ * Copyright (c) 2025 Catbee Technologies. https://catbee.in/license
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in all
14
+ * copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ * SOFTWARE.
23
+ */
24
+
25
+ import { scrypt, createHmac, createHash, randomBytes, timingSafeEqual, createCipheriv, createDecipheriv } from 'crypto';
26
+ import { promisify } from 'util';
27
+ import { uuid } from '@catbee/utils/id';
28
+
29
+ var __defProp = Object.defineProperty;
30
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
31
+ function hmac(algorithm, input, secret, encoding = "hex") {
32
+ return createHmac(algorithm, secret).update(input).digest(encoding);
33
+ }
34
+ __name(hmac, "hmac");
35
+ function hash(algorithm, input, encoding = "hex") {
36
+ return createHash(algorithm).update(input).digest(encoding);
37
+ }
38
+ __name(hash, "hash");
39
+ function sha256Hmac(input, secret) {
40
+ return hmac("sha256", input, secret);
41
+ }
42
+ __name(sha256Hmac, "sha256Hmac");
43
+ function sha1(input, encoding = "hex") {
44
+ return hash("sha1", input, encoding);
45
+ }
46
+ __name(sha1, "sha1");
47
+ function sha256(input, encoding = "hex") {
48
+ return hash("sha256", input, encoding);
49
+ }
50
+ __name(sha256, "sha256");
51
+ function md5(input) {
52
+ return hash("md5", input);
53
+ }
54
+ __name(md5, "md5");
55
+ function randomString() {
56
+ return sha256(uuid());
57
+ }
58
+ __name(randomString, "randomString");
59
+ function generateRandomBytes(byteLength = 32) {
60
+ return randomBytes(byteLength);
61
+ }
62
+ __name(generateRandomBytes, "generateRandomBytes");
63
+ function generateRandomBytesAsString(byteLength = 32, encoding = "hex") {
64
+ return randomBytes(byteLength).toString(encoding);
65
+ }
66
+ __name(generateRandomBytesAsString, "generateRandomBytesAsString");
67
+ function generateApiKey(prefix = "", byteLength = 24) {
68
+ const randomString2 = generateRandomBytesAsString(byteLength, "base64");
69
+ const key = randomString2.replace(/[+/=]/g, "").substring(0, 32);
70
+ return prefix ? `${prefix}_${key}` : key;
71
+ }
72
+ __name(generateApiKey, "generateApiKey");
73
+ function safeCompare(a, b) {
74
+ if (typeof a === "string" && typeof b === "string") {
75
+ const bufA = Buffer.from(a);
76
+ const bufB = Buffer.from(b);
77
+ if (bufA.length !== bufB.length) return false;
78
+ return timingSafeEqual(bufA, bufB);
79
+ } else if ((a instanceof Buffer || a instanceof Uint8Array) && (b instanceof Buffer || b instanceof Uint8Array)) {
80
+ if (a.length !== b.length) return false;
81
+ return timingSafeEqual(a instanceof Buffer ? a : Buffer.from(a), b instanceof Buffer ? b : Buffer.from(b));
82
+ }
83
+ throw new Error("Cannot compare: inputs must be strings, Buffers, or Uint8Arrays");
84
+ }
85
+ __name(safeCompare, "safeCompare");
86
+ var scryptAsync = promisify(scrypt);
87
+ async function encrypt(data, key, options = {}) {
88
+ const algorithm = options.algorithm || "aes-256-gcm";
89
+ const inputEncoding = options.inputEncoding || "utf8";
90
+ const outputEncoding = options.outputEncoding || "hex";
91
+ const iv = randomBytes(16);
92
+ const derivedKey = typeof key === "string" ? await scryptAsync(key, iv.slice(0, 8), 32) : key;
93
+ const cipher = createCipheriv(algorithm, derivedKey, iv);
94
+ let ciphertext;
95
+ if (typeof data === "string") {
96
+ ciphertext = cipher.update(data, inputEncoding, outputEncoding);
97
+ ciphertext += cipher.final(outputEncoding);
98
+ } else {
99
+ const encrypted = Buffer.concat([
100
+ cipher.update(data),
101
+ cipher.final()
102
+ ]);
103
+ ciphertext = encrypted.toString(outputEncoding) ;
104
+ }
105
+ const authTag = algorithm.includes("gcm") ? cipher.getAuthTag() : void 0;
106
+ return {
107
+ ciphertext,
108
+ iv,
109
+ authTag,
110
+ algorithm
111
+ };
112
+ }
113
+ __name(encrypt, "encrypt");
114
+ async function decrypt(encryptedData, key, options = {}) {
115
+ const algorithm = options.algorithm || encryptedData.algorithm || "aes-256-gcm";
116
+ const inputEncoding = options.inputEncoding || "hex";
117
+ const outputEncoding = options.outputEncoding || "utf8";
118
+ const derivedKey = typeof key === "string" ? await scryptAsync(key, encryptedData.iv.slice(0, 8), 32) : key;
119
+ const decipher = createDecipheriv(algorithm, derivedKey, encryptedData.iv);
120
+ if (encryptedData.authTag && algorithm.includes("gcm")) {
121
+ decipher.setAuthTag(encryptedData.authTag);
122
+ }
123
+ let decrypted;
124
+ if (typeof encryptedData.ciphertext === "string") {
125
+ decrypted = decipher.update(encryptedData.ciphertext, inputEncoding, outputEncoding);
126
+ decrypted += decipher.final(outputEncoding);
127
+ } else {
128
+ const result = Buffer.concat([
129
+ decipher.update(encryptedData.ciphertext),
130
+ decipher.final()
131
+ ]);
132
+ decrypted = result.toString(outputEncoding) ;
133
+ }
134
+ return decrypted;
135
+ }
136
+ __name(decrypt, "decrypt");
137
+ function createSignedToken(payload, secret, expiresInSeconds = 3600) {
138
+ const tokenPayload = {
139
+ ...payload,
140
+ exp: Math.floor(Date.now() / 1e3) + expiresInSeconds
141
+ };
142
+ const payloadStr = JSON.stringify(tokenPayload);
143
+ const base64Payload = Buffer.from(payloadStr).toString("base64url");
144
+ const signature = hmac("sha256", base64Payload, secret, "base64url");
145
+ return `${base64Payload}.${signature}`;
146
+ }
147
+ __name(createSignedToken, "createSignedToken");
148
+ function verifySignedToken(token, secret) {
149
+ try {
150
+ const [payloadB64, signature] = token.split(".");
151
+ if (!payloadB64 || !signature) return null;
152
+ const expectedSignature = hmac("sha256", payloadB64, secret, "base64url");
153
+ if (!safeCompare(signature, expectedSignature)) return null;
154
+ const payloadStr = Buffer.from(payloadB64, "base64url").toString("utf8");
155
+ const payload = JSON.parse(payloadStr);
156
+ if (payload.exp && payload.exp < Math.floor(Date.now() / 1e3)) {
157
+ return null;
158
+ }
159
+ return payload;
160
+ } catch {
161
+ return null;
162
+ }
163
+ }
164
+ __name(verifySignedToken, "verifySignedToken");
165
+
166
+ export { createSignedToken, decrypt, encrypt, generateApiKey, generateRandomBytes, generateRandomBytesAsString, hash, hmac, md5, randomString, safeCompare, sha1, sha256, sha256Hmac, verifySignedToken };