@ugo-code/streamline.js
Version:
A utility module which provides straight-forward, powerful functions for working with asynchronous JavaScript
57 lines (56 loc) • 2.77 kB
TypeScript
/**
* 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 a TTL.
*
* @param plaintext The string to encrypt.
* @param secretKey The secret key for key derivation.
* @param ttl The Time-To-Live in milliseconds. Pass `null` to disable expiration. Defaults to 1 hour.
* @returns A Promise resolving to a URL-safe, Base64 encoded string containing: expiration + salt + iv + encryptedData.
* @throws {CryptoError} If the environment is unsupported or encryption fails.
*/
export declare function encryptString(plaintext: string, secretKey: string, options?: {
ttl?: number | null;
}): Promise<string>;
/**
* Decrypts a string that was encrypted with encryptString, checking its TTL.
*
* @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} With codes:
* - `EXPIRED`: The data's TTL has passed.
* - `INVALID_DATA`: The encrypted payload is malformed or too short.
* - `DECRYPTION_FAILED`: The secret key is likely incorrect or the data was tampered with.
* - `UNSUPPORTED_ENVIRONMENT`: Web Crypto API is not available.
*/
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>;