dromanis.finora.functions.common
v3.11.1
Published
The set of common utiltities used across by different lambda functions
Downloads
81
Readme
dromanis.finora.functions.common
A TypeScript-first utility library providing common functionality for AWS Lambda functions in the Dromanis Finora ecosystem. This package offers robust JWT authentication and CORS handling capabilities designed specifically for serverless API Gateway integrations.
🚀 Features
- JWT Authentication: Secure authentication middleware with automatic token validation and payload extraction
- CORS Handling: Comprehensive CORS support for API Gateway responses with customizable headers
- TypeScript-First: Full type safety with comprehensive TypeScript definitions
- AWS Lambda Optimized: Built specifically for AWS Lambda and API Gateway integration
- Fully Tested: Comprehensive test suite with 100% code coverage
- Zero Dependencies: Minimal runtime dependencies for optimal Lambda performance
📦 Installation
npm install dromanis.finora.functions.common🛠️ Usage
JWT Authentication
The userAuthenticator class provides JWT token validation for your Lambda functions.
Basic Usage
import { userAuthenticator } from 'dromanis.finora.functions.common';
import { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda';
const authenticator = new userAuthenticator();
export const handler = async (event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> => {
// Authenticate the request
const authResult = authenticator.authenticate(event);
if (authResult.statusCode !== 200) {
// Authentication failed - return error response
return authResult;
}
// Access the decoded token payload
const userData = authResult.decodedToken;
console.log('Authenticated user:', userData);
// Your business logic here
return {
statusCode: 200,
body: JSON.stringify({
message: 'Success!',
user: userData
})
};
};Authentication Requirements
- Environment Variable: Set
JWT_SECRETenvironment variable - Authorization Header: Include
Authorization: Bearer <token>in request headers - Token Format: Valid JWT token signed with the same secret
Response Format
Success Response (200):
{
statusCode: 200,
body: '{"message": "Authenticated"}',
decodedToken: {
// Your JWT payload (user, role, etc.)
}
}Error Responses:
401: Missing/invalid Authorization header or invalid/expired token500: JWT secret not configured
CORS Handling
The corsHandler class manages CORS headers for your API Gateway responses.
Basic Usage
import { corsHandler } from 'dromanis.finora.functions.common';
import { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda';
const cors = new corsHandler();
export const handler = async (event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> => {
// Handle preflight OPTIONS requests
if (event.httpMethod === 'OPTIONS') {
return cors.handleOptionsMethod();
}
// Your main business logic
const response: APIGatewayProxyResult = {
statusCode: 200,
body: JSON.stringify({ message: 'Success!' })
};
// Add CORS headers to your response
return cors.handleWithCors(response);
};CORS Configuration
The CORS handler automatically adds the following headers:
Access-Control-Allow-Origin: *Access-Control-Allow-Headers: *Access-Control-Allow-Methods: GET,POST,PUT,DELETE,OPTIONS
Methods
handleWithCors(response: APIGatewayProxyResult): APIGatewayProxyResult
- Adds CORS headers to your existing response
- Preserves existing headers
- Returns the modified response with CORS headers
handleOptionsMethod(): APIGatewayProxyResult
- Handles preflight OPTIONS requests
- Returns a 200 response with appropriate CORS headers
- Use this for preflight request handling
Combined Usage
import { userAuthenticator, corsHandler } from 'dromanis.finora.functions.common';
import { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda';
const authenticator = new userAuthenticator();
const cors = new corsHandler();
export const handler = async (event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> => {
// Handle preflight requests
if (event.httpMethod === 'OPTIONS') {
return cors.handleOptionsMethod();
}
// Authenticate request
const authResult = authenticator.authenticate(event);
if (authResult.statusCode !== 200) {
return cors.handleWithCors(authResult);
}
// Your business logic
const response = {
statusCode: 200,
body: JSON.stringify({
message: 'Authenticated and authorized!',
user: authResult.decodedToken
})
};
// Return response with CORS headers
return cors.handleWithCors(response);
};🔧 Environment Setup
Required Environment Variables
JWT_SECRET: Secret key for JWT token verification (required for authentication)
Example Environment Configuration
# .env file
JWT_SECRET=your-super-secure-jwt-secret-key🧪 Testing
This package includes comprehensive tests using Jest and TypeScript.
Running Tests
# Run all tests
npm test
# Run tests in watch mode
npm run test:watch
# Run tests with coverage
npm run test:coverageTest Coverage
The test suite covers:
- JWT authentication scenarios (valid/invalid tokens, missing secrets, etc.)
- CORS header handling (with/without existing headers)
- Error handling and edge cases
- TypeScript type checking
🏗️ Development
Project Structure
src/
├── __tests__/ # Test files
│ ├── corsHandler.test.ts
│ └── userAuthenticator.test.ts
├── corsHandler.ts # CORS handling utilities
├── userAuthenticator.ts # JWT authentication utilities
└── index.ts # Main exportsBuild Process
# Clean build directory
npm run clean
# Build TypeScript to JavaScript
npm run build
# Run tests
npm testDevelopment Setup
- Clone the repository
- Install dependencies:
npm install - Set up environment variables
- Run tests:
npm test - Build:
npm run build
📋 API Reference
userAuthenticator
class userAuthenticator {
authenticate(event: APIGatewayProxyEvent): AuthenticationResult
}
interface AuthenticationResult {
statusCode: number;
body: string;
decodedToken?: any; // Present only on successful authentication
}corsHandler
class corsHandler {
handleWithCors(response: APIGatewayProxyResult): APIGatewayProxyResult
handleOptionsMethod(): APIGatewayProxyResult
}🤝 Contributing
We welcome contributions! Please follow these steps:
- Fork the repository
- Create a feature branch:
git checkout -b feature/amazing-feature - Make your changes and add tests
- Ensure tests pass:
npm test - Commit your changes:
git commit -m 'Add amazing feature' - Push to the branch:
git push origin feature/amazing-feature - Open a Pull Request
Code Quality
This project uses:
- Husky: Git hooks for automated testing
- Jest: Testing framework
- TypeScript: Type safety
- ESLint: Code linting (configured via Husky)
All commits are automatically tested before being accepted.
📝 License
This project is licensed under the ISC License - see the LICENSE file for details.
🏢 About Dromanis Finora
This package is part of the Dromanis Finora ecosystem, providing financial technology solutions built on AWS serverless architecture.
For questions, issues, or feature requests, please open an issue on the GitHub repository.
