A comprehensive audit trail system has been successfully implemented for the TruthBounty API. This system tracks all critical user actions related to claims, evidence verification, and rewards distribution.
-
AuditLog Entity (
src/audit/entities/audit-log.entity.ts)- Stores all audit trail records
- Tracks action type, entity type, user, state changes, and metadata
- Includes IP address, user agent, and correlation ID for tracing
- Fully indexed for efficient querying
-
AuditTrailService (
src/audit/services/audit-trail.service.ts)- Core service for logging and querying audit records
- Methods for filtering by entity, user, action type, or date range
- Change history tracking and audit summaries
- Non-blocking async logging
-
AuditLog Decorator (
src/audit/decorators/audit-log.decorator.ts)- Simplified decorator for automatic logging of methods
- Captures before/after state
- Supports flexible entity ID extraction
-
AuditLoggingInterceptor (
src/audit/interceptors/audit-logging.interceptor.ts)- Global interceptor for processing decorated methods
- Catches successes and errors
- Extracts user/wallet information from context
-
AuditLog Controller (
src/audit/controllers/audit-log.controller.ts)- REST endpoints for querying audit logs
- Supports filtering, pagination, and summaries
- Change history and timeline views
-
AuditModule (
src/audit/audit.module.ts)- Global module making audit services available application-wide
- Exports AuditTrailService and AuditLoggingInterceptor
- Injected AuditTrailService
- Added logging decorator on
createClaim() - Added manual logging in:
resolveClaim()- logs verdict and confidence changesfinalizeClaim()- logs finalization event
- Injected AuditTrailService
- Added logging for:
createEvidence()- logs evidence submissionaddEvidenceVersion()- logs evidence updatesverifyEvidence()- logs verification completion
All endpoints follow RESTful conventions:
GET /audit # Get all audit logs with filters
GET /audit?entityType=CLAIM # Filter by entity type
GET /audit?actionType=CLAIM_CREATED # Filter by action type
GET /audit?userId=user-id # Filter by user
GET /audit?limit=50&offset=100 # Pagination
GET /audit/entity/CLAIM/claim-id # Get audit logs for specific entity
GET /audit/user/user-id # Get all user actions
GET /audit/action/CLAIM_CREATED # Get all logs for action type
GET /audit/changes/CLAIM/claim-id # Get change history
GET /audit/summary?entityType=CLAIM # Get action summary by type
File: src/migrations/1704067200000-AddAuditLogs.ts
Creates audit_logs table with:
- Automatic UUID primary key
- Comprehensive indexing for performance
- Indexes on: userId, entityType, actionType, createdAt, entityId
- Composite indexes on: (userId, createdAt), (actionType, createdAt)
CLAIM_CREATED- New claim submittedCLAIM_UPDATED- Claim data modifiedCLAIM_RESOLVED- Claim verdict determinedCLAIM_FINALIZED- Claim locked/finalized
EVIDENCE_SUBMITTED- Evidence provided for claimEVIDENCE_UPDATED- Evidence version updatedEVIDENCE_FLAGGED- Evidence marked as problematicEVIDENCE_VERIFIED- Evidence verified/approvedVERIFICATION_COMPLETED- Verification process completed
REWARD_CALCULATED- Reward amount computedREWARD_DISTRIBUTED- Reward sent to userREWARD_CLAIMED- User claimed their reward
USER_CREATED- New user registeredUSER_UPDATED- User profile changedWALLET_LINKED- Wallet connected to accountVERIFICATION_INITIATED- Verification started
src/audit/
├── entities/
│ ├── audit-log.entity.ts # AuditLog model with enums
│ └── index.ts
├── services/
│ ├── audit-trail.service.ts # Core audit service
│ └── index.ts
├── decorators/
│ ├── audit-log.decorator.ts # @AuditLog decorator
│ └── index.ts
├── interceptors/
│ ├── audit-logging.interceptor.ts # Global logging interceptor
│ └── index.ts
├── controllers/
│ ├── audit-log.controller.ts # REST API endpoints
│ └── index.ts
└── audit.module.ts # AuditModule
src/migrations/
└── 1704067200000-AddAuditLogs.ts # TypeORM migration
docs/
├── AUDIT_TRAIL.md # Complete documentation
└── AUDIT_SETUP.md # Setup and integration guide
- Every critical action is logged with:
- Who performed it (userId)
- What entity was affected (entityType, entityId)
- When it happened (createdAt)
- Where from (ipAddress, userAgent)
- What changed (beforeState, afterState)
- Query by entity to see complete history
- Query by user to see user activity
- Query by action type to find patterns
- Query by date range for compliance
- Get summaries grouped by action type
- Captures state before and after each action
- Automatic diff computation
- Change history endpoint shows evolution over time
- Comprehensive indexing for fast queries
- Non-blocking async logging
- Pagination support to handle large datasets
- Optimized database queries with QueryBuilder
- Immutable audit logs (append-only)
- Correlation IDs for request tracing
- Retention policies supported
- IP and user agent tracking
src/app.module.ts- Added AuditModule and AuditLoggingInterceptorsrc/claims/claims.service.ts- Added audit logging for claim operationssrc/claims/evidence.service.ts- Added audit logging for evidence operations
- All files under
src/audit/ - Migration file for audit_logs table
- Documentation files (AUDIT_TRAIL.md, AUDIT_SETUP.md)
await this.auditTrailService.log({
actionType: AuditActionType.CLAIM_CREATED,
entityType: AuditEntityType.CLAIM,
entityId: claimId,
userId: currentUserId,
description: 'Claim created',
afterState: claimData,
});@AuditLog({
actionType: AuditActionType.CLAIM_CREATED,
entityType: AuditEntityType.CLAIM,
captureAfterState: true,
})
async createClaim(data) { }// Get all logs for a claim
const logs = await this.auditTrailService.getEntityAuditLogs(
AuditEntityType.CLAIM,
claimId,
);
// Get change history
const history = await this.auditTrailService.getChangeHistory(
AuditEntityType.CLAIM,
claimId,
);
// Get user actions
const userLogs = await this.auditTrailService.getUserAuditLogs(userId);# Get all claim creation actions
curl "http://localhost:3000/audit?entityType=CLAIM&actionType=CLAIM_CREATED"
# Get specific claim's audit trail
curl "http://localhost:3000/audit/entity/CLAIM/abc-123"
# Get user's activity
curl "http://localhost:3000/audit/user/user-xyz"
# Get change history
curl "http://localhost:3000/audit/changes/CLAIM/abc-123"
# Get summary
curl "http://localhost:3000/audit/summary?entityType=CLAIM&days=30"npm run typeorm migration:runnpm run start# Create a claim
curl -X POST http://localhost:3000/claims \
-H "Content-Type: application/json" \
-d '{"data": "test"}'
# Query audit logs
curl http://localhost:3000/audit-
Audit Reports
- Generate compliance reports
- Export audit logs CSV/PDF
- Schedule recurring reports
-
Audit Alerting
- Real-time alerts on suspicious patterns
- Anomaly detection
- Integration with monitoring tools
-
Audit Analytics
- Dashboard showing audit trends
- User behavior analytics
- Fraud detection patterns
-
Advanced Features
- Digital signatures for tamper-proof logs
- Encryption for sensitive data
- Multi-tenant audit isolation
- Archive old logs to cold storage
-
Rewards Integration
- Add audit logging to rewards service
- Track reward calculations and distributions
- Log payment transactions
-
User Management Integration
- Log user created/updated events
- Log wallet linking events
- Log verification initiated events
- AUDIT_TRAIL.md - Complete feature documentation, API reference, and best practices
- AUDIT_SETUP.md - Integration guide with code examples and troubleshooting
✅ Ensure traceability - All critical actions logged with user, timestamp, IP, UA
✅ Track claim submission - CLAIM_CREATED, CLAIM_UPDATED, CLAIM_RESOLVED, CLAIM_FINALIZED
✅ Track verification - EVIDENCE_SUBMITTED, EVIDENCE_UPDATED, EVIDENCE_VERIFIED
✅ Track rewards - REWARD_CALCULATED, REWARD_DISTRIBUTED, REWARD_CLAIMED (template ready, service stubbed)
✅ Audit logs stored - Persisted in SQLite via TypeORM
✅ Audit logs queryable - Full REST API with filtering, pagination, summaries, and change history
To verify the audit system works:
# 1. Create a claim
curl -X POST http://localhost:3000/claims \
-H "Content-Type: application/json" \
-d '{"data": "test"}'
# 2. Query all audit logs
curl http://localhost:3000/audit
# 3. Query specific entity logs
curl http://localhost:3000/audit/entity/CLAIM/{CLAIM_ID}
# 4. Query change history
curl http://localhost:3000/audit/changes/CLAIM/{CLAIM_ID}
# 5. Get summary
curl http://localhost:3000/audit/summaryAll logs should appear with full details: action type, entity ID, timestamp, user ID, and state changes.