UNPKG

@ugo-code/streamline.js

Version:

A utility module which provides straight-forward, powerful functions for working with asynchronous JavaScript

58 lines (57 loc) 2.77 kB
/** * A set of specific error codes for cryptographic operations. */ export type CryptoErrorCode = "UNSUPPORTED_ENVIRONMENT" | "ENCRYPTION_FAILED" | "DECRYPTION_FAILED" | "INVALID_DATA" | "EXPIRED"; /** * Custom error class for handling specific cryptographic failures. * This allows for robust error handling using `instanceof` or by checking the `code`. */ export declare class CryptoError extends Error { readonly code: CryptoErrorCode; readonly cause?: Error; constructor(code: CryptoErrorCode, message: string, cause?: Error); } /** * Encrypts a plaintext string using AES-256-GCM, embedding TTL and iteration count. * * @param plaintext The string to encrypt. * @param secretKey The secret key for key derivation. * @param options Configuration for TTL and PBKDF2 iterations. * @param options.ttl The Time-To-Live in milliseconds. Pass `null` for no expiration. Defaults to 1 hour. * @param options.pbkdf2Iterations The number of iterations for key derivation. * **WARNING**: Reducing this from the default weakens security. * @returns A Promise resolving to a URL-safe, Base64 encoded string. * @throws {CryptoError} If the environment is unsupported or encryption fails. */ export declare function encryptString(plaintext: string, secretKey: string, options?: { ttl?: number | null; pbkdf2Iterations?: number; }): Promise<string>; /** * Decrypts a string that was encrypted with encryptString, checking its TTL. * The iteration count is automatically extracted from the payload. * * @param encryptedDataB64 The Base64 encoded string from encryptString. * @param secretKey The *same* secret key used for encryption. * @returns A Promise resolving to the original plaintext string. * @throws {CryptoError} */ export declare function decryptString(encryptedDataB64: string, secretKey: string): Promise<string>; /** * Asynchronously calculates a deterministic SHA-256 hash of any JavaScript object. * * This function handles complex data structures including Maps, Sets, Dates, * BigInts, and circular references. It creates a consistent, sorted string * representation of the object, ensuring that the same logical object always * produces the same hash, regardless of key order or environment. * * @param obj The object to hash. This can be any serializable JavaScript value. * @returns A promise that resolves to a string containing the hexadecimal representation of the SHA-256 hash. * @example * const obj1 = { b: 2, a: { c: 3, d: new Set([1, 2]) } }; * const obj2 = { a: { d: new Set([2, 1]), c: 3 }, b: 2 }; * const hash1 = await hashObject(obj1); * const hash2 = await hashObject(obj2); * // hash1 will be identical to hash2 */ export declare function hashObject(obj: any): Promise<string>;