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
+2
View File
@@ -2,6 +2,8 @@ export { lightboxNotificationFields } from './globals/Notifications/fields.js'
export { applyGlobalOverrides } from './globals/overrides.js'
export type { GlobalOverride, GlobalOverrides, IpalGlobalSlug } from './globals/overrides.js'
export { applyPanelRole, countBelowPanelRole, DEFAULT_PANEL_ROLE, panelAccess, resolvePanelRole } from './modules/access/panelRole.js'
export { applyAdminOnlyCreate, applyFirstUserRoute, buildFirstUserGuard, openSignUpCollections, staffCreateAccess } from './modules/access/selfRegistration.js'
export type { FirstUserRouteOption } from './modules/access/selfRegistration.js'
export type { AccountsOptions } from './modules/access/types.js'
export type { AccessOption, Role } from './modules/access/index.js'
export {
+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()
}
+17
View File
@@ -13,6 +13,23 @@ export type Role = (typeof ROLE_HIERARCHY)[number]
* where they apply; each one has its own switch, `accounts: false` turns them all off.
*/
export type AccountsOptions = {
/**
* Only an admin creates accounts in a staff collection (the one the panel
* logs in with, `access.authCollection`, `access.staffCollections`) — also
* in the project's own collection, where Payload's default would let any
* logged-in account do it. A `create` rule the project wrote stays.
* `false` = Payload's default on collections without a rule, as before.
*/
adminOnlyCreate?: false
/**
* Which auth collections Payload's first-user route
* (`POST /api/<slug>/first-register`) answers for while they are empty.
* Default `'panel'`: only the collection the panel logs in with — the
* first account of a site, which becomes admin. A list of slugs = those.
* `'all'` = Payload's behaviour (every empty auth collection). A collection
* whose own `create` rule allows an anonymous request keeps its route.
*/
firstUserRoute?: 'all' | 'panel' | string[]
/**
* The lowest role that may open the admin panel. Default `'editor'`: an
* account that holds only `user` (the default role of a new account) sees
+13
View File
@@ -157,6 +157,19 @@ export const securityRules: DoctorRule[] = [
group: 'security',
source: 'static',
},
{
// An auth collection anyone can register in. Often exactly what the project wants (customers) — said, not judged.
id: 'open-signup',
check: (ctx) =>
(ctx.deep?.openSignUp ?? []).map((slug) => ({
fix: `intended (a customer zone)? silence it with a reason in ipal-doctor.json; otherwise give "${slug}" a create rule`,
message: `sign-up is open on "${slug}": an anonymous request can create an account there`,
severity: 'info' as const,
})),
docs: 'docs/access.md',
group: 'security',
source: 'deep',
},
{
// Turnstile lets submissions through while it is misconfigured or Cloudflare fails ("degraded") — visible here.
id: 'turnstile-degraded',
+8 -1
View File
@@ -5,6 +5,7 @@ import { readFileSync } from 'node:fs'
import type { DoctorStatus } from './types.js'
import { openSignUpCollections } from '../access/selfRegistration.js'
import { countPendingCookies } from '../consent/scanner/approval.js'
import { COOKIE_REVIEW_SLUG } from '../consent/scanner/collection.js'
import { secondFactorPassed, SETUP_FROM_FIELD } from '../security/totp/secondFactor.js'
@@ -61,7 +62,13 @@ export async function collectDoctorStatus(payload: BasePayload): Promise<DoctorS
/* the global cannot be read: unknown */
}
}
return { node: process.version, pendingCookies, plugin: pluginVersion(), turnstile, turnstileSecretFromEnv: secretFromEnv, usersSetupClosed, usersWithout2fa }
let openSignUp: null | string[] = null
try {
openSignUp = await openSignUpCollections(payload as never)
} catch {
openSignUp = null
}
return { node: process.version, openSignUp, pendingCookies, plugin: pluginVersion(), turnstile, turnstileSecretFromEnv: secretFromEnv, usersSetupClosed, usersWithout2fa }
}
export type DoctorEndpointOptions = {
+2
View File
@@ -61,6 +61,8 @@ export type DoctorStatus = {
/** null = not compared (the endpoint cannot read files). */
importMapCurrent?: boolean | null
node?: string
/** Auth collections whose `create` rule lets an anonymous request through (slugs only). */
openSignUp?: null | string[]
pendingCookies?: null | number
plugin?: string
/** The Turnstile integration's recorded state (Site integrations): never a key, only the state. null = not known. */
+8
View File
@@ -14,6 +14,7 @@ import { buildSiteIntegrations } from './globals/SiteIntegrations/index.js'
import { buildSiteSettings } from './globals/SiteSettings/index.js'
import { adminOnly, adminOrSelfIn, injectRoles, registerStaffCollections, staffCollectionSlugs } from './modules/access/index.js'
import { applyPanelRole, countBelowPanelRole, resolvePanelRole } from './modules/access/panelRole.js'
import { applyAdminOnlyCreate, applyFirstUserRoute } from './modules/access/selfRegistration.js'
import { applyAdminI18n } from './modules/admin-i18n/apply.js'
import { buildAdminImageEndpoints } from './modules/branding/adminImages.js'
import { buildAdminMeta, DEFAULT_AGENCY, syncAdminMeta } from './modules/branding/adminMeta.js'
@@ -565,6 +566,13 @@ export const ipalKit = (options: IpalOptions): Plugin => {
panelRoleFor = { slug: rolesSlug, role: panelRole }
}
}
// Account rules (accounts.*): nobody creates an account for themselves.
if (accounts) {
const panelSlug = config.admin?.user ?? (config.collections ?? []).find((c) => c.auth)?.slug
const staffSlugs = [...new Set([panelSlug, options.access?.authCollection, ...(options.access?.staffCollections ?? [])].filter((s): s is string => Boolean(s)))]
if (accounts.adminOnlyCreate !== false) {config = applyAdminOnlyCreate(config, staffSlugs)}
config = applyFirstUserRoute(config, accounts.firstUserRoute)
}
// For predicates called without `req.payload` (isAdmin(req.user) in a hook): what this config
// says now, under a token; the Payload instance takes the entry over when the config goes live
// (adoptConfig), with `admin.user` as Payload resolved it.