@catbee/utils 1.1.0 → 2.0.0-next.1

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 (90) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +79 -43
  3. package/array/index.cjs +355 -0
  4. package/array/index.d.ts +317 -0
  5. package/array/index.mjs +327 -0
  6. package/async/index.cjs +484 -0
  7. package/async/index.d.ts +299 -0
  8. package/async/index.mjs +463 -0
  9. package/cache/index.cjs +292 -0
  10. package/cache/index.d.ts +179 -0
  11. package/cache/index.mjs +290 -0
  12. package/config/index.cjs +150 -0
  13. package/config/index.d.ts +88 -0
  14. package/config/index.mjs +143 -0
  15. package/context-store/index.cjs +267 -0
  16. package/context-store/index.d.ts +216 -0
  17. package/context-store/index.mjs +261 -0
  18. package/crypto/index.cjs +182 -0
  19. package/crypto/index.d.ts +187 -0
  20. package/crypto/index.mjs +166 -0
  21. package/date/index.cjs +340 -0
  22. package/date/index.d.ts +214 -0
  23. package/date/index.mjs +326 -0
  24. package/decorators/index.cjs +2051 -0
  25. package/decorators/index.d.ts +708 -0
  26. package/decorators/index.mjs +2010 -0
  27. package/dir/index.cjs +417 -0
  28. package/dir/index.d.ts +219 -0
  29. package/dir/index.mjs +390 -0
  30. package/env/index.cjs +745 -0
  31. package/env/index.d.ts +403 -0
  32. package/env/index.mjs +742 -0
  33. package/exception/index.cjs +362 -0
  34. package/exception/index.d.ts +256 -0
  35. package/exception/index.mjs +338 -0
  36. package/fs/index.cjs +287 -0
  37. package/fs/index.d.ts +229 -0
  38. package/fs/index.mjs +258 -0
  39. package/http-status-codes/index.cjs +96 -0
  40. package/http-status-codes/index.d.ts +291 -0
  41. package/http-status-codes/index.mjs +94 -0
  42. package/id/index.cjs +62 -0
  43. package/id/index.d.ts +61 -0
  44. package/id/index.mjs +56 -0
  45. package/index.cjs +218 -0
  46. package/index.d.ts +51 -0
  47. package/index.mjs +51 -0
  48. package/logger/index.cjs +334 -0
  49. package/logger/index.d.ts +213 -0
  50. package/logger/index.mjs +313 -0
  51. package/middleware/index.cjs +177 -0
  52. package/middleware/index.d.ts +127 -0
  53. package/middleware/index.mjs +170 -0
  54. package/obj/index.cjs +305 -0
  55. package/obj/index.d.ts +160 -0
  56. package/obj/index.mjs +289 -0
  57. package/package.json +172 -20
  58. package/performance/index.cjs +231 -0
  59. package/performance/index.d.ts +162 -0
  60. package/performance/index.mjs +225 -0
  61. package/request/index.cjs +202 -0
  62. package/request/index.d.ts +265 -0
  63. package/request/index.mjs +194 -0
  64. package/response/index.cjs +234 -0
  65. package/response/index.d.ts +342 -0
  66. package/response/index.mjs +222 -0
  67. package/server/index.cjs +1631 -0
  68. package/server/index.d.ts +809 -0
  69. package/server/index.mjs +1622 -0
  70. package/stream/index.cjs +151 -0
  71. package/stream/index.d.ts +114 -0
  72. package/stream/index.mjs +144 -0
  73. package/string/index.cjs +109 -0
  74. package/string/index.d.ts +126 -0
  75. package/string/index.mjs +95 -0
  76. package/type/index.cjs +129 -0
  77. package/type/index.d.ts +131 -0
  78. package/type/index.mjs +119 -0
  79. package/types/index.cjs +34 -0
  80. package/types/index.d.ts +798 -0
  81. package/types/index.mjs +32 -0
  82. package/url/index.cjs +199 -0
  83. package/url/index.d.ts +166 -0
  84. package/url/index.mjs +187 -0
  85. package/validation/index.cjs +259 -0
  86. package/validation/index.d.ts +209 -0
  87. package/validation/index.mjs +231 -0
  88. package/build/index.cjs +0 -7694
  89. package/build/index.d.ts +0 -5792
  90. package/build/index.mjs +0 -7386
@@ -0,0 +1,261 @@
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 { AsyncLocalStorage } from 'async_hooks';
26
+
27
+ var __defProp = Object.defineProperty;
28
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
29
+ var StoreKeys = {
30
+ LOGGER: Symbol("LOGGER"),
31
+ REQUEST_ID: Symbol("REQUEST_ID"),
32
+ USER: Symbol("USER"),
33
+ SESSION: Symbol("SESSION"),
34
+ TRANSACTION_ID: Symbol("TRANSACTION_ID"),
35
+ USER_ID: Symbol("USER_ID"),
36
+ TENANT_ID: Symbol("TENANT_ID"),
37
+ TRACE_ID: Symbol("TRACE_ID"),
38
+ CORRELATION_ID: Symbol("CORRELATION_ID")
39
+ };
40
+ function getRequestId() {
41
+ return ContextStore.get(StoreKeys.REQUEST_ID);
42
+ }
43
+ __name(getRequestId, "getRequestId");
44
+ function getFromContext(key) {
45
+ return ContextStore.get(key);
46
+ }
47
+ __name(getFromContext, "getFromContext");
48
+ var ContextStore = class _ContextStore {
49
+ static {
50
+ __name(this, "ContextStore");
51
+ }
52
+ /**
53
+ * The underlying AsyncLocalStorage instance for context.
54
+ * @private
55
+ */
56
+ static storage = new AsyncLocalStorage();
57
+ /**
58
+ * Returns the raw AsyncLocalStorage instance for advanced access.
59
+ *
60
+ * @returns {AsyncLocalStorage<Store>} The AsyncLocalStorage instance.
61
+ */
62
+ static getInstance() {
63
+ return this.storage;
64
+ }
65
+ /**
66
+ * Retrieves a value from the async context store by symbol key.
67
+ *
68
+ * @typeParam T - The expected return type of the value.
69
+ * @param {symbol} key - Unique symbol used as the store key.
70
+ * @returns {T | undefined} The value found (typed) or undefined if not present.
71
+ */
72
+ static get(key) {
73
+ const store = this.storage.getStore();
74
+ return store?.[key];
75
+ }
76
+ /**
77
+ * Sets a value in the current context store by symbol key.
78
+ *
79
+ * @typeParam T - The value type to set.
80
+ * @param {symbol} key - Unique symbol key.
81
+ * @param {T} value - Value to set in context.
82
+ * @throws {Error} If called outside an active context (not within a .run call or in the wrong async boundaries).
83
+ */
84
+ static set(key, value) {
85
+ const store = this.storage.getStore();
86
+ if (!store) {
87
+ throw new Error(`Failed to set ${String(key)}: AsyncLocalStorage store is not initialized.`);
88
+ }
89
+ store[key] = value;
90
+ }
91
+ /**
92
+ * Retrieves the entire context store object for the current async context.
93
+ *
94
+ * @returns {Store | undefined} The current store object or undefined if called outside a context.
95
+ */
96
+ static getAll() {
97
+ return this.storage.getStore();
98
+ }
99
+ /**
100
+ * Initializes a new async context and executes a callback within it.
101
+ * This must be called at the beginning of a request or logical async flow.
102
+ *
103
+ * @typeParam T - The callback's return type.
104
+ * @param {Store} store - The initial key-value store object.
105
+ * @param {() => T} callback - The function to run within the new context.
106
+ * @returns {T} The result of the callback function.
107
+ */
108
+ static run(store, callback) {
109
+ return this.storage.run(store, callback);
110
+ }
111
+ /**
112
+ * Checks if a key exists in the current context store.
113
+ *
114
+ * @param {symbol} key - The symbol key to check.
115
+ * @returns {boolean} True if the key exists, false otherwise.
116
+ */
117
+ static has(key) {
118
+ const store = this.storage.getStore();
119
+ return store !== void 0 && key in store;
120
+ }
121
+ /**
122
+ * Removes a value from the current context store by symbol key.
123
+ *
124
+ * @param {symbol} key - The symbol key to delete.
125
+ * @returns {boolean} True if the key was deleted, false if the key wasn't found or no active context.
126
+ * @throws {Error} If called outside an active context.
127
+ */
128
+ static delete(key) {
129
+ const store = this.storage.getStore();
130
+ if (!store) {
131
+ throw new Error(`Failed to delete ${String(key)}: AsyncLocalStorage store is not initialized.`);
132
+ }
133
+ return delete store[key];
134
+ }
135
+ /**
136
+ * Updates multiple values in the current context store at once.
137
+ *
138
+ * @param {Partial<Record<symbol, unknown>>} values - Object containing symbol keys and values to update.
139
+ * @throws {Error} If called outside an active context.
140
+ */
141
+ static patch(values) {
142
+ const store = this.storage.getStore();
143
+ if (!store) {
144
+ throw new Error("Failed to patch: AsyncLocalStorage store is not initialized.");
145
+ }
146
+ Object.getOwnPropertySymbols(values).forEach((key) => {
147
+ store[key] = values[key];
148
+ });
149
+ }
150
+ /**
151
+ * Executes a callback with a temporary store value that only exists during execution.
152
+ * Original store is restored after callback completes.
153
+ *
154
+ * @typeParam T - The callback's return type.
155
+ * @param {symbol} key - The symbol key to temporarily set.
156
+ * @param {unknown} value - The temporary value.
157
+ * @param {() => T} callback - The function to execute with the temporary value.
158
+ * @returns {T} The result of the callback function.
159
+ * @throws {Error} If called outside an active context.
160
+ */
161
+ static withValue(key, value, callback) {
162
+ const store = this.storage.getStore();
163
+ if (!store) {
164
+ throw new Error(`Failed to set temporary value: AsyncLocalStorage store is not initialized.`);
165
+ }
166
+ const hasOriginal = key in store;
167
+ const originalValue = store[key];
168
+ store[key] = value;
169
+ try {
170
+ return callback();
171
+ } finally {
172
+ if (hasOriginal) {
173
+ store[key] = originalValue;
174
+ } else {
175
+ delete store[key];
176
+ }
177
+ }
178
+ }
179
+ /**
180
+ * Creates a new context that inherits values from the current context.
181
+ *
182
+ * @typeParam T - The callback's return type.
183
+ * @param {Partial<Record<symbol, unknown>>} newValues - New values to add to or override in the context.
184
+ * @param {() => T} callback - The function to execute in the new context.
185
+ * @returns {T} The result of the callback function.
186
+ */
187
+ static extend(newValues, callback) {
188
+ const currentStore = this.storage.getStore() || {};
189
+ const newStore = {
190
+ ...currentStore
191
+ };
192
+ Object.getOwnPropertySymbols(newValues).forEach((key) => {
193
+ newStore[key] = newValues[key];
194
+ });
195
+ return this.storage.run(newStore, callback);
196
+ }
197
+ /**
198
+ * Creates Express middleware that initializes a context for each request.
199
+ *
200
+ * @param {(req: any) => Partial<Record<symbol, unknown>>} initialValuesFactory - Function that returns initial context values.
201
+ * @returns Express middleware function.
202
+ */
203
+ static createExpressMiddleware(initialValuesFactory = () => ({})) {
204
+ return (req, _res, next) => {
205
+ const initialValues = initialValuesFactory(req);
206
+ _ContextStore.run(initialValues, next);
207
+ };
208
+ }
209
+ };
210
+ var TypedContextKey = class {
211
+ static {
212
+ __name(this, "TypedContextKey");
213
+ }
214
+ symbol;
215
+ defaultValue;
216
+ /**
217
+ * Creates a new typed context key.
218
+ *
219
+ * @param symbol - The unique symbol for this key
220
+ * @param defaultValue - Optional default value if key is not found
221
+ */
222
+ constructor(symbol, defaultValue) {
223
+ this.symbol = symbol;
224
+ this.defaultValue = defaultValue;
225
+ }
226
+ /**
227
+ * Gets the current value for this key.
228
+ *
229
+ * @returns The value or defaultValue if not found
230
+ */
231
+ get() {
232
+ const value = ContextStore.get(this.symbol);
233
+ return value !== void 0 ? value : this.defaultValue;
234
+ }
235
+ /**
236
+ * Sets the value for this key.
237
+ *
238
+ * @param value The value to set
239
+ */
240
+ set(value) {
241
+ ContextStore.set(this.symbol, value);
242
+ }
243
+ /**
244
+ * Checks if this key exists in the context.
245
+ *
246
+ * @returns True if the key exists
247
+ */
248
+ exists() {
249
+ return ContextStore.has(this.symbol);
250
+ }
251
+ /**
252
+ * Deletes this key from the context.
253
+ *
254
+ * @returns True if the key was deleted
255
+ */
256
+ delete() {
257
+ return ContextStore.delete(this.symbol);
258
+ }
259
+ };
260
+
261
+ export { ContextStore, StoreKeys, TypedContextKey, getFromContext, getRequestId };
@@ -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,187 @@
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 'node:crypto';
26
+
27
+ type BufferEncoding = 'ascii' | 'utf8' | 'utf-8' | 'utf16le' | 'utf-16le' | 'ucs2' | 'ucs-2' | 'base64' | 'base64url' | 'latin1' | 'binary' | 'hex';
28
+ /**
29
+ * Generates an HMAC digest using the specified algorithm and secret key.
30
+ *
31
+ * @param {string} algorithm - The hashing algorithm (e.g., 'sha256', 'sha1').
32
+ * @param {string} input - The string to hash.
33
+ * @param {string} secret - The secret key for HMAC.
34
+ * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding ('hex', 'base64', etc).
35
+ * @returns {string} HMAC digest as a string.
36
+ */
37
+ declare function hmac(algorithm: string, input: string, secret: string, encoding?: BinaryToTextEncoding): string;
38
+ /**
39
+ * Generates a hash digest using the specified algorithm.
40
+ *
41
+ * @param {string} algorithm - The hashing algorithm (e.g., 'sha256', 'md5').
42
+ * @param {string} input - The string to hash.
43
+ * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding ('hex', 'base64', etc).
44
+ * @returns {string} Hash digest as a string.
45
+ */
46
+ declare function hash(algorithm: string, input: string, encoding?: BinaryToTextEncoding): string;
47
+ /**
48
+ * Generates an HMAC-SHA256 digest.
49
+ *
50
+ * @param {string} input - The string to hash.
51
+ * @param {string} secret - The secret key.
52
+ * @returns {string} SHA-256 HMAC digest as a string.
53
+ */
54
+ declare function sha256Hmac(input: string, secret: string): string;
55
+ /**
56
+ * Generates a SHA1 hash digest.
57
+ *
58
+ * @param {string} input - The string to hash.
59
+ * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.
60
+ * @returns {string} SHA-1 hash as a string.
61
+ */
62
+ declare function sha1(input: string, encoding?: BinaryToTextEncoding): string;
63
+ /**
64
+ * Generates a SHA256 hash digest.
65
+ *
66
+ * @param {string} input - The string to hash.
67
+ * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.
68
+ * @returns {string} SHA-256 hash as a string.
69
+ */
70
+ declare function sha256(input: string, encoding?: BinaryToTextEncoding): string;
71
+ /**
72
+ * Generates an MD5 hash digest.
73
+ *
74
+ * @param {string} input - The string to hash.
75
+ * @returns {string} MD5 hash as a string.
76
+ */
77
+ declare function md5(input: string): string;
78
+ /**
79
+ * Generates a cryptographically strong random string by hashing a random UUID with SHA-256.
80
+ *
81
+ * @returns {string} Random string hashed with SHA-256 (hex encoding).
82
+ */
83
+ declare function randomString(): string;
84
+ /**
85
+ * Generates a secure random buffer of specified byte length.
86
+ *
87
+ * @param {number} [byteLength=32] - Number of random bytes to generate.
88
+ * @returns {Buffer} Buffer containing random bytes.
89
+ */
90
+ declare function generateRandomBytes(byteLength?: number): Buffer;
91
+ /**
92
+ * Generates a secure random string of specified byte length with specified encoding.
93
+ *
94
+ * @param {number} [byteLength=32] - Number of random bytes to generate.
95
+ * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.
96
+ * @returns {string} Random string in specified encoding.
97
+ */
98
+ declare function generateRandomBytesAsString(byteLength?: number, encoding?: BinaryToTextEncoding): string;
99
+ /**
100
+ * Generates a secure API key with a specified format.
101
+ *
102
+ * @param {string} [prefix=''] - Optional prefix for the key.
103
+ * @param {number} [byteLength=24] - Number of random bytes to generate.
104
+ * @returns {string} Formatted API key.
105
+ */
106
+ declare function generateApiKey(prefix?: string, byteLength?: number): string;
107
+ /**
108
+ * Compares two strings, arrays, or buffers in constant time to prevent timing attacks.
109
+ *
110
+ * @param {string | Buffer | Uint8Array} a - First value to compare
111
+ * @param {string | Buffer | Uint8Array} b - Second value to compare
112
+ * @returns {boolean} True if values are equal
113
+ */
114
+ declare function safeCompare(a: string | Buffer | Uint8Array, b: string | Buffer | Uint8Array): boolean;
115
+ /**
116
+ * Interface for encryption options
117
+ */
118
+ interface EncryptionOptions {
119
+ /** Algorithm to use (default: aes-256-gcm) */
120
+ algorithm?: CipherGCMTypes;
121
+ /** Input encoding for plaintext if string (default: utf8) */
122
+ inputEncoding?: BufferEncoding;
123
+ /** Output encoding for ciphertext (default: hex) */
124
+ outputEncoding?: BinaryToTextEncoding;
125
+ }
126
+ /**
127
+ * Interface for decryption options
128
+ */
129
+ interface DecryptionOptions {
130
+ /** Algorithm to use (default: aes-256-gcm) */
131
+ algorithm?: CipherGCMTypes;
132
+ /** Input encoding for ciphertext if string (default: hex) */
133
+ inputEncoding?: BinaryToTextEncoding;
134
+ /** Output encoding for plaintext (default: utf8) */
135
+ outputEncoding?: BufferEncoding;
136
+ }
137
+ /**
138
+ * Result of encryption operation including all data needed for decryption
139
+ */
140
+ interface EncryptionResult {
141
+ /** Encrypted data (string or Buffer based on options) */
142
+ ciphertext: string | Buffer;
143
+ /** Initialization vector */
144
+ iv: Buffer;
145
+ /** Authentication tag (for GCM mode) */
146
+ authTag?: Buffer;
147
+ /** Algorithm used */
148
+ algorithm: string;
149
+ }
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
+ declare function encrypt(data: string | Buffer, key: string | Buffer, options?: EncryptionOptions): Promise<EncryptionResult>;
159
+ /**
160
+ * Decrypts data that was encrypted with the encrypt function.
161
+ *
162
+ * @param {EncryptionResult} encryptedData - The encrypted data and metadata
163
+ * @param {string | Buffer} key - Decryption key or passphrase
164
+ * @param {DecryptionOptions} [options] - Decryption options
165
+ * @returns {Promise<string | Buffer>} Decrypted data
166
+ */
167
+ declare function decrypt(encryptedData: EncryptionResult, key: string | Buffer, options?: DecryptionOptions): Promise<string | Buffer>;
168
+ /**
169
+ * Creates a signed token with an expiration time and payload.
170
+ *
171
+ * @param {object} payload - Data to include in the token
172
+ * @param {string} secret - Secret key for signing
173
+ * @param {number} [expiresInSeconds=3600] - Token expiration in seconds
174
+ * @returns {string} Signed token string
175
+ */
176
+ declare function createSignedToken(payload: Record<string, any>, secret: string, expiresInSeconds?: number): string;
177
+ /**
178
+ * Verifies and decodes a signed token.
179
+ *
180
+ * @param {string} token - The token to verify
181
+ * @param {string} secret - Secret key for verification
182
+ * @returns {object | null} Decoded payload if valid, null if invalid
183
+ */
184
+ declare function verifySignedToken(token: string, secret: string): Record<string, any> | null;
185
+
186
+ export { createSignedToken, decrypt, encrypt, generateApiKey, generateRandomBytes, generateRandomBytesAsString, hash, hmac, md5, randomString, safeCompare, sha1, sha256, sha256Hmac, verifySignedToken };
187
+ export type { BufferEncoding, DecryptionOptions, EncryptionOptions, EncryptionResult };