# express-auditor

> Audit express requests and responses

Latest version **0.0.6** (published 2021-11-17) · MIT license · 0 weekly downloads

## Install

```sh
npm install express-auditor
pnpm add express-auditor
yarn add express-auditor
bun add express-auditor
```

## Health

**Score 20/100 (F)** — status: abandoned.

Positive: has types; no vulnerabilities.

Warnings: low downloads; no esm support; pre 1.0.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 0.0.6 |
| Published | 2021-11-17 |
| First published | 2021-11-13 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | CommonJS |
| Dependencies | 3 |
| Unpacked size | 37.2 KB |
| Known vulnerabilities | 0 (+1 in 1 direct dependencies) |
| Install scripts | no |
| Author | Arthur Santos |
| Maintainers | jarthursantos |

## Links

- npm: https://www.npmjs.com/package/express-auditor
- Repository: https://github.com/jarthursantos/express-auditor
- Homepage: https://github.com/jarthursantos/express-auditor#readme
- Issues: https://github.com/jarthursantos/express-auditor/issues
- npm.io page: https://npm.io/package/express-auditor

## Dependencies (3)

- [uuid](https://npm.io/package/uuid.md) ^8.3.2
- [express](https://npm.io/package/express.md) ^4.17.1
- [on-finished](https://npm.io/package/on-finished.md) ^2.3.0

## Recent versions

- 0.0.6 (latest) — 2021-11-17
- 0.0.5 — 2021-11-13
- 0.0.3 — 2021-11-13
- 0.0.2 — 2021-11-13
- 0.0.1 — 2021-11-13

## README

# express-auditor
Audit express requests and responses

## Installation

Install this package in your [NodeJS](https://nodejs.org/) project

```bash
$ yarn add express-auditor
```

 or
 
```bash
$ npm i express-auditor
```

## Getting started

Creating a auditor instance

```ts
import express from 'express'
import { createAuditor } from 'express-auditor'

const app = express()

// create auditor and middleware instance
const { auditor, handler, errorHandler } = createAuditor(/* options */)

// setup the body/response types to auditor catch him
app.use(express.json())

// the handler object return is the express middleware
app.use(handler)

/*
  routes, middlewares, ...etc
*/

// put errorHandler after all definitions to catch uncaught exceptions in your routes
app.use(errorHandler)

app.listen(3000, () => console.log('app is running'))
```

### Using `audit` in routes

The `audit` property is injected in all `Request` object

```ts
app.use('/', (request: Request, response: Response) => {
  // request.audit.doSomething

  /* do something */
})
```

By default two plugins are available

- `request.audit.execution`: this plugin is independent, he collect request, response, start time and and time data from each HTTP call
- `request.audit.metadata`: this plugin provide methods to make audit more rich
  - `setUser(username)`: specify why user are execution request
  - `setType(type)`: request action type, like `'CREATE_NEW_USER'` to post filters
  - `setDescription(description)`: Action description to post consume
  - `addObject(object)`: string array, used to specify why objects the request is manipulating
  - `addDetail(detail)`: string array, to provide details about actions, like `'Default permissions applied to new user'`
  - `addChange({ property, from, to })`: object array, to register all changes from registered type in the object list

Call this methods are optional, but add rich data to post consume

### Listening audited data

With `auditor` instance you can listen when response has sended to client

```ts
// Use this callback to save or show audited request
auditor.on('finish', (store) => {
  console.log(store)
  /*
    this go print in your terminal:
    {
      metadata: {
        executedAt: Date,
        objects: Array,
        details: Array,
        changes: Array
      },
      execution: {
        startAt: number,
        finishedAt: number,

        request: {
          body: object,
          method: string,
          url: string,
          params: object,
          query: object[],
          headers: object[],
          protocol: string,
          ip: string
        },

        response: {
          body: string,
          headers: object,
          statusCode: number,
          statusMessage: string
        },

        exception?: {
          name: string,
          message: string,
          stack: StackTrace[]
        }
      }
    }
  */
})
```

## Options

In `createAuditor` you can pass the following options

### Filter

Pass `filter` option to filter which requests/responses can be audited, if filter return false, audition is stopped and `finish` callback are not called

```ts
{
  filter: {
    request: {
      // HTTP verbs
      methods: ['GET', 'POST', 'PUT', 'DELETE']
    },

    response: {
      // 'Content-Type' header value
      contentType: ['application/json']
    }
  },
}

// OR

{
  filter: {
    request: (request: Request) => {
      /* ...some verification */
      
      return true
    },
    
    response: (response: Response) => {
      /* ...some verification */
      
      return true
    }
  }
}
```

### Plugins

Pass `plugins` option you can add external/custom features do audition

```ts
{
  // Array with external/custom plugins
  plugins: [/* some plugins */],
}
```

Custom plugin example:

```ts
{
  plugins: [
    {
      // property name to be create in `request.audit` object
      name: 'name',

      create(req, res) {
        const store = {};

        return {
          // plugin state
          store,

          // injected actions in `request.audit.{name}` object
          plugin: {
            foobar() {
              // your can perform changes in state using plugin actions
              store.name = 'foobar'

              console.log('foobar')
            }
          },

          finish(store) {
            // store: root state of the audition

            // you can call actions using `this.plugin.foobar`
          }
        }
      }
    }
  ]
}

// now in all express route you can call `foobar()`

app.get('/', (request, response) => {
  request.audit.name.foobar() // 'foobar'

  response.send('o/')
})

```

---
_Source: https://npm.io/package/express-auditor · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
