UNPKG

meru-stablecoin-lib

Version:

A comprehensive TypeScript library for stablecoin operations including encryption utilities, error handling, and validation tools

230 lines (176 loc) 5.83 kB
# Meru Stablecoin Library A comprehensive TypeScript library for stablecoin operations including encryption utilities, error handling, and validation tools. ## Features - 🔐 **Encryption Utilities**: Secure API key generation, signature creation, and data encryption - 🚨 **Error Handling**: Standardized error and success response formats - ✅ **Validation**: Custom validation error handling - 📦 **TypeScript**: Full TypeScript support with type definitions - 🛡️ **Security**: HMAC-SHA256 signatures and AES-256-CBC encryption - ☁️ **AWS KMS Integration**: Optional AWS KMS for secret management with environment fallback ## Installation ```bash npm install meru-stablecoin-lib ``` ## Quick Start ```typescript import { EncryptionUtil, kmsManager, sendErrorResponse, sendSuccessResponse, ValidationError } from 'meru-stablecoin-lib'; // Initialize encryption with KMS (if available) await EncryptionUtil.initialize(); // Generate API keys const { publicKey, secretKey, hashedSecret } = EncryptionUtil.generateApiKeys(); // Create signatures const signature = EncryptionUtil.createSignature('payload', 'secret-key'); // Encrypt data const encrypted = EncryptionUtil.encrypt('sensitive-data'); // Get secrets from KMS or environment const secret = await kmsManager.getSecret('mySecret', 'fallback-value'); ``` ## API Reference ### EncryptionUtil #### `generateApiKeys()` Generates a new set of API keys with hashed secret. ```typescript const keys = EncryptionUtil.generateApiKeys(); // Returns: { publicKey: string, secretKey: string, hashedSecret: string } ``` #### `createSignature(payload: string, secretKey: string): string` Creates an HMAC-SHA256 signature for the given payload. #### `verifySignature(secretKey: string, encryptedPrivateKey: string): boolean` Verifies a signature using timing-safe comparison. #### `encrypt(text: string): string` Encrypts text using AES-256-CBC encryption. #### `initialize(): Promise<void>` Initializes the encryption key from KMS or environment variables. ### KMS Integration #### `kmsManager.getSecret(secretName: string, fallbackValue: string): Promise<string>` Retrieves a secret from AWS KMS or falls back to environment variables. ```typescript const secret = await kmsManager.getSecret('encryptionKey', 'fallback-key'); ``` #### `kmsManager.encryptSecret(secretValue: string, secretName: string): Promise<string | null>` Encrypts a secret using AWS KMS. ```typescript const encrypted = await kmsManager.encryptSecret('my-secret', 'secretName'); ``` ### Error Handling #### `sendErrorResponse(res, statusCode, errorCode, message, details?, path?, suggestion?, requestId?, documentation_url?)` Sends a standardized error response. ```typescript sendErrorResponse( res, 404, 'RESOURCE_NOT_FOUND', 'User not found', 'The requested user does not exist', '/api/users/123', 'Check the user ID and try again' ); ``` #### `sendSuccessResponse(res, data, message?, statusCode?)` Sends a standardized success response. ```typescript sendSuccessResponse( res, { user: { id: 1, name: 'John' } }, 'User retrieved successfully', 200 ); ``` ### ValidationError Custom error class for validation failures. ```typescript throw new ValidationError('Validation failed', { email: ['Email is required', 'Email format is invalid'], password: ['Password must be at least 8 characters'] }); ``` ## Response Formats ### Error Response Format ```json { "status": "error", "statusCode": 400, "error": { "code": "VALIDATION_ERROR", "message": "Validation failed", "details": "Multiple validation errors occurred", "timestamp": "2024-01-01T00:00:00.000Z", "path": "/api/users", "suggestion": "Check the request body and try again" }, "requestId": "req_123456", "documentation_url": "https://docs.example.com/errors" } ``` ### Success Response Format ```json { "status": "success", "statusCode": 200, "data": { "user": { "id": 1, "name": "John Doe" } }, "message": "User created successfully", "timestamp": "2024-01-01T00:00:00.000Z" } ``` ## Development ### Prerequisites - Node.js >= 16.0.0 - npm or yarn ### Setup ```bash # Install dependencies npm install # Install AWS SDK (optional, for KMS support) npm install @aws-sdk/client-kms # Build the library npm run build # Development mode with watch npm run dev ``` ### Environment Variables The library supports both AWS KMS and environment variables for secret management: #### KMS Configuration (Optional) ```bash AWS_KMS_ENABLED=true AWS_REGION=us-east-1 AWS_KMS_KEY_ID=your-kms-key-id AWS_KMS_ALIAS=alias/your-kms-alias ``` #### KMS Encrypted Secrets ```bash KMS_ENCRYPTIONKEY=base64-encoded-encrypted-key KMS_MYSECRET=base64-encoded-encrypted-secret ``` #### Fallback Environment Variables ```bash ENCRYPTION_KEY=your-fallback-encryption-key ``` ### Publishing ```bash # Build and publish to npm npm publish ``` ## License Proprietary License - This software is for use by Meru Team and authorized partners only. See [LICENSE](LICENSE) file for details. ## Contributing 1. Fork the repository 2. Create your feature branch (`git checkout -b feature/amazing-feature`) 3. Commit your changes (`git commit -m 'Add some amazing feature'`) 4. Push to the branch (`git push origin feature/amazing-feature`) 5. Open a Pull Request ## Support - 📧 Email: support@meru.com - 🐛 Issues: [GitHub Issues](https://github.com/getmeru/meru-stablecoin-lib/issues) - 📖 Documentation: [GitHub Wiki](https://github.com/getmeru/meru-stablecoin-lib/wiki)