focusreactive

payload plugin guard

by focusreactive
payload-plugins
Roles & permissions
v3
^3.90.0
MIT

Overview

Summary generated from the README

Lets a project define who may do what in one access policy file that covers every collection, global, field and job operation. The policy is applied to the built config with a wrapper function, and the boot fails when entries are missing, unknown or still hand-written. Plugins built on it declare named capabilities that the project grants, and their endpoints and Local API calls go through the guard. Requires Node 22.22 or later and Payload 3.90 or later, and is server-only.

Features

  • Access policy file checked against generated types, refusing to boot on missing or unknown entries
  • Typed gates and filters with and, or and not combinators
  • Guarded endpoints of panel, machine and public kinds with body size limits
  • Caller and system Local API wrappers that enforce access or restrict slugs
  • Endpoint census that fails the config on unreviewed endpoints
  • Refusal logging with an onRefusal listener and a capability lookup endpoint

Use cases

  • Replace scattered req.user checks with a single reviewed access policy across all collections and plugins
  • Build a Payload plugin whose endpoints and data access are granted by the host project through named capabilities
  • Detect probing by logging and counting refused requests to guarded endpoints

From the author

One guarded door for Payload CMS plugins: an access policy file, typed predicates, guarded endpoints and Local API wrappers

Installation

npm i @focus-reactive/payload-plugin-guard

37

Stars

5

Forks

33

Open Issues

Today

Last Updated

664

Weekly Downloads

v0.1.1

npm Version

295.2 KB

Unpacked Size

1

Dependencies

Repository stars

37+22 since Sep 7

Show data
Repository stars by day (UTC)
DateStars
Dec 6, 202637
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

Shared by 15 plugins in focusreactive/payload-plugins.

npm weekly downloads

Trends appear after 7 days of data. Collecting since Dec 5 — 2 daily snapshots so far.

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

Health Score

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

README

@focus-reactive/payload-plugin-guard

One guarded door for the @focus-reactive/* plugins for Payload CMS v3. The project writes who may do what in one access policy file, and every plugin built on the guard reads its rights from that file instead of checking req.user on its own.

The package is server-only and needs Node 22.22 or later (engines.node is >=22.22.0); it was verified on Node 22, 24 and 26. Run the server on Node, not on the bun runtime: there safeFetch throws, because bun's fetch cannot be pinned to the checked addresses, so every plugin request that goes through it fails. Its one runtime dependency is undici, which safeFetch uses to pin its connection; payload (^3.90.0) is its only peer dependency.

What it gives you

  • An access policy file that assigns access to every collection, global, field and job operation of the final config, and refuses to boot when anything is missing, unknown or still hand-written.
  • Typed predicates: gates (yes or no) and filters (yes, no or a where), with combinators.
  • Guarded plugins: a plugin declares named capabilities, the project grants each one with a gate, and the plugin's endpoints, collections and Local API calls go through the guard.
  • An endpoint census that fails the config when an endpoint was registered outside the guard and was not reviewed.

The policy file

Write the policy next to payload.config.ts and check it against the generated types with satisfies. A collection or global that has no entry, an entry for a slug that does not exist, or a missing operation is a type error.

// src/access.policy.ts
import {
  and,
  anyone,
  defineAccessPolicy,
  filter,
  gate,
  nobody,
  or,
  type AccessPolicy,
} from "@focus-reactive/payload-plugin-guard";
import type { PayloadRequest } from "payload";
import type { Config } from "./payload-types";

const roles = (req: PayloadRequest): string[] =>
  req.user?.collection === "users" ? (req.user.roles ?? []) : [];

const isAdmin = gate(({ req }) => roles(req).includes("admin"));
const isEditor = gate(({ req }) => roles(req).some((role) => ["admin", "editor"].includes(role)));
const isStaff = gate(({ req }) => req.user?.collection === "users");
const ownPages = filter(({ req }) =>
  req.user?.collection === "users" ? { owner: { equals: req.user.id } } : false
);

export const accessPolicy = defineAccessPolicy({
  collections: {
    users: {
      create: isAdmin,
      read: isStaff,
      update: isAdmin,
      delete: isAdmin,
      unlock: isAdmin,
      admin: isStaff,
      fields: { roles: { update: isAdmin } },
    },
    pages: {
      create: isEditor,
      read: or(isAdmin, and(isStaff, ownPages)),
      update: or(isAdmin, and(isEditor, ownPages)),
      delete: isAdmin,
      readVersions: or(isAdmin, and(isStaff, ownPages)),
      fields: { internalNote: { read: isAdmin } },
    },
    "ab-experiments": { create: nobody, read: isStaff, update: nobody, delete: nobody },
    "payload-kv": "payload-default",
    "payload-locked-documents": "payload-default",
    "payload-preferences": "payload-default",
    "payload-migrations": { create: nobody, read: isAdmin, update: nobody, delete: nobody },
  },
  globals: {
    settings: { read: anyone, update: isAdmin },
  },
  jobs: { run: isAdmin, queue: isAdmin, cancel: isAdmin },
  plugins: {
    ab: { duplicate: isEditor, manage: isAdmin },
  },
  allowedEndpoints: [
    { method: "get", path: "/health", reason: "Load balancer health check, returns no data" },
  ],
}) satisfies AccessPolicy<Config>;

payload generate:types normally ends payload-types.ts with declare module "payload" { interface GeneratedTypes extends Config {} }. That block types Payload's slugs for every program that contains the file, and the policy brings the file into every program that imports payload.config.ts. A program that imports the config and also builds other configs, such as integration tests with their own collections, then fails to type-check on every slug of its own. Keep the block out of the generated file and give it its own file that only the app's tsconfig.json includes:

// payload.config.ts
typescript: { outputFile: path.resolve(dirname, "payload-types.ts"), declare: false },
// src/payload-generated-types.d.ts
import type { Config } from "./payload-types";

declare module "payload" {
  export interface GeneratedTypes extends Config {}
}

The policy still imports Config from ./payload-types and is checked in every program that contains it, and the app keeps its typed Local API. A test tsconfig that includes only its own folder does not pick up the .d.ts file. Run payload generate:types after changing the option, and after adding a collection.

Applying the policy

Apply it to the result of buildConfig:

// src/payload.config.ts
import { buildConfig } from "payload";
import { withAccessPolicy } from "@focus-reactive/payload-plugin-guard";
import { abPlugin } from "@focus-reactive/payload-plugin-ab";
import { accessPolicy } from "./access.policy";

export default withAccessPolicy(
  accessPolicy,
  buildConfig({
    // ...
    plugins: [abPlugin({ access: accessPolicy.plugins.ab })],
  })
);

withAccessPolicy works on the sanitized config, so it also covers the collections Payload adds after the plugins have run. Give Payload the config it returns. An unchanged shallow copy ({ ...config }) also works; a copy with any key changed after the policy was applied stops the boot and names the changed keys, so make such changes inside buildConfig or in a plugin. It does four things, in this order:

  1. Assigns every entry to the config. A readVersions filter is rewritten for the versions collection, so it is written with the document's own field paths.
  2. Checks the policy against the config and throws one error that lists every problem: a collection, global or field with no entry; an entry for a slug that does not exist; "payload-default" on a collection that is not Payload-internal; a hand-written access function left on a collection, global or field; a guarded plugin whose capabilities are missing from plugins or were given different gates; a plugin-locked operation that is not nobody; a guarded plugin whose name is a collection slug or starts with globals, because Payload routes those paths to the collection or to globals and never reaches the plugin's endpoints.
  3. Runs the endpoint census on the config (see below).
  4. Runs the census again after the project's own onInit.

Rules worth knowing:

  • An auth collection needs admin; other collections cannot have it.
  • A collection or global with versions needs readVersions.
  • A config without globals may leave out the globals key; with globals, a missing key reports every global as missing.
  • "payload-default" keeps Payload's own access and is accepted only for payload-preferences, payload-locked-documents, payload-jobs, payload-kv, the folders collection and payload-query-presets. Payload's defaults admit any signed-in user, so the guard also requires a panel user: a user of another auth collection is refused. Query presets accept nothing else, because their access carries the per-preset sharing rules. payload-migrations needs a real entry: Payload gives it no access of its own, which lets any logged-in user read it. The global payload-jobs-stats, which Payload adds when a task or workflow has a schedule, needs { read: nobody, update: nobody }: the job scheduler reads and writes it through the database adapter, so no user needs it. The boot error names the entry to write for both.
  • A plugin field with its own access fails the boot until the policy gives that field an entry.
  • Field paths go through groups, arrays, named tabs and blocks: layout.hero.secret is the field secret of the block hero in the blocks field layout, whether the block is inline or referenced by slug from config.blocks. A block referenced by slug is one set of fields wherever it is used, so every entry that reaches one of its fields must give it the same gates. Every block in config.blocks is audited for hand-written field access, including blocks only rich text uses.
  • After adding a collection, add its policy entry and run payload generate:types.

Predicates

A gate answers yes or no. A filter answers yes, no, or a where that limits the documents. Only a strict true allows; a gate that returns anything but a boolean, or a filter that returns an empty object, throws.

Payload reads any truthy result as "allow" on create, on field access, on admin and on jobs, so those take gates only. A Gate is accepted wherever a Filter is, never the other way round.

HelperResult
gate(({ req }) => boolean)a gate
filter(({ req, id, data }) => boolean | Where)a filter
and(...predicates), or(...predicates)a gate when every input is a gate, otherwise a filter
not(gate)a gate
forVersions(filter)the filter with paths rewritten for the versions collection (title to version.title, id to parent)
nobodya gate that is always false
anyonea gate that is always true, for deliberately public reads
panelUsera gate that is true for a user of the admin user collection who may open the admin
siteRendera gate that is true only for a read made through site(payload), see Reads of the public site

principalOf(req) returns who is calling: anonymous, foreign (a user of another auth collection, or one the admin collection's access.admin refuses) or panel, together with the channel (session, api-key, mcp). panelUser is a floor, never a grant: low-role users and MCP agents are panel too. The admin gate of the admin user collection cannot itself use panelUser.

A guarded plugin

import type { CollectionSlug } from "payload";
import { createGuardedPlugin, GuardError, project } from "@focus-reactive/payload-plugin-guard";

interface AbOptions {
  collections: string[];
  cronSecret?: string;
}

export const abPlugin = createGuardedPlugin<AbOptions, "duplicate" | "manage">({
  name: "ab",
  capabilities: ["duplicate", "manage"],
  owns: () => ({ collections: ["ab-experiments"] }),
  manages: (options) => options.collections,
  setup: ({ config, options, guard }) => {
    guard.endpoint({
      kind: "panel",
      capability: "duplicate",
      method: "post",
      path: "/duplicate",
      input: (raw) => {
        const { collection, id } = raw as { collection?: unknown; id?: unknown };
        if (typeof id !== "string") {
          throw new GuardError(400, "id is required");
        }
        return { collection: guard.slug(collection) as CollectionSlug, id };
      },
      handler: async ({ input, caller }) => {
        const source = await caller.findByID({ collection: input.collection, id: input.id });
        const { id: _id, ...data } = source;
        const copy = await caller.create({ collection: input.collection, data });
        return { id: copy?.id ?? null };
      },
    });

    guard.endpoint({
      kind: "machine",
      secret: options.cronSecret,
      method: "post",
      path: "/rotate",
      input: () => undefined,
      handler: async ({ system }) => {
        const running = await system("rotate running experiments").find({
          collection: "ab-experiments",
        });
        return project(running, (result) => ({ rotated: result.totalDocs }));
      },
    });

    return {
      ...config,
      collections: [
        ...(config.collections ?? []),
        guard.collection({
          slug: "ab-experiments",
          locked: ["create", "update", "delete"],
          fields: [
            { name: "parent", type: "text", required: true },
            guard.serverField({ name: "startedBy", type: "number" }),
          ],
          hooks: { beforeChange: [guard.stamp("startedBy", ({ req }) => req.user?.id)] },
        }),
      ],
    };
  },
});

A plugin name is lowercase letters, digits and dashes, because it is the prefix of every endpoint path.

The definition lists the slugs the plugin's system may touch:

  • owns: the collections and globals the plugin creates with guard.collection and guard.global.
  • manages: the project's collections and globals the plugin reads and writes, the only slugs guard.slug accepts.
  • reads: slugs the plugin's system may only read, such as the admin user collection; every write to them is refused. It gets the options and the sanitized config, so reads: (_options, config) => [config.admin.user] names the admin user collection whatever the project called it.

The project passes the gates from its policy; access is a required option with no default:

abPlugin({ collections: ["pages"], cronSecret: process.env.AB_CRON_SECRET, access: accessPolicy.plugins.ab });

withAccessPolicy checks that the plugin got exactly the gates in policy.plugins.ab. A guarded plugin refuses to start when the config did not go through withAccessPolicy, on every init.

Generic options

A factory that takes a type argument, like abTestingPlugin<TVariantData>(options), keeps it by annotating the exported constant; type arguments do not exist at runtime, so no cast is needed:

import { createGuardedPlugin, type GuardedPluginOptions } from "@focus-reactive/payload-plugin-guard";
import type { Plugin } from "payload";

const guarded = createGuardedPlugin<AbOptions, AbCapability>({ /* ... */ });

export const abTestingPlugin: <TVariantData extends object = object>(
  options: GuardedPluginOptions<AbOptions<TVariantData>, AbCapability>
) => Plugin = guarded;
Types for helpers

These are exported so a plugin can pass the facade or its pieces into helpers in other files:

TypeWhat it is
Guard<TCaps>the guard facade given to setup; Guard<TCaps>["system"] types a stored guard.system
GuardedPluginOptions<TOptions, TCaps>the plugin's options with the required access
HookArgs<H>the arguments of a Payload hook type H plus caller and system
HookTools{ caller, system } as hooks get them
PanelHandlerArgs<I>, MachineHandlerArgs<I>, PublicHandlerArgs<I>the arguments of an endpoint handler of each kind
Caller, System<A>the Local API wrappers

Endpoints

guard.endpoint() registers the endpoint at the root, under /<plugin name>/, so the example above answers POST /api/ab/duplicate. The guard never adds an endpoint to a collection or a global.

KindWho gets inHandler gets
panel401 for anonymous, 403 for a foreign user, 403 for a channel not in channels (default ["session"]), then the capability gateinput, caller, system, principal, req, params, query
machineAuthorization: Bearer <secret>, compared in constant time; an empty secret leaves the endpoint unregisteredinput, system, req, params, query
publicanyoneinput, req, params, query
  • POST, PUT, PATCH and DELETE need Content-Type: application/json and an input parser; the body is capped at maxBodyBytes (64 KiB by default). The parser throws on invalid input and the request is answered with 400.
  • The handler's input is what the parser returns, with no type arguments to write. TypeScript reads an object from top to bottom, so the type reaches the handler only when input comes before handler; written after it, or left out on a GET, the handler gets unknown. A parser that only passes the body on, input: (raw) => raw, gives unknown, and the handler then checks the shape itself.
  • The handler returns data (sent as JSON) or a Response.
  • A thrown error is logged in full and answered with a generic body. Throw GuardError(status, publicMessage) to choose the status and the message. GuardError extends Payload's APIError, so thrown from a hook during a Payload REST or GraphQL request it is answered with its own status and message too.
  • GET /<plugin name>/capabilities is registered for every plugin with capabilities and reserved: see Capability lookup for admin UI.
Logging
What happensLevelLogged
A 401 or 403 from a guarded endpoint: anonymous, foreign user, channel, capability gate, machine secret, or a GuardError/APIError with that status from the handlerwarnguard: { plugin, kind, endpoint, capability, status, reason, principal: { kind, channel, user: { collection, id } } }
A 401 or 403 thrown inside guard.hookwarnguard: { plugin, hook, status, reason, principal }, where hook names the collection or global, field and operation
A not-found answer or another 4xxnot logged
Anything else thrownerrorthe error

Request bodies, headers, secrets and user emails are never logged. A stream of refusals from one principal or address is what probing looks like. withAccessPolicy sets Payload's own loggingLevels.GuardError to info unless the project set it, so Payload does not log a refused hook again as an error.

Listening to refusals

To count refusals, alert on them or send them to a store of your own, pass onRefusal as the third argument of withAccessPolicy:

export default withAccessPolicy(accessPolicy, buildConfig({ /* ... */ }), {
  onRefusal: ({ status, plugin, method, path, principal, channel, reason, capability }) => {
    metrics.increment("guard.refusal", { plugin, reason });
  },
});

It hears every refusal the table above logs at warn, after it is logged. reason is anonymous, foreign, channel, capability or secret when the guard refused the caller, and access for a 401 or 403 thrown inside a handler or a guarded hook. principal is the principal's kind and channel its channel; the event carries no user, request, body or header, and it is frozen. The listener cannot change the answer: the guard does not wait for it, and an error it throws or a promise it rejects is logged as an error while the request is still refused as before.

Capability lookup for admin UI

Every guarded plugin with capabilities answers GET /api/<plugin name>/capabilities with one boolean per capability of that plugin, for the user who asks:

// a client component of the ab plugin
const { routes } = useConfig().config;
const response = await fetch(`${routes.api}/ab/capabilities`, { credentials: "include" });
const can = (await response.json()) as { createVariant: boolean; splitTraffic: boolean };
  • The answer is computed with the gates from the policy and sent with Cache-Control: no-store.
  • Anonymous callers get 401; a foreign user or a channel other than session gets 403, as on a panel endpoint.
  • It lists only the asking plugin's capabilities and says nothing about other users.
  • Use it to hide or disable controls; every request is still checked on the server.

Capability check on the server

holdsCapability(req, { plugin, capability }) answers whether the request holds a capability of a guarded plugin, with the same checks as a panel endpoint: a panel user, on a listed channel (channels, default ["session"]), whom the plugin's gate from the policy admits. Use it where no guarded endpoint runs: a server component of an admin view, a hook, or a check of a stored grant when the user it names comes back.

import { holdsCapability } from "@focus-reactive/payload-plugin-guard";

const canSeeSessions = await holdsCapability(req, { plugin: "analytics", capability: "viewSessions" });
  • It answers false to anonymous callers, foreign users and other channels; it never throws for them.
  • It throws when the plugin or the capability does not exist, or when the config did not go through withAccessPolicy, because that is a mistake in the code, not an answer.
  • A capability is never enough on its own: check the user's right on the document as well, as a panel endpoint does.

Local API: caller and system

caller runs the Local API as the requesting user, with overrideAccess: false; it does not accept overrideAccess, user or showHiddenFields.

  • A refused read and a missing document look the same: findByID, update and delete throw the same NotFound, find returns an empty page and count returns zero.
  • findByIDOrNull and findGlobalOrNull answer null instead of throwing when the document is missing or the caller may not read it, so a plugin never catches Forbidden or NotFound by hand. findGlobal itself throws Payload's Forbidden when the policy refuses the read.
  • create, update, duplicate and updateGlobal return the document as the caller may read it, or null.
  • duplicate needs the caller's own read right on the source and create right on the collection; a source the caller cannot read throws the same NotFound as a missing one.
  • update and delete take an id; delete returns { id }.
  • caller.can("update", { collection, id }) answers with the caller's own right on that document.
  • findVersions, findVersionByID and findGlobalVersions apply readVersions; a refused version throws the same NotFound as a missing one and a refused list is an empty page.
  • restoreVersion needs the caller's own read right on the version and update right on the document, and returns the document as the caller may read it, or null.
  • Reads accept draft: true for any collection, including ones the plugin cannot type.

system(reason) runs with access off, at depth 0 by default, and only on the slugs the plugin owns and manages, plus reads of the slugs it lists in reads. Endpoint handlers and guard.hook get it bound to the plugin; guard.system(req, reason) gives the same system anywhere else in the plugin, such as a job handler, a hook added without guard.hook or a helper that only has req. Its results are branded: an endpoint refuses to return them, or anything inside them, until they go through project(result, (value) => ...), which returns plain data. The handler of guard.endpoint, route() and action() does not compile when its return type carries the brand, and the response is checked again at runtime; a return typed any, such as a React element, compiles and is still checked at runtime. It has the same methods as caller except duplicate, can and findGlobalOrNull (findByIDOrNull answers null for a missing document), plus writes the Local API cannot express:

  • updatePublishedWithoutDraft({ collection, id, data }) sets fields on the published document of a collection with drafts and leaves its latest draft as it is, for example a value that must go live without publishing the editor's unfinished changes. It takes only top-level, unlocalized, single-value scalar fields (text, textarea, email, number, checkbox, date, select, radio) and checks each value's type. It writes the stored document through the database adapter: no hooks, no validation, no new version. It returns false when the document has no published version.
  • insertRow({ collection, data }), updateRowIf({ collection, id, where, data }) and deleteRows({ collection, where }) write rows of a collection the calling plugin owns and locks for that operation (create, update, delete), through the database adapter: no hooks, no validation, no versions, no access. They are for stores only the plugin writes: an append-only log that a hook refuses to change, or a compare-and-set that must be one statement. updateRowIf updates the row with id only while it also matches where, and returns null when it no longer does. A collection that the calling plugin does not own, or whose operation it does not lock, is refused, even when another plugin owns and locks it. Only the system of a guarded plugin writes rows: the standalone system(req, reason, slugs) refuses them.

These and updatePublishedWithoutDraft are the guard's only database writes, so a plugin never needs payload.db. Outside a plugin, the same functions are available as caller(req) and system(req, reason, slugs). The standalone system has the same reads and writes on the slugs it is given, except row writes, because it belongs to no plugin that could own and lock a collection. Their types are exported as Caller and System, for helpers that take them as an argument.

Reads of the public site

A site that renders next to Payload reads its content through the Local API, with no user. Give those reads their own rule with the gate siteRender, and make them with site(payload):

// src/access.policy.ts
const published = filter(() => ({ _status: { equals: "published" } }));
// ...
pages: { read: or(isStaff, and(siteRender, published)), /* ... */ },
// the site's data layer
import { site } from "@focus-reactive/payload-plugin-guard";

const { docs } = await site(payload).find({ collection: "pages", where: { slug: { equals: slug } } });
  • siteRender is true for a read made through site(payload), and for the reads Payload makes on its behalf: the relations it populates and the hooks that pass its req on.
  • It is false for REST, GraphQL, the MCP endpoint and every request of the admin panel. The admin renders its pages and answers its server functions (form state, list and document views, folders) through the Local API, with the signed-in user or with none, so a rule on req.payloadAPI === "local" or on a missing user admits the admin panel too.
  • No request can set it: site() marks the read with an object only the guard holds, and no body, header or query equals it.
  • site() reads with overrideAccess: false and refuses overrideAccess, req, showHiddenFields and disableErrors. It has find, findByID, findByIDOrNull, count and findGlobal, and no writes.
  • It takes user, for example the signed-in editor of a draft preview: the read then gets what the policy gives that user or the site.
  • Use siteRender only in read rules, and limit it to what every visitor may see, such as published documents: any server code that calls site() reads what it admits.
  • site() reads outside the transaction of a request; a hook reads with caller(req) or system(req, reason, slugs).

Owned data and fields

  • guard.collection() and guard.global() create the plugin's own collections and globals. They take no access and no endpoints: access comes from the policy only. A locked operation must be nobody in the policy, so nobody reaches it over REST or GraphQL and the plugin writes through system. Consumer overrides add fields and hooks; they cannot remove plugin fields or set access.
  • guard.serverField(field) closes create and update on a field, so only system writes it.
  • guard.stamp(fieldName, ({ req, operation }) => value) is a beforeChange hook that overwrites the field on every write that carries a user.
  • guard.slug(input) returns the slug when the plugin manages it, otherwise throws GuardError(400). Its type covers collections and globals; narrow it when the plugin manages only collections.
  • guard.hook(fn) turns fn into a Payload hook that also gets caller and system bound to the plugin. The hook type comes from where the hook is placed (hooks: { afterChange: [guard.hook(...)] }) or is named: guard.hook<CollectionAfterChangeHook>(fn). A hook written in another file types its arguments with HookArgs<CollectionAfterChangeHook>.

Routes and server actions in project code

route() and action() give a Next.js route handler and a "use server" action of the project the same checks as guard.endpoint. The handler never gets payload: it gets caller, which acts with the rights of the request's user, and in every kind system(reason, slugs), the standalone system.

// src/app/(frontend)/next/preview/route.ts
import config from "@payload-config";
import { route } from "@focus-reactive/payload-plugin-guard";
import { redirect } from "next/navigation";
import { isEditor } from "@/access.policy";

export const GET = route({
  config,
  method: "GET",
  kind: "panel",
  gate: isEditor,
  input: (raw) => ({ path: String((raw as { path?: unknown }).path ?? "/") }),
  handler: ({ input }) => {
    redirect(input.path.startsWith("/") ? input.path : "/");
  },
});
// src/lib/search/search.ts
"use server";

import config from "@payload-config";
import { action } from "@focus-reactive/payload-plugin-guard";
import { headers } from "next/headers";

export const search = action({
  config,
  headers,
  name: "search",
  kind: "public",
  input: (raw) => ({ query: String((raw as { query?: unknown }).query ?? "").slice(0, 200) }),
  handler: async ({ input, caller }) => {
    const pages = await caller.find({ collection: "pages", where: { title: { like: input.query } } });
    return pages.docs.map((page) => ({ id: page.id, title: page.title }));
  },
});
KindWho gets inHandler gets
panela principal of the admin user collection on a channel in channels (default ["session"]) whom gate admits; 401 for anonymous, 403 otherwiseinput, caller, system, principal
machinea request that presents secret, compared in constant time; an empty secret answers 404input, caller (anonymous), system
publicanyoneinput, caller (with the request's rights), system
  • system(reason, slugs) is the same in every kind: access off, limited to slugs, results branded until project(). A public handler gets it too, because project code has no req to call system with otherwise, and a route that anyone may call still has work no visitor may do directly, such as provisioning the user of a verified sign-in. Since anyone can trigger it, keep it to work whose outcome does not depend on who calls, and return only what project() lets through.
  • config is the config withAccessPolicy returned, or the promise of it, such as the @payload-config import. When Payload cannot start for it, the config did not go through withAccessPolicy, or its boot failed, a route answers a generic 500 and an action { ok: false, status: 500, error }, and the error is logged with console.error, since there is no Payload logger to use.
  • gate is a gate, such as one from the policy file; anything else throws when the route or action is defined.
  • A route also hands the handler request and the route's params. method must match the request (a GET route also answers HEAD), or it answers 405. POST, PUT, PATCH and DELETE need Content-Type: application/json and an input parser, and the body is capped at maxBodyBytes (64 KiB by default). A GET parser gets the search parameters as an object. A machine route reads the secret from Authorization: Bearer <secret>, or from token(request), for a link that carries it in the query, such as the preview link of Live Preview.
  • An action takes headers (pass headers from next/headers), a name for the log, and an input parser for its one argument, capped at maxInputBytes (64 KiB by default, form data included). A machine action reads Authorization: Bearer <secret>. It answers { ok: true, data } or { ok: false, status, error }.
  • The answers to a refusal, invalid input and a thrown error are the same generic bodies an endpoint gives, and the refusals are logged and heard by onRefusal with plugin left out.
  • redirect(), notFound() and the other errors Next throws to end a request (an error with a digest) pass through unchanged.
  • Returning a system() result without project() answers 500, as in an endpoint.
  • bun run check-security accepts a "use server" file whose every exported value is an action() call, without a security-allow comment.

Endpoint census

The census walks the config and classifies every endpoint as Payload core, made by the guard, or unregistered. Payload core is every endpoint Payload registers itself, including those of optional features such as API key reveal (auth.useAPIKey.reveal) and orderable collections. Core endpoints are recognised by handler identity against a reference config the guard builds; the handlers Payload creates anew for each config, such as the POST /reorder of orderable, are recognised by their place and their source text. It fails when an unregistered root endpoint is not in policy.allowedEndpoints, or when any custom endpoint sits on a collection or a global, where it can shadow Payload's own routes.

A plugin that is not built on the guard registers its endpoints the same way your own code does, so each of them needs an entry. Some appear only when an environment variable is set, and then the census fails on the deployment and not on your machine. @payloadcms/storage-vercel-blob with clientUploads: true is one: with BLOB_READ_WRITE_TOKEN set it adds POST /vercel-blob-client-upload-route. Read what the endpoint checks before you allow it, and write that down as the reason:

allowedEndpoints: [
  {
    method: "post",
    path: "/vercel-blob-client-upload-route",
    reason: "Vercel Blob client uploads; the storage plugin requires a signed-in user with create or update access to the upload collection",
  },
],

It runs twice:

  • In withAccessPolicy, so a config with an endpoint the census refuses never reaches Payload: the promise withAccessPolicy returns rejects, and every Payload init that awaits it fails.
  • After the project's onInit, for the root endpoints added there.

The endpoint lists cannot change outside these checks:

  • The collection and global endpoint arrays are frozen when the policy is applied.
  • The root endpoint array accepts changes only during the first onInit of the config, and is frozen after it.
  • A config whose onInit never runs, because Payload was started with disableOnInit or because Payload's development reload swapped it in, keeps the root list the first census checked.

@payloadcms/next adds its Open Graph image route, GET /og, to the root endpoints on the first API request, which can come before or after the census. The guard treats it as core when it arrives after withAccessPolicy and outside onInit, and lets it in after the census; it is the only change the frozen root array accepts. Its handler cannot be imported from outside the Next.js bundle, so it is recognised by when it arrives and by its shape, not by identity. A GET /og registered in the config or during onInit is classified like any other endpoint.

census(payload) returns the same report, with custom GraphQL queries and mutations, job tasks and workflows, and admin views.

A failed boot is final

When a boot check of the guard fails for a config, the config stays refused for the life of the process:

  • Every later Payload init of that config fails with the same error. This matters because Payload retries a failed init on the next request and skips onInit on that retry.
  • Access functions from the policy, guarded endpoints, caller, system and holdsCapability throw that error for a request of that config; guarded endpoints, route() and action() answer it with a generic 500.

The boot checks are the policy check, the census, the check that Payload got the config withAccessPolicy returned or an unchanged copy of it, and a guarded plugin's check that the config went through withAccessPolicy. The guard repeats the last two, and refuses a config whose boot failed, when Payload sets up the database adapter, which every init does, also one that skips onInit. A fixed config is a new config object, and the guard checks it anew.

Helpers

  • safeEqual(a, b): constant-time string comparison.
  • escapeHtml(text): escapes & < > " '.
  • sandboxHeaders(allow?): Content-Security-Policy: sandbox and X-Content-Type-Options: nosniff, for responses that render user content. allow lifts only scripts, forms, popups or modals (sandboxHeaders(["scripts"]) sends sandbox allow-scripts); the document always keeps an opaque origin, so its scripts never act as the CMS origin.
  • publicUser(user, nameField): { id, name }, never the email.
  • safeFetch(url, { allowedHosts, timeoutMs, privateHosts, ...init }): fetches only allowed hosts over http or https, refuses private, loopback and link-local addresses, and never follows redirects.
    • The connection goes only to the addresses that were checked: the host is resolved once, and the request never resolves it again, so a host that answers a public address for the check and a private one afterwards cannot reach the private one. Under the bun runtime, whose fetch cannot be pinned, safeFetch throws instead of fetching.
    • timeoutMs (10 seconds by default) aborts the request and the reading of its body; the call then rejects with a TimeoutError, and a signal you pass still aborts it too.
    • privateHosts: { hosts, reason } lets listed hosts resolve to private or loopback addresses, for a service the project runs on its own network, such as a local render service. Each host must also be in allowedHosts, both lists come from the project's config, never from a request, and the reason (at least ten characters) says why, so the allowance is visible in review. Redirects are still not followed, so an allowed private host cannot send the request anywhere else.

Similar plugins