npm package: @shy-dev/node-audit-logger
Description: Node.js middleware and logger to track user activity logs in MongoDB.
Author: Your Name
Latest version: 1.1.0

# Node Audit Logger

A fully ready-to-publish npm package for Node.js applications to track user activity logs. It supports multiple projects with separate MongoDB clusters and provides an Express middleware plus a custom event logger.

## Installation

```bash
npm install @shy-dev/node-audit-logger
```

## Usage

### 1. Initialize Middleware

In your Express app, initialize the logger before defining routes:

```typescript
import express from 'express';
import { init, LoggerScope } from '@shy-dev/node-audit-logger';

const app = express();
app.use(express.json());

// Initialize and use the middleware
const auditMiddleware = await init({
  mongoUri: process.env.MONGO_URI, // Your MongoDB connection string
  jwtSecret: process.env.JWT_SECRET, // Optional: for decoding JWTs automatically
  consoleLoggerScope: LoggerScope.ALL, // Optional: Control console output (ALL, SERVER_ONLY, WORKER_ONLY, NONE)
  options: {
    skipPaths: ['/health', '/metrics'], // Paths to skip logging
    maskRequest: true,      // Mask sensitive data in request
    maskResponse: true,     // Mask sensitive data in response
    logPaginatedResponse: 'partial', // 'full', 'partial', 'none', or false
    // Optional: Enable Queue
    // useQueue: true,
    // queueOptions: { host: '127.0.0.1', port: 6379 }
  }
});

app.use(auditMiddleware);

app.listen(3000, () => console.log('Server running'));
```

### 2. Explicit User ID Setting

Sometimes the user ID is not available in the request headers (e.g., during login or registration). You can explicitly set the user ID for the current request using the `setAuditUserId` helper:

```typescript
import { setAuditUserId } from '@shy-dev/node-audit-logger';

app.post('/login', async (req, res) => {
  const user = await loginUser(req.body);
  
  // Explicitly link this request log to the user
  setAuditUserId(res, user.id);
  
  res.json({ token: '...' });
});
```

### 3. Manual Event Logging

You can also log custom events that are not tied to HTTP requests:

```typescript
import { logEvent } from '@shy-dev/node-audit-logger';

await logEvent({
  userId: 'user-id',
  type: 'SYSTEM',
  action: 'CRON_JOB',
  actionMessage: 'Daily cleanup completed',
  metadata: { itemsProcessed: 100 }
});
```

## Configuration Options

### Init Options (`init`)

| Option | Type | Default | Description |
|---|---|---|---|
| `mongoUri` | `string` | **Required** | MongoDB connection string. |
| `jwtSecret` | `string` | `undefined` | JWT secret for decoding tokens from `Authorization` header. |
| `options` | `AuditLoggerOptions` | `{}` | Middleware configuration options (see below). |
| `consoleLoggerScope` | `LoggerScope` | `ALL` | Controls console output. Options: `ALL`, `SERVER_ONLY`, `WORKER_ONLY`, `NONE`. |

### Middleware Options (`options`)

| Option | Type | Default | Description |
|---|---|---|---|
| `skipPaths` | `string[]` | `[]` | List of paths to exclude from logging (prefix match). |
| `maskRequest` | `boolean` | `true` | Whether to mask sensitive data (password, token, etc.) in request body/headers. |
| `maskResponse` | `boolean` | `true` | Whether to mask sensitive data in response body. |
| `logPaginatedResponse` | `'full' \| 'partial' \| 'none' \| false` | `'full'` | Controls response logging. `'partial'` truncates large arrays. `'none'` or `false` skips response body. |
| `useQueue` | `boolean` | `false` | If `true`, logs are sent to a Redis queue instead of saving directly. |
| `queueOptions` | `object` | `undefined` | Redis connection options for BullMQ (e.g., `{ host: 'localhost', port: 6379 }`). Required if `useQueue` is `true`. |
| `startWorker` | `boolean` | `false` | If `true`, automatically starts the queue worker in the same process. |
| `customModel` | `Mongoose Model` | `undefined` | A custom Mongoose model to use for saving logs. |

## Advanced Features

### Queue Support (Redis)

To offload log saving to a background process, enable the queue:

1.  **Configure Middleware:**
    ```typescript
    const auditMiddleware = await init({
      mongoUri: process.env.MONGO_URI,
      options: {
        useQueue: true,
        queueOptions: { host: '127.0.0.1', port: 6379 }
      }
    });
    ```

2.  **Run Worker:**
    You can either start the worker automatically by setting `startWorker: true` in options, or run it in a separate process:

    ```typescript
    // worker.ts
    import { startWorker } from '@shy-dev/node-audit-logger';

    const MONGO_URI = process.env.MONGO_URI;
    const REDIS_OPTIONS = { host: '127.0.0.1', port: 6379 };

    startWorker(MONGO_URI, REDIS_OPTIONS).catch(console.error);
    ```

### Custom Mongoose Model

You can provide your own Mongoose model to save logs to a custom collection or with a custom schema.

1.  **Define Your Model:**
    ```typescript
    import mongoose from 'mongoose';

    const mySchema = new mongoose.Schema({
      // ... your custom schema fields
    }, { strict: false });

    const MyCustomLog = mongoose.model('MyCustomLog', mySchema);
    ```

2.  **Pass to Middleware:**
    ```typescript
    const auditMiddleware = await init({
      mongoUri: process.env.MONGO_URI,
      options: {
        customModel: MyCustomLog
      }
    });
    ```

### Sensitive Data Masking

The logger automatically masks sensitive fields in requests and responses. By default, it looks for keys like:
`password`, `token`, `authorization`, `secret`, `creditCard`, `cvv`, `ssn`, etc.

You can toggle this behavior using `maskRequest` and `maskResponse` options.

## License

MIT