trieb-work

payload audit

by trieb-work
Logging & monitoring
v3
^3.0.0
MIT

Overview

Summary generated from the README

Attaches hooks to all collections and writes an immutable entry to a generated audit-logs collection for each create, update, delete and file event. Native login, logout and lockout events are recorded, and external auth can emit events through a helper. It is added through the plugins array and targets Payload 3.

Features

  • Zero-config hooks on every collection with an opt-out list
  • Immutable audit-logs collection that denies API writes
  • Records actor, document, IP address and user agent per entry
  • Delegation and impersonation chains plus optional forensic metadata like token fingerprints
  • Retention pruning by age or count via a scheduled job
  • Tenant scoping compatible with the multi-tenant plugin

Use cases

  • Record who changed what and when to support GDPR, SOC 2 or ISO 27001 accountability
  • Investigate suspected credential abuse using auth strategy and token fingerprint data
  • Keep per-tenant activity trails in multi-tenant Payload applications

From the author

Payload CMS plugin for automatic, compliance-ready audit logging across all collections

Installation

npm i @trieb.work/payload-audit

5

Stars

0

Forks

1

Open Issues

2 months ago

Last Updated

237

Weekly Downloads

v1.3.0

npm Version

227.3 KB

Unpacked Size

0

Dependencies

GitHub stars

5+2 since Sep 7

Show data
GitHub stars by day (UTC)
DateStars
Dec 6, 20265
Dec 5, 20265
Dec 4, 20265
Dec 3, 20265
Dec 2, 20265
Dec 1, 20265
Nov 30, 20265
Nov 29, 20265
Nov 28, 20265
Nov 27, 20265
Nov 26, 20265
Nov 25, 20265
Nov 24, 20265
Nov 23, 20265
Nov 22, 20265
Nov 21, 20265
Nov 20, 20265
Nov 19, 20264
Nov 18, 20264
Nov 17, 20264
Nov 16, 20264
Nov 15, 20264
Nov 14, 20264
Nov 13, 20264
Nov 12, 20264
Nov 11, 20264
Nov 10, 20264
Nov 9, 20264
Nov 8, 20264
Nov 7, 20264
Nov 6, 20264
Nov 5, 20264
Nov 4, 20264
Nov 3, 20264
Nov 2, 20264
Nov 1, 20264
Oct 31, 20264
Oct 30, 20264
Oct 29, 20264
Oct 28, 20264
Oct 27, 20264
Oct 26, 20264
Oct 25, 20264
Oct 24, 20264
Oct 23, 20264
Oct 22, 20264
Oct 21, 20264
Oct 20, 20264
Oct 19, 20264
Oct 18, 20264
Oct 17, 20264
Oct 16, 20264
Oct 15, 20264
Oct 14, 20264
Oct 13, 20264
Oct 12, 20264
Oct 11, 20264
Oct 10, 20264
Oct 9, 20264
Oct 8, 20264
Oct 7, 20264
Oct 6, 20264
Oct 5, 20264
Oct 4, 20264
Oct 3, 20264
Oct 2, 20264
Oct 1, 20264
Sep 30, 20264
Sep 29, 20264
Sep 28, 20264
Sep 27, 20264
Sep 26, 20264
Sep 25, 20264
Sep 24, 20264
Sep 23, 20264
Sep 22, 20264
Sep 21, 20264
Sep 20, 20264
Sep 19, 20264
Sep 18, 20264
Sep 17, 20264
Sep 16, 20264
Sep 15, 20264
Sep 14, 20263
Sep 13, 20263
Sep 12, 20263
Sep 11, 20263
Sep 10, 20263
Sep 9, 20263
Sep 8, 20263
Sep 7, 20263
npm weekly downloads

184+143 since Sep 7

Show data
npm weekly downloads by day (UTC)
DateWeekly downloads
Dec 6, 2026184
Dec 5, 2026171
Dec 4, 2026156
Dec 3, 2026134
Dec 2, 2026111
Dec 1, 2026112
Nov 30, 2026114
Nov 29, 2026129
Nov 28, 2026128
Nov 27, 2026128
Nov 26, 2026137
Nov 25, 2026220
Nov 24, 2026225
Nov 23, 2026223
Nov 22, 2026212
Nov 21, 2026234
Nov 20, 2026236
Nov 19, 2026248
Nov 18, 2026178
Nov 17, 2026183
Nov 16, 2026185
Nov 15, 2026206
Nov 14, 2026184
Nov 13, 2026227
Nov 12, 2026271
Nov 11, 2026271
Nov 10, 2026276
Nov 9, 2026300
Nov 8, 2026320
Nov 7, 2026370
Nov 6, 2026354
Nov 5, 2026322
Nov 4, 2026402
Nov 3, 2026421
Nov 2, 2026420
Nov 1, 2026417
Oct 31, 2026426
Oct 30, 2026479
Oct 29, 2026426
Oct 28, 2026311
Oct 27, 2026384
Oct 26, 2026508
Oct 25, 2026752
Oct 24, 2026897
Oct 23, 2026790
Oct 22, 2026882
Oct 21, 20261,030
Oct 20, 2026995
Oct 19, 2026882
Oct 18, 2026650
Oct 17, 2026484
Oct 16, 2026502
Oct 15, 2026430
Oct 14, 2026297
Oct 13, 2026215
Oct 12, 2026180
Oct 11, 2026141
Oct 10, 2026102
Oct 9, 2026112
Oct 8, 2026129
Oct 7, 2026187
Oct 6, 2026216
Oct 5, 2026217
Oct 4, 2026246
Oct 3, 2026260
Oct 2, 2026280
Oct 1, 2026272
Sep 30, 2026202
Sep 29, 2026180
Sep 28, 2026186
Sep 27, 2026148
Sep 26, 2026142
Sep 25, 2026103
Sep 24, 2026109
Sep 23, 2026138
Sep 22, 2026148
Sep 21, 2026166
Sep 20, 2026176
Sep 19, 2026179
Sep 18, 2026321
Sep 17, 2026292
Sep 16, 2026270
Sep 15, 2026258
Sep 14, 2026228
Sep 13, 2026210
Sep 12, 2026184
Sep 11, 202638
Sep 10, 202636
Sep 9, 202642
Sep 8, 202640
Sep 7, 202641

Each point is npm's rolling 7-day download count.

Health Score

58/100Good

Composite score based on GitHub activity, stars, npm downloads, publish recency, dependency count, and package size.

Badge for your README

Payload Directory health badge
Markdown
[![Payload Directory](https://payloaddirectory.dev/badge/1253340893-root.svg)](https://payloaddirectory.dev/plugins/1253340893-root)
HTML
<a href="https://payloaddirectory.dev/plugins/1253340893-root"><img src="https://payloaddirectory.dev/badge/1253340893-root.svg" alt="Payload Directory"></a>
Updated Sep 9, 2026Created May 29, 2026Published Sep 9, 2026

README

@trieb.work/payload-audit

npm version CI License: MIT Payload CMS

Automatic, compliance-ready audit logging and audit trail plugin for Payload CMS. Zero-config change tracking with delegation, forensics, retention, and multi-tenancy built in.

Manually wiring up audit logs for every collection is tedious and easy to get wrong — one forgotten hook and your audit trail has a gap. payload-audit attaches itself to every collection in your Payload config automatically and writes an immutable log entry for every create, update, and delete, so you get a complete, tamper-proof activity trail with a single line of configuration.

It's built to help satisfy the logging and accountability requirements of NIS-2, CRA, GDPR, SEC Cyber Disclosure Rules, HIPAA, PCI-DSS 4.0, ISO/IEC 27001, and SOC 2 — but it's just as useful as a general-purpose "who changed what, when" activity log for any Payload project.

Features

  • Zero-config coverage — hooks into every collection automatically, with an opt-out list (disabledCollections). No per-collection setup.
  • Auth events — native Payload login/logout/lockout are recorded automatically; external auth (passwordless, Better Auth, …) uses a one-line emitAuthEvent call.
  • Immutable audit trail — the generated audit-logs collection denies create/update/delete through the API; entries can only be written internally by the plugin, so the log can't be altered or deleted by users.
  • Rich context per entry — actor (with email/name snapshot that survives user deletion), document id and title, IP address, and user agent.
  • File tracking — upload-enabled collections get dedicated file_upload / file_delete actions.
  • Delegation & impersonation aware (RFC 8693 act semantics) — records who performed an action on behalf of whom, including nested delegation chains (User → Agent → Service), via onBehalfOf and delegationChain.
  • Forensic metadata for breach investigation — optionally capture auth strategy, HTTP method, request path, and a non-reversible token fingerprint (sha256) to correlate every action performed with a stolen credential, without ever storing the raw token.
  • Custom actions — extend the built-in action types with your own (extraActions), e.g. impersonation.started, for manually emitted entries.
  • Configurable retention — prune entries by age (maxAge), by count (maxEntries), or both, via a scheduled Payload job (custom cron/queue supported, or trigger manually).
  • Multi-tenant scoping — optional tenant relationship on every entry, with auto-detection and out-of-the-box interop with @payloadcms/plugin-multi-tenant.
  • Configurable read access — lock down who can view the audit trail via a standard Payload access.read function.
  • Programmatic API — writeAuditLog, resolveDelegation, extractTenant, resolveDocTitle, and pruneAuditLogs are all exported for custom hooks and scripts. A skipAuditLog request-context flag lets you suppress logging for a single operation when you emit a more specific entry yourself.

Quick start

pnpm add @trieb.work/payload-audit
// payload.config.ts
import { auditLogPlugin } from '@trieb.work/payload-audit'

export default buildConfig({
  // ...
  plugins: [
    auditLogPlugin({
      disabledCollections: ['sessions'],
      retention: { maxAge: 365 }, // keep one year of history
    }),
  ],
})

That's it — every collection now writes to an audit-logs collection automatically. Open the admin UI to see the trail.

Configuration

All options are optional; sensible, safe defaults are used when omitted.

auditLogPlugin({
  // Master switch. `false` turns the plugin into a no-op.
  enabled: true,

  // Slug of the generated audit collection. Default: 'audit-logs'.
  collectionSlug: 'audit-logs',

  // Collections that should never be audited (in addition to the audit
  // collection itself and Payload's internal collections).
  disabledCollections: ['sessions'],

  // Read access for the audit trail. Default: any authenticated user.
  access: { read: ({ req }) => req.user?.role === 'admin' },

  // Prune old entries by age and/or count via a scheduled job.
  retention: { maxAge: 365, maxEntries: 100_000, cron: '0 0 * * *' },

  // Scope entries per tenant. Interoperates with @payloadcms/plugin-multi-tenant.
  multiTenant: { enabled: true, autoDetect: true },

  // Opt-in forensic metadata for breach investigation.
  forensics: {
    authStrategy: true,
    requestMethod: true,
    tokenFingerprint: true,
  },

  // RFC 8693 delegation/impersonation-aware logging. Enabled by default.
  delegation: { enabled: true, maxChainDepth: 10 },

  // Custom action types beyond create/update/delete/file_upload/file_delete.
  extraActions: [
    { value: 'impersonation.started', label: 'Impersonation started' },
  ],
})

Authentication events

Native Payload auth (email/password, API keys, anything that goes through payload.login() / logout() / refresh()) is recorded automatically:

  • auth.login.success / auth.login.failure
  • auth.logout
  • auth.account.locked (when maxLoginAttempts is enabled)
  • auth.token.refresh and auth.password.forgot are off by default (noisy / PII). Enable them via authEvents.events.
auditLogPlugin({
  authEvents: {
    events: { refresh: true },
    captureIdentifier: 'known-user', // default: store email only if the account exists
  },
})

Internal user-document writes during login (sessions, loginAttempts) are not logged as update.

Failed login and lockout are recorded via Payload's afterError hook, which runs for REST and GraphQL. Local API payload.login() rethrows without that hook, so those paths are covered by HTTP-level tests.

External auth (emitAuthEvent)

Plugins that replace Payload's login (passwordless, Better Auth, custom endpoints) never fire afterLogin. Call emitAuthEvent at the login / logout / failure site — the plugin already stored its options on payload.config.custom, so the call is one argument besides req:

import { emitAuthEvent } from '@trieb.work/payload-audit'

await emitAuthEvent({ req, event: 'login.success', user })
await emitAuthEvent({ req, event: 'login.failure', identifier: email })
await emitAuthEvent({ req, event: 'logout', user })

Register the auth plugin first, then auditLogPlugin, then attach hooks to collections the auth plugin created (e.g. sessions):

import type { Plugin } from 'payload'
import { emitAuthEvent } from '@trieb.work/payload-audit'

plugins: [authPlugin(), auditLogPlugin(), attachSessionAuthAudit('sessions')]

function attachSessionAuthAudit(slug: string): Plugin {
  return (config) => {
    const collection = config.collections?.find((c) => c.slug === slug)
    if (!collection) return config
    collection.hooks ??= {}
    collection.hooks.afterChange = [
      ...(collection.hooks.afterChange ?? []),
      async ({ doc, operation, req }) => {
        if (operation === 'create') {
          const user =
            typeof doc.user === 'object' ? doc.user : { id: doc.user }
          await emitAuthEvent({ req, event: 'login.success', user })
        }
        return doc
      },
    ]
    collection.hooks.afterDelete = [
      ...(collection.hooks.afterDelete ?? []),
      async ({ doc, req }) => {
        const user =
          typeof doc?.user === 'object' ? doc.user : { id: doc?.user }
        await emitAuthEvent({ req, event: 'logout', user })
        return doc
      },
    ]
    return config
  }
}

The same snippet works for Better Auth (payload-auth): use the session collection slug that plugin registers (sessions by default).

See the exported TypeScript types (AuditLogPluginConfig and friends) for the full reference and inline documentation.

Compliance mapping

RequirementCovered by
Who changed what, when (GDPR Art. 30, SOC 2 CC7)Automatic actor/action/timestamp capture on every collection
Tamper-proof records (ISO 27001 A.8.15, PCI-DSS 4.0 10.3)Immutable collection, API writes always denied
Incident detection & forensics (NIS-2, SEC Cyber Disclosure)Forensics metadata, token fingerprinting, delegation chains
Data retention limits (GDPR storage limitation)Configurable retention (age/count) with scheduled pruning
Access accountability across tenants (HIPAA, SOC 2)Multi-tenant scoping of the audit trail

This is a starting point, not legal advice — always validate against your own compliance obligations.

Development

pnpm install
pnpm dev          # start the dev Payload app (zero-config, in-memory Mongo)
pnpm build        # build the publishable plugin

Testing

The test suite is split into three layers:

  • Unit tests (pnpm test:int) — Fast, isolated tests for helpers (extractRequestMeta, resolveDocTitle, extractTenant) and plugin config wiring. Uses Vitest with vite-tsconfig-paths.

  • Integration tests (pnpm test:int) — Same Vitest run, but tests live against a real Payload instance (via getPayload with the dev config and mongodb-memory-server). Covers create/update/delete logging, upload tracking, multi-tenant scoping, retention pruning, immutability, native login events, and emitAuthEvent against real @trieb.work/payload-auth-pwless and payload-auth (Better Auth).

  • E2E tests (pnpm test:e2e) — Playwright tests against the running admin UI. Requires a built dev app first:

    pnpm build:dev   # or start the dev server manually
    pnpm test:e2e
    

Run everything:

pnpm test          # test:int + test:e2e

Contributing

Issues and pull requests are welcome — see the GitHub repository.

License

MIT © trieb.work

Similar plugins