Comprehensive request validation has been implemented across all API endpoints to ensure data integrity, security, and consistent error handling.
File: src/utils/validators.js
Provides reusable validation functions:
isValidStellarPublicKey()- Validates Stellar public key format (G + 56 chars)isValidStellarSecretKey()- Validates Stellar secret key format (S + 56 chars)isValidAmount()- Ensures amount is positive and > 0isValidTransactionHash()- Validates 64-character hex stringsisValidDate()- Validates ISO date formatisValidDateRange()- Validates date range logicwalletExists()- Checks if wallet ID exists in databasewalletAddressExists()- Checks if wallet address existstransactionExists()- Checks if transaction ID existssanitizeString()- Trims and sanitizes string input
File: src/middleware/validation.js
Express middleware functions for route protection:
validateDonationCreate- Validates donation creation requestsvalidateTransactionVerify- Validates transaction verification requestsvalidateDateRange- Validates date range query parametersvalidateWalletCreate- Validates wallet creation requestsvalidateWalletId- Validates wallet ID parametersvalidatePublicKey()- Flexible public key validator
Files:
tests/validation.test.js- Unit tests for validation utilitiestests/validation-middleware.test.js- Integration tests for middleware
Comprehensive test coverage including:
- Valid input acceptance
- Invalid input rejection
- Edge cases (zero, negative, null, undefined)
- Format validation
- Business logic validation
Files:
VALIDATION.md- Complete validation documentationVALIDATION_QUICK_REFERENCE.md- Quick reference guide
Changes:
- Added validation middleware to POST /donations
- Added validation middleware to POST /donations/verify
- Improved error response format with error codes
- Standardized success/error response structure
Endpoints Updated:
POST /donations- Validates amount, donor, recipientPOST /donations/verify- Validates transaction hashGET /donations/:id- Enhanced error handling
Changes:
- Added
validateDateRangemiddleware to all endpoints - Removed duplicate validation code
- Standardized error responses
- Improved error codes
Endpoints Updated:
GET /stats/dailyGET /stats/weeklyGET /stats/summaryGET /stats/donorsGET /stats/recipients
Changes:
- Created complete wallet management endpoints
- Added comprehensive validation
- Implemented duplicate prevention
Endpoints Created:
POST /wallets- Create wallet with validationGET /wallets- List all walletsGET /wallets/:id- Get wallet by ID with validationPOST /wallets/lookup- Lookup wallet by address
Changes:
- Added wallet routes to application
- Integrated new validation middleware
Changes:
- Added
dbPathconfiguration - Added
networkconfiguration - Added
portconfiguration
Changes:
- Added test scripts (test, test:watch, test:coverage)
- Added jest and supertest as dev dependencies
- Must be a positive number
- Must be greater than 0
- Rejects NaN, Infinity, negative values
- Must start with 'G' (public key)
- Must be exactly 56 characters
- Must contain only valid base32 characters (A-Z, 2-7)
- Must be exactly 64 characters
- Must contain only hexadecimal characters
- Both dates required
- Must be valid ISO format
- Start date must be before or equal to end date
- Must exist in database
- Returns 404 if not found
- Donor and recipient must be different
- Duplicate wallet addresses prevented
- Clear error messages for all violations
All validation errors follow a consistent structure:
{
"success": false,
"error": {
"code": "ERROR_CODE",
"message": "Human-readable error message",
"field": "fieldName"
}
}MISSING_FIELD- Required field not providedMISSING_PARAMETER- URL parameter missingMISSING_PARAMETERS- Query parameters missingINVALID_AMOUNT- Amount validation failedINVALID_STELLAR_ADDRESS- Invalid Stellar address formatINVALID_TRANSACTION_HASH- Invalid hash formatINVALID_DATE_RANGE- Invalid date rangeINVALID_TRANSACTION- Business logic violationWALLET_NOT_FOUND- Wallet doesn't exist (404)DONATION_NOT_FOUND- Donation doesn't exist (404)WALLET_EXISTS- Duplicate wallet (409)
- Unit tests for all validation functions
- Integration tests for all middleware
- Edge case testing
- Error response validation
npm test # Run all tests
npm test -- tests/validation.test.js # Unit tests only
npm test -- tests/validation-middleware.test.js # Integration tests
npm test:coverage # With coverage report- Input Sanitization - All strings trimmed and validated
- Type Safety - Strict type checking prevents coercion attacks
- Format Validation - Regex patterns ensure correct formats
- Existence Checks - Database lookups verify resources exist
- Duplicate Prevention - Prevents duplicate wallet registrations
- Clear Error Messages - Helps developers without exposing internals
✅ Amount must be > 0
- Implemented in
isValidAmount()validator - Applied to all donation endpoints
- Clear error messages returned
✅ Wallet IDs must exist
- Implemented in
walletExists()validator - Applied to wallet lookup endpoints
- Returns 404 with clear message
✅ Public keys must be valid Stellar addresses
- Implemented in
isValidStellarPublicKey()validator - Applied to all endpoints accepting addresses
- Validates format (G + 56 chars, base32)
✅ Return clear error messages
- Standardized error response format
- Specific error codes for each validation type
- Field-level error identification
- Human-readable messages
curl -X POST http://localhost:3000/donations \
-H "Content-Type: application/json" \
-d '{
"amount": 10.5,
"recipient": "GBRPYHIL2CI3FNQ4BXLFMNDLFJUNPU2HY3ZMFSHONUCEOASW7QC7OX2H"
}'{
"success": false,
"error": {
"code": "INVALID_AMOUNT",
"message": "Amount must be a positive number greater than 0",
"field": "amount"
}
}{
"success": false,
"error": {
"code": "INVALID_STELLAR_ADDRESS",
"message": "Invalid Stellar public key format. Must start with G and be 56 characters",
"field": "recipient"
}
}To use the validation:
-
Install dependencies:
npm install
-
Run tests:
npm test -
Start the server:
npm start
-
Test endpoints:
- Use the examples in VALIDATION.md
- Try invalid inputs to see error responses
- Check VALIDATION_QUICK_REFERENCE.md for patterns
- Data Integrity - Invalid data rejected before processing
- Security - Prevents injection and malformed requests
- Developer Experience - Clear, actionable error messages
- Maintainability - Centralized validation logic
- Testability - Comprehensive test coverage
- Consistency - Uniform error handling across all endpoints