cap-audit-middleware

1.0.2 • Public • Published

CAP Audit Middleware

A middleware library for audit logging in SAP Cloud Application Programming (CAP) applications.

Features

  • Entity-based or global audit logging
  • Configurable logging for CREATE, UPDATE, and DELETE operations
  • Multiple storage options:
    • Database storage (via CAP service)
    • JSON file storage
    • Webhook integration with external systems
  • Tracking of pre-operation and post-operation data
  • Filtering of unwanted or sensitive data
  • Customizable user resolution

Installation

npm install cap-audit-middleware

Usage

Basic Setup

const cds = require('@sap/cds');
const { AuditMiddleware, storage } = require('cap-audit-middleware');

//server.js
cds.on("bootstrap", async(app) =>  {
  // Configure the audit middleware
  setupWithDatabaseStorage();
});
async function setupWithDatabaseStorage() {
  const srv = await cds.connect.to('db');
  const auditMiddleware = new AuditMiddleware({
    storage: new storage.DatabaseStorage({
      db: srv,
      table: 'AuditLogs'
    }),
    // At least one entity must be specified in entities parameter
    entities: ['ProductService.Products', 'OrderService.Orders'],
    // Optional: log only specific operations
    operations: ['CREATE', 'UPDATE', 'DELETE'],
    // Optional: user resolution
    userResolver: (req) => req.user?.id || 'anonymous',
    // Optional: log request/response payload
    logPayload: true
  });
  
  // Initialize middleware with the service
  auditMiddleware.initialize(srv);
}

Storage Options

Database Storage

Stores audit logs using your CDS database.

const dbStorage = new storage.DatabaseStorage({
  db: srv,                           // CDS database service
  table: 'AuditLogs',                // Optional: table name (default: 'ServiceLogs')
  autoCreateTable: true              // Optional: create table if it doesn't exist (default: true)
});

You can use the AuditLogs aspect defined in the index.cds file:

using { sap.cap.auditLogs } from 'cap-audit-middleware';

entity MyAuditLogs : auditLogs.AuditLogs {
  // Add your custom fields
  timestamp : Timestamp;
  ipAddress : String;
}

JSON File Storage

Stores audit logs in a local JSON file.

const fileStorage = new storage.JsonFileStorage({
  filePath: './logs', // File path
  prettyPrint: true,                  // Optional: format JSON for readability
  appendMode: true                    // Optional: append mode (true) or overwrite (false)
});

Webhook Storage

Sends audit logs as HTTP requests to an external API.

const webhookStorage = new storage.WebhookStorage({
  url: 'https://example.com/audit-webhook', // Webhook URL
  headers: {                                // Optional: HTTP headers
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YOUR_API_KEY'
  },
  timeout: 3000                             // Optional: request timeout (ms)
});

Advanced Configuration

Before Log Hook

To modify or enrich audit data before it's stored:

const auditMiddleware = new AuditMiddleware({
  storage: myStorage,
  // ... other options ...
  beforeLog: async (logEntry, req) => {
    // Clean sensitive data
    if (logEntry.entity === 'Users' && logEntry.data) {
      delete logEntry.data.password;
    }
    // Add additional information
    logEntry.applicationName = 'MyCapApp';
    logEntry.environment = process.env.NODE_ENV;
  }
});

Example Use Cases

Audit Logging for Specific Entities Only

const auditMiddleware = new AuditMiddleware({
  storage: myStorage,
  entities: ['ProductService.Products', 'OrderService.Orders', 'CustomerService.Customers'],
  operations: ['CREATE', 'UPDATE', 'DELETE']
});

Audit Logging for Specific Operations Only

const auditMiddleware = new AuditMiddleware({
  storage: myStorage,
  operations: ['CREATE', 'DELETE'] // Only log create and delete operations
});

Filtering Sensitive Data

const auditMiddleware = new AuditMiddleware({
  storage: myStorage,
  beforeLog: (logEntry) => {
    // Clean sensitive fields from user data
    if (logEntry.entity === 'Users' && logEntry.data) {
      delete logEntry.data.password;
      delete logEntry.data.creditCardNumber;
    }
  }
});

/cap-audit-middleware/

    Package Sidebar

    Install

    npm i cap-audit-middleware

    Weekly Downloads

    8

    Version

    1.0.2

    License

    MIT

    Unpacked Size

    20.5 kB

    Total Files

    9

    Last publish

    Collaborators

    • eyupbaycol