focusreactive

payload plugin audit log

by focusreactive
payload-plugins
Logging & monitoring
v3
^3.90.0
MIT

Overview

Summary generated from the README

Adds an append-only audit-events collection that records who changed which document or global and when, plus sign-ins, failed logins and password resets. Actors include users, API keys, MCP agents and system calls. Only changed field paths are stored, not values. It requires Payload 3.90 or later, React 19 and the companion guard plugin for access policies, and supports Postgres, SQLite and MongoDB.

Features

  • Records create, update, autosave, delete, publish, unpublish and version restore events
  • Tracks sign-ins, sign-outs, failed logins and password resets with hashed identifiers
  • Identifies actors such as users, API keys, MCP agents, system and anonymous callers
  • Exports events as CSV or NDJSON from the admin list view with filters kept
  • Optional retention job that deletes events older than a set number of days
  • Helpers withAuditActor and logAuditEvent to label scripts and log custom events

Use cases

  • Review who edited or published content for compliance and editorial accountability
  • Audit actions taken by API keys and AI agents connected through MCP
  • Detect repeated failed sign-in attempts against an account

From the author

Audit log for Payload CMS: document, global and auth changes, with API keys and AI agents (MCP) as actors, and CSV / NDJSON export

Installation

npm i @focus-reactive/payload-plugin-audit-log

37

Stars

5

Forks

33

Open Issues

Today

Last Updated

58

Weekly Downloads

v2.0.1

npm Version

311.0 KB

Unpacked Size

1

Dependencies

Repository stars

37+22 since Sep 6

Show data
Repository stars by day (UTC)
DateStars
Dec 5, 202637
Dec 4, 202637
Dec 3, 202637
Dec 2, 202637
Dec 1, 202636
Nov 30, 202635
Nov 29, 202635
Nov 28, 202634
Nov 27, 202634
Nov 26, 202634
Nov 25, 202634
Nov 24, 202634
Nov 23, 202634
Nov 22, 202634
Nov 21, 202634
Nov 20, 202633
Nov 19, 202632
Nov 18, 202632
Nov 17, 202632
Nov 16, 202632
Nov 15, 202632
Nov 14, 202632
Nov 13, 202632
Nov 12, 202632
Nov 11, 202632
Nov 10, 202632
Nov 9, 202631
Nov 8, 202631
Nov 7, 202631
Nov 6, 202631
Nov 5, 202631
Nov 4, 202630
Nov 3, 202630
Nov 2, 202630
Nov 1, 202630
Oct 31, 202630
Oct 30, 202630
Oct 29, 202630
Oct 28, 202630
Oct 27, 202630
Oct 26, 202630
Oct 25, 202630
Oct 24, 202629
Oct 23, 202629
Oct 22, 202629
Oct 21, 202629
Oct 20, 202629
Oct 19, 202629
Oct 18, 202629
Oct 17, 202627
Oct 16, 202626
Oct 15, 202626
Oct 14, 202626
Oct 13, 202625
Oct 12, 202625
Oct 11, 202625
Oct 10, 202625
Oct 9, 202625
Oct 8, 202625
Oct 7, 202625
Oct 6, 202624
Oct 5, 202624
Oct 4, 202624
Oct 3, 202623
Oct 2, 202622
Oct 1, 202622
Sep 30, 202620
Sep 29, 202620
Sep 28, 202620
Sep 27, 202620
Sep 26, 202619
Sep 25, 202618
Sep 24, 202618
Sep 23, 202618
Sep 22, 202618
Sep 21, 202618
Sep 20, 202618
Sep 19, 202618
Sep 18, 202618
Sep 17, 202618
Sep 16, 202618
Sep 15, 202618
Sep 14, 202618
Sep 13, 202617
Sep 12, 202617
Sep 11, 202617
Sep 10, 202616
Sep 9, 202616
Sep 8, 202616
Sep 7, 202615
Sep 6, 202615

Shared by 15 plugins in focusreactive/payload-plugins.

npm weekly downloads

77+77 since Nov 24

Show data
npm weekly downloads by day (UTC)
DateWeekly downloads
Dec 5, 202677
Dec 4, 202687
Dec 3, 2026295
Dec 2, 2026493
Dec 1, 2026485
Nov 30, 2026481
Nov 29, 2026464
Nov 28, 2026443
Nov 27, 2026425
Nov 26, 2026210
Nov 25, 20260
Nov 24, 20260

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

Health Score

68/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/1177993877-payload-plugin-audit-log.svg)](https://payloaddirectory.dev/plugins/1177993877-payload-plugin-audit-log)
HTML
<a href="https://payloaddirectory.dev/plugins/1177993877-payload-plugin-audit-log"><img src="https://payloaddirectory.dev/badge/1177993877-payload-plugin-audit-log.svg" alt="Payload Directory"></a>
Updated Dec 5, 2026Created Mar 10, 2026Published Dec 4, 2026

README

@focus-reactive/payload-plugin-audit-log

Audit log for Payload CMS v3: an append-only collection of who changed which document or global and when, plus sign-ins, API keys and AI agents, with CSV / NDJSON export. A change records the paths of the fields that changed, not their values; What an event stores lists everything else it keeps.

Audit log list with action and actor pills and export buttons

Filter by actor, action or targetChanged field paths, IP and User-Agent
Audit log filtered by actorChanges, IP and User-Agent of one event

AI Integration Prompt

Copy and paste this prompt into your AI assistant (Cursor, Claude, etc.) to integrate the plugin into an existing Payload project.

I want to add an audit log to my Payload CMS v3 project using
@focus-reactive/payload-plugin-audit-log. Follow these steps in order, and stop to ask me where a step says so.

## Rules you must follow

- Never write an access rule that admits every logged-in user: no `Boolean(req.user)`, no `() => true`,
  no `({ req }) => !!req.user`. A rule names a role, or it is `nobody`.
- Do not invent roles. Ask me which roles may read the log and which may export it.
- Write every policy entry by hand in `src/access.policy.ts`, and grant each capability and each
  collection right explicitly to the roles I name. Nothing is open by default.
- When the boot or a request fails, fix the cause or ask me. Never use `anyone`, a looser gate,
  `overrideAccess` or a removed or disabled check to make an error go away.
- Do not add `overrideAccess: true` anywhere, and do not add `access` to the plugin's collection.

## How it works

The plugin adds an append-only collection "audit-events" (admin group "Settings") that records document
and global changes (create, update, autosave, delete, publish, unpublish, version restore), sign-ins,
sign-outs, failed sign-ins and password resets. Each event stores the actor (user, API key, MCP agent,
system, anonymous), the target, the paths of changed fields, IP and User-Agent. Nobody can create, edit or
delete events over REST, GraphQL, the admin panel or the Local API; only the plugin writes them.
Who may read events is the `read` rule of "audit-events" in the project's access policy.
The plugin declares one capability that the project grants in the same policy:
- `export`: download the events the caller may read as CSV or NDJSON (GET /api/audit-log/export).

## Step 1: install

pnpm add @focus-reactive/payload-plugin-audit-log @focus-reactive/payload-plugin-guard

Check that `payload` and `@payloadcms/ui` are 3.90 or later; if they are not, upgrade them first.
React 19 is required. Postgres, SQLite and MongoDB are supported.

## Step 2: ask me about roles

Look at the auth collection named in `admin.user` and the roles it has. Ask me:
"Which roles may read the audit log?" and "Which roles may export it?"
Wait for my answers. Write each answer as a gate or filter in the policy file in step 3.
A role that may export must also be able to read: an export holds only the events its caller may read.

## Step 3: the access policy file

Open `src/access.policy.ts`, or create it if the project has none, following the guard README
(`defineAccessPolicy`, `gate`, `filter`, `nobody`, checked with `satisfies AccessPolicy<Config>`).
If you create it, every collection and global of the config needs an entry: move each existing
`access` of the project into the file, and ask me for every rule you cannot read from the code.
Add these entries for this plugin:

collections: {
  'audit-events': { create: nobody, read: <the rule from my first answer>, update: nobody, delete: nobody },
},
plugins: {
  'audit-log': { export: <the gate from my second answer> },
},

Only if I want old events deleted (retention, step 4): Payload then adds its jobs collection and a
global for scheduled jobs, so also add
  collections: { 'payload-jobs': 'payload-default' }
  globals: { 'payload-jobs-stats': { read: nobody, update: nobody } }

## Step 4: register the plugin and wrap the config

// payload.config.ts
import { buildConfig } from 'payload'
import { withAccessPolicy } from '@focus-reactive/payload-plugin-guard'
import { auditLogPlugin } from '@focus-reactive/payload-plugin-audit-log'
import { accessPolicy } from './access.policy'

export default withAccessPolicy(
  accessPolicy,
  buildConfig({
    // ...the existing config
    plugins: [
      // after any plugin that creates collections or globals
      auditLogPlugin({
        access: accessPolicy.plugins['audit-log'],
        retention: { days: 365 }, // optional, default: keep forever
      }),
    ],
  })
)

With @payloadcms/plugin-mcp (order: 10), give the audit plugin a higher order so MCP keys and agents
are audited: Object.assign(auditLogPlugin({ ... }), { order: 11 })

Run `payload generate:importmap`, then start the app.
A missing or wrong policy entry stops the boot with a list of what to fix.
Fix each item; never loosen a rule to make an error go away.
Postgres / SQLite with migrations: run `payload migrate:create add_audit_log && payload migrate`.
With retention, make sure jobs run (jobs.autoRun, or a cron calling payload.jobs.run()).

Scripts and agents: wrap Local API calls to name the actor, otherwise they are logged as "system":
  import { withAuditActor } from '@focus-reactive/payload-plugin-audit-log'
  await withAuditActor({ type: 'system', label: 'nightly import' }, () => payload.update({ ... }))

## Step 5: verify, and show me the output

With the app running, send each request and show me the status code.
Every one of them must be refused. If one succeeds, the policy is wrong: stop and tell me.

1. Anonymous export, expect 401:
   curl -i 'http://localhost:3000/api/audit-log/export?format=csv'
2. The same request with the session cookie of a user whose role may not export, expect 403.
3. Anonymous read of the log, expect 403:
   curl -i http://localhost:3000/api/audit-events
4. A read of the log with the session cookie of a user whose role may not read it, expect 403.
5. A write to the log with an admin's session cookie, expect 403:
   curl -i -X POST http://localhost:3000/api/audit-events -H 'Content-Type: application/json' -d '{}'

Then edit and publish a document, sign in with a wrong password, open Settings → Audit log as a user who
may read it, and press Export CSV as a user who may export. Custom events (for example SSO logins): see
logAuditEvent in the plugin README.

Setup

pnpm add @focus-reactive/payload-plugin-audit-log @focus-reactive/payload-plugin-guard
// src/access.policy.ts
import { defineAccessPolicy, gate, nobody } from "@focus-reactive/payload-plugin-guard";

const isAdmin = gate(({ req }) => req.user?.collection === "users" && req.user.roles?.includes("admin"));

export const accessPolicy = defineAccessPolicy({
  collections: {
    // ...an entry for every collection of the project
    "audit-events": { create: nobody, read: isAdmin, update: nobody, delete: nobody },
  },
  plugins: {
    "audit-log": { export: isAdmin },
  },
});
// payload.config.ts
import { withAccessPolicy } from "@focus-reactive/payload-plugin-guard";
import { auditLogPlugin } from "@focus-reactive/payload-plugin-audit-log";
import { buildConfig } from "payload";
import { accessPolicy } from "./access.policy";

export default withAccessPolicy(
  accessPolicy,
  buildConfig({
    plugins: [auditLogPlugin({ access: accessPolicy.plugins["audit-log"], retention: { days: 365 } })],
  })
);
  • Requires payload and @payloadcms/ui 3.90+, react 19, and @focus-reactive/payload-plugin-guard.
  • Databases: Postgres, SQLite, MongoDB. On Postgres / SQLite run payload migrate:create and payload migrate after installing and after upgrades that change select options.
  • Run payload generate:importmap for the export buttons.
  • Place the plugin after plugins that add collections or globals. @payloadcms/plugin-mcp has order: 10, so give the audit plugin a higher order to audit its API keys.
  • With retention, Payload adds its jobs collection and the payload-jobs-stats global, so the policy also needs "payload-jobs": "payload-default" and globals: { "payload-jobs-stats": { read: nobody, update: nobody } }.

Events

ActionWhen
doc.createA document is created or duplicated
doc.updateA document is changed, autosaved, moved to trash or restored from trash
doc.deleteA document is deleted permanently
doc.publish / doc.unpublishA document's status changes to / from published
doc.restoreA version is restored
global.update / global.publish / global.unpublishA global is changed, autosaved, published or unpublished
auth.login / auth.logoutLogin or logout through Payload
auth.login_failedFailed REST or GraphQL login (metadata.reason: invalid_credentials or locked)
auth.password_reset_requested / auth.password_resetForgot-password and reset-password
audit.export / audit.retention_purgeThe log was exported or purged
  • Only Payload operations and hooks are recorded. Raw payload.db calls and SQL get no events; seeds and migrations get none of their own. Local API calls without a user are recorded with the system actor.
  • Role changes and API key changes are plain doc.update / doc.create / doc.delete events of the user or key collection.
  • An autosave is a doc.update or global.update event with metadata.autosave: true. Filter on it to hide autosaves from a review.
  • changes lists changed field paths. Array and block rows are matched by id: an edited row gives items.2.title, an added row items.2, a removed or reordered row items. JSON and rich text fields are reported by their own path.
  • When the changed paths cannot be worked out, the event is still recorded, with changes: ["…"], and the cause is logged.
  • Event fields: occurredAt, action, status, actor, onBehalfOf, agent, via, target (kind, slug, docId, label, locale), changes, overrideAccess, requestId, ip, userAgent, metadata.
  • via is admin for a REST request of a user of the admin user collection signed in with the admin panel's session cookie, rest for any other REST request (an API key, a token in the Authorization header, another auth collection, no user), and graphql, mcp or local for the other channels. It never depends on a header that a caller can set without signing in, such as Referer.

Failed logins

  • The identifier that was typed (email or username) is never stored, because people type passwords into it by mistake. metadata.identifierHash is a keyed hash of it (HMAC-SHA256 with the Payload secret, of the trimmed, lowercased identifier), so repeated attempts against one account can be grouped without keeping the text. The actor is anonymous, without a label.
  • At most 30 failed logins a minute are recorded per server process. The first one recorded after a pause carries metadata.notRecordedBefore with the number that were left out.
  • GraphQL login mutations are recorded whether they are sent under their own name or an alias, with the identifier inline or as a variable.

What an event stores

Field values of the changed document are not stored, only their paths. These values are stored:

  • target.label: the document's useAsTitle field at the time of the event.
  • actor.label and onBehalfOf.label: the user's email, name or username, or the label passed to withAuditActor / logAuditEvent.
  • ip and userAgent from the request headers, unless recordIpAndUserAgent: false.
  • metadata of audit.export: the format, the field names used in the export's filter (not their values) and the row limit.
  • metadata of auth.login_failed: the reason and the identifier hash described above.
  • metadata you pass to logAuditEvent, as given.

Actors

  • user: a signed-in user.
  • api_key: a request authenticated with a Payload API key.
  • agent: an MCP request, or code that sets the actor to agent.
  • system: a Local API call without a user.
  • anonymous: a request without a user.

withAuditActor labels every Local API call inside the callback. req.context.auditActor (CTX_ACTOR) sets the actor for one request.

import { withAuditActor } from "@focus-reactive/payload-plugin-audit-log";

await withAuditActor({ type: "system", label: "initial content" }, async () => {
  await payload.create({ collection: "pages", data: { title: "Home" } });
});

logAuditEvent(payload, { action, target, status?, changes?, overrideAccess?, metadata?, actorOverride?, req?, headers? }) writes a custom event, such as an SSO login. It does nothing when the plugin is not installed or disabled.

Options

OptionDefaultMeaning
accessrequired{ export }: the gate from your access policy, accessPolicy.plugins["audit-log"]
enabledtruefalse adds nothing to the config
slug"audit-events"Slug of the log collection
excludeCollections[]Collections not to log; the log itself is always excluded
excludeGlobals[]Globals not to log
retentionnot set{ days, queue?, cron? }: delete events older than days (1–36500)
recordIpAndUserAgenttrueStore ip and userAgent from request headers
maxChangedPaths200Maximum entries in changes; a longer list ends with …

Invalid retention.days or maxChangedPaths throws when the config is built.

Access and capabilities

WhatDecided by
Reading events (admin list, REST, GraphQL, Local API with overrideAccess: false)the read rule of audit-events in your policy
Exportingthe export capability, and then the same read rule for each event
Creating, updating, deleting eventsnobody: the plugin locks these operations, and the guard refuses a policy that grants them

The plugin owns audit-events: it writes events and the retention job deletes old ones through the guard, and nothing else can, even with overrideAccess. There is no default read rule: the policy entry is required, and the guard refuses to boot without it.

Export

  • GET /api/audit-log/export?format=csv|ndjson, with the REST where filter and search (at most 200 characters).
  • It answers signed-in users of the admin user collection, through a session or an API key, who hold the export capability. Anonymous callers get 401; users of another auth collection and users without the capability get 403.
  • The file holds only the events the caller may read under the policy's read rule.
  • Export CSV and Export NDJSON buttons in the admin list view keep the current filter and search. They are shown only to users who may export (GET /api/audit-log/capabilities).
  • At most 100,000 rows per request. Each export writes an audit.export event.
  • A collection of your own with the slug audit-log would hide the endpoints, so the guard refuses such a config at boot.

Retention

retention.days registers a job that runs daily at 03:00 on queue default (override with cron / queue). It requires a jobs runner: jobs.autoRun or an external call to payload.jobs.handleSchedules() and payload.jobs.run(). Without retention events are kept forever.

Performance

  • Reads (find, findByID, findGlobal, REST GET) are unaffected.
  • On Postgres a write takes 0.6–2 ms longer; bulk updates about 1.25 ms per document.
  • Two saves read the stored document once more (about 4.5 ms):
    • a publish by id over a draft in an autosave collection;
    • a save by id that is neither a draft save nor a publish while the latest version is a draft.
  • Each event takes 0.5–0.6 KB including indexes. Autosave adds one event per autosave. The admin list count and search box scan the table, so set retention.days.

Limitations

  • Writes outside Payload operations (raw SQL, payload.db, direct database access) are not audited, by design.
  • No hash chain: rows can be changed by anyone with database access.
  • Without a transaction, a failed save keeps what it already wrote: a change may have no event, or an event may remain for a failed save.
  • On MongoDB, events are written after commit; if the process stops in between, the change has no event.
  • Agents outside MCP are recorded as agents only if they set the actor.
  • Fields cleared by the database (ON DELETE SET NULL) are not recorded.
  • Failed logins through the Local API are not recorded.
  • The failed-login limit counts per server process, so several instances record up to 30 a minute each.
  • ip and userAgent come from client headers; trust ip only behind a proxy that sets x-forwarded-for.
  • job in via is never detected; label task handlers to get it.
  • A successful REST login of a user of the admin user collection is via: "admin" whichever client sent it, because a login carries no session yet.

Upgrading

Migrating from 1.x

2.0 moves the plugin onto @focus-reactive/payload-plugin-guard; Upgrading to the guard explains the model all the plugins share, with a complete example. Every access rule is now written by hand in your project's src/access.policy.ts, and nothing is open by default: an entry you leave out stops the boot, and a capability you do not grant is refused for everyone.

What changes
  • Payload and every @payloadcms/* package 3.90 or later, with the React and Next versions Payload 3.90 requires, Node 22.22 or later, and @focus-reactive/payload-plugin-guard installed next to the plugin.
  • access: { read } is replaced by the policy: the old read rule becomes the read entry of audit-events, and downloading the log is the export capability. There is no default any more: 1.x let every user of the admin user collection read and export the whole log.
  • REST and GraphQL writes to audit-events are refused for everyone; only the plugin writes events.
  • The export moved from /api/audit-events/export to /api/audit-log/export, and the search term is capped at 200 characters. The admin buttons already use the new path.
  • Failed logins no longer store the typed identifier as the actor's label; metadata.identifierHash replaces it, and at most 30 are recorded a minute per process.
  • Autosaves are recorded, with metadata.autosave: true.
  • via is admin only for a REST request signed in with the admin panel's session cookie; 1.x read it from the Referer header.
Steps
  1. Upgrade payload and every @payloadcms/* package to 3.90 or later, run the server on Node 22.22 or later, and install the guard: pnpm add @focus-reactive/payload-plugin-guard @focus-reactive/payload-plugin-audit-log.

  2. Add the plugin's entries to src/access.policy.ts, with gates for your own roles; if the project has no policy file yet, write it first as the guide describes.

    // src/access.policy.ts, inside defineAccessPolicy({ ... })
    collections: {
      "audit-events": { create: nobody, read: isAdmin, update: nobody, delete: nobody },
      "payload-jobs": "payload-default", // only with retention
    },
    globals: {
      "payload-jobs-stats": { read: nobody, update: nobody }, // only with retention
    },
    plugins: {
      "audit-log": { export: isAdmin },
    },
    
    • export: download the log as CSV or NDJSON from GET /api/audit-log/export.
    • audit-events: read decides who may read the log in the admin and over the API; every write stays nobody.
    • payload-jobs and payload-jobs-stats: Payload adds them when retention schedules the purge job.
  3. Pass access: accessPolicy.plugins["audit-log"] to auditLogPlugin, and export the config wrapped: export default withAccessPolicy(accessPolicy, buildConfig({ ... })).

  4. Database: no migration; the log collection keeps its columns.

  5. Re-test: an anonymous GET /api/audit-log/export?format=csv answers 401 and one from a user without export 403; POST /api/audit-events as an admin answers 403; a user without the read rule gets 403 from GET /api/audit-events; then change a document and sign in with a wrong password, and check that both appear in the log.

License

MIT

Similar plugins