npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@widiramadhan/audit-trail

v1.0.0

Published

Enterprise-grade Audit Trail Plugin for Node.js with TypeScript - Performance Monitoring, System Integration Audit, Data Accountability & User Activity Tracking with Advanced Security Features

Readme

audit-trail

Enterprise-grade Audit Trail Plugin for Node.js + TypeScript with Advanced Security Features

npm version npm downloads License: MIT TypeScript Node.js Security GDPR

✨ Features

Core Logging

  • User Activity Tracking - Monitor user actions (CREATE, UPDATE, DELETE, READ)
  • System Integration Audit - Log external API calls and third-party services
  • Data Accountability - Track data access for GDPR/compliance
  • Performance Monitoring - Track response times, memory, CPU usage

Security (Enterprise-Grade)

  • 🔒 AES-256-GCM Encryption - Data encryption at rest
  • 🔒 RBAC - Role-based access control (4 roles, 6 permissions)
  • 🔒 Rate Limiting - DoS protection (per user & IP)
  • 🔒 Input Validation - SQL injection & XSS prevention
  • 🔒 Integrity Checking - HMAC-based tamper detection
  • 🔒 IP Whitelisting - Restrict admin operations

Production-Ready

  • 🚀 Retry Mechanism - Exponential backoff for failed operations
  • 🚀 Circuit Breaker - Prevent cascading failures
  • 🚀 Batch Logging - Queue-based batch insert (100x faster)
  • 🚀 Health Checks - Kubernetes liveness/readiness probes
  • 🚀 Metrics - Prometheus-compatible metrics export
  • 🚀 Graceful Shutdown - Zero data loss on shutdown

Developer Experience

  • Zero Configuration - Auto-creates tables on first run
  • TypeScript - Full type definitions
  • Express Middleware - Auto-log HTTP requests
  • Axios Interceptor - Auto-log API calls

📦 Installation

npm install @widiramadhan/audit-trail

Peer Dependencies

npm install knex pg uuid

🚀 Quick Start

Option 1: Try the Example App

# Clone or download the repository
cd example-apps

# Setup environment
cp .env.example .env
# Edit .env with your database credentials

# Run the example app
node app.js

# Server will start on http://localhost:3000
# Try: curl http://localhost:3000/api/products

Option 2: Use in Your Project

1. Setup Environment

Create .env:

DB_HOST=localhost
DB_PORT=5432
DB_NAME=audit_trail_db
DB_USER=postgres
DB_PASSWORD=your_password
APP_NAME=my-app

2. Initialize (Auto-creates tables!)

const auditTrail = require('@widiramadhan/audit-trail');

// Tables auto-created on first use
auditTrail.ConfigManager.getInstance();

3. Start Logging

await auditTrail.setUserActivity({
  user_id: 'USER123',
  action: 'CREATE',
  entity: 'product',
  platform: 'web',
  service_name: 'inventory'
});

📝 Usage Examples

User Activity

// CREATE
await auditTrail.setUserActivity({
  user_id: req.userId,
  action: 'CREATE',
  entity: 'order',
  platform: 'web',
  service_name: 'orders',
  entity_id: 'ORD123',
  after: { total: 100 }
});

// UPDATE
await auditTrail.setUserActivity({
  user_id: req.userId,
  action: 'UPDATE',
  entity: 'product',
  platform: 'mobile',
  service_name: 'inventory',
  before: { price: 99 },
  after: { price: 79 }
});
\`\`\`

### Express Middleware

\`\`\`javascript
const express = require('express');
const app = express();

// Auto-log all HTTP requests
app.use(auditTrail.createHttpLogger({
  getUserId: (req) => req.headers['x-user-id']
}));
\`\`\`

### Extract User ID from JWT

\`\`\`javascript
const jwt = require('jsonwebtoken');

app.use((req, res, next) => {
  const token = req.headers.authorization?.split(' ')[1];
  if (token) {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    req.userId = decoded.userId;
  }
  next();
});
\`\`\`

## �� Security Features

### Encryption

\`\`\`javascript
const { getEncryptionInstance } = require('@widiramadhan/audit-trail');
const encryption = getEncryptionInstance();

const encrypted = encryption.encrypt('sensitive data');
const decrypted = encryption.decrypt(encrypted.encrypted, encrypted.iv, encrypted.authTag);
\`\`\`

### Rate Limiting

\`\`\`javascript
const { getUserRateLimiter } = require('@widiramadhan/audit-trail');
const limiter = getUserRateLimiter();

await limiter.checkLimit(req.userId);
\`\`\`

### RBAC

\`\`\`javascript
const { AuditAuthorizationMiddleware, AuditPermission } = require('@widiramadhan/audit-trail');

app.get('/api/audit/logs',
  AuditAuthorizationMiddleware.checkPermission(AuditPermission.READ_ALL),
  async (req, res) => {
    const logs = await auditTrail.query({});
    res.json(logs);
  }
);
\`\`\`

## 🚀 Production Features

### Health Checks

\`\`\`javascript
const { getHealthCheck } = require('@widiramadhan/audit-trail');
const health = getHealthCheck();

app.get('/health/live', async (req, res) => {
  res.json(await health.liveness());
});

app.get('/health/ready', async (req, res) => {
  const status = await health.readiness();
  res.status(status.ready ? 200 : 503).json(status);
});
\`\`\`

### Metrics (Prometheus)

\`\`\`javascript
const { getMetrics } = require('@widiramadhan/audit-trail');
const metrics = getMetrics();

app.get('/metrics', (req, res) => {
  res.set('Content-Type', 'text/plain');
  res.send(metrics.toPrometheus());
});
\`\`\`

### Graceful Shutdown

\`\`\`javascript
const { initializeGracefulShutdown } = require('@widiramadhan/audit-trail');

initializeGracefulShutdown();
// Automatic cleanup on SIGTERM/SIGINT
\`\`\`

## 📊 Compliance

- ✅ **GDPR** - Data protection & privacy
- ✅ **SOC 2** - Security controls & audit trails
- ✅ **HIPAA** - Healthcare data security
- ✅ **PCI DSS** - Payment data security
- ✅ **ISO 27001** - Information security management

## 📚 API Reference

### Core Functions

- \`setUserActivity(input)\` - Log user actions
- \`setSystemIntegration(input)\` - Log API calls
- \`setDataAccountability(input)\` - Log data access
- \`setPerformance(input)\` - Log performance metrics

### Security Functions

- \`getEncryptionInstance()\` - Get encryption service
- \`getUserRateLimiter()\` - Get rate limiter
- \`getIntegrityChecker()\` - Get integrity checker
- \`AuditInputValidator\` - Input validation utilities

### Production Functions

- \`getRetryPolicy()\` - Get retry mechanism
- \`getCircuitBreaker()\` - Get circuit breaker
- \`getBatchLogger()\` - Get batch logger
- \`getHealthCheck()\` - Get health check service
- \`getMetrics()\` - Get metrics collector
- \`initializeGracefulShutdown()\` - Setup graceful shutdown

## 🐳 Docker

\`\`\`dockerfile
FROM node:16-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
EXPOSE 3000
CMD ["node", "app.js"]
\`\`\`

## ☸️ Kubernetes

\`\`\`yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: audit-trail-app
spec:
  replicas: 3
  template:
    spec:
      containers:
      - name: app
        image: your-app:latest
        ports:
        - containerPort: 3000
        livenessProbe:
          httpGet:
            path: /health/live
            port: 3000
        readinessProbe:
          httpGet:
            path: /health/ready
            port: 3000
\`\`\`

## 🔧 Configuration

\`\`\`env
# Database
DB_HOST=localhost
DB_PORT=5432
DB_NAME=audit_trail_db
DB_USER=postgres
DB_PASSWORD=your_password

# Security
AUDIT_ENCRYPTION_KEY=  # openssl rand -hex 32
AUDIT_HASH_SALT=       # openssl rand -hex 32
AUDIT_INTEGRITY_KEY=   # openssl rand -hex 32

# Rate Limiting
AUDIT_RATE_LIMIT_POINTS=100
AUDIT_RATE_LIMIT_DURATION=60

# Batch Logging
AUDIT_BATCH_SIZE=100
AUDIT_FLUSH_INTERVAL=5000
\`\`\`

## 🤝 Contributing

Contributions welcome! See [CONTRIBUTING.md](CONTRIBUTING.md)

## 📄 License

MIT © IMEXS

## 🔗 Links

- [npm Package](https://www.npmjs.com/package/audit-trail)
- [GitHub](https://github.com/imexs/audit-trail)
- [Changelog](CHANGELOG.md)

---

**Made with ❤️ by IMEXS**