@catbee/utils 0.0.2 → 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/build/esm/config.d.ts +1 -1
- package/build/esm/config.js +7 -7
- package/build/esm/config.js.map +1 -1
- package/build/esm/index.d.ts +20 -19
- package/build/esm/index.js +20 -19
- package/build/esm/index.js.map +1 -1
- package/build/esm/types/api-response.d.ts +2 -2
- package/build/esm/types/api-response.js.map +1 -1
- package/build/esm/utils/array.utils.d.ts +1 -1
- package/build/esm/utils/array.utils.js +17 -27
- package/build/esm/utils/array.utils.js.map +1 -1
- package/build/esm/utils/async.utils.d.ts +1 -5
- package/build/esm/utils/async.utils.js +17 -20
- package/build/esm/utils/async.utils.js.map +1 -1
- package/build/esm/utils/cache.utils.js +2 -2
- package/build/esm/utils/cache.utils.js.map +1 -1
- package/build/esm/utils/context-store.utils.d.ts +1 -1
- package/build/esm/utils/context-store.utils.js +8 -8
- package/build/esm/utils/context-store.utils.js.map +1 -1
- package/build/esm/utils/crypto.utils.d.ts +2 -2
- package/build/esm/utils/crypto.utils.js +37 -45
- package/build/esm/utils/crypto.utils.js.map +1 -1
- package/build/esm/utils/decorators.utils.d.ts +7 -7
- package/build/esm/utils/decorators.utils.js +31 -31
- package/build/esm/utils/decorators.utils.js.map +1 -1
- package/build/esm/utils/dir.utils.d.ts +4 -4
- package/build/esm/utils/dir.utils.js +18 -20
- package/build/esm/utils/dir.utils.js.map +1 -1
- package/build/esm/utils/env.utils.js +22 -26
- package/build/esm/utils/env.utils.js.map +1 -1
- package/build/esm/utils/exception.utils.d.ts +1 -1
- package/build/esm/utils/exception.utils.js +26 -29
- package/build/esm/utils/exception.utils.js.map +1 -1
- package/build/esm/utils/fs.utils.d.ts +3 -3
- package/build/esm/utils/fs.utils.js +19 -23
- package/build/esm/utils/fs.utils.js.map +1 -1
- package/build/esm/utils/http-status-codes.js.map +1 -1
- package/build/esm/utils/id.utils.js +8 -8
- package/build/esm/utils/id.utils.js.map +1 -1
- package/build/esm/utils/logger.utils.d.ts +13 -4
- package/build/esm/utils/logger.utils.js +15 -15
- package/build/esm/utils/logger.utils.js.map +1 -1
- package/build/esm/utils/middleware.utils.d.ts +5 -4
- package/build/esm/utils/middleware.utils.js +19 -19
- package/build/esm/utils/middleware.utils.js.map +1 -1
- package/build/esm/utils/obj.utils.js +16 -27
- package/build/esm/utils/obj.utils.js.map +1 -1
- package/build/esm/utils/response.utils.d.ts +2 -2
- package/build/esm/utils/response.utils.js +11 -11
- package/build/esm/utils/response.utils.js.map +1 -1
- package/build/esm/utils/string.utils.js +17 -17
- package/build/esm/utils/string.utils.js.map +1 -1
- package/build/esm/utils/url.utils.js +20 -22
- package/build/esm/utils/url.utils.js.map +1 -1
- package/build/esm/utils/validate.utils.js +11 -15
- package/build/esm/utils/validate.utils.js.map +1 -1
- package/build/esnext/config.d.ts +1 -1
- package/build/esnext/config.js +7 -7
- package/build/esnext/config.js.map +1 -1
- package/build/esnext/index.d.ts +20 -19
- package/build/esnext/index.js +20 -19
- package/build/esnext/index.js.map +1 -1
- package/build/esnext/types/api-response.d.ts +2 -2
- package/build/esnext/types/api-response.js.map +1 -1
- package/build/esnext/utils/array.utils.d.ts +1 -1
- package/build/esnext/utils/array.utils.js +23 -31
- package/build/esnext/utils/array.utils.js.map +1 -1
- package/build/esnext/utils/async.utils.d.ts +1 -5
- package/build/esnext/utils/async.utils.js +22 -22
- package/build/esnext/utils/async.utils.js.map +1 -1
- package/build/esnext/utils/cache.utils.js +3 -3
- package/build/esnext/utils/cache.utils.js.map +1 -1
- package/build/esnext/utils/context-store.utils.d.ts +1 -1
- package/build/esnext/utils/context-store.utils.js +10 -10
- package/build/esnext/utils/context-store.utils.js.map +1 -1
- package/build/esnext/utils/crypto.utils.d.ts +2 -2
- package/build/esnext/utils/crypto.utils.js +37 -47
- package/build/esnext/utils/crypto.utils.js.map +1 -1
- package/build/esnext/utils/decorators.utils.d.ts +7 -7
- package/build/esnext/utils/decorators.utils.js +33 -33
- package/build/esnext/utils/decorators.utils.js.map +1 -1
- package/build/esnext/utils/dir.utils.d.ts +4 -4
- package/build/esnext/utils/dir.utils.js +22 -24
- package/build/esnext/utils/dir.utils.js.map +1 -1
- package/build/esnext/utils/env.utils.js +24 -26
- package/build/esnext/utils/env.utils.js.map +1 -1
- package/build/esnext/utils/exception.utils.d.ts +1 -1
- package/build/esnext/utils/exception.utils.js +26 -29
- package/build/esnext/utils/exception.utils.js.map +1 -1
- package/build/esnext/utils/fs.utils.d.ts +3 -3
- package/build/esnext/utils/fs.utils.js +21 -25
- package/build/esnext/utils/fs.utils.js.map +1 -1
- package/build/esnext/utils/http-status-codes.js.map +1 -1
- package/build/esnext/utils/id.utils.js +8 -8
- package/build/esnext/utils/id.utils.js.map +1 -1
- package/build/esnext/utils/logger.utils.d.ts +13 -4
- package/build/esnext/utils/logger.utils.js +15 -15
- package/build/esnext/utils/logger.utils.js.map +1 -1
- package/build/esnext/utils/middleware.utils.d.ts +5 -4
- package/build/esnext/utils/middleware.utils.js +19 -19
- package/build/esnext/utils/middleware.utils.js.map +1 -1
- package/build/esnext/utils/obj.utils.js +17 -26
- package/build/esnext/utils/obj.utils.js.map +1 -1
- package/build/esnext/utils/response.utils.d.ts +2 -2
- package/build/esnext/utils/response.utils.js +11 -11
- package/build/esnext/utils/response.utils.js.map +1 -1
- package/build/esnext/utils/string.utils.js +17 -17
- package/build/esnext/utils/string.utils.js.map +1 -1
- package/build/esnext/utils/url.utils.js +21 -23
- package/build/esnext/utils/url.utils.js.map +1 -1
- package/build/esnext/utils/validate.utils.js +14 -16
- package/build/esnext/utils/validate.utils.js.map +1 -1
- package/build/src/config.d.ts +1 -1
- package/build/src/config.js +6 -6
- package/build/src/config.js.map +1 -1
- package/build/src/index.d.ts +20 -19
- package/build/src/index.js +1 -0
- package/build/src/index.js.map +1 -1
- package/build/src/types/api-response.d.ts +2 -2
- package/build/src/types/api-response.js.map +1 -1
- package/build/src/utils/array.utils.d.ts +1 -1
- package/build/src/utils/array.utils.js +22 -30
- package/build/src/utils/array.utils.js.map +1 -1
- package/build/src/utils/async.utils.d.ts +1 -5
- package/build/src/utils/async.utils.js +22 -22
- package/build/src/utils/async.utils.js.map +1 -1
- package/build/src/utils/cache.utils.js +2 -2
- package/build/src/utils/cache.utils.js.map +1 -1
- package/build/src/utils/context-store.utils.d.ts +1 -1
- package/build/src/utils/context-store.utils.js +9 -9
- package/build/src/utils/context-store.utils.js.map +1 -1
- package/build/src/utils/crypto.utils.d.ts +2 -2
- package/build/src/utils/crypto.utils.js +35 -45
- package/build/src/utils/crypto.utils.js.map +1 -1
- package/build/src/utils/decorators.utils.d.ts +7 -7
- package/build/src/utils/decorators.utils.js +32 -32
- package/build/src/utils/decorators.utils.js.map +1 -1
- package/build/src/utils/dir.utils.d.ts +4 -4
- package/build/src/utils/dir.utils.js +16 -18
- package/build/src/utils/dir.utils.js.map +1 -1
- package/build/src/utils/env.utils.js +22 -24
- package/build/src/utils/env.utils.js.map +1 -1
- package/build/src/utils/exception.utils.d.ts +1 -1
- package/build/src/utils/exception.utils.js +23 -26
- package/build/src/utils/exception.utils.js.map +1 -1
- package/build/src/utils/fs.utils.d.ts +3 -3
- package/build/src/utils/fs.utils.js +15 -19
- package/build/src/utils/fs.utils.js.map +1 -1
- package/build/src/utils/http-status-codes.js.map +1 -1
- package/build/src/utils/id.utils.js +7 -7
- package/build/src/utils/id.utils.js.map +1 -1
- package/build/src/utils/logger.utils.d.ts +13 -4
- package/build/src/utils/logger.utils.js +12 -12
- package/build/src/utils/logger.utils.js.map +1 -1
- package/build/src/utils/middleware.utils.d.ts +5 -4
- package/build/src/utils/middleware.utils.js +12 -12
- package/build/src/utils/middleware.utils.js.map +1 -1
- package/build/src/utils/obj.utils.js +17 -26
- package/build/src/utils/obj.utils.js.map +1 -1
- package/build/src/utils/response.utils.d.ts +2 -2
- package/build/src/utils/response.utils.js +9 -9
- package/build/src/utils/response.utils.js.map +1 -1
- package/build/src/utils/string.utils.js +17 -17
- package/build/src/utils/string.utils.js.map +1 -1
- package/build/src/utils/url.utils.js +20 -22
- package/build/src/utils/url.utils.js.map +1 -1
- package/build/src/utils/validate.utils.js +14 -16
- package/build/src/utils/validate.utils.js.map +1 -1
- package/package.json +1 -1
|
@@ -9,12 +9,12 @@ const async_hooks_1 = require("async_hooks");
|
|
|
9
9
|
* Add new symbols here to avoid duplication.
|
|
10
10
|
*/
|
|
11
11
|
exports.StoreKeys = {
|
|
12
|
-
LOGGER: Symbol(
|
|
13
|
-
REQUEST_ID: Symbol(
|
|
14
|
-
USER_ID: Symbol(
|
|
15
|
-
TENANT_ID: Symbol(
|
|
16
|
-
TRACE_ID: Symbol(
|
|
17
|
-
CORRELATION_ID: Symbol(
|
|
12
|
+
LOGGER: Symbol('logger'),
|
|
13
|
+
REQUEST_ID: Symbol('requestId'),
|
|
14
|
+
USER_ID: Symbol('userId'),
|
|
15
|
+
TENANT_ID: Symbol('tenantId'),
|
|
16
|
+
TRACE_ID: Symbol('traceId'),
|
|
17
|
+
CORRELATION_ID: Symbol('correlationId')
|
|
18
18
|
};
|
|
19
19
|
/**
|
|
20
20
|
* Retrieves the current request ID from the async context, if available.
|
|
@@ -137,9 +137,9 @@ class ContextStore {
|
|
|
137
137
|
static patch(values) {
|
|
138
138
|
const store = this.storage.getStore();
|
|
139
139
|
if (!store) {
|
|
140
|
-
throw new Error(
|
|
140
|
+
throw new Error('Failed to patch: AsyncLocalStorage store is not initialized.');
|
|
141
141
|
}
|
|
142
|
-
Object.getOwnPropertySymbols(values).forEach(
|
|
142
|
+
Object.getOwnPropertySymbols(values).forEach(key => {
|
|
143
143
|
store[key] = values[key];
|
|
144
144
|
});
|
|
145
145
|
}
|
|
@@ -191,7 +191,7 @@ class ContextStore {
|
|
|
191
191
|
// Create new store with current values plus new ones
|
|
192
192
|
const newStore = Object.assign({}, currentStore);
|
|
193
193
|
// Add new values
|
|
194
|
-
Object.getOwnPropertySymbols(newValues).forEach(
|
|
194
|
+
Object.getOwnPropertySymbols(newValues).forEach(key => {
|
|
195
195
|
newStore[key] = newValues[key];
|
|
196
196
|
});
|
|
197
197
|
// Run with extended store
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context-store.utils.js","sourceRoot":"","sources":["../../../src/utils/context-store.utils.ts"],"names":[],"mappings":";;;AA4BA,oCAEC;AAQD,wCAEC;AAxCD,6CAAgD;AAUhD;;;GAGG;AACU,QAAA,SAAS,GAAG;IACvB,MAAM,EAAE,MAAM,CAAC,QAAQ,CAAC;IACxB,UAAU,EAAE,MAAM,CAAC,WAAW,CAAC;IAC/B,OAAO,EAAE,MAAM,CAAC,QAAQ,CAAC;IACzB,SAAS,EAAE,MAAM,CAAC,UAAU,CAAC;IAC7B,QAAQ,EAAE,MAAM,CAAC,SAAS,CAAC;IAC3B,cAAc,EAAE,MAAM,CAAC,eAAe,CAAC;CACxC,CAAC;AAEF;;;;GAIG;AACH,SAAgB,YAAY;IAC1B,OAAO,YAAY,CAAC,GAAG,CAAS,iBAAS,CAAC,UAAU,CAAC,CAAC;AACxD,CAAC;AAED;;;;;GAKG;AACH,SAAgB,cAAc,CAAI,GAAW;IAC3C,OAAO,YAAY,CAAC,GAAG,CAAI,GAAG,CAAC,CAAC;AAClC,CAAC;AAED;;;;;;;;;;;;;;;GAeG;AACH,MAAa,YAAY;IAOvB;;;;OAIG;IACH,MAAM,CAAC,WAAW;QAChB,OAAO,IAAI,CAAC,OAAO,CAAC;IACtB,CAAC;IAED;;;;;;OAMG;IACH,MAAM,CAAC,GAAG,CAAI,GAAW;QACvB,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC;QACtC,OAAO,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAG,GAAG,CAAkB,CAAC;IACvC,CAAC;IAED;;;;;;;OAOG;IACH,MAAM,CAAC,GAAG,CAAI,GAAW,EAAE,KAAQ;QACjC,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,C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AgDC","sourcesContent":["import { AsyncLocalStorage } from \"async_hooks\";\n\n/**\n * Type representing the store object used in AsyncLocalStorage.\n * Keys must be unique symbols to ensure isolation and prevent collisions.\n */\nexport interface Store {\n [key: symbol]: unknown;\n}\n\n/**\n * Predefined symbols used as keys in AsyncLocalStorage.\n * Add new symbols here to avoid duplication.\n */\nexport const StoreKeys = {\n LOGGER: Symbol(\"logger\"),\n REQUEST_ID: Symbol(\"requestId\"),\n USER_ID: Symbol(\"userId\"),\n TENANT_ID: Symbol(\"tenantId\"),\n TRACE_ID: Symbol(\"traceId\"),\n CORRELATION_ID: Symbol(\"correlationId\"),\n};\n\n/**\n * Retrieves the current request ID from the async context, if available.\n *\n * @returns {string | undefined} The request ID string or undefined if not present in the current context.\n */\nexport function getRequestId(): string | undefined {\n return ContextStore.get<string>(StoreKeys.REQUEST_ID);\n}\n\n/**\n * Type-safe getter for common context values.\n *\n * @param key The store key symbol\n * @returns The typed value from the store\n */\nexport function getFromContext<T>(key: symbol): T | undefined {\n return ContextStore.get<T>(key);\n}\n\n/**\n * ContextStore manages per-request scoped context using AsyncLocalStorage.\n * It allows storing and retrieving data across async calls (e.g., request ID, logger).\n *\n * Example (Express middleware):\n * ```\n * // Middleware to initialize context and logger\n * app.use((req, res, next) => {\n * const requestId = req.headers[\"x-request-id\"]?.toString() || crypto.randomUUID();\n * ContextStore.run({ [StoreKeys.REQUEST_ID]: requestId }, () => {\n * ContextStore.set(StoreKeys.LOGGER, getLogger().child({ reqId: requestId }));\n * next();\n * });\n * });\n * ```\n */\nexport class ContextStore {\n /**\n * The underlying AsyncLocalStorage instance for context.\n * @private\n */\n private static readonly storage = new AsyncLocalStorage<Store>();\n\n /**\n * Returns the raw AsyncLocalStorage instance for advanced access.\n *\n * @returns {AsyncLocalStorage<Store>} The AsyncLocalStorage instance.\n */\n static getInstance(): AsyncLocalStorage<Store> {\n return this.storage;\n }\n\n /**\n * Retrieves a value from the async context store by symbol key.\n *\n * @typeParam T - The expected return type of the value.\n * @param {symbol} key - Unique symbol used as the store key.\n * @returns {T | undefined} The value found (typed) or undefined if not present.\n */\n static get<T>(key: symbol): T | undefined {\n const store = this.storage.getStore();\n return store?.[key] as T | undefined;\n }\n\n /**\n * Sets a value in the current context store by symbol key.\n *\n * @typeParam T - The value type to set.\n * @param {symbol} key - Unique symbol key.\n * @param {T} value - Value to set in context.\n * @throws {Error} If called outside an active context (not within a .run call or in the wrong async boundaries).\n */\n static set<T>(key: symbol, value: T): void {\n const store = this.storage.getStore();\n if (!store) {\n throw new Error(\n `Failed to set ${String(key)}: AsyncLocalStorage store is not initialized.`,\n );\n }\n store[key] = value;\n }\n\n /**\n * Retrieves the entire context store object for the current async context.\n *\n * @returns {Store | undefined} The current store object or undefined if called outside a context.\n */\n static getAll(): Store | undefined {\n return this.storage.getStore();\n }\n\n /**\n * Initializes a new async context and executes a callback within it.\n * This must be called at the beginning of a request or logical async flow.\n *\n * @typeParam T - The callback's return type.\n * @param {Store} store - The initial key-value store object.\n * @param {() => T} callback - The function to run within the new context.\n * @returns {T} The result of the callback function.\n */\n static run<T>(store: Store, callback: () => T): T {\n return this.storage.run(store, callback);\n }\n\n /**\n * Checks if a key exists in the current context store.\n *\n * @param {symbol} key - The symbol key to check.\n * @returns {boolean} True if the key exists, false otherwise.\n */\n static has(key: symbol): boolean {\n const store = this.storage.getStore();\n return store !== undefined && key in store;\n }\n\n /**\n * Removes a value from the current context store by symbol key.\n *\n * @param {symbol} key - The symbol key to delete.\n * @returns {boolean} True if the key was deleted, false if the key wasn't found or no active context.\n * @throws {Error} If called outside an active context.\n */\n static delete(key: symbol): boolean {\n const store = this.storage.getStore();\n if (!store) {\n throw new Error(\n `Failed to delete ${String(key)}: AsyncLocalStorage store is not initialized.`,\n );\n }\n return delete store[key];\n }\n\n /**\n * Updates multiple values in the current context store at once.\n *\n * @param {Partial<Record<symbol, unknown>>} values - Object containing symbol keys and values to update.\n * @throws {Error} If called outside an active context.\n */\n static patch(values: Partial<Record<symbol, unknown>>): void {\n const store = this.storage.getStore();\n if (!store) {\n throw new Error(\n \"Failed to patch: AsyncLocalStorage store is not initialized.\",\n );\n }\n Object.getOwnPropertySymbols(values).forEach((key) => {\n store[key] = values[key];\n });\n }\n /**\n * Executes a callback with a temporary store value that only exists during execution.\n * Original store is restored after callback completes.\n *\n * @typeParam T - The callback's return type.\n * @param {symbol} key - The symbol key to temporarily set.\n * @param {unknown} value - The temporary value.\n * @param {() => T} callback - The function to execute with the temporary value.\n * @returns {T} The result of the callback function.\n * @throws {Error} If called outside an active context.\n */\n static withValue<T>(key: symbol, value: unknown, callback: () => T): T {\n const store = this.storage.getStore();\n if (!store) {\n throw new Error(\n `Failed to set temporary value: AsyncLocalStorage store is not initialized.`,\n );\n }\n\n // Save original value\n const hasOriginal = key in store;\n const originalValue = store[key];\n\n // Set temporary value\n store[key] = value;\n\n try {\n // Run callback\n return callback();\n } finally {\n // Restore original value\n if (hasOriginal) {\n store[key] = originalValue;\n } else {\n delete store[key];\n }\n }\n }\n\n /**\n * Creates a new context that inherits values from the current context.\n *\n * @typeParam T - The callback's return type.\n * @param {Partial<Record<symbol, unknown>>} newValues - New values to add to or override in the context.\n * @param {() => T} callback - The function to execute in the new context.\n * @returns {T} The result of the callback function.\n */\n static extend<T>(\n newValues: Partial<Record<symbol, unknown>>,\n callback: () => T,\n ): T {\n const currentStore = this.storage.getStore() || {};\n\n // Create new store with current values plus new ones\n const newStore: Store = { ...currentStore };\n\n // Add new values\n Object.getOwnPropertySymbols(newValues).forEach((key) => {\n newStore[key] = newValues[key];\n });\n\n // Run with extended store\n return this.storage.run(newStore, callback);\n }\n\n /**\n * Creates Express middleware that initializes a context for each request.\n *\n * @param {(req: any) => Partial<Record<symbol, unknown>>} initialValuesFactory - Function that returns initial context values.\n * @returns Express middleware function.\n */\n static createExpressMiddleware(\n initialValuesFactory: (\n req: any,\n ) => Partial<Record<symbol, unknown>> = () => ({}),\n ) {\n return (req: any, res: any, next: any) => {\n const initialValues = initialValuesFactory(req);\n ContextStore.run(initialValues as Store, next);\n };\n }\n}\n\n/**\n * Type-safe wrapper for accessing and modifying context values with specific types.\n *\n * @typeParam T - The value type.\n */\nexport class TypedContextKey<T> {\n /**\n * Creates a new typed context key.\n *\n * @param symbol - The unique symbol for this key\n * @param defaultValue - Optional default value if key is not found\n */\n constructor(\n private symbol: symbol,\n private defaultValue?: T,\n ) {}\n\n /**\n * Gets the current value for this key.\n *\n * @returns The value or defaultValue if not found\n */\n get(): T | undefined {\n const value = ContextStore.get<T>(this.symbol);\n return value !== undefined ? value : this.defaultValue;\n }\n\n /**\n * Sets the value for this key.\n *\n * @param value The value to set\n */\n set(value: T): void {\n ContextStore.set<T>(this.symbol, value);\n }\n\n /**\n * Checks if this key exists in the context.\n *\n * @returns True if the key exists\n */\n exists(): boolean {\n return ContextStore.has(this.symbol);\n }\n\n /**\n * Deletes this key from the context.\n *\n * @returns True if the key was deleted\n */\n delete(): boolean {\n return ContextStore.delete(this.symbol);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"context-store.utils.js","sourceRoot":"","sources":["../../../src/utils/context-store.utils.ts"],"names":[],"mappings":";;;AA4BA,oCAEC;AAQD,wCAEC;AAxCD,6CAAgD;AAUhD;;;GAGG;AACU,QAAA,SAAS,GAAG;IACvB,MAAM,EAAE,MAAM,CAAC,QAAQ,CAAC;IACxB,UAAU,EAAE,MAAM,CAAC,WAAW,CAAC;IAC/B,OAAO,EAAE,MAAM,CAAC,QAAQ,CAAC;IACzB,SAAS,EAAE,MAAM,CAAC,UAAU,CAAC;IAC7B,QAAQ,EAAE,MAAM,CAAC,SAAS,CAAC;IAC3B,cAAc,EAAE,MAAM,CAAC,eAAe,CAAC;CACxC,CAAC;AAEF;;;;GAIG;AACH,SAAgB,YAAY;IAC1B,OAAO,YAAY,CAAC,GAAG,CAAS,iBAAS,CAAC,UAAU,CAAC,CAAC;AACxD,CAAC;AAED;;;;;GAKG;AACH,SAAgB,cAAc,CAAI,GAAW;IAC3C,OAAO,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IAAI,CAAC,MAAM,CAAC,CAAC;QAC/C,OAAO,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,YAAY,CAAC;IACzD,CAAC;IAED;;;;OAIG;IACH,GAAG,CAAC,KAAQ;QACV,YAAY,CAAC,GAAG,CAAI,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;IAC1C,CAAC;IAED;;;;OAIG;IACH,MAAM;QACJ,OAAO,YAAY,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IACvC,CAAC;IAED;;;;OAIG;IACH,MAAM;QACJ,OAAO,YAAY,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IAC1C,CAAC;CACF;AAhDD,0CAgDC","sourcesContent":["import { AsyncLocalStorage } from 'async_hooks';\n\n/**\n * Type representing the store object used in AsyncLocalStorage.\n * Keys must be unique symbols to ensure isolation and prevent collisions.\n */\nexport interface Store {\n [key: symbol]: unknown;\n}\n\n/**\n * Predefined symbols used as keys in AsyncLocalStorage.\n * Add new symbols here to avoid duplication.\n */\nexport const StoreKeys = {\n LOGGER: Symbol('logger'),\n REQUEST_ID: Symbol('requestId'),\n USER_ID: Symbol('userId'),\n TENANT_ID: Symbol('tenantId'),\n TRACE_ID: Symbol('traceId'),\n CORRELATION_ID: Symbol('correlationId')\n};\n\n/**\n * Retrieves the current request ID from the async context, if available.\n *\n * @returns {string | undefined} The request ID string or undefined if not present in the current context.\n */\nexport function getRequestId(): string | undefined {\n return ContextStore.get<string>(StoreKeys.REQUEST_ID);\n}\n\n/**\n * Type-safe getter for common context values.\n *\n * @param key The store key symbol\n * @returns The typed value from the store\n */\nexport function getFromContext<T>(key: symbol): T | undefined {\n return ContextStore.get<T>(key);\n}\n\n/**\n * ContextStore manages per-request scoped context using AsyncLocalStorage.\n * It allows storing and retrieving data across async calls (e.g., request ID, logger).\n *\n * Example (Express middleware):\n * ```\n * // Middleware to initialize context and logger\n * app.use((req, res, next) => {\n * const requestId = req.headers[\"x-request-id\"]?.toString() || crypto.randomUUID();\n * ContextStore.run({ [StoreKeys.REQUEST_ID]: requestId }, () => {\n * ContextStore.set(StoreKeys.LOGGER, getLogger().child({ reqId: requestId }));\n * next();\n * });\n * });\n * ```\n */\nexport class ContextStore {\n /**\n * The underlying AsyncLocalStorage instance for context.\n * @private\n */\n private static readonly storage = new AsyncLocalStorage<Store>();\n\n /**\n * Returns the raw AsyncLocalStorage instance for advanced access.\n *\n * @returns {AsyncLocalStorage<Store>} The AsyncLocalStorage instance.\n */\n static getInstance(): AsyncLocalStorage<Store> {\n return this.storage;\n }\n\n /**\n * Retrieves a value from the async context store by symbol key.\n *\n * @typeParam T - The expected return type of the value.\n * @param {symbol} key - Unique symbol used as the store key.\n * @returns {T | undefined} The value found (typed) or undefined if not present.\n */\n static get<T>(key: symbol): T | undefined {\n const store = this.storage.getStore();\n return store?.[key] as T | undefined;\n }\n\n /**\n * Sets a value in the current context store by symbol key.\n *\n * @typeParam T - The value type to set.\n * @param {symbol} key - Unique symbol key.\n * @param {T} value - Value to set in context.\n * @throws {Error} If called outside an active context (not within a .run call or in the wrong async boundaries).\n */\n static set<T>(key: symbol, value: T): void {\n const store = this.storage.getStore();\n if (!store) {\n throw new Error(`Failed to set ${String(key)}: AsyncLocalStorage store is not initialized.`);\n }\n store[key] = value;\n }\n\n /**\n * Retrieves the entire context store object for the current async context.\n *\n * @returns {Store | undefined} The current store object or undefined if called outside a context.\n */\n static getAll(): Store | undefined {\n return this.storage.getStore();\n }\n\n /**\n * Initializes a new async context and executes a callback within it.\n * This must be called at the beginning of a request or logical async flow.\n *\n * @typeParam T - The callback's return type.\n * @param {Store} store - The initial key-value store object.\n * @param {() => T} callback - The function to run within the new context.\n * @returns {T} The result of the callback function.\n */\n static run<T>(store: Store, callback: () => T): T {\n return this.storage.run(store, callback);\n }\n\n /**\n * Checks if a key exists in the current context store.\n *\n * @param {symbol} key - The symbol key to check.\n * @returns {boolean} True if the key exists, false otherwise.\n */\n static has(key: symbol): boolean {\n const store = this.storage.getStore();\n return store !== undefined && key in store;\n }\n\n /**\n * Removes a value from the current context store by symbol key.\n *\n * @param {symbol} key - The symbol key to delete.\n * @returns {boolean} True if the key was deleted, false if the key wasn't found or no active context.\n * @throws {Error} If called outside an active context.\n */\n static delete(key: symbol): boolean {\n const store = this.storage.getStore();\n if (!store) {\n throw new Error(`Failed to delete ${String(key)}: AsyncLocalStorage store is not initialized.`);\n }\n return delete store[key];\n }\n\n /**\n * Updates multiple values in the current context store at once.\n *\n * @param {Partial<Record<symbol, unknown>>} values - Object containing symbol keys and values to update.\n * @throws {Error} If called outside an active context.\n */\n static patch(values: Partial<Record<symbol, unknown>>): void {\n const store = this.storage.getStore();\n if (!store) {\n throw new Error('Failed to patch: AsyncLocalStorage store is not initialized.');\n }\n Object.getOwnPropertySymbols(values).forEach(key => {\n store[key] = values[key];\n });\n }\n /**\n * Executes a callback with a temporary store value that only exists during execution.\n * Original store is restored after callback completes.\n *\n * @typeParam T - The callback's return type.\n * @param {symbol} key - The symbol key to temporarily set.\n * @param {unknown} value - The temporary value.\n * @param {() => T} callback - The function to execute with the temporary value.\n * @returns {T} The result of the callback function.\n * @throws {Error} If called outside an active context.\n */\n static withValue<T>(key: symbol, value: unknown, callback: () => T): T {\n const store = this.storage.getStore();\n if (!store) {\n throw new Error(`Failed to set temporary value: AsyncLocalStorage store is not initialized.`);\n }\n\n // Save original value\n const hasOriginal = key in store;\n const originalValue = store[key];\n\n // Set temporary value\n store[key] = value;\n\n try {\n // Run callback\n return callback();\n } finally {\n // Restore original value\n if (hasOriginal) {\n store[key] = originalValue;\n } else {\n delete store[key];\n }\n }\n }\n\n /**\n * Creates a new context that inherits values from the current context.\n *\n * @typeParam T - The callback's return type.\n * @param {Partial<Record<symbol, unknown>>} newValues - New values to add to or override in the context.\n * @param {() => T} callback - The function to execute in the new context.\n * @returns {T} The result of the callback function.\n */\n static extend<T>(newValues: Partial<Record<symbol, unknown>>, callback: () => T): T {\n const currentStore = this.storage.getStore() || {};\n\n // Create new store with current values plus new ones\n const newStore: Store = { ...currentStore };\n\n // Add new values\n Object.getOwnPropertySymbols(newValues).forEach(key => {\n newStore[key] = newValues[key];\n });\n\n // Run with extended store\n return this.storage.run(newStore, callback);\n }\n\n /**\n * Creates Express middleware that initializes a context for each request.\n *\n * @param {(req: any) => Partial<Record<symbol, unknown>>} initialValuesFactory - Function that returns initial context values.\n * @returns Express middleware function.\n */\n static createExpressMiddleware(initialValuesFactory: (req: any) => Partial<Record<symbol, unknown>> = () => ({})) {\n return (req: any, res: any, next: any) => {\n const initialValues = initialValuesFactory(req);\n ContextStore.run(initialValues as Store, next);\n };\n }\n}\n\n/**\n * Type-safe wrapper for accessing and modifying context values with specific types.\n *\n * @typeParam T - The value type.\n */\nexport class TypedContextKey<T> {\n /**\n * Creates a new typed context key.\n *\n * @param symbol - The unique symbol for this key\n * @param defaultValue - Optional default value if key is not found\n */\n constructor(\n private symbol: symbol,\n private defaultValue?: T\n ) {}\n\n /**\n * Gets the current value for this key.\n *\n * @returns The value or defaultValue if not found\n */\n get(): T | undefined {\n const value = ContextStore.get<T>(this.symbol);\n return value !== undefined ? value : this.defaultValue;\n }\n\n /**\n * Sets the value for this key.\n *\n * @param value The value to set\n */\n set(value: T): void {\n ContextStore.set<T>(this.symbol, value);\n }\n\n /**\n * Checks if this key exists in the context.\n *\n * @returns True if the key exists\n */\n exists(): boolean {\n return ContextStore.has(this.symbol);\n }\n\n /**\n * Deletes this key from the context.\n *\n * @returns True if the key was deleted\n */\n delete(): boolean {\n return ContextStore.delete(this.symbol);\n }\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { BinaryToTextEncoding, CipherGCMTypes } from
|
|
2
|
-
export type BufferEncoding =
|
|
1
|
+
import { BinaryToTextEncoding, CipherGCMTypes } from 'crypto';
|
|
2
|
+
export type BufferEncoding = 'ascii' | 'utf8' | 'utf-8' | 'utf16le' | 'utf-16le' | 'ucs2' | 'ucs-2' | 'base64' | 'base64url' | 'latin1' | 'binary' | 'hex';
|
|
3
3
|
/**
|
|
4
4
|
* Generates an HMAC digest using the specified algorithm and secret key.
|
|
5
5
|
*
|
|
@@ -26,7 +26,7 @@ const util_1 = require("util");
|
|
|
26
26
|
* @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding ('hex', 'base64', etc).
|
|
27
27
|
* @returns {string} HMAC digest as a string.
|
|
28
28
|
*/
|
|
29
|
-
function hmac(algorithm, input, secret, encoding =
|
|
29
|
+
function hmac(algorithm, input, secret, encoding = 'hex') {
|
|
30
30
|
return (0, crypto_1.createHmac)(algorithm, secret).update(input).digest(encoding);
|
|
31
31
|
}
|
|
32
32
|
/**
|
|
@@ -37,7 +37,7 @@ function hmac(algorithm, input, secret, encoding = "hex") {
|
|
|
37
37
|
* @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding ('hex', 'base64', etc).
|
|
38
38
|
* @returns {string} Hash digest as a string.
|
|
39
39
|
*/
|
|
40
|
-
function hash(algorithm, input, encoding =
|
|
40
|
+
function hash(algorithm, input, encoding = 'hex') {
|
|
41
41
|
return (0, crypto_1.createHash)(algorithm).update(input).digest(encoding);
|
|
42
42
|
}
|
|
43
43
|
/**
|
|
@@ -48,7 +48,7 @@ function hash(algorithm, input, encoding = "hex") {
|
|
|
48
48
|
* @returns {string} SHA-256 HMAC digest as a string.
|
|
49
49
|
*/
|
|
50
50
|
function sha256Hmac(input, secret) {
|
|
51
|
-
return hmac(
|
|
51
|
+
return hmac('sha256', input, secret);
|
|
52
52
|
}
|
|
53
53
|
/**
|
|
54
54
|
* Generates a SHA1 hash digest.
|
|
@@ -57,8 +57,8 @@ function sha256Hmac(input, secret) {
|
|
|
57
57
|
* @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.
|
|
58
58
|
* @returns {string} SHA-1 hash as a string.
|
|
59
59
|
*/
|
|
60
|
-
function sha1(input, encoding =
|
|
61
|
-
return hash(
|
|
60
|
+
function sha1(input, encoding = 'hex') {
|
|
61
|
+
return hash('sha1', input, encoding);
|
|
62
62
|
}
|
|
63
63
|
/**
|
|
64
64
|
* Generates a SHA256 hash digest.
|
|
@@ -67,8 +67,8 @@ function sha1(input, encoding = "hex") {
|
|
|
67
67
|
* @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.
|
|
68
68
|
* @returns {string} SHA-256 hash as a string.
|
|
69
69
|
*/
|
|
70
|
-
function sha256(input, encoding =
|
|
71
|
-
return hash(
|
|
70
|
+
function sha256(input, encoding = 'hex') {
|
|
71
|
+
return hash('sha256', input, encoding);
|
|
72
72
|
}
|
|
73
73
|
/**
|
|
74
74
|
* Generates an MD5 hash digest.
|
|
@@ -77,7 +77,7 @@ function sha256(input, encoding = "hex") {
|
|
|
77
77
|
* @returns {string} MD5 hash as a string.
|
|
78
78
|
*/
|
|
79
79
|
function md5(input) {
|
|
80
|
-
return hash(
|
|
80
|
+
return hash('md5', input);
|
|
81
81
|
}
|
|
82
82
|
/**
|
|
83
83
|
* Generates a cryptographically strong random string by hashing a random UUID with SHA-256.
|
|
@@ -103,7 +103,7 @@ function generateRandomBytes(byteLength = 32) {
|
|
|
103
103
|
* @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.
|
|
104
104
|
* @returns {string} Random string in specified encoding.
|
|
105
105
|
*/
|
|
106
|
-
function generateRandomBytesAsString(byteLength = 32, encoding =
|
|
106
|
+
function generateRandomBytesAsString(byteLength = 32, encoding = 'hex') {
|
|
107
107
|
return (0, crypto_1.randomBytes)(byteLength).toString(encoding);
|
|
108
108
|
}
|
|
109
109
|
/**
|
|
@@ -113,10 +113,10 @@ function generateRandomBytesAsString(byteLength = 32, encoding = "hex") {
|
|
|
113
113
|
* @param {number} [byteLength=24] - Number of random bytes to generate.
|
|
114
114
|
* @returns {string} Formatted API key.
|
|
115
115
|
*/
|
|
116
|
-
function generateApiKey(prefix =
|
|
117
|
-
const randomString = generateRandomBytesAsString(byteLength,
|
|
116
|
+
function generateApiKey(prefix = '', byteLength = 24) {
|
|
117
|
+
const randomString = generateRandomBytesAsString(byteLength, 'base64');
|
|
118
118
|
const key = randomString
|
|
119
|
-
.replace(/[+/=]/g,
|
|
119
|
+
.replace(/[+/=]/g, '') // Remove non-URL-safe characters
|
|
120
120
|
.substring(0, 32); // Limit length
|
|
121
121
|
return prefix ? `${prefix}_${key}` : key;
|
|
122
122
|
}
|
|
@@ -128,7 +128,7 @@ function generateApiKey(prefix = "", byteLength = 24) {
|
|
|
128
128
|
* @returns {boolean} True if values are equal
|
|
129
129
|
*/
|
|
130
130
|
function safeCompare(a, b) {
|
|
131
|
-
if (typeof a ===
|
|
131
|
+
if (typeof a === 'string' && typeof b === 'string') {
|
|
132
132
|
// Convert strings to buffers
|
|
133
133
|
const bufA = Buffer.from(a);
|
|
134
134
|
const bufB = Buffer.from(b);
|
|
@@ -137,14 +137,13 @@ function safeCompare(a, b) {
|
|
|
137
137
|
return false;
|
|
138
138
|
return (0, crypto_1.timingSafeEqual)(bufA, bufB);
|
|
139
139
|
}
|
|
140
|
-
else if ((a instanceof Buffer || a instanceof Uint8Array) &&
|
|
141
|
-
(b instanceof Buffer || b instanceof Uint8Array)) {
|
|
140
|
+
else if ((a instanceof Buffer || a instanceof Uint8Array) && (b instanceof Buffer || b instanceof Uint8Array)) {
|
|
142
141
|
// Compare lengths first
|
|
143
142
|
if (a.length !== b.length)
|
|
144
143
|
return false;
|
|
145
144
|
return (0, crypto_1.timingSafeEqual)(a instanceof Buffer ? a : Buffer.from(a), b instanceof Buffer ? b : Buffer.from(b));
|
|
146
145
|
}
|
|
147
|
-
throw new Error(
|
|
146
|
+
throw new Error('Cannot compare: inputs must be strings, Buffers, or Uint8Arrays');
|
|
148
147
|
}
|
|
149
148
|
// Promisified version of scrypt for key derivation
|
|
150
149
|
const scryptAsync = (0, util_1.promisify)(crypto_1.scrypt);
|
|
@@ -157,36 +156,32 @@ const scryptAsync = (0, util_1.promisify)(crypto_1.scrypt);
|
|
|
157
156
|
* @returns {Promise<EncryptionResult>} Encrypted data with metadata
|
|
158
157
|
*/
|
|
159
158
|
async function encrypt(data, key, options = {}) {
|
|
160
|
-
const algorithm = options.algorithm ||
|
|
161
|
-
const inputEncoding = options.inputEncoding ||
|
|
162
|
-
const outputEncoding = options.outputEncoding ||
|
|
159
|
+
const algorithm = options.algorithm || 'aes-256-gcm';
|
|
160
|
+
const inputEncoding = options.inputEncoding || 'utf8';
|
|
161
|
+
const outputEncoding = options.outputEncoding || 'hex';
|
|
163
162
|
// Generate a random IV
|
|
164
163
|
const iv = (0, crypto_1.randomBytes)(16);
|
|
165
164
|
// Derive key using scrypt if key is a string (passphrase)
|
|
166
|
-
const derivedKey = typeof key ===
|
|
165
|
+
const derivedKey = typeof key === 'string' ? await scryptAsync(key, iv.slice(0, 8), 32) : key;
|
|
167
166
|
// Create cipher
|
|
168
167
|
const cipher = (0, crypto_1.createCipheriv)(algorithm, derivedKey, iv);
|
|
169
168
|
// Encrypt the data
|
|
170
169
|
let ciphertext;
|
|
171
|
-
if (typeof data ===
|
|
170
|
+
if (typeof data === 'string') {
|
|
172
171
|
ciphertext = cipher.update(data, inputEncoding, outputEncoding);
|
|
173
172
|
ciphertext += cipher.final(outputEncoding);
|
|
174
173
|
}
|
|
175
174
|
else {
|
|
176
175
|
const encrypted = Buffer.concat([cipher.update(data), cipher.final()]);
|
|
177
|
-
ciphertext = outputEncoding
|
|
178
|
-
? encrypted.toString(outputEncoding)
|
|
179
|
-
: encrypted;
|
|
176
|
+
ciphertext = outputEncoding ? encrypted.toString(outputEncoding) : encrypted;
|
|
180
177
|
}
|
|
181
178
|
// Get authentication tag if using GCM mode
|
|
182
|
-
const authTag = algorithm.includes(
|
|
183
|
-
? cipher.getAuthTag()
|
|
184
|
-
: undefined;
|
|
179
|
+
const authTag = algorithm.includes('gcm') ? cipher.getAuthTag() : undefined;
|
|
185
180
|
return {
|
|
186
181
|
ciphertext,
|
|
187
182
|
iv,
|
|
188
183
|
authTag,
|
|
189
|
-
algorithm
|
|
184
|
+
algorithm
|
|
190
185
|
};
|
|
191
186
|
}
|
|
192
187
|
/**
|
|
@@ -198,30 +193,25 @@ async function encrypt(data, key, options = {}) {
|
|
|
198
193
|
* @returns {Promise<string | Buffer>} Decrypted data
|
|
199
194
|
*/
|
|
200
195
|
async function decrypt(encryptedData, key, options = {}) {
|
|
201
|
-
const algorithm = options.algorithm || encryptedData.algorithm ||
|
|
202
|
-
const inputEncoding = options.inputEncoding ||
|
|
203
|
-
const outputEncoding = options.outputEncoding ||
|
|
196
|
+
const algorithm = options.algorithm || encryptedData.algorithm || 'aes-256-gcm';
|
|
197
|
+
const inputEncoding = options.inputEncoding || 'hex';
|
|
198
|
+
const outputEncoding = options.outputEncoding || 'utf8';
|
|
204
199
|
// Derive key using scrypt if key is a string (passphrase)
|
|
205
|
-
const derivedKey = typeof key ===
|
|
206
|
-
? await scryptAsync(key, encryptedData.iv.slice(0, 8), 32)
|
|
207
|
-
: key;
|
|
200
|
+
const derivedKey = typeof key === 'string' ? await scryptAsync(key, encryptedData.iv.slice(0, 8), 32) : key;
|
|
208
201
|
// Create decipher
|
|
209
202
|
const decipher = (0, crypto_1.createDecipheriv)(algorithm, derivedKey, encryptedData.iv);
|
|
210
203
|
// Set auth tag if using GCM mode
|
|
211
|
-
if (encryptedData.authTag && algorithm.includes(
|
|
204
|
+
if (encryptedData.authTag && algorithm.includes('gcm')) {
|
|
212
205
|
decipher.setAuthTag(encryptedData.authTag);
|
|
213
206
|
}
|
|
214
207
|
// Decrypt the data
|
|
215
208
|
let decrypted;
|
|
216
|
-
if (typeof encryptedData.ciphertext ===
|
|
209
|
+
if (typeof encryptedData.ciphertext === 'string') {
|
|
217
210
|
decrypted = decipher.update(encryptedData.ciphertext, inputEncoding, outputEncoding);
|
|
218
211
|
decrypted += decipher.final(outputEncoding);
|
|
219
212
|
}
|
|
220
213
|
else {
|
|
221
|
-
const result = Buffer.concat([
|
|
222
|
-
decipher.update(encryptedData.ciphertext),
|
|
223
|
-
decipher.final(),
|
|
224
|
-
]);
|
|
214
|
+
const result = Buffer.concat([decipher.update(encryptedData.ciphertext), decipher.final()]);
|
|
225
215
|
decrypted = outputEncoding ? result.toString(outputEncoding) : result;
|
|
226
216
|
}
|
|
227
217
|
return decrypted;
|
|
@@ -240,9 +230,9 @@ function createSignedToken(payload, secret, expiresInSeconds = 3600) {
|
|
|
240
230
|
// Convert to string
|
|
241
231
|
const payloadStr = JSON.stringify(tokenPayload);
|
|
242
232
|
// Base64 encode the payload
|
|
243
|
-
const base64Payload = Buffer.from(payloadStr).toString(
|
|
233
|
+
const base64Payload = Buffer.from(payloadStr).toString('base64url');
|
|
244
234
|
// Create signature
|
|
245
|
-
const signature = hmac(
|
|
235
|
+
const signature = hmac('sha256', base64Payload, secret, 'base64url');
|
|
246
236
|
// Combine payload and signature
|
|
247
237
|
return `${base64Payload}.${signature}`;
|
|
248
238
|
}
|
|
@@ -256,15 +246,15 @@ function createSignedToken(payload, secret, expiresInSeconds = 3600) {
|
|
|
256
246
|
function verifySignedToken(token, secret) {
|
|
257
247
|
try {
|
|
258
248
|
// Split token into parts
|
|
259
|
-
const [payloadB64, signature] = token.split(
|
|
249
|
+
const [payloadB64, signature] = token.split('.');
|
|
260
250
|
if (!payloadB64 || !signature)
|
|
261
251
|
return null;
|
|
262
252
|
// Verify signature
|
|
263
|
-
const expectedSignature = hmac(
|
|
253
|
+
const expectedSignature = hmac('sha256', payloadB64, secret, 'base64url');
|
|
264
254
|
if (!safeCompare(signature, expectedSignature))
|
|
265
255
|
return null;
|
|
266
256
|
// Decode payload
|
|
267
|
-
const payloadStr = Buffer.from(payloadB64,
|
|
257
|
+
const payloadStr = Buffer.from(payloadB64, 'base64url').toString('utf8');
|
|
268
258
|
const payload = JSON.parse(payloadStr);
|
|
269
259
|
// Check expiration
|
|
270
260
|
if (payload.exp && payload.exp < Math.floor(Date.now() / 1000)) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"crypto.ut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AO,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(\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 function 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 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(\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 function 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 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(\n byteLength: number = 32,\n encoding: BinaryToTextEncoding = \"hex\",\n): 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(\n prefix: string = \"\",\n byteLength: number = 24,\n): 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(\n a: string | Buffer | Uint8Array,\n b: string | Buffer | Uint8Array,\n): 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 (\n (a instanceof Buffer || a instanceof Uint8Array) &&\n (b instanceof Buffer || b instanceof Uint8Array)\n ) {\n // Compare lengths first\n if (a.length !== b.length) return false;\n\n return timingSafeEqual(\n a instanceof Buffer ? a : Buffer.from(a),\n b instanceof Buffer ? b : Buffer.from(b),\n );\n }\n\n throw new Error(\n \"Cannot compare: inputs must be strings, Buffers, or Uint8Arrays\",\n );\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>(\n scrypt,\n);\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 =\n 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(\n data,\n inputEncoding,\n outputEncoding as BufferEncoding,\n );\n ciphertext += cipher.final(outputEncoding as BufferEncoding);\n } else {\n const encrypted = Buffer.concat([cipher.update(data), cipher.final()]);\n ciphertext = outputEncoding\n ? encrypted.toString(outputEncoding)\n : encrypted;\n }\n\n // Get authentication tag if using GCM mode\n const authTag = algorithm.includes(\"gcm\")\n ? (cipher as any).getAuthTag()\n : 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 =\n 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 =\n typeof key === \"string\"\n ? await scryptAsync(key, encryptedData.iv.slice(0, 8), 32)\n : 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(\n encryptedData.ciphertext,\n inputEncoding as BufferEncoding,\n outputEncoding,\n );\n decrypted += decipher.final(outputEncoding);\n } else {\n const result = Buffer.concat([\n decipher.update(encryptedData.ciphertext),\n decipher.final(),\n ]);\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(\n token: string,\n secret: string,\n): 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"]}
|
|
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,MAAc;IACtD,OAAO,IAAI,CAAC,QAAQ,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC;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I,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"]}
|
|
@@ -1,21 +1,20 @@
|
|
|
1
|
-
import
|
|
2
|
-
|
|
1
|
+
import 'reflect-metadata';
|
|
2
|
+
interface Request {
|
|
3
3
|
query: any;
|
|
4
4
|
params: any;
|
|
5
5
|
body?: any;
|
|
6
6
|
[key: string]: any;
|
|
7
7
|
}
|
|
8
|
-
|
|
8
|
+
interface Response {
|
|
9
9
|
json: (body: any) => void;
|
|
10
10
|
headersSent: boolean;
|
|
11
11
|
[key: string]: any;
|
|
12
12
|
}
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
13
|
+
type NextFunction = (err?: any) => void;
|
|
14
|
+
type RequestHandler = (req: Request, res: Response, next: NextFunction) => any;
|
|
15
|
+
interface Router {
|
|
16
16
|
[method: string]: (path: string, ...handlers: RequestHandler[]) => void;
|
|
17
17
|
}
|
|
18
|
-
export type HttpMethod = "get" | "post" | "put" | "patch" | "delete" | "options" | "head" | "trace" | "connect";
|
|
19
18
|
export declare const Get: (path: string) => MethodDecorator;
|
|
20
19
|
export declare const Post: (path: string) => MethodDecorator;
|
|
21
20
|
export declare const Put: (path: string) => MethodDecorator;
|
|
@@ -37,4 +36,5 @@ export declare function Header(name: string, value: string): MethodDecorator;
|
|
|
37
36
|
export declare function Before(fn: Function): MethodDecorator;
|
|
38
37
|
export declare function After(fn: Function): MethodDecorator;
|
|
39
38
|
export declare function registerControllers(router: Router, controllers: any[]): void;
|
|
39
|
+
export {};
|
|
40
40
|
//# sourceMappingURL=decorators.utils.d.ts.map
|
|
@@ -11,9 +11,9 @@ exports.After = After;
|
|
|
11
11
|
exports.registerControllers = registerControllers;
|
|
12
12
|
require("reflect-metadata");
|
|
13
13
|
// --- End sample Express interfaces ---
|
|
14
|
-
const ROUTES_KEY = Symbol(
|
|
15
|
-
const MIDDLEWARE_KEY = Symbol(
|
|
16
|
-
const PARAMS_KEY = Symbol(
|
|
14
|
+
const ROUTES_KEY = Symbol('routes');
|
|
15
|
+
const MIDDLEWARE_KEY = Symbol('middlewares');
|
|
16
|
+
const PARAMS_KEY = Symbol('params');
|
|
17
17
|
// ---- Route Decorators ----
|
|
18
18
|
function createRouteDecorator(method) {
|
|
19
19
|
return (path) => {
|
|
@@ -22,25 +22,25 @@ function createRouteDecorator(method) {
|
|
|
22
22
|
routes.push({
|
|
23
23
|
path,
|
|
24
24
|
method,
|
|
25
|
-
handlerName: propertyKey
|
|
25
|
+
handlerName: propertyKey
|
|
26
26
|
});
|
|
27
27
|
Reflect.defineMetadata(ROUTES_KEY, routes, target.constructor);
|
|
28
28
|
};
|
|
29
29
|
};
|
|
30
30
|
}
|
|
31
|
-
exports.Get = createRouteDecorator(
|
|
32
|
-
exports.Post = createRouteDecorator(
|
|
33
|
-
exports.Put = createRouteDecorator(
|
|
34
|
-
exports.Patch = createRouteDecorator(
|
|
35
|
-
exports.Delete = createRouteDecorator(
|
|
36
|
-
exports.Options = createRouteDecorator(
|
|
37
|
-
exports.Head = createRouteDecorator(
|
|
38
|
-
exports.Trace = createRouteDecorator(
|
|
39
|
-
exports.Connect = createRouteDecorator(
|
|
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
40
|
// ---- Controller Decorator ----
|
|
41
41
|
function Controller(basePath) {
|
|
42
|
-
return
|
|
43
|
-
Reflect.defineMetadata(
|
|
42
|
+
return target => {
|
|
43
|
+
Reflect.defineMetadata('basePath', basePath, target);
|
|
44
44
|
};
|
|
45
45
|
}
|
|
46
46
|
// ---- Middleware Decorator ----
|
|
@@ -62,20 +62,20 @@ function createParamDecorator(type, key) {
|
|
|
62
62
|
};
|
|
63
63
|
};
|
|
64
64
|
}
|
|
65
|
-
exports.Query = createParamDecorator(
|
|
66
|
-
exports.Param = createParamDecorator(
|
|
67
|
-
exports.Body = createParamDecorator(
|
|
68
|
-
exports.Req = createParamDecorator(
|
|
69
|
-
exports.Res = createParamDecorator(
|
|
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
70
|
// Custom HTTP status code decorator
|
|
71
|
-
const HTTP_CODE_KEY = Symbol(
|
|
71
|
+
const HTTP_CODE_KEY = Symbol('httpCode');
|
|
72
72
|
function HttpCode(status) {
|
|
73
73
|
return (target, propertyKey, descriptor) => {
|
|
74
74
|
Reflect.defineMetadata(HTTP_CODE_KEY, status, target, propertyKey);
|
|
75
75
|
};
|
|
76
76
|
}
|
|
77
77
|
// Custom header decorator
|
|
78
|
-
const HEADER_KEY = Symbol(
|
|
78
|
+
const HEADER_KEY = Symbol('headers');
|
|
79
79
|
function Header(name, value) {
|
|
80
80
|
return (target, propertyKey, descriptor) => {
|
|
81
81
|
const headers = Reflect.getMetadata(HEADER_KEY, target, propertyKey) || {};
|
|
@@ -84,8 +84,8 @@ function Header(name, value) {
|
|
|
84
84
|
};
|
|
85
85
|
}
|
|
86
86
|
// Before/After hooks (not Express middleware, but can be used for logging, etc.)
|
|
87
|
-
const BEFORE_KEY = Symbol(
|
|
88
|
-
const AFTER_KEY = Symbol(
|
|
87
|
+
const BEFORE_KEY = Symbol('before');
|
|
88
|
+
const AFTER_KEY = Symbol('after');
|
|
89
89
|
function Before(fn) {
|
|
90
90
|
return (target, propertyKey, descriptor) => {
|
|
91
91
|
const hooks = Reflect.getMetadata(BEFORE_KEY, target, propertyKey) || [];
|
|
@@ -102,9 +102,9 @@ function After(fn) {
|
|
|
102
102
|
}
|
|
103
103
|
// ---- Register Controllers ----
|
|
104
104
|
function registerControllers(router, controllers) {
|
|
105
|
-
controllers.forEach(
|
|
105
|
+
controllers.forEach(ControllerClass => {
|
|
106
106
|
const instance = new ControllerClass();
|
|
107
|
-
const basePath = Reflect.getMetadata(
|
|
107
|
+
const basePath = Reflect.getMetadata('basePath', ControllerClass) || '';
|
|
108
108
|
const routes = Reflect.getMetadata(ROUTES_KEY, ControllerClass) || [];
|
|
109
109
|
routes.forEach(({ path, method, handlerName }) => {
|
|
110
110
|
const middlewares = Reflect.getMetadata(MIDDLEWARE_KEY, instance, handlerName) || [];
|
|
@@ -123,19 +123,19 @@ function registerControllers(router, controllers) {
|
|
|
123
123
|
params.forEach(({ index, type, key }) => {
|
|
124
124
|
var _a;
|
|
125
125
|
switch (type) {
|
|
126
|
-
case
|
|
126
|
+
case 'query':
|
|
127
127
|
args[index] = key ? req.query[key] : req.query;
|
|
128
128
|
break;
|
|
129
|
-
case
|
|
129
|
+
case 'param':
|
|
130
130
|
args[index] = key ? req.params[key] : req.params;
|
|
131
131
|
break;
|
|
132
|
-
case
|
|
132
|
+
case 'body':
|
|
133
133
|
args[index] = key ? (_a = req.body) === null || _a === void 0 ? void 0 : _a[key] : req.body;
|
|
134
134
|
break;
|
|
135
|
-
case
|
|
135
|
+
case 'req':
|
|
136
136
|
args[index] = req;
|
|
137
137
|
break;
|
|
138
|
-
case
|
|
138
|
+
case 'res':
|
|
139
139
|
args[index] = res;
|
|
140
140
|
break;
|
|
141
141
|
}
|
|
@@ -144,7 +144,7 @@ function registerControllers(router, controllers) {
|
|
|
144
144
|
const result = instance[handlerName](...args);
|
|
145
145
|
// Support both sync and async handlers
|
|
146
146
|
const awaited = result instanceof Promise ? await result : result;
|
|
147
|
-
if (!res.headersSent && typeof awaited !==
|
|
147
|
+
if (!res.headersSent && typeof awaited !== 'undefined') {
|
|
148
148
|
if (httpCode)
|
|
149
149
|
(_a = res.status) === null || _a === void 0 ? void 0 : _a.call(res, httpCode);
|
|
150
150
|
for (const [k, v] of Object.entries(headers))
|