M1 (6): nobody creates an account for themselves

accounts.adminOnlyCreate (on): a staff collection without a create rule gets
"an admin, fully signed in" instead of Payload's "any logged-in user" — also the
project's own collection; a rule the project wrote stays.
accounts.firstUserRoute ('panel'): Payload's first-user route answers only for
the collection the panel logs in with. For any other empty auth collection it is
refused, unless that collection's own create rule lets an anonymous request in.
Checked and closed: an empty second staff collection, whose first visitor became
a staff admin (test/accountRulesOff.test.ts records the old behaviour, which
accounts: false / firstUserRoute: 'all' still give).
Doctor: open-signup (deep, info) names auth collections with open sign-up.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-25 00:39:12 +01:00
co-authored by Claude Fable 5.2
parent cd60b73685
commit c6fc0d21fe
10 changed files with 364 additions and 5 deletions
+99
View File
@@ -0,0 +1,99 @@
import type { Access, CollectionBeforeOperationHook, Config } from 'payload'
import { Forbidden } from 'payload'
import { userMeetsRole } from './predicates.js'
/**
* Nobody creates an account for themselves.
*
* Two doors, both closed by default (`accounts.adminOnlyCreate`, `accounts.firstUserRoute`):
*
* 1. **`create` on a staff collection.** Payload's default for a collection without a `create`
* rule is "any logged-in user". On a project's own staff collection that let every signed-in
* account — the lowest role included — make accounts. Default now: an admin (a staff account
* that passes `userMeetsRole(req, 'admin')`, the second factor included). A `create` rule the
* project wrote stays.
*
* 2. **Payload's first-user route** (`POST /api/<slug>/first-register`) exists for EVERY auth
* collection and answers while that collection is empty — also for one that allows no
* sign-up, and for a second staff collection, whose first account would be staff. Default
* now: only the collection the panel logs in with (the first account of a site, which
* becomes admin). Another collection's route answers only when that collection's own
* `create` rule lets an anonymous request through (it allows sign-up anyway).
*
* A visitor collection that allows sign-up (`customers` with `create: () => true`) is not
* touched by either.
*/
/** `create` for a staff collection: an admin, fully signed in. */
export const staffCreateAccess: Access = ({ req }) => userMeetsRole(req, 'admin')
/** Adds `staffCreateAccess` to the named collections where the project wrote no `create` rule. */
export function applyAdminOnlyCreate(config: Config, staffSlugs: string[]): Config {
return {
...config,
collections: (config.collections ?? []).map((collection) =>
collection.auth && staffSlugs.includes(collection.slug) && !collection.access?.create ? { ...collection, access: { ...collection.access, create: staffCreateAccess } } : collection,
),
}
}
/** `accounts.firstUserRoute`: `'panel'` (default) = the panel's login collection only; slugs = those; `'all'` = Payload's behaviour. */
export type FirstUserRouteOption = 'all' | 'panel' | string[]
const FIRST_REGISTER = /\/first-register\/?$/
/**
* `beforeOperation` hook for an auth collection: refuses the first-user route unless the
* collection is allowed (see above). Not involved in any other create.
*/
export function buildFirstUserGuard(option: FirstUserRouteOption = 'panel'): CollectionBeforeOperationHook {
return async ({ args, collection, operation, req }) => {
if (operation !== 'create' || !req?.pathname || !FIRST_REGISTER.test(req.pathname)) {return args}
const slug = collection.slug
const allowed = Array.isArray(option) ? option.includes(slug) : slug === req.payload.config.admin?.user
if (allowed) {return args}
// a collection that lets a visitor sign up anyway may keep its first-user route
let open = false
try {
open = Boolean(await collection.access?.create?.({ data: (args as { data?: unknown }).data, req: { ...req, user: null } } as never))
} catch {
open = false
}
if (!open) {throw new Forbidden(req.t)}
return args
}
}
/** Adds the guard to every auth collection (it lets the allowed ones through itself). `'all'` adds nothing. */
export function applyFirstUserRoute(config: Config, option: FirstUserRouteOption = 'panel'): Config {
if (option === 'all') {return config}
if (option !== 'panel' && !Array.isArray(option)) {
throw new Error(`[ipal] accounts.firstUserRoute must be 'panel', 'all' or a list of collection slugs, got ${JSON.stringify(option)}.`)
}
const guard = buildFirstUserGuard(option)
return {
...config,
collections: (config.collections ?? []).map((collection) =>
collection.auth ? { ...collection, hooks: { ...collection.hooks, beforeOperation: [guard, ...(collection.hooks?.beforeOperation ?? [])] } } : collection,
),
}
}
/**
* Auth collections whose `create` rule lets an anonymous request through — open sign-up.
* For the doctor (slugs only). A rule that throws, or needs more than `{ req }`, counts as closed.
*/
export async function openSignUpCollections(payload: { collections: Record<string, { config: { access?: { create?: Access }; auth?: unknown; slug: string } }> }): Promise<string[]> {
const open: string[] = []
for (const { config } of Object.values(payload.collections ?? {})) {
if (!config.auth) {continue}
try {
if (await config.access?.create?.({ req: { payload, user: null } } as never)) {open.push(config.slug)}
} catch {
/* closed */
}
}
return open.sort()
}