@catbee/utils 0.0.1 → 0.0.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.
- package/README.md +303 -107
- package/build/esm/config.d.ts +13 -1
- package/build/esm/config.js +16 -4
- package/build/esm/config.js.map +1 -1
- package/build/esm/index.d.ts +20 -18
- package/build/esm/index.js +20 -18
- package/build/esm/index.js.map +1 -1
- package/build/esm/types/api-response.d.ts +83 -1
- package/build/esm/types/api-response.js.map +1 -1
- package/build/esm/utils/array.utils.d.ts +65 -2
- package/build/esm/utils/array.utils.js +147 -20
- package/build/esm/utils/array.utils.js.map +1 -1
- package/build/esm/utils/async.utils.d.ts +56 -1
- package/build/esm/utils/async.utils.js +166 -11
- package/build/esm/utils/async.utils.js.map +1 -1
- package/build/esm/utils/cache.utils.d.ts +67 -4
- package/build/esm/utils/cache.utils.js +210 -28
- package/build/esm/utils/cache.utils.js.map +1 -1
- package/build/esm/utils/context-store.utils.d.ts +102 -1
- package/build/esm/utils/context-store.utils.js +185 -3
- package/build/esm/utils/context-store.utils.js.map +1 -1
- package/build/esm/utils/crypto.utils.d.ts +110 -8
- package/build/esm/utils/crypto.utils.js +298 -23
- package/build/esm/utils/crypto.utils.js.map +1 -1
- package/build/esm/utils/decorators.utils.d.ts +40 -0
- package/build/esm/utils/decorators.utils.js +312 -0
- package/build/esm/utils/decorators.utils.js.map +1 -0
- package/build/esm/utils/dir.utils.d.ts +122 -1
- package/build/esm/utils/dir.utils.js +578 -3
- package/build/esm/utils/dir.utils.js.map +1 -1
- package/build/esm/utils/env.utils.d.ts +83 -0
- package/build/esm/utils/env.utils.js +235 -6
- package/build/esm/utils/env.utils.js.map +1 -1
- package/build/esm/utils/exception.utils.d.ts +117 -1
- package/build/esm/utils/exception.utils.js +331 -12
- package/build/esm/utils/exception.utils.js.map +1 -1
- package/build/esm/utils/fs.utils.d.ts +132 -0
- package/build/esm/utils/fs.utils.js +421 -4
- package/build/esm/utils/fs.utils.js.map +1 -1
- package/build/esm/utils/http-status-codes.d.ts +87 -178
- package/build/esm/utils/http-status-codes.js +92 -178
- package/build/esm/utils/http-status-codes.js.map +1 -1
- package/build/esm/utils/id.utils.d.ts +11 -10
- package/build/esm/utils/id.utils.js +30 -21
- package/build/esm/utils/id.utils.js.map +1 -1
- package/build/esm/utils/logger.utils.d.ts +35 -2
- package/build/esm/utils/logger.utils.js +68 -14
- package/build/esm/utils/logger.utils.js.map +1 -1
- package/build/esm/utils/middleware.utils.d.ts +73 -0
- package/build/esm/utils/middleware.utils.js +158 -0
- package/build/esm/utils/middleware.utils.js.map +1 -0
- package/build/esm/utils/obj.utils.d.ts +65 -3
- package/build/esm/utils/obj.utils.js +206 -18
- package/build/esm/utils/obj.utils.js.map +1 -1
- package/build/esm/utils/response.utils.d.ts +103 -2
- package/build/esm/utils/response.utils.js +156 -3
- package/build/esm/utils/response.utils.js.map +1 -1
- package/build/esm/utils/string.utils.d.ts +61 -5
- package/build/esm/utils/string.utils.js +109 -19
- package/build/esm/utils/string.utils.js.map +1 -1
- package/build/esm/utils/url.utils.d.ts +117 -0
- package/build/esm/utils/url.utils.js +287 -2
- package/build/esm/utils/url.utils.js.map +1 -1
- package/build/esm/utils/validate.utils.d.ts +110 -0
- package/build/esm/utils/validate.utils.js +190 -8
- package/build/esm/utils/validate.utils.js.map +1 -1
- package/build/esnext/config.d.ts +13 -1
- package/build/esnext/config.js +16 -4
- package/build/esnext/config.js.map +1 -1
- package/build/esnext/index.d.ts +20 -18
- package/build/esnext/index.js +20 -18
- package/build/esnext/index.js.map +1 -1
- package/build/esnext/types/api-response.d.ts +83 -1
- package/build/esnext/types/api-response.js.map +1 -1
- package/build/esnext/utils/array.utils.d.ts +65 -2
- package/build/esnext/utils/array.utils.js +140 -21
- package/build/esnext/utils/array.utils.js.map +1 -1
- package/build/esnext/utils/async.utils.d.ts +56 -1
- package/build/esnext/utils/async.utils.js +130 -14
- package/build/esnext/utils/async.utils.js.map +1 -1
- package/build/esnext/utils/cache.utils.d.ts +67 -4
- package/build/esnext/utils/cache.utils.js +137 -9
- package/build/esnext/utils/cache.utils.js.map +1 -1
- package/build/esnext/utils/context-store.utils.d.ts +102 -1
- package/build/esnext/utils/context-store.utils.js +171 -3
- package/build/esnext/utils/context-store.utils.js.map +1 -1
- package/build/esnext/utils/crypto.utils.d.ts +110 -8
- package/build/esnext/utils/crypto.utils.js +199 -19
- package/build/esnext/utils/crypto.utils.js.map +1 -1
- package/build/esnext/utils/decorators.utils.d.ts +40 -0
- package/build/esnext/utils/decorators.utils.js +155 -0
- package/build/esnext/utils/decorators.utils.js.map +1 -0
- package/build/esnext/utils/dir.utils.d.ts +122 -1
- package/build/esnext/utils/dir.utils.js +307 -3
- package/build/esnext/utils/dir.utils.js.map +1 -1
- package/build/esnext/utils/env.utils.d.ts +83 -0
- package/build/esnext/utils/env.utils.js +191 -8
- package/build/esnext/utils/env.utils.js.map +1 -1
- package/build/esnext/utils/exception.utils.d.ts +117 -1
- package/build/esnext/utils/exception.utils.js +222 -12
- package/build/esnext/utils/exception.utils.js.map +1 -1
- package/build/esnext/utils/fs.utils.d.ts +132 -0
- package/build/esnext/utils/fs.utils.js +268 -4
- package/build/esnext/utils/fs.utils.js.map +1 -1
- package/build/esnext/utils/http-status-codes.d.ts +87 -178
- package/build/esnext/utils/http-status-codes.js +92 -178
- package/build/esnext/utils/http-status-codes.js.map +1 -1
- package/build/esnext/utils/id.utils.d.ts +11 -10
- package/build/esnext/utils/id.utils.js +28 -20
- package/build/esnext/utils/id.utils.js.map +1 -1
- package/build/esnext/utils/logger.utils.d.ts +35 -2
- package/build/esnext/utils/logger.utils.js +56 -14
- package/build/esnext/utils/logger.utils.js.map +1 -1
- package/build/esnext/utils/middleware.utils.d.ts +73 -0
- package/build/esnext/utils/middleware.utils.js +157 -0
- package/build/esnext/utils/middleware.utils.js.map +1 -0
- package/build/esnext/utils/obj.utils.d.ts +65 -3
- package/build/esnext/utils/obj.utils.js +169 -14
- package/build/esnext/utils/obj.utils.js.map +1 -1
- package/build/esnext/utils/response.utils.d.ts +103 -2
- package/build/esnext/utils/response.utils.js +141 -3
- package/build/esnext/utils/response.utils.js.map +1 -1
- package/build/esnext/utils/string.utils.d.ts +61 -5
- package/build/esnext/utils/string.utils.js +110 -14
- package/build/esnext/utils/string.utils.js.map +1 -1
- package/build/esnext/utils/url.utils.d.ts +117 -0
- package/build/esnext/utils/url.utils.js +248 -2
- package/build/esnext/utils/url.utils.js.map +1 -1
- package/build/esnext/utils/validate.utils.d.ts +110 -0
- package/build/esnext/utils/validate.utils.js +190 -8
- package/build/esnext/utils/validate.utils.js.map +1 -1
- package/build/src/config.d.ts +13 -1
- package/build/src/config.js +15 -3
- package/build/src/config.js.map +1 -1
- package/build/src/index.d.ts +20 -18
- package/build/src/index.js +2 -0
- package/build/src/index.js.map +1 -1
- package/build/src/types/api-response.d.ts +83 -1
- package/build/src/types/api-response.js.map +1 -1
- package/build/src/utils/array.utils.d.ts +65 -2
- package/build/src/utils/array.utils.js +147 -22
- package/build/src/utils/array.utils.js.map +1 -1
- package/build/src/utils/async.utils.d.ts +56 -1
- package/build/src/utils/async.utils.js +137 -17
- package/build/src/utils/async.utils.js.map +1 -1
- package/build/src/utils/cache.utils.d.ts +67 -4
- package/build/src/utils/cache.utils.js +137 -9
- package/build/src/utils/cache.utils.js.map +1 -1
- package/build/src/utils/context-store.utils.d.ts +102 -1
- package/build/src/utils/context-store.utils.js +173 -3
- package/build/src/utils/context-store.utils.js.map +1 -1
- package/build/src/utils/crypto.utils.d.ts +110 -8
- package/build/src/utils/crypto.utils.js +214 -27
- package/build/src/utils/crypto.utils.js.map +1 -1
- package/build/src/utils/decorators.utils.d.ts +40 -0
- package/build/src/utils/decorators.utils.js +165 -0
- package/build/src/utils/decorators.utils.js.map +1 -0
- package/build/src/utils/dir.utils.d.ts +122 -1
- package/build/src/utils/dir.utils.js +314 -0
- package/build/src/utils/dir.utils.js.map +1 -1
- package/build/src/utils/env.utils.d.ts +83 -0
- package/build/src/utils/env.utils.js +192 -9
- package/build/src/utils/env.utils.js.map +1 -1
- package/build/src/utils/exception.utils.d.ts +117 -1
- package/build/src/utils/exception.utils.js +233 -11
- package/build/src/utils/exception.utils.js.map +1 -1
- package/build/src/utils/fs.utils.d.ts +132 -0
- package/build/src/utils/fs.utils.js +281 -3
- package/build/src/utils/fs.utils.js.map +1 -1
- package/build/src/utils/http-status-codes.d.ts +87 -178
- package/build/src/utils/http-status-codes.js +92 -178
- package/build/src/utils/http-status-codes.js.map +1 -1
- package/build/src/utils/id.utils.d.ts +11 -10
- package/build/src/utils/id.utils.js +28 -20
- package/build/src/utils/id.utils.js.map +1 -1
- package/build/src/utils/logger.utils.d.ts +35 -2
- package/build/src/utils/logger.utils.js +56 -11
- package/build/src/utils/logger.utils.js.map +1 -1
- package/build/src/utils/middleware.utils.d.ts +73 -0
- package/build/src/utils/middleware.utils.js +163 -0
- package/build/src/utils/middleware.utils.js.map +1 -0
- package/build/src/utils/obj.utils.d.ts +65 -3
- package/build/src/utils/obj.utils.js +179 -18
- package/build/src/utils/obj.utils.js.map +1 -1
- package/build/src/utils/response.utils.d.ts +103 -2
- package/build/src/utils/response.utils.js +147 -2
- package/build/src/utils/response.utils.js.map +1 -1
- package/build/src/utils/string.utils.d.ts +61 -5
- package/build/src/utils/string.utils.js +122 -20
- package/build/src/utils/string.utils.js.map +1 -1
- package/build/src/utils/url.utils.d.ts +117 -0
- package/build/src/utils/url.utils.js +256 -1
- package/build/src/utils/url.utils.js.map +1 -1
- package/build/src/utils/validate.utils.d.ts +110 -0
- package/build/src/utils/validate.utils.js +204 -8
- package/build/src/utils/validate.utils.js.map +1 -1
- package/package.json +20 -12
|
@@ -1,7 +1,22 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.
|
|
3
|
+
exports.hmac = hmac;
|
|
4
|
+
exports.hash = hash;
|
|
5
|
+
exports.sha256Hmac = sha256Hmac;
|
|
6
|
+
exports.sha1 = sha1;
|
|
7
|
+
exports.sha256 = sha256;
|
|
8
|
+
exports.md5 = md5;
|
|
9
|
+
exports.randomString = randomString;
|
|
10
|
+
exports.generateRandomBytes = generateRandomBytes;
|
|
11
|
+
exports.generateRandomBytesAsString = generateRandomBytesAsString;
|
|
12
|
+
exports.generateApiKey = generateApiKey;
|
|
13
|
+
exports.safeCompare = safeCompare;
|
|
14
|
+
exports.encrypt = encrypt;
|
|
15
|
+
exports.decrypt = decrypt;
|
|
16
|
+
exports.createSignedToken = createSignedToken;
|
|
17
|
+
exports.verifySignedToken = verifySignedToken;
|
|
4
18
|
const crypto_1 = require("crypto");
|
|
19
|
+
const util_1 = require("util");
|
|
5
20
|
/**
|
|
6
21
|
* Generates an HMAC digest using the specified algorithm and secret key.
|
|
7
22
|
*
|
|
@@ -11,10 +26,9 @@ const crypto_1 = require("crypto");
|
|
|
11
26
|
* @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding ('hex', 'base64', etc).
|
|
12
27
|
* @returns {string} HMAC digest as a string.
|
|
13
28
|
*/
|
|
14
|
-
|
|
29
|
+
function hmac(algorithm, input, secret, encoding = 'hex') {
|
|
15
30
|
return (0, crypto_1.createHmac)(algorithm, secret).update(input).digest(encoding);
|
|
16
|
-
}
|
|
17
|
-
exports.hmac = hmac;
|
|
31
|
+
}
|
|
18
32
|
/**
|
|
19
33
|
* Generates a hash digest using the specified algorithm.
|
|
20
34
|
*
|
|
@@ -23,10 +37,9 @@ exports.hmac = hmac;
|
|
|
23
37
|
* @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding ('hex', 'base64', etc).
|
|
24
38
|
* @returns {string} Hash digest as a string.
|
|
25
39
|
*/
|
|
26
|
-
|
|
40
|
+
function hash(algorithm, input, encoding = 'hex') {
|
|
27
41
|
return (0, crypto_1.createHash)(algorithm).update(input).digest(encoding);
|
|
28
|
-
}
|
|
29
|
-
exports.hash = hash;
|
|
42
|
+
}
|
|
30
43
|
/**
|
|
31
44
|
* Generates an HMAC-SHA256 digest.
|
|
32
45
|
*
|
|
@@ -34,10 +47,9 @@ exports.hash = hash;
|
|
|
34
47
|
* @param {string} secret - The secret key.
|
|
35
48
|
* @returns {string} SHA-256 HMAC digest as a string.
|
|
36
49
|
*/
|
|
37
|
-
|
|
38
|
-
return
|
|
39
|
-
}
|
|
40
|
-
exports.sha256Hmac = sha256Hmac;
|
|
50
|
+
function sha256Hmac(input, secret) {
|
|
51
|
+
return hmac('sha256', input, secret);
|
|
52
|
+
}
|
|
41
53
|
/**
|
|
42
54
|
* Generates a SHA1 hash digest.
|
|
43
55
|
*
|
|
@@ -45,10 +57,9 @@ exports.sha256Hmac = sha256Hmac;
|
|
|
45
57
|
* @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.
|
|
46
58
|
* @returns {string} SHA-1 hash as a string.
|
|
47
59
|
*/
|
|
48
|
-
|
|
49
|
-
return
|
|
50
|
-
}
|
|
51
|
-
exports.sha1 = sha1;
|
|
60
|
+
function sha1(input, encoding = 'hex') {
|
|
61
|
+
return hash('sha1', input, encoding);
|
|
62
|
+
}
|
|
52
63
|
/**
|
|
53
64
|
* Generates a SHA256 hash digest.
|
|
54
65
|
*
|
|
@@ -56,27 +67,203 @@ exports.sha1 = sha1;
|
|
|
56
67
|
* @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.
|
|
57
68
|
* @returns {string} SHA-256 hash as a string.
|
|
58
69
|
*/
|
|
59
|
-
|
|
60
|
-
return
|
|
61
|
-
}
|
|
62
|
-
exports.sha256 = sha256;
|
|
70
|
+
function sha256(input, encoding = 'hex') {
|
|
71
|
+
return hash('sha256', input, encoding);
|
|
72
|
+
}
|
|
63
73
|
/**
|
|
64
74
|
* Generates an MD5 hash digest.
|
|
65
75
|
*
|
|
66
76
|
* @param {string} input - The string to hash.
|
|
67
77
|
* @returns {string} MD5 hash as a string.
|
|
68
78
|
*/
|
|
69
|
-
|
|
70
|
-
return
|
|
71
|
-
}
|
|
72
|
-
exports.md5 = md5;
|
|
79
|
+
function md5(input) {
|
|
80
|
+
return hash('md5', input);
|
|
81
|
+
}
|
|
73
82
|
/**
|
|
74
83
|
* Generates a cryptographically strong random string by hashing a random UUID with SHA-256.
|
|
75
84
|
*
|
|
76
85
|
* @returns {string} Random string hashed with SHA-256 (hex encoding).
|
|
77
86
|
*/
|
|
78
|
-
|
|
79
|
-
return
|
|
80
|
-
}
|
|
81
|
-
|
|
87
|
+
function randomString() {
|
|
88
|
+
return sha256((0, crypto_1.randomUUID)());
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Generates a secure random buffer of specified byte length.
|
|
92
|
+
*
|
|
93
|
+
* @param {number} [byteLength=32] - Number of random bytes to generate.
|
|
94
|
+
* @returns {Buffer} Buffer containing random bytes.
|
|
95
|
+
*/
|
|
96
|
+
function generateRandomBytes(byteLength = 32) {
|
|
97
|
+
return (0, crypto_1.randomBytes)(byteLength);
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Generates a secure random string of specified byte length with specified encoding.
|
|
101
|
+
*
|
|
102
|
+
* @param {number} [byteLength=32] - Number of random bytes to generate.
|
|
103
|
+
* @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.
|
|
104
|
+
* @returns {string} Random string in specified encoding.
|
|
105
|
+
*/
|
|
106
|
+
function generateRandomBytesAsString(byteLength = 32, encoding = 'hex') {
|
|
107
|
+
return (0, crypto_1.randomBytes)(byteLength).toString(encoding);
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Generates a secure API key with a specified format.
|
|
111
|
+
*
|
|
112
|
+
* @param {string} [prefix=''] - Optional prefix for the key.
|
|
113
|
+
* @param {number} [byteLength=24] - Number of random bytes to generate.
|
|
114
|
+
* @returns {string} Formatted API key.
|
|
115
|
+
*/
|
|
116
|
+
function generateApiKey(prefix = '', byteLength = 24) {
|
|
117
|
+
const randomString = generateRandomBytesAsString(byteLength, 'base64');
|
|
118
|
+
const key = randomString
|
|
119
|
+
.replace(/[+/=]/g, '') // Remove non-URL-safe characters
|
|
120
|
+
.substring(0, 32); // Limit length
|
|
121
|
+
return prefix ? `${prefix}_${key}` : key;
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Compares two strings, arrays, or buffers in constant time to prevent timing attacks.
|
|
125
|
+
*
|
|
126
|
+
* @param {string | Buffer | Uint8Array} a - First value to compare
|
|
127
|
+
* @param {string | Buffer | Uint8Array} b - Second value to compare
|
|
128
|
+
* @returns {boolean} True if values are equal
|
|
129
|
+
*/
|
|
130
|
+
function safeCompare(a, b) {
|
|
131
|
+
if (typeof a === 'string' && typeof b === 'string') {
|
|
132
|
+
// Convert strings to buffers
|
|
133
|
+
const bufA = Buffer.from(a);
|
|
134
|
+
const bufB = Buffer.from(b);
|
|
135
|
+
// Compare lengths first (not constant time, but prevents timing attack on contents)
|
|
136
|
+
if (bufA.length !== bufB.length)
|
|
137
|
+
return false;
|
|
138
|
+
return (0, crypto_1.timingSafeEqual)(bufA, bufB);
|
|
139
|
+
}
|
|
140
|
+
else if ((a instanceof Buffer || a instanceof Uint8Array) && (b instanceof Buffer || b instanceof Uint8Array)) {
|
|
141
|
+
// Compare lengths first
|
|
142
|
+
if (a.length !== b.length)
|
|
143
|
+
return false;
|
|
144
|
+
return (0, crypto_1.timingSafeEqual)(a instanceof Buffer ? a : Buffer.from(a), b instanceof Buffer ? b : Buffer.from(b));
|
|
145
|
+
}
|
|
146
|
+
throw new Error('Cannot compare: inputs must be strings, Buffers, or Uint8Arrays');
|
|
147
|
+
}
|
|
148
|
+
// Promisified version of scrypt for key derivation
|
|
149
|
+
const scryptAsync = (0, util_1.promisify)(crypto_1.scrypt);
|
|
150
|
+
/**
|
|
151
|
+
* Encrypts data using a symmetric key with secure defaults (AES-256-GCM).
|
|
152
|
+
*
|
|
153
|
+
* @param {string | Buffer} data - Data to encrypt
|
|
154
|
+
* @param {string | Buffer} key - Encryption key or passphrase
|
|
155
|
+
* @param {EncryptionOptions} [options] - Encryption options
|
|
156
|
+
* @returns {Promise<EncryptionResult>} Encrypted data with metadata
|
|
157
|
+
*/
|
|
158
|
+
async function encrypt(data, key, options = {}) {
|
|
159
|
+
const algorithm = options.algorithm || 'aes-256-gcm';
|
|
160
|
+
const inputEncoding = options.inputEncoding || 'utf8';
|
|
161
|
+
const outputEncoding = options.outputEncoding || 'hex';
|
|
162
|
+
// Generate a random IV
|
|
163
|
+
const iv = (0, crypto_1.randomBytes)(16);
|
|
164
|
+
// Derive key using scrypt if key is a string (passphrase)
|
|
165
|
+
const derivedKey = typeof key === 'string' ? await scryptAsync(key, iv.slice(0, 8), 32) : key;
|
|
166
|
+
// Create cipher
|
|
167
|
+
const cipher = (0, crypto_1.createCipheriv)(algorithm, derivedKey, iv);
|
|
168
|
+
// Encrypt the data
|
|
169
|
+
let ciphertext;
|
|
170
|
+
if (typeof data === 'string') {
|
|
171
|
+
ciphertext = cipher.update(data, inputEncoding, outputEncoding);
|
|
172
|
+
ciphertext += cipher.final(outputEncoding);
|
|
173
|
+
}
|
|
174
|
+
else {
|
|
175
|
+
const encrypted = Buffer.concat([cipher.update(data), cipher.final()]);
|
|
176
|
+
ciphertext = outputEncoding ? encrypted.toString(outputEncoding) : encrypted;
|
|
177
|
+
}
|
|
178
|
+
// Get authentication tag if using GCM mode
|
|
179
|
+
const authTag = algorithm.includes('gcm') ? cipher.getAuthTag() : undefined;
|
|
180
|
+
return {
|
|
181
|
+
ciphertext,
|
|
182
|
+
iv,
|
|
183
|
+
authTag,
|
|
184
|
+
algorithm
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* Decrypts data that was encrypted with the encrypt function.
|
|
189
|
+
*
|
|
190
|
+
* @param {EncryptionResult} encryptedData - The encrypted data and metadata
|
|
191
|
+
* @param {string | Buffer} key - Decryption key or passphrase
|
|
192
|
+
* @param {DecryptionOptions} [options] - Decryption options
|
|
193
|
+
* @returns {Promise<string | Buffer>} Decrypted data
|
|
194
|
+
*/
|
|
195
|
+
async function decrypt(encryptedData, key, options = {}) {
|
|
196
|
+
const algorithm = options.algorithm || encryptedData.algorithm || 'aes-256-gcm';
|
|
197
|
+
const inputEncoding = options.inputEncoding || 'hex';
|
|
198
|
+
const outputEncoding = options.outputEncoding || 'utf8';
|
|
199
|
+
// Derive key using scrypt if key is a string (passphrase)
|
|
200
|
+
const derivedKey = typeof key === 'string' ? await scryptAsync(key, encryptedData.iv.slice(0, 8), 32) : key;
|
|
201
|
+
// Create decipher
|
|
202
|
+
const decipher = (0, crypto_1.createDecipheriv)(algorithm, derivedKey, encryptedData.iv);
|
|
203
|
+
// Set auth tag if using GCM mode
|
|
204
|
+
if (encryptedData.authTag && algorithm.includes('gcm')) {
|
|
205
|
+
decipher.setAuthTag(encryptedData.authTag);
|
|
206
|
+
}
|
|
207
|
+
// Decrypt the data
|
|
208
|
+
let decrypted;
|
|
209
|
+
if (typeof encryptedData.ciphertext === 'string') {
|
|
210
|
+
decrypted = decipher.update(encryptedData.ciphertext, inputEncoding, outputEncoding);
|
|
211
|
+
decrypted += decipher.final(outputEncoding);
|
|
212
|
+
}
|
|
213
|
+
else {
|
|
214
|
+
const result = Buffer.concat([decipher.update(encryptedData.ciphertext), decipher.final()]);
|
|
215
|
+
decrypted = outputEncoding ? result.toString(outputEncoding) : result;
|
|
216
|
+
}
|
|
217
|
+
return decrypted;
|
|
218
|
+
}
|
|
219
|
+
/**
|
|
220
|
+
* Creates a signed token with an expiration time and payload.
|
|
221
|
+
*
|
|
222
|
+
* @param {object} payload - Data to include in the token
|
|
223
|
+
* @param {string} secret - Secret key for signing
|
|
224
|
+
* @param {number} [expiresInSeconds=3600] - Token expiration in seconds
|
|
225
|
+
* @returns {string} Signed token string
|
|
226
|
+
*/
|
|
227
|
+
function createSignedToken(payload, secret, expiresInSeconds = 3600) {
|
|
228
|
+
// Create payload with expiration
|
|
229
|
+
const tokenPayload = Object.assign(Object.assign({}, payload), { exp: Math.floor(Date.now() / 1000) + expiresInSeconds });
|
|
230
|
+
// Convert to string
|
|
231
|
+
const payloadStr = JSON.stringify(tokenPayload);
|
|
232
|
+
// Base64 encode the payload
|
|
233
|
+
const base64Payload = Buffer.from(payloadStr).toString('base64url');
|
|
234
|
+
// Create signature
|
|
235
|
+
const signature = hmac('sha256', base64Payload, secret, 'base64url');
|
|
236
|
+
// Combine payload and signature
|
|
237
|
+
return `${base64Payload}.${signature}`;
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* Verifies and decodes a signed token.
|
|
241
|
+
*
|
|
242
|
+
* @param {string} token - The token to verify
|
|
243
|
+
* @param {string} secret - Secret key for verification
|
|
244
|
+
* @returns {object | null} Decoded payload if valid, null if invalid
|
|
245
|
+
*/
|
|
246
|
+
function verifySignedToken(token, secret) {
|
|
247
|
+
try {
|
|
248
|
+
// Split token into parts
|
|
249
|
+
const [payloadB64, signature] = token.split('.');
|
|
250
|
+
if (!payloadB64 || !signature)
|
|
251
|
+
return null;
|
|
252
|
+
// Verify signature
|
|
253
|
+
const expectedSignature = hmac('sha256', payloadB64, secret, 'base64url');
|
|
254
|
+
if (!safeCompare(signature, expectedSignature))
|
|
255
|
+
return null;
|
|
256
|
+
// Decode payload
|
|
257
|
+
const payloadStr = Buffer.from(payloadB64, 'base64url').toString('utf8');
|
|
258
|
+
const payload = JSON.parse(payloadStr);
|
|
259
|
+
// Check expiration
|
|
260
|
+
if (payload.exp && payload.exp < Math.floor(Date.now() / 1000)) {
|
|
261
|
+
return null;
|
|
262
|
+
}
|
|
263
|
+
return payload;
|
|
264
|
+
}
|
|
265
|
+
catch (_a) {
|
|
266
|
+
return null;
|
|
267
|
+
}
|
|
268
|
+
}
|
|
82
269
|
//# sourceMappingURL=crypto.utils.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"crypto.utils.js","sourceRoot":"","sources":["../../../src/utils/crypto.utils.ts"],"names":[],"mappings":";;;AAAA,mCAKgB;AAEhB;;;;;;;;GAQG;AACI,MAAM,IAAI,G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GAAG,OAEd;AAEF;;;;GAIG;AACI,MAAM,YAAY,GAAG,GAAW,EAAE;IACvC,OAAO,IAAA,cAAM,EAAC,IAAA,mBAAU,GAAE,CAAC,CAAC;AAC9B,CAAC,CAAC;AAFW,QAAA,YAAY,gBAEvB","sourcesContent":["import {\n createHmac,\n createHash,\n BinaryToTextEncoding,\n randomUUID,\n} from \"crypto\";\n\n/**\n * Generates an HMAC digest using the specified algorithm and secret key.\n *\n * @param {string} algorithm - The hashing algorithm (e.g., 'sha256', 'sha1').\n * @param {string} input - The string to hash.\n * @param {string} secret - The secret key for HMAC.\n * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding ('hex', 'base64', etc).\n * @returns {string} HMAC digest as a string.\n */\nexport const hmac = (\n algorithm: string,\n input: string,\n secret: string,\n encoding: BinaryToTextEncoding = \"hex\",\n): string => {\n return createHmac(algorithm, secret).update(input).digest(encoding);\n};\n\n/**\n * Generates a hash digest using the specified algorithm.\n *\n * @param {string} algorithm - The hashing algorithm (e.g., 'sha256', 'md5').\n * @param {string} input - The string to hash.\n * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding ('hex', 'base64', etc).\n * @returns {string} Hash digest as a string.\n */\nexport const hash = (\n algorithm: string,\n input: string,\n encoding: BinaryToTextEncoding = \"hex\",\n): string => {\n return createHash(algorithm).update(input).digest(encoding);\n};\n\n/**\n * Generates an HMAC-SHA256 digest.\n *\n * @param {string} input - The string to hash.\n * @param {string} secret - The secret key.\n * @returns {string} SHA-256 HMAC digest as a string.\n */\nexport const sha256Hmac = (input: string, secret: string): string => {\n return hmac(\"sha256\", input, secret);\n};\n\n/**\n * Generates a SHA1 hash digest.\n *\n * @param {string} input - The string to hash.\n * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.\n * @returns {string} SHA-1 hash as a string.\n */\nexport const sha1 = (\n input: string,\n encoding: BinaryToTextEncoding = \"hex\",\n): string => {\n return hash(\"sha1\", input, encoding);\n};\n\n/**\n * Generates a SHA256 hash digest.\n *\n * @param {string} input - The string to hash.\n * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.\n * @returns {string} SHA-256 hash as a string.\n */\nexport const sha256 = (\n input: string,\n encoding: BinaryToTextEncoding = \"hex\",\n): string => {\n return hash(\"sha256\", input, encoding);\n};\n\n/**\n * Generates an MD5 hash digest.\n *\n * @param {string} input - The string to hash.\n * @returns {string} MD5 hash as a string.\n */\nexport const md5 = (input: string): string => {\n return hash(\"md5\", input);\n};\n\n/**\n * Generates a cryptographically strong random string by hashing a random UUID with SHA-256.\n *\n * @returns {string} Random string hashed with SHA-256 (hex encoding).\n */\nexport const randomString = (): string => {\n return sha256(randomUUID());\n};\n"]}
|
|
1
|
+
{"version":3,"file":"crypto.utils.js","sourceRoot":"","sources":["../../../src/utils/crypto.utils.ts"],"names":[],"mappings":";;AAqCA,oBAEC;AAUD,oBAEC;AASD,gCAEC;AASD,oBAEC;AASD,wBAEC;AAQD,kBAEC;AAOD,oCAEC;AAQD,kDAEC;AASD,kEAEC;AASD,wCAOC;AASD,kCAkBC;AAmDD,0BAsCC;AAUD,0BAgCC;AAUD,8CAsBC;AASD,8CAwBC;AA3WD,mCAWgB;AAChB,+BAAiC;AAgBjC;;;;;;;;GAQG;AACH,SAAgB,IAAI,CAAC,SAAiB,EAAE,KAAa,EAAE,MAAc,EAAE,WAAiC,KAAK;IAC3G,OAAO,IAAA,mBAAU,EAAC,SAAS,EAAE,MAAM,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;AACtE,CAAC;AAED;;;;;;;GAOG;AACH,SAAgB,IAAI,CAAC,SAAiB,EAAE,KAAa,EAAE,WAAiC,KAAK;IAC3F,OAAO,IAAA,mBAAU,EAAC,SAAS,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;AAC9D,CAAC;AAED;;;;;;GAMG;AACH,SAAgB,UAAU,CAAC,KAAa,EAAE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;QAC1E,IAAI,CAAC,WAAW,CAAC,SAAS,EAAE,iBAAiB,CAAC;YAAE,OAAO,IAAI,CAAC;QAE5D,iBAAiB;QACjB,MAAM,UAAU,GAAG,MAAM,CAAC,IAAI,CAAC,UAAU,EAAE,WAAW,CAAC,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;QACzE,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;QAEvC,mBAAmB;QACnB,IAAI,OAAO,CAAC,GAAG,IAAI,OAAO,CAAC,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,EAAE,CAAC;YAC/D,OAAO,IAAI,CAAC;QACd,CAAC;QAED,OAAO,OAAO,CAAC;IACjB,CAAC;IAAC,WAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import {\n createHmac,\n createHash,\n BinaryToTextEncoding,\n randomUUID,\n randomBytes,\n createCipheriv,\n createDecipheriv,\n scrypt,\n timingSafeEqual,\n CipherGCMTypes\n} from 'crypto';\nimport { promisify } from 'util';\n\nexport type BufferEncoding =\n | 'ascii'\n | 'utf8'\n | 'utf-8'\n | 'utf16le'\n | 'utf-16le'\n | 'ucs2'\n | 'ucs-2'\n | 'base64'\n | 'base64url'\n | 'latin1'\n | 'binary'\n | 'hex';\n\n/**\n * Generates an HMAC digest using the specified algorithm and secret key.\n *\n * @param {string} algorithm - The hashing algorithm (e.g., 'sha256', 'sha1').\n * @param {string} input - The string to hash.\n * @param {string} secret - The secret key for HMAC.\n * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding ('hex', 'base64', etc).\n * @returns {string} HMAC digest as a string.\n */\nexport function hmac(algorithm: string, input: string, secret: string, encoding: BinaryToTextEncoding = 'hex'): string {\n return createHmac(algorithm, secret).update(input).digest(encoding);\n}\n\n/**\n * Generates a hash digest using the specified algorithm.\n *\n * @param {string} algorithm - The hashing algorithm (e.g., 'sha256', 'md5').\n * @param {string} input - The string to hash.\n * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding ('hex', 'base64', etc).\n * @returns {string} Hash digest as a string.\n */\nexport function hash(algorithm: string, input: string, encoding: BinaryToTextEncoding = 'hex'): string {\n return createHash(algorithm).update(input).digest(encoding);\n}\n\n/**\n * Generates an HMAC-SHA256 digest.\n *\n * @param {string} input - The string to hash.\n * @param {string} secret - The secret key.\n * @returns {string} SHA-256 HMAC digest as a string.\n */\nexport function sha256Hmac(input: string, secret: string): string {\n return hmac('sha256', input, secret);\n}\n\n/**\n * Generates a SHA1 hash digest.\n *\n * @param {string} input - The string to hash.\n * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.\n * @returns {string} SHA-1 hash as a string.\n */\nexport function sha1(input: string, encoding: BinaryToTextEncoding = 'hex'): string {\n return hash('sha1', input, encoding);\n}\n\n/**\n * Generates a SHA256 hash digest.\n *\n * @param {string} input - The string to hash.\n * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.\n * @returns {string} SHA-256 hash as a string.\n */\nexport function sha256(input: string, encoding: BinaryToTextEncoding = 'hex'): string {\n return hash('sha256', input, encoding);\n}\n\n/**\n * Generates an MD5 hash digest.\n *\n * @param {string} input - The string to hash.\n * @returns {string} MD5 hash as a string.\n */\nexport function md5(input: string): string {\n return hash('md5', input);\n}\n\n/**\n * Generates a cryptographically strong random string by hashing a random UUID with SHA-256.\n *\n * @returns {string} Random string hashed with SHA-256 (hex encoding).\n */\nexport function randomString(): string {\n return sha256(randomUUID());\n}\n\n/**\n * Generates a secure random buffer of specified byte length.\n *\n * @param {number} [byteLength=32] - Number of random bytes to generate.\n * @returns {Buffer} Buffer containing random bytes.\n */\nexport function generateRandomBytes(byteLength: number = 32): Buffer {\n return randomBytes(byteLength);\n}\n\n/**\n * Generates a secure random string of specified byte length with specified encoding.\n *\n * @param {number} [byteLength=32] - Number of random bytes to generate.\n * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.\n * @returns {string} Random string in specified encoding.\n */\nexport function generateRandomBytesAsString(byteLength: number = 32, encoding: BinaryToTextEncoding = 'hex'): string {\n return randomBytes(byteLength).toString(encoding);\n}\n\n/**\n * Generates a secure API key with a specified format.\n *\n * @param {string} [prefix=''] - Optional prefix for the key.\n * @param {number} [byteLength=24] - Number of random bytes to generate.\n * @returns {string} Formatted API key.\n */\nexport function generateApiKey(prefix: string = '', byteLength: number = 24): string {\n const randomString = generateRandomBytesAsString(byteLength, 'base64');\n const key = randomString\n .replace(/[+/=]/g, '') // Remove non-URL-safe characters\n .substring(0, 32); // Limit length\n\n return prefix ? `${prefix}_${key}` : key;\n}\n\n/**\n * Compares two strings, arrays, or buffers in constant time to prevent timing attacks.\n *\n * @param {string | Buffer | Uint8Array} a - First value to compare\n * @param {string | Buffer | Uint8Array} b - Second value to compare\n * @returns {boolean} True if values are equal\n */\nexport function safeCompare(a: string | Buffer | Uint8Array, b: string | Buffer | Uint8Array): boolean {\n if (typeof a === 'string' && typeof b === 'string') {\n // Convert strings to buffers\n const bufA = Buffer.from(a);\n const bufB = Buffer.from(b);\n\n // Compare lengths first (not constant time, but prevents timing attack on contents)\n if (bufA.length !== bufB.length) return false;\n\n return timingSafeEqual(bufA, bufB);\n } else if ((a instanceof Buffer || a instanceof Uint8Array) && (b instanceof Buffer || b instanceof Uint8Array)) {\n // Compare lengths first\n if (a.length !== b.length) return false;\n\n return timingSafeEqual(a instanceof Buffer ? a : Buffer.from(a), b instanceof Buffer ? b : Buffer.from(b));\n }\n\n throw new Error('Cannot compare: inputs must be strings, Buffers, or Uint8Arrays');\n}\n\n/**\n * Interface for encryption options\n */\nexport interface EncryptionOptions {\n /** Algorithm to use (default: aes-256-gcm) */\n algorithm?: CipherGCMTypes;\n /** Input encoding for plaintext if string (default: utf8) */\n inputEncoding?: BufferEncoding;\n /** Output encoding for ciphertext (default: hex) */\n outputEncoding?: BinaryToTextEncoding;\n}\n\n/**\n * Interface for decryption options\n */\nexport interface DecryptionOptions {\n /** Algorithm to use (default: aes-256-gcm) */\n algorithm?: CipherGCMTypes;\n /** Input encoding for ciphertext if string (default: hex) */\n inputEncoding?: BinaryToTextEncoding;\n /** Output encoding for plaintext (default: utf8) */\n outputEncoding?: BufferEncoding;\n}\n\n/**\n * Result of encryption operation including all data needed for decryption\n */\nexport interface EncryptionResult {\n /** Encrypted data (string or Buffer based on options) */\n ciphertext: string | Buffer;\n /** Initialization vector */\n iv: Buffer;\n /** Authentication tag (for GCM mode) */\n authTag?: Buffer;\n /** Algorithm used */\n algorithm: string;\n}\n\n// Promisified version of scrypt for key derivation\nconst scryptAsync = promisify<string | Buffer, string | Buffer, number, Buffer>(scrypt);\n\n/**\n * Encrypts data using a symmetric key with secure defaults (AES-256-GCM).\n *\n * @param {string | Buffer} data - Data to encrypt\n * @param {string | Buffer} key - Encryption key or passphrase\n * @param {EncryptionOptions} [options] - Encryption options\n * @returns {Promise<EncryptionResult>} Encrypted data with metadata\n */\nexport async function encrypt(\n data: string | Buffer,\n key: string | Buffer,\n options: EncryptionOptions = {}\n): Promise<EncryptionResult> {\n const algorithm = options.algorithm || 'aes-256-gcm';\n const inputEncoding = options.inputEncoding || 'utf8';\n const outputEncoding = options.outputEncoding || 'hex';\n\n // Generate a random IV\n const iv = randomBytes(16);\n\n // Derive key using scrypt if key is a string (passphrase)\n const derivedKey = typeof key === 'string' ? await scryptAsync(key, iv.slice(0, 8), 32) : key;\n\n // Create cipher\n const cipher = createCipheriv(algorithm, derivedKey, iv);\n\n // Encrypt the data\n let ciphertext: string | Buffer;\n\n if (typeof data === 'string') {\n ciphertext = cipher.update(data, inputEncoding, outputEncoding as BufferEncoding);\n ciphertext += cipher.final(outputEncoding as BufferEncoding);\n } else {\n const encrypted = Buffer.concat([cipher.update(data), cipher.final()]);\n ciphertext = outputEncoding ? encrypted.toString(outputEncoding) : encrypted;\n }\n\n // Get authentication tag if using GCM mode\n const authTag = algorithm.includes('gcm') ? (cipher as any).getAuthTag() : undefined;\n\n return {\n ciphertext,\n iv,\n authTag,\n algorithm\n };\n}\n\n/**\n * Decrypts data that was encrypted with the encrypt function.\n *\n * @param {EncryptionResult} encryptedData - The encrypted data and metadata\n * @param {string | Buffer} key - Decryption key or passphrase\n * @param {DecryptionOptions} [options] - Decryption options\n * @returns {Promise<string | Buffer>} Decrypted data\n */\nexport async function decrypt(\n encryptedData: EncryptionResult,\n key: string | Buffer,\n options: DecryptionOptions = {}\n): Promise<string | Buffer> {\n const algorithm = options.algorithm || encryptedData.algorithm || 'aes-256-gcm';\n const inputEncoding = options.inputEncoding || 'hex';\n const outputEncoding = options.outputEncoding || 'utf8';\n\n // Derive key using scrypt if key is a string (passphrase)\n const derivedKey = typeof key === 'string' ? await scryptAsync(key, encryptedData.iv.slice(0, 8), 32) : key;\n\n // Create decipher\n const decipher = createDecipheriv(algorithm, derivedKey, encryptedData.iv);\n\n // Set auth tag if using GCM mode\n if (encryptedData.authTag && algorithm.includes('gcm')) {\n (decipher as any).setAuthTag(encryptedData.authTag);\n }\n\n // Decrypt the data\n let decrypted: string | Buffer;\n\n if (typeof encryptedData.ciphertext === 'string') {\n decrypted = decipher.update(encryptedData.ciphertext, inputEncoding as BufferEncoding, outputEncoding);\n decrypted += decipher.final(outputEncoding);\n } else {\n const result = Buffer.concat([decipher.update(encryptedData.ciphertext), decipher.final()]);\n decrypted = outputEncoding ? result.toString(outputEncoding) : result;\n }\n\n return decrypted;\n}\n\n/**\n * Creates a signed token with an expiration time and payload.\n *\n * @param {object} payload - Data to include in the token\n * @param {string} secret - Secret key for signing\n * @param {number} [expiresInSeconds=3600] - Token expiration in seconds\n * @returns {string} Signed token string\n */\nexport function createSignedToken(\n payload: Record<string, any>,\n secret: string,\n expiresInSeconds: number = 3600\n): string {\n // Create payload with expiration\n const tokenPayload = {\n ...payload,\n exp: Math.floor(Date.now() / 1000) + expiresInSeconds\n };\n\n // Convert to string\n const payloadStr = JSON.stringify(tokenPayload);\n\n // Base64 encode the payload\n const base64Payload = Buffer.from(payloadStr).toString('base64url');\n\n // Create signature\n const signature = hmac('sha256', base64Payload, secret, 'base64url');\n\n // Combine payload and signature\n return `${base64Payload}.${signature}`;\n}\n\n/**\n * Verifies and decodes a signed token.\n *\n * @param {string} token - The token to verify\n * @param {string} secret - Secret key for verification\n * @returns {object | null} Decoded payload if valid, null if invalid\n */\nexport function verifySignedToken(token: string, secret: string): Record<string, any> | null {\n try {\n // Split token into parts\n const [payloadB64, signature] = token.split('.');\n\n if (!payloadB64 || !signature) return null;\n\n // Verify signature\n const expectedSignature = hmac('sha256', payloadB64, secret, 'base64url');\n if (!safeCompare(signature, expectedSignature)) return null;\n\n // Decode payload\n const payloadStr = Buffer.from(payloadB64, 'base64url').toString('utf8');\n const payload = JSON.parse(payloadStr);\n\n // Check expiration\n if (payload.exp && payload.exp < Math.floor(Date.now() / 1000)) {\n return null;\n }\n\n return payload;\n } catch {\n return null;\n }\n}\n"]}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import 'reflect-metadata';
|
|
2
|
+
interface Request {
|
|
3
|
+
query: any;
|
|
4
|
+
params: any;
|
|
5
|
+
body?: any;
|
|
6
|
+
[key: string]: any;
|
|
7
|
+
}
|
|
8
|
+
interface Response {
|
|
9
|
+
json: (body: any) => void;
|
|
10
|
+
headersSent: boolean;
|
|
11
|
+
[key: string]: any;
|
|
12
|
+
}
|
|
13
|
+
type NextFunction = (err?: any) => void;
|
|
14
|
+
type RequestHandler = (req: Request, res: Response, next: NextFunction) => any;
|
|
15
|
+
interface Router {
|
|
16
|
+
[method: string]: (path: string, ...handlers: RequestHandler[]) => void;
|
|
17
|
+
}
|
|
18
|
+
export declare const Get: (path: string) => MethodDecorator;
|
|
19
|
+
export declare const Post: (path: string) => MethodDecorator;
|
|
20
|
+
export declare const Put: (path: string) => MethodDecorator;
|
|
21
|
+
export declare const Patch: (path: string) => MethodDecorator;
|
|
22
|
+
export declare const Delete: (path: string) => MethodDecorator;
|
|
23
|
+
export declare const Options: (path: string) => MethodDecorator;
|
|
24
|
+
export declare const Head: (path: string) => MethodDecorator;
|
|
25
|
+
export declare const Trace: (path: string) => MethodDecorator;
|
|
26
|
+
export declare const Connect: (path: string) => MethodDecorator;
|
|
27
|
+
export declare function Controller(basePath: string): ClassDecorator;
|
|
28
|
+
export declare function Use(...middlewares: RequestHandler[]): MethodDecorator;
|
|
29
|
+
export declare const Query: (paramKey?: string) => ParameterDecorator;
|
|
30
|
+
export declare const Param: (paramKey?: string) => ParameterDecorator;
|
|
31
|
+
export declare const Body: (paramKey?: string) => ParameterDecorator;
|
|
32
|
+
export declare const Req: (paramKey?: string) => ParameterDecorator;
|
|
33
|
+
export declare const Res: (paramKey?: string) => ParameterDecorator;
|
|
34
|
+
export declare function HttpCode(status: number): MethodDecorator;
|
|
35
|
+
export declare function Header(name: string, value: string): MethodDecorator;
|
|
36
|
+
export declare function Before(fn: Function): MethodDecorator;
|
|
37
|
+
export declare function After(fn: Function): MethodDecorator;
|
|
38
|
+
export declare function registerControllers(router: Router, controllers: any[]): void;
|
|
39
|
+
export {};
|
|
40
|
+
//# sourceMappingURL=decorators.utils.d.ts.map
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/* eslint-disable @typescript-eslint/no-unused-vars */
|
|
3
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4
|
+
exports.Res = exports.Req = exports.Body = exports.Param = exports.Query = exports.Connect = exports.Trace = exports.Head = exports.Options = exports.Delete = exports.Patch = exports.Put = exports.Post = exports.Get = void 0;
|
|
5
|
+
exports.Controller = Controller;
|
|
6
|
+
exports.Use = Use;
|
|
7
|
+
exports.HttpCode = HttpCode;
|
|
8
|
+
exports.Header = Header;
|
|
9
|
+
exports.Before = Before;
|
|
10
|
+
exports.After = After;
|
|
11
|
+
exports.registerControllers = registerControllers;
|
|
12
|
+
require("reflect-metadata");
|
|
13
|
+
// --- End sample Express interfaces ---
|
|
14
|
+
const ROUTES_KEY = Symbol('routes');
|
|
15
|
+
const MIDDLEWARE_KEY = Symbol('middlewares');
|
|
16
|
+
const PARAMS_KEY = Symbol('params');
|
|
17
|
+
// ---- Route Decorators ----
|
|
18
|
+
function createRouteDecorator(method) {
|
|
19
|
+
return (path) => {
|
|
20
|
+
return (target, propertyKey, descriptor) => {
|
|
21
|
+
const routes = Reflect.getMetadata(ROUTES_KEY, target.constructor) || [];
|
|
22
|
+
routes.push({
|
|
23
|
+
path,
|
|
24
|
+
method,
|
|
25
|
+
handlerName: propertyKey
|
|
26
|
+
});
|
|
27
|
+
Reflect.defineMetadata(ROUTES_KEY, routes, target.constructor);
|
|
28
|
+
};
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
exports.Get = createRouteDecorator('get');
|
|
32
|
+
exports.Post = createRouteDecorator('post');
|
|
33
|
+
exports.Put = createRouteDecorator('put');
|
|
34
|
+
exports.Patch = createRouteDecorator('patch');
|
|
35
|
+
exports.Delete = createRouteDecorator('delete');
|
|
36
|
+
exports.Options = createRouteDecorator('options');
|
|
37
|
+
exports.Head = createRouteDecorator('head');
|
|
38
|
+
exports.Trace = createRouteDecorator('trace');
|
|
39
|
+
exports.Connect = createRouteDecorator('connect');
|
|
40
|
+
// ---- Controller Decorator ----
|
|
41
|
+
function Controller(basePath) {
|
|
42
|
+
return target => {
|
|
43
|
+
Reflect.defineMetadata('basePath', basePath, target);
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
// ---- Middleware Decorator ----
|
|
47
|
+
function Use(...middlewares) {
|
|
48
|
+
return (target, propertyKey, descriptor) => {
|
|
49
|
+
const existing = Reflect.getMetadata(MIDDLEWARE_KEY, target, propertyKey) || [];
|
|
50
|
+
Reflect.defineMetadata(MIDDLEWARE_KEY, [...existing, ...middlewares], target, propertyKey);
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
// ---- Parameter Decorators ----
|
|
54
|
+
function createParamDecorator(type, key) {
|
|
55
|
+
return (paramKey) => {
|
|
56
|
+
return (target, propertyKey, parameterIndex) => {
|
|
57
|
+
const params = Reflect.getMetadata(PARAMS_KEY, target, propertyKey) || [];
|
|
58
|
+
// Ensure parameters are ordered by index
|
|
59
|
+
params.push({ index: parameterIndex, type, key: paramKey || key });
|
|
60
|
+
params.sort((a, b) => a.index - b.index);
|
|
61
|
+
Reflect.defineMetadata(PARAMS_KEY, params, target, propertyKey);
|
|
62
|
+
};
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
exports.Query = createParamDecorator('query');
|
|
66
|
+
exports.Param = createParamDecorator('param');
|
|
67
|
+
exports.Body = createParamDecorator('body');
|
|
68
|
+
exports.Req = createParamDecorator('req');
|
|
69
|
+
exports.Res = createParamDecorator('res');
|
|
70
|
+
// Custom HTTP status code decorator
|
|
71
|
+
const HTTP_CODE_KEY = Symbol('httpCode');
|
|
72
|
+
function HttpCode(status) {
|
|
73
|
+
return (target, propertyKey, descriptor) => {
|
|
74
|
+
Reflect.defineMetadata(HTTP_CODE_KEY, status, target, propertyKey);
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
// Custom header decorator
|
|
78
|
+
const HEADER_KEY = Symbol('headers');
|
|
79
|
+
function Header(name, value) {
|
|
80
|
+
return (target, propertyKey, descriptor) => {
|
|
81
|
+
const headers = Reflect.getMetadata(HEADER_KEY, target, propertyKey) || {};
|
|
82
|
+
headers[name] = value;
|
|
83
|
+
Reflect.defineMetadata(HEADER_KEY, headers, target, propertyKey);
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
// Before/After hooks (not Express middleware, but can be used for logging, etc.)
|
|
87
|
+
const BEFORE_KEY = Symbol('before');
|
|
88
|
+
const AFTER_KEY = Symbol('after');
|
|
89
|
+
function Before(fn) {
|
|
90
|
+
return (target, propertyKey, descriptor) => {
|
|
91
|
+
const hooks = Reflect.getMetadata(BEFORE_KEY, target, propertyKey) || [];
|
|
92
|
+
hooks.push(fn);
|
|
93
|
+
Reflect.defineMetadata(BEFORE_KEY, hooks, target, propertyKey);
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
function After(fn) {
|
|
97
|
+
return (target, propertyKey, descriptor) => {
|
|
98
|
+
const hooks = Reflect.getMetadata(AFTER_KEY, target, propertyKey) || [];
|
|
99
|
+
hooks.push(fn);
|
|
100
|
+
Reflect.defineMetadata(AFTER_KEY, hooks, target, propertyKey);
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
// ---- Register Controllers ----
|
|
104
|
+
function registerControllers(router, controllers) {
|
|
105
|
+
controllers.forEach(ControllerClass => {
|
|
106
|
+
const instance = new ControllerClass();
|
|
107
|
+
const basePath = Reflect.getMetadata('basePath', ControllerClass) || '';
|
|
108
|
+
const routes = Reflect.getMetadata(ROUTES_KEY, ControllerClass) || [];
|
|
109
|
+
routes.forEach(({ path, method, handlerName }) => {
|
|
110
|
+
const middlewares = Reflect.getMetadata(MIDDLEWARE_KEY, instance, handlerName) || [];
|
|
111
|
+
const params = Reflect.getMetadata(PARAMS_KEY, instance, handlerName) || [];
|
|
112
|
+
const httpCode = Reflect.getMetadata(HTTP_CODE_KEY, instance, handlerName);
|
|
113
|
+
const headers = Reflect.getMetadata(HEADER_KEY, instance, handlerName) || {};
|
|
114
|
+
const beforeHooks = Reflect.getMetadata(BEFORE_KEY, instance, handlerName) || [];
|
|
115
|
+
const afterHooks = Reflect.getMetadata(AFTER_KEY, instance, handlerName) || [];
|
|
116
|
+
const handler = async (req, res, next) => {
|
|
117
|
+
var _a, _b;
|
|
118
|
+
try {
|
|
119
|
+
for (const fn of beforeHooks)
|
|
120
|
+
await fn(req, res);
|
|
121
|
+
const args = [];
|
|
122
|
+
if (params.length) {
|
|
123
|
+
params.forEach(({ index, type, key }) => {
|
|
124
|
+
var _a;
|
|
125
|
+
switch (type) {
|
|
126
|
+
case 'query':
|
|
127
|
+
args[index] = key ? req.query[key] : req.query;
|
|
128
|
+
break;
|
|
129
|
+
case 'param':
|
|
130
|
+
args[index] = key ? req.params[key] : req.params;
|
|
131
|
+
break;
|
|
132
|
+
case 'body':
|
|
133
|
+
args[index] = key ? (_a = req.body) === null || _a === void 0 ? void 0 : _a[key] : req.body;
|
|
134
|
+
break;
|
|
135
|
+
case 'req':
|
|
136
|
+
args[index] = req;
|
|
137
|
+
break;
|
|
138
|
+
case 'res':
|
|
139
|
+
args[index] = res;
|
|
140
|
+
break;
|
|
141
|
+
}
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
const result = instance[handlerName](...args);
|
|
145
|
+
// Support both sync and async handlers
|
|
146
|
+
const awaited = result instanceof Promise ? await result : result;
|
|
147
|
+
if (!res.headersSent && typeof awaited !== 'undefined') {
|
|
148
|
+
if (httpCode)
|
|
149
|
+
(_a = res.status) === null || _a === void 0 ? void 0 : _a.call(res, httpCode);
|
|
150
|
+
for (const [k, v] of Object.entries(headers))
|
|
151
|
+
(_b = res.set) === null || _b === void 0 ? void 0 : _b.call(res, k, v);
|
|
152
|
+
res.json(awaited);
|
|
153
|
+
}
|
|
154
|
+
for (const fn of afterHooks)
|
|
155
|
+
await fn(req, res, awaited);
|
|
156
|
+
}
|
|
157
|
+
catch (err) {
|
|
158
|
+
next(err);
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
router[method](basePath + path, ...middlewares, handler);
|
|
162
|
+
});
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
//# sourceMappingURL=decorators.utils.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"decorators.utils.js","sourceRoot":"","sources":["../../../src/utils/decorators.utils.ts"],"names":[],"mappings":";AAAA,sDAAsD;;;AAmEtD,gCAIC;AAGD,kBAKC;AAuBD,4BAIC;AAID,wBAMC;AAKD,wBAMC;AACD,sBAMC;AAGD,kDAyDC;AAhMD,4BAA0B;AAmB1B,wCAAwC;AAExC,MAAM,UAAU,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC;AACpC,MAAM,cAAc,GAAG,MAAM,CAAC,aAAa,CAAC,CAAC;AAC7C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KAAK,KAAK;oCACR,IAAI,CAAC,KAAK,CAAC,GAAG,GAAG,CAAC;oCAClB,MAAM;4BACV,CAAC;wBACH,CAAC,CAAC,CAAC;oBACL,CAAC;oBACD,MAAM,MAAM,GAAI,QAAgB,CAAC,WAAW,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC;oBACvD,uCAAuC;oBACvC,MAAM,OAAO,GAAG,MAAM,YAAY,OAAO,CAAC,CAAC,CAAC,MAAM,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC;oBAClE,IAAI,CAAC,GAAG,CAAC,WAAW,IAAI,OAAO,OAAO,KAAK,WAAW,EAAE,CAAC;wBACvD,IAAI,QAAQ;4BAAE,MAAA,GAAG,CAAC,MAAM,oDAAG,QAAQ,CAAC,CAAC;wBACrC,KAAK,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC;4BAAE,MAAA,GAAG,CAAC,GAAG,oDAAG,CAAC,EAAE,CAAC,CAAC,CAAC;wBAC9D,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;oBACpB,CAAC;oBACD,KAAK,MAAM,EAAE,IAAI,UAAU;wBAAE,MAAM,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC;gBAC3D,CAAC;gBAAC,OAAO,GAAG,EAAE,CAAC;oBACb,IAAI,CAAC,GAAG,CAAC,CAAC;gBACZ,CAAC;YACH,CAAC,CAAC;YAED,MAAc,CAAC,MAAM,CAAC,CAAC,QAAQ,GAAG,IAAI,EAAE,GAAG,WAAW,EAAE,OAAO,CAAC,CAAC;QACpE,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["/* eslint-disable @typescript-eslint/no-unused-vars */\n\nimport 'reflect-metadata';\n\n// --- Sample Express interfaces for type safety ---\ninterface Request {\n query: any;\n params: any;\n body?: any;\n [key: string]: any;\n}\ninterface Response {\n json: (body: any) => void;\n headersSent: boolean;\n [key: string]: any;\n}\ntype NextFunction = (err?: any) => void;\ntype RequestHandler = (req: Request, res: Response, next: NextFunction) => any;\ninterface Router {\n [method: string]: (path: string, ...handlers: RequestHandler[]) => void;\n}\n// --- End sample Express interfaces ---\n\nconst ROUTES_KEY = Symbol('routes');\nconst MIDDLEWARE_KEY = Symbol('middlewares');\nconst PARAMS_KEY = Symbol('params');\n\ntype HttpMethod = 'get' | 'post' | 'put' | 'patch' | 'delete' | 'options' | 'head' | 'trace' | 'connect';\n\ninterface RouteDefinition {\n path: string;\n method: HttpMethod;\n handlerName: string;\n}\n\ninterface ParamDefinition {\n index: number;\n type: 'query' | 'param' | 'body' | 'req' | 'res';\n key?: string;\n}\n\n// ---- Route Decorators ----\nfunction createRouteDecorator(method: HttpMethod) {\n return (path: string): MethodDecorator => {\n return (target, propertyKey, descriptor) => {\n const routes: RouteDefinition[] = Reflect.getMetadata(ROUTES_KEY, target.constructor) || [];\n routes.push({\n path,\n method,\n handlerName: propertyKey as string\n });\n Reflect.defineMetadata(ROUTES_KEY, routes, target.constructor);\n };\n };\n}\n\nexport const Get = createRouteDecorator('get');\nexport const Post = createRouteDecorator('post');\nexport const Put = createRouteDecorator('put');\nexport const Patch = createRouteDecorator('patch');\nexport const Delete = createRouteDecorator('delete');\nexport const Options = createRouteDecorator('options');\nexport const Head = createRouteDecorator('head');\nexport const Trace = createRouteDecorator('trace');\nexport const Connect = createRouteDecorator('connect');\n\n// ---- Controller Decorator ----\nexport function Controller(basePath: string): ClassDecorator {\n return target => {\n Reflect.defineMetadata('basePath', basePath, target);\n };\n}\n\n// ---- Middleware Decorator ----\nexport function Use(...middlewares: RequestHandler[]): MethodDecorator {\n return (target, propertyKey, descriptor) => {\n const existing: RequestHandler[] = Reflect.getMetadata(MIDDLEWARE_KEY, target, propertyKey as string) || [];\n Reflect.defineMetadata(MIDDLEWARE_KEY, [...existing, ...middlewares], target, propertyKey as string);\n };\n}\n\n// ---- Parameter Decorators ----\nfunction createParamDecorator(type: ParamDefinition['type'], key?: string) {\n return (paramKey?: string): ParameterDecorator => {\n return (target, propertyKey, parameterIndex) => {\n const params: ParamDefinition[] = Reflect.getMetadata(PARAMS_KEY, target, propertyKey as string) || [];\n // Ensure parameters are ordered by index\n params.push({ index: parameterIndex, type, key: paramKey || key });\n params.sort((a, b) => a.index - b.index);\n Reflect.defineMetadata(PARAMS_KEY, params, target, propertyKey as string);\n };\n };\n}\n\nexport const Query = createParamDecorator('query');\nexport const Param = createParamDecorator('param');\nexport const Body = createParamDecorator('body');\nexport const Req = createParamDecorator('req');\nexport const Res = createParamDecorator('res');\n\n// Custom HTTP status code decorator\nconst HTTP_CODE_KEY = Symbol('httpCode');\nexport function HttpCode(status: number): MethodDecorator {\n return (target, propertyKey, descriptor) => {\n Reflect.defineMetadata(HTTP_CODE_KEY, status, target, propertyKey as string);\n };\n}\n\n// Custom header decorator\nconst HEADER_KEY = Symbol('headers');\nexport function Header(name: string, value: string): MethodDecorator {\n return (target, propertyKey, descriptor) => {\n const headers: Record<string, string> = Reflect.getMetadata(HEADER_KEY, target, propertyKey as string) || {};\n headers[name] = value;\n Reflect.defineMetadata(HEADER_KEY, headers, target, propertyKey as string);\n };\n}\n\n// Before/After hooks (not Express middleware, but can be used for logging, etc.)\nconst BEFORE_KEY = Symbol('before');\nconst AFTER_KEY = Symbol('after');\nexport function Before(fn: Function): MethodDecorator {\n return (target, propertyKey, descriptor) => {\n const hooks: Function[] = Reflect.getMetadata(BEFORE_KEY, target, propertyKey as string) || [];\n hooks.push(fn);\n Reflect.defineMetadata(BEFORE_KEY, hooks, target, propertyKey as string);\n };\n}\nexport function After(fn: Function): MethodDecorator {\n return (target, propertyKey, descriptor) => {\n const hooks: Function[] = Reflect.getMetadata(AFTER_KEY, target, propertyKey as string) || [];\n hooks.push(fn);\n Reflect.defineMetadata(AFTER_KEY, hooks, target, propertyKey as string);\n };\n}\n\n// ---- Register Controllers ----\nexport function registerControllers(router: Router, controllers: any[]) {\n controllers.forEach(ControllerClass => {\n const instance = new ControllerClass();\n const basePath: string = Reflect.getMetadata('basePath', ControllerClass) || '';\n const routes: RouteDefinition[] = Reflect.getMetadata(ROUTES_KEY, ControllerClass) || [];\n\n routes.forEach(({ path, method, handlerName }) => {\n const middlewares: RequestHandler[] = Reflect.getMetadata(MIDDLEWARE_KEY, instance, handlerName) || [];\n const params: ParamDefinition[] = Reflect.getMetadata(PARAMS_KEY, instance, handlerName) || [];\n\n const httpCode: number | undefined = Reflect.getMetadata(HTTP_CODE_KEY, instance, handlerName);\n const headers: Record<string, string> = Reflect.getMetadata(HEADER_KEY, instance, handlerName) || {};\n const beforeHooks: Function[] = Reflect.getMetadata(BEFORE_KEY, instance, handlerName) || [];\n const afterHooks: Function[] = Reflect.getMetadata(AFTER_KEY, instance, handlerName) || [];\n\n const handler: RequestHandler = async (req, res, next) => {\n try {\n for (const fn of beforeHooks) await fn(req, res);\n const args: any[] = [];\n if (params.length) {\n params.forEach(({ index, type, key }) => {\n switch (type) {\n case 'query':\n args[index] = key ? req.query[key] : req.query;\n break;\n case 'param':\n args[index] = key ? req.params[key] : req.params;\n break;\n case 'body':\n args[index] = key ? req.body?.[key] : req.body;\n break;\n case 'req':\n args[index] = req;\n break;\n case 'res':\n args[index] = res;\n break;\n }\n });\n }\n const result = (instance as any)[handlerName](...args);\n // Support both sync and async handlers\n const awaited = result instanceof Promise ? await result : result;\n if (!res.headersSent && typeof awaited !== 'undefined') {\n if (httpCode) res.status?.(httpCode);\n for (const [k, v] of Object.entries(headers)) res.set?.(k, v);\n res.json(awaited);\n }\n for (const fn of afterHooks) await fn(req, res, awaited);\n } catch (err) {\n next(err);\n }\n };\n\n (router as any)[method](basePath + path, ...middlewares, handler);\n });\n });\n}\n"]}
|