@catbee/utils 2.0.0-next.0 → 2.0.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 (122) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +102 -52
  3. package/array/index.cjs +215 -74
  4. package/array/index.d.ts +345 -2
  5. package/array/index.mjs +201 -74
  6. package/async/index.cjs +116 -39
  7. package/async/index.d.ts +292 -2
  8. package/async/index.mjs +116 -40
  9. package/cache/index.cjs +2 -2
  10. package/cache/index.d.ts +156 -2
  11. package/cache/index.mjs +3 -3
  12. package/config/index.cjs +80 -66
  13. package/config/index.d.ts +65 -3
  14. package/config/index.mjs +77 -65
  15. package/context-store/index.cjs +2 -3
  16. package/context-store/index.d.ts +193 -2
  17. package/context-store/index.mjs +2 -3
  18. package/crypto/index.cjs +55 -5
  19. package/crypto/index.d.ts +225 -2
  20. package/crypto/index.mjs +52 -7
  21. package/date/index.cjs +676 -2
  22. package/date/index.d.ts +676 -2
  23. package/date/index.mjs +665 -3
  24. package/decorator/index.cjs +2172 -0
  25. package/{decorators/decorators.utils.d.ts → decorator/index.d.ts} +58 -54
  26. package/decorator/index.mjs +2131 -0
  27. package/{dir → directory}/index.cjs +5 -4
  28. package/{dir/dir.utils.d.ts → directory/index.d.ts} +24 -21
  29. package/{dir → directory}/index.mjs +5 -4
  30. package/env/index.cjs +100 -68
  31. package/env/index.d.ts +391 -2
  32. package/env/index.mjs +100 -68
  33. package/exception/index.cjs +1 -1
  34. package/exception/index.d.ts +233 -2
  35. package/exception/index.mjs +1 -1
  36. package/fs/index.cjs +71 -37
  37. package/fs/index.d.ts +206 -2
  38. package/fs/index.mjs +65 -35
  39. package/http-status-codes/index.cjs +1 -1
  40. package/http-status-codes/index.d.ts +268 -2
  41. package/http-status-codes/index.mjs +1 -1
  42. package/id/index.cjs +1 -1
  43. package/id/index.d.ts +38 -2
  44. package/id/index.mjs +1 -1
  45. package/index.cjs +13 -13
  46. package/index.d.ts +5 -5
  47. package/index.mjs +5 -5
  48. package/logger/index.cjs +13 -15
  49. package/logger/index.d.ts +190 -2
  50. package/logger/index.mjs +14 -16
  51. package/middleware/index.cjs +1 -1
  52. package/middleware/index.d.ts +104 -2
  53. package/middleware/index.mjs +1 -1
  54. package/object/index.cjs +379 -0
  55. package/{obj/obj.utils.d.ts → object/index.d.ts} +73 -33
  56. package/object/index.mjs +360 -0
  57. package/package.json +41 -23
  58. package/performance/index.cjs +4 -4
  59. package/performance/index.d.ts +139 -2
  60. package/performance/index.mjs +4 -4
  61. package/request/index.cjs +37 -25
  62. package/request/index.d.ts +242 -3
  63. package/request/index.mjs +37 -25
  64. package/response/index.cjs +1 -1
  65. package/response/index.d.ts +319 -3
  66. package/response/index.mjs +1 -1
  67. package/server/index.cjs +249 -146
  68. package/server/index.d.ts +866 -5
  69. package/server/index.mjs +248 -144
  70. package/stream/index.cjs +1 -1
  71. package/stream/index.d.ts +91 -2
  72. package/stream/index.mjs +1 -1
  73. package/string/index.cjs +34 -1
  74. package/string/index.d.ts +146 -2
  75. package/string/index.mjs +31 -2
  76. package/type/index.cjs +19 -2
  77. package/type/index.d.ts +144 -2
  78. package/type/index.mjs +17 -3
  79. package/types/index.cjs +1 -1
  80. package/types/index.d.ts +775 -5
  81. package/types/index.mjs +1 -1
  82. package/url/index.cjs +63 -5
  83. package/url/index.d.ts +200 -2
  84. package/url/index.mjs +59 -6
  85. package/{validate → validation}/index.cjs +91 -44
  86. package/{validate/validate.utils.d.ts → validation/index.d.ts} +33 -24
  87. package/{validate → validation}/index.mjs +87 -44
  88. package/array/array.utils.d.ts +0 -191
  89. package/async/async.utils.d.ts +0 -296
  90. package/cache/cache.utils.d.ts +0 -176
  91. package/config/config.d.ts +0 -57
  92. package/context-store/context-store.utils.d.ts +0 -212
  93. package/crypto/crypto.utils.d.ts +0 -183
  94. package/date/date.utils.d.ts +0 -190
  95. package/decorators/index.cjs +0 -913
  96. package/decorators/index.d.ts +0 -25
  97. package/decorators/index.mjs +0 -872
  98. package/dir/index.d.ts +0 -25
  99. package/env/env.utils.d.ts +0 -400
  100. package/exception/exception.utils.d.ts +0 -253
  101. package/fs/fs.utils.d.ts +0 -196
  102. package/http-status-codes/http-status-codes.d.ts +0 -289
  103. package/id/id.utils.d.ts +0 -59
  104. package/logger/logger.utils.d.ts +0 -210
  105. package/middleware/middleware.utils.d.ts +0 -123
  106. package/obj/index.cjs +0 -317
  107. package/obj/index.d.ts +0 -25
  108. package/obj/index.mjs +0 -301
  109. package/performance/performance.utils.d.ts +0 -159
  110. package/request/request.utils.d.ts +0 -109
  111. package/response/response.utils.d.ts +0 -186
  112. package/server/server.builder.d.ts +0 -531
  113. package/server/server.d.ts +0 -303
  114. package/stream/stream.utils.d.ts +0 -111
  115. package/string/string.utils.d.ts +0 -124
  116. package/type/type.utils.d.ts +0 -129
  117. package/types/api-response.d.ts +0 -175
  118. package/types/common.d.ts +0 -148
  119. package/types/config.d.ts +0 -88
  120. package/types/server.d.ts +0 -291
  121. package/url/url.utils.d.ts +0 -164
  122. package/validate/index.d.ts +0 -25
@@ -1,7 +1,7 @@
1
1
  /*
2
2
  * The MIT License
3
3
  *
4
- * Copyright (c) 2025 Catbee Technologies. https://catbee.in/license
4
+ * Copyright (c) 2026 Catbee Technologies. https://catbee.in/license
5
5
  *
6
6
  * Permission is hereby granted, free of charge, to any person obtaining a copy
7
7
  * of this software and associated documentation files (the "Software"), to deal
@@ -231,8 +231,7 @@ var TypedContextKey = class {
231
231
  * @returns The value or defaultValue if not found
232
232
  */
233
233
  get() {
234
- const value = ContextStore.get(this.symbol);
235
- return value !== void 0 ? value : this.defaultValue;
234
+ return ContextStore.get(this.symbol) ?? this.defaultValue;
236
235
  }
237
236
  /**
238
237
  * Sets the value for this key.
@@ -1,7 +1,7 @@
1
1
  /*
2
2
  * The MIT License
3
3
  *
4
- * Copyright (c) 2025 Catbee Technologies. https://catbee.in/license
4
+ * Copyright (c) 2026 Catbee Technologies. https://catbee.in/license
5
5
  *
6
6
  * Permission is hereby granted, free of charge, to any person obtaining a copy
7
7
  * of this software and associated documentation files (the "Software"), to deal
@@ -22,4 +22,195 @@
22
22
  * SOFTWARE.
23
23
  */
24
24
 
25
- export * from './context-store.utils';
25
+ import { AsyncLocalStorage } from 'node:async_hooks';
26
+
27
+ /**
28
+ * Type representing the store object used in AsyncLocalStorage.
29
+ * Keys must be unique symbols to ensure isolation and prevent collisions.
30
+ */
31
+ interface Store {
32
+ [key: symbol]: unknown;
33
+ }
34
+ /**
35
+ * Predefined symbols used as keys in AsyncLocalStorage.
36
+ * Add new symbols here to avoid duplication.
37
+ */
38
+ declare const StoreKeys: {
39
+ LOGGER: symbol;
40
+ REQUEST_ID: symbol;
41
+ USER: symbol;
42
+ SESSION: symbol;
43
+ TRANSACTION_ID: symbol;
44
+ USER_ID: symbol;
45
+ TENANT_ID: symbol;
46
+ TRACE_ID: symbol;
47
+ CORRELATION_ID: symbol;
48
+ };
49
+ /**
50
+ * Retrieves the current request ID from the async context, if available.
51
+ *
52
+ * @returns {string | undefined} The request ID string or undefined if not present in the current context.
53
+ */
54
+ declare function getRequestId(): string | undefined;
55
+ /**
56
+ * Type-safe getter for common context values.
57
+ *
58
+ * @param key The store key symbol
59
+ * @returns The typed value from the store
60
+ */
61
+ declare function getFromContext<T>(key: symbol): T | undefined;
62
+ /**
63
+ * ContextStore manages per-request scoped context using AsyncLocalStorage.
64
+ * It allows storing and retrieving data across async calls (e.g., request ID, logger).
65
+ *
66
+ * Example (Express middleware):
67
+ * ```
68
+ * // Middleware to initialize context and logger
69
+ * app.use((req, res, next) => {
70
+ * const requestId = req.headers["x-request-id"]?.toString() || crypto.randomUUID();
71
+ * ContextStore.run({ [StoreKeys.REQUEST_ID]: requestId }, () => {
72
+ * ContextStore.set(StoreKeys.LOGGER, getLogger().child({ requestId }));
73
+ * next();
74
+ * });
75
+ * });
76
+ * ```
77
+ */
78
+ declare class ContextStore {
79
+ /**
80
+ * The underlying AsyncLocalStorage instance for context.
81
+ * @private
82
+ */
83
+ private static readonly storage;
84
+ /**
85
+ * Returns the raw AsyncLocalStorage instance for advanced access.
86
+ *
87
+ * @returns {AsyncLocalStorage<Store>} The AsyncLocalStorage instance.
88
+ */
89
+ static getInstance(): AsyncLocalStorage<Store>;
90
+ /**
91
+ * Retrieves a value from the async context store by symbol key.
92
+ *
93
+ * @typeParam T - The expected return type of the value.
94
+ * @param {symbol} key - Unique symbol used as the store key.
95
+ * @returns {T | undefined} The value found (typed) or undefined if not present.
96
+ */
97
+ static get<T>(key: symbol): T | undefined;
98
+ /**
99
+ * Sets a value in the current context store by symbol key.
100
+ *
101
+ * @typeParam T - The value type to set.
102
+ * @param {symbol} key - Unique symbol key.
103
+ * @param {T} value - Value to set in context.
104
+ * @throws {Error} If called outside an active context (not within a .run call or in the wrong async boundaries).
105
+ */
106
+ static set<T>(key: symbol, value: T): void;
107
+ /**
108
+ * Retrieves the entire context store object for the current async context.
109
+ *
110
+ * @returns {Store | undefined} The current store object or undefined if called outside a context.
111
+ */
112
+ static getAll(): Store | undefined;
113
+ /**
114
+ * Initializes a new async context and executes a callback within it.
115
+ * This must be called at the beginning of a request or logical async flow.
116
+ *
117
+ * @typeParam T - The callback's return type.
118
+ * @param {Store} store - The initial key-value store object.
119
+ * @param {() => T} callback - The function to run within the new context.
120
+ * @returns {T} The result of the callback function.
121
+ */
122
+ static run<T>(store: Store, callback: () => T): T;
123
+ /**
124
+ * Checks if a key exists in the current context store.
125
+ *
126
+ * @param {symbol} key - The symbol key to check.
127
+ * @returns {boolean} True if the key exists, false otherwise.
128
+ */
129
+ static has(key: symbol): boolean;
130
+ /**
131
+ * Removes a value from the current context store by symbol key.
132
+ *
133
+ * @param {symbol} key - The symbol key to delete.
134
+ * @returns {boolean} True if the key was deleted, false if the key wasn't found or no active context.
135
+ * @throws {Error} If called outside an active context.
136
+ */
137
+ static delete(key: symbol): boolean;
138
+ /**
139
+ * Updates multiple values in the current context store at once.
140
+ *
141
+ * @param {Partial<Record<symbol, unknown>>} values - Object containing symbol keys and values to update.
142
+ * @throws {Error} If called outside an active context.
143
+ */
144
+ static patch(values: Partial<Record<symbol, unknown>>): void;
145
+ /**
146
+ * Executes a callback with a temporary store value that only exists during execution.
147
+ * Original store is restored after callback completes.
148
+ *
149
+ * @typeParam T - The callback's return type.
150
+ * @param {symbol} key - The symbol key to temporarily set.
151
+ * @param {unknown} value - The temporary value.
152
+ * @param {() => T} callback - The function to execute with the temporary value.
153
+ * @returns {T} The result of the callback function.
154
+ * @throws {Error} If called outside an active context.
155
+ */
156
+ static withValue<T>(key: symbol, value: unknown, callback: () => T): T;
157
+ /**
158
+ * Creates a new context that inherits values from the current context.
159
+ *
160
+ * @typeParam T - The callback's return type.
161
+ * @param {Partial<Record<symbol, unknown>>} newValues - New values to add to or override in the context.
162
+ * @param {() => T} callback - The function to execute in the new context.
163
+ * @returns {T} The result of the callback function.
164
+ */
165
+ static extend<T>(newValues: Partial<Record<symbol, unknown>>, callback: () => T): T;
166
+ /**
167
+ * Creates Express middleware that initializes a context for each request.
168
+ *
169
+ * @param {(req: any) => Partial<Record<symbol, unknown>>} initialValuesFactory - Function that returns initial context values.
170
+ * @returns Express middleware function.
171
+ */
172
+ static createExpressMiddleware(initialValuesFactory?: (req: any) => Partial<Record<symbol, unknown>>): (req: any, _res: any, next: any) => void;
173
+ }
174
+ /**
175
+ * Type-safe wrapper for accessing and modifying context values with specific types.
176
+ *
177
+ * @typeParam T - The value type.
178
+ */
179
+ declare class TypedContextKey<T> {
180
+ private readonly symbol;
181
+ private readonly defaultValue?;
182
+ /**
183
+ * Creates a new typed context key.
184
+ *
185
+ * @param symbol - The unique symbol for this key
186
+ * @param defaultValue - Optional default value if key is not found
187
+ */
188
+ constructor(symbol: symbol, defaultValue?: T | undefined);
189
+ /**
190
+ * Gets the current value for this key.
191
+ *
192
+ * @returns The value or defaultValue if not found
193
+ */
194
+ get(): T | undefined;
195
+ /**
196
+ * Sets the value for this key.
197
+ *
198
+ * @param value The value to set
199
+ */
200
+ set(value: T): void;
201
+ /**
202
+ * Checks if this key exists in the context.
203
+ *
204
+ * @returns True if the key exists
205
+ */
206
+ exists(): boolean;
207
+ /**
208
+ * Deletes this key from the context.
209
+ *
210
+ * @returns True if the key was deleted
211
+ */
212
+ delete(): boolean;
213
+ }
214
+
215
+ export { ContextStore, StoreKeys, TypedContextKey, getFromContext, getRequestId };
216
+ export type { Store };
@@ -1,7 +1,7 @@
1
1
  /*
2
2
  * The MIT License
3
3
  *
4
- * Copyright (c) 2025 Catbee Technologies. https://catbee.in/license
4
+ * Copyright (c) 2026 Catbee Technologies. https://catbee.in/license
5
5
  *
6
6
  * Permission is hereby granted, free of charge, to any person obtaining a copy
7
7
  * of this software and associated documentation files (the "Software"), to deal
@@ -229,8 +229,7 @@ var TypedContextKey = class {
229
229
  * @returns The value or defaultValue if not found
230
230
  */
231
231
  get() {
232
- const value = ContextStore.get(this.symbol);
233
- return value !== void 0 ? value : this.defaultValue;
232
+ return ContextStore.get(this.symbol) ?? this.defaultValue;
234
233
  }
235
234
  /**
236
235
  * Sets the value for this key.
package/crypto/index.cjs CHANGED
@@ -1,7 +1,7 @@
1
1
  /*
2
2
  * The MIT License
3
3
  *
4
- * Copyright (c) 2025 Catbee Technologies. https://catbee.in/license
4
+ * Copyright (c) 2026 Catbee Technologies. https://catbee.in/license
5
5
  *
6
6
  * Permission is hereby granted, free of charge, to any person obtaining a copy
7
7
  * of this software and associated documentation files (the "Software"), to deal
@@ -30,6 +30,8 @@ var id = require('@catbee/utils/id');
30
30
 
31
31
  var __defProp = Object.defineProperty;
32
32
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
33
+ var pbkdf2Async = util.promisify(crypto.pbkdf2);
34
+ var scryptAsync = util.promisify(crypto.scrypt);
33
35
  function hmac(algorithm, input, secret, encoding = "hex") {
34
36
  return crypto.createHmac(algorithm, secret).update(input).digest(encoding);
35
37
  }
@@ -85,13 +87,13 @@ function safeCompare(a, b) {
85
87
  throw new Error("Cannot compare: inputs must be strings, Buffers, or Uint8Arrays");
86
88
  }
87
89
  __name(safeCompare, "safeCompare");
88
- var scryptAsync = util.promisify(crypto.scrypt);
89
90
  async function encrypt(data, key, options = {}) {
90
91
  const algorithm = options.algorithm || "aes-256-gcm";
91
92
  const inputEncoding = options.inputEncoding || "utf8";
92
93
  const outputEncoding = options.outputEncoding || "hex";
93
94
  const iv = crypto.randomBytes(16);
94
- const derivedKey = typeof key === "string" ? await scryptAsync(key, iv.slice(0, 8), 32) : key;
95
+ const salt = crypto.randomBytes(8);
96
+ const derivedKey = typeof key === "string" ? await scryptAsync(key, salt, 32) : key;
95
97
  const cipher = crypto.createCipheriv(algorithm, derivedKey, iv);
96
98
  let ciphertext;
97
99
  if (typeof data === "string") {
@@ -109,7 +111,8 @@ async function encrypt(data, key, options = {}) {
109
111
  ciphertext,
110
112
  iv,
111
113
  authTag,
112
- algorithm
114
+ algorithm,
115
+ salt
113
116
  };
114
117
  }
115
118
  __name(encrypt, "encrypt");
@@ -117,7 +120,7 @@ async function decrypt(encryptedData, key, options = {}) {
117
120
  const algorithm = options.algorithm || encryptedData.algorithm || "aes-256-gcm";
118
121
  const inputEncoding = options.inputEncoding || "hex";
119
122
  const outputEncoding = options.outputEncoding || "utf8";
120
- const derivedKey = typeof key === "string" ? await scryptAsync(key, encryptedData.iv.slice(0, 8), 32) : key;
123
+ const derivedKey = typeof key === "string" ? await scryptAsync(key, encryptedData.salt, 32) : key;
121
124
  const decipher = crypto.createDecipheriv(algorithm, derivedKey, encryptedData.iv);
122
125
  if (encryptedData.authTag && algorithm.includes("gcm")) {
123
126
  decipher.setAuthTag(encryptedData.authTag);
@@ -164,19 +167,66 @@ function verifySignedToken(token, secret) {
164
167
  }
165
168
  }
166
169
  __name(verifySignedToken, "verifySignedToken");
170
+ async function pbkdf2Hash(password, salt, keyLength = 32, iterations = 31e4) {
171
+ return pbkdf2Async(password, salt, iterations, keyLength, "sha256");
172
+ }
173
+ __name(pbkdf2Hash, "pbkdf2Hash");
174
+ function generateNonce(byteLength = 16, encoding = "hex") {
175
+ return crypto.randomBytes(byteLength).toString(encoding);
176
+ }
177
+ __name(generateNonce, "generateNonce");
178
+ function secureRandomInt(min, max) {
179
+ if (min > max) throw new Error("min must be less than or equal to max");
180
+ const range = max - min + 1;
181
+ const bytesNeeded = Math.ceil(Math.log2(range) / 8);
182
+ const maxValid = Math.floor(256 ** bytesNeeded / range) * range;
183
+ let randomValue;
184
+ do {
185
+ const bytes = crypto.randomBytes(bytesNeeded);
186
+ randomValue = bytes.reduce((acc, byte, i) => acc + byte * 256 ** i, 0);
187
+ } while (randomValue >= maxValid);
188
+ return min + randomValue % range;
189
+ }
190
+ __name(secureRandomInt, "secureRandomInt");
191
+ async function hashPassword(password, saltLength = 16, keyLength = 32) {
192
+ const salt = crypto.randomBytes(saltLength);
193
+ const scryptAsync2 = util.promisify(crypto.scrypt);
194
+ const derivedKey = await scryptAsync2(password, salt, keyLength);
195
+ return `${salt.toString("base64")}:${derivedKey.toString("base64")}`;
196
+ }
197
+ __name(hashPassword, "hashPassword");
198
+ async function verifyPassword(password, hash2) {
199
+ try {
200
+ const [saltB64, keyB64] = hash2.split(":");
201
+ if (!saltB64 || !keyB64) return false;
202
+ const salt = Buffer.from(saltB64, "base64");
203
+ const key = Buffer.from(keyB64, "base64");
204
+ const scryptAsync2 = util.promisify(crypto.scrypt);
205
+ const derivedKey = await scryptAsync2(password, salt, key.length);
206
+ return crypto.timingSafeEqual(key, derivedKey);
207
+ } catch {
208
+ return false;
209
+ }
210
+ }
211
+ __name(verifyPassword, "verifyPassword");
167
212
 
168
213
  exports.createSignedToken = createSignedToken;
169
214
  exports.decrypt = decrypt;
170
215
  exports.encrypt = encrypt;
171
216
  exports.generateApiKey = generateApiKey;
217
+ exports.generateNonce = generateNonce;
172
218
  exports.generateRandomBytes = generateRandomBytes;
173
219
  exports.generateRandomBytesAsString = generateRandomBytesAsString;
174
220
  exports.hash = hash;
221
+ exports.hashPassword = hashPassword;
175
222
  exports.hmac = hmac;
176
223
  exports.md5 = md5;
224
+ exports.pbkdf2Hash = pbkdf2Hash;
177
225
  exports.randomString = randomString;
178
226
  exports.safeCompare = safeCompare;
227
+ exports.secureRandomInt = secureRandomInt;
179
228
  exports.sha1 = sha1;
180
229
  exports.sha256 = sha256;
181
230
  exports.sha256Hmac = sha256Hmac;
231
+ exports.verifyPassword = verifyPassword;
182
232
  exports.verifySignedToken = verifySignedToken;
package/crypto/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  /*
2
2
  * The MIT License
3
3
  *
4
- * Copyright (c) 2025 Catbee Technologies. https://catbee.in/license
4
+ * Copyright (c) 2026 Catbee Technologies. https://catbee.in/license
5
5
  *
6
6
  * Permission is hereby granted, free of charge, to any person obtaining a copy
7
7
  * of this software and associated documentation files (the "Software"), to deal
@@ -22,4 +22,227 @@
22
22
  * SOFTWARE.
23
23
  */
24
24
 
25
- export * from './crypto.utils';
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
+ /** Salt used for key derivation */
150
+ salt: Buffer;
151
+ }
152
+ /**
153
+ * Encrypts data using a symmetric key with secure defaults (AES-256-GCM).
154
+ *
155
+ * @param {string | Buffer} data - Data to encrypt
156
+ * @param {string | Buffer} key - Encryption key or passphrase
157
+ * @param {EncryptionOptions} [options] - Encryption options
158
+ * @returns {Promise<EncryptionResult>} Encrypted data with metadata
159
+ */
160
+ declare function encrypt(data: string | Buffer, key: string | Buffer, options?: EncryptionOptions): Promise<EncryptionResult>;
161
+ /**
162
+ * Decrypts data that was encrypted with the encrypt function.
163
+ *
164
+ * @param {EncryptionResult} encryptedData - The encrypted data and metadata
165
+ * @param {string | Buffer} key - Decryption key or passphrase
166
+ * @param {DecryptionOptions} [options] - Decryption options
167
+ * @returns {Promise<string | Buffer>} Decrypted data
168
+ */
169
+ declare function decrypt(encryptedData: EncryptionResult, key: string | Buffer, options?: DecryptionOptions): Promise<string | Buffer>;
170
+ /**
171
+ * Creates a signed token with an expiration time and payload.
172
+ *
173
+ * @param {object} payload - Data to include in the token
174
+ * @param {string} secret - Secret key for signing
175
+ * @param {number} [expiresInSeconds=3600] - Token expiration in seconds
176
+ * @returns {string} Signed token string
177
+ */
178
+ declare function createSignedToken(payload: Record<string, any>, secret: string, expiresInSeconds?: number): string;
179
+ /**
180
+ * Verifies and decodes a signed token.
181
+ *
182
+ * @param {string} token - The token to verify
183
+ * @param {string} secret - Secret key for verification
184
+ * @returns {object | null} Decoded payload if valid, null if invalid
185
+ */
186
+ declare function verifySignedToken(token: string, secret: string): Record<string, any> | null;
187
+ /**
188
+ * Derives a cryptographic key using PBKDF2 (SHA-256).
189
+ *
190
+ * @param password - Password to derive key from
191
+ * @param salt - Cryptographic salt (use unique per password)
192
+ * @param keyLength - Output key length in bytes (default 32)
193
+ * @param iterations - Number of hashing iterations (default 310000, OWASP recommended)
194
+ * @returns Derived key as Buffer
195
+ *
196
+ * @example
197
+ * const key = await pbkdf2Hash('myPassword', 'mySalt');
198
+ */
199
+ declare function pbkdf2Hash(password: string, salt: string | Buffer, keyLength?: number, iterations?: number): Promise<Buffer>;
200
+ /**
201
+ * Generates a cryptographically secure nonce (number used once).
202
+ *
203
+ * @param {number} [byteLength=16] - Length of nonce in bytes.
204
+ * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.
205
+ * @returns {string} Nonce string.
206
+ *
207
+ * @example
208
+ * const nonce = generateNonce(16, 'base64'); // Random nonce
209
+ */
210
+ declare function generateNonce(byteLength?: number, encoding?: BinaryToTextEncoding): string;
211
+ /**
212
+ * Generates a cryptographically secure random integer in a range.
213
+ *
214
+ * @param {number} min - Minimum value (inclusive).
215
+ * @param {number} max - Maximum value (inclusive).
216
+ * @returns {number} Random integer.
217
+ *
218
+ * @example
219
+ * const random = secureRandomInt(1, 100); // Random number 1-100
220
+ */
221
+ declare function secureRandomInt(min: number, max: number): number;
222
+ /**
223
+ * Hashes a password using scrypt (memory-hard function).
224
+ *
225
+ * @param {string} password - The password to hash.
226
+ * @param {number} [saltLength=16] - Length of salt in bytes.
227
+ * @param {number} [keyLength=32] - Length of derived key.
228
+ * @returns {Promise<string>} Hash string containing salt and key.
229
+ *
230
+ * @example
231
+ * const hash = await hashPassword('myPassword');
232
+ * // Returns format: salt:hash (both base64)
233
+ */
234
+ declare function hashPassword(password: string, saltLength?: number, keyLength?: number): Promise<string>;
235
+ /**
236
+ * Verifies a password against a scrypt hash.
237
+ *
238
+ * @param {string} password - The password to verify.
239
+ * @param {string} hash - The hash to verify against (from hashPassword).
240
+ * @returns {Promise<boolean>} True if password matches.
241
+ *
242
+ * @example
243
+ * const isValid = await verifyPassword('myPassword', storedHash);
244
+ */
245
+ declare function verifyPassword(password: string, hash: string): Promise<boolean>;
246
+
247
+ export { createSignedToken, decrypt, encrypt, generateApiKey, generateNonce, generateRandomBytes, generateRandomBytesAsString, hash, hashPassword, hmac, md5, pbkdf2Hash, randomString, safeCompare, secureRandomInt, sha1, sha256, sha256Hmac, verifyPassword, verifySignedToken };
248
+ export type { BufferEncoding, DecryptionOptions, EncryptionOptions, EncryptionResult };