K-1, K-2: only a roles field that holds a LIST counts; the start-up check asks each collection its own way

K-1 the plugin counts roles only from an array (getRoles). A single-valued roles field — a select, text or
    relationship without hasMany, a radio — never makes a plugin admin, yet canHoldStaffRole said true: on a
    project's own login collection with a single role select nobody could create, change, delete or unlock accounts,
    the account holding admin included. rolesAreAList(collection) is now a precondition of the admin rules. The same
    for hasPluginRoles: a single select whose values are all the plugin's had the admin rules already in 1.16.7 and
    gets 'an account of this collection' now — its accounts manage each other again; the value still grants nothing.
    A relationship with hasMany counts (ids that are text).
K-2 staffCollectionsNobodyManages returns { stuck, unchecked } and checks collection by collection: no query where
    the field cannot hold admin; a count for a select with hasMany; for text / json / relationship the accounts are
    read and the plugin's own test is applied. Where it cannot check it says so and claims nothing.
Tests: the reviewer's shapes over HTTP and the warning's table against a running Payload, 2FA off and on.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-25 03:44:25 +01:00
co-authored by Claude Fable 5.2
parent ccc6f85924
commit c3d95988e1
11 changed files with 406 additions and 47 deletions
+84 -25
View File
@@ -103,9 +103,32 @@ const roleValues = (collection: Staffish): null | unknown[] => {
return field.options.map((option) => (typeof option === 'string' ? option : (option as { value?: unknown })?.value))
}
/** True when the collection carries the plugin's roles: a `roles` select at the top level of the data (also inside a row or an unnamed tab) whose values are all the plugin's. */
/** Field types that hold ONE value unless `hasMany` says otherwise, and those that never hold a list of role names. */
const SINGLE_UNLESS_MANY = ['select', 'text', 'relationship', 'upload']
const NEVER_A_ROLE_LIST = ['radio', 'number', 'date', 'checkbox', 'email', 'textarea', 'code', 'point']
/**
* True when the collection's `roles` field can put an ARRAY on the account. The plugin's predicates count roles
* only from an array (`getRoles` in predicates.ts): an account whose `roles` is the single value `'admin'` — a
* select or text without `hasMany`, a radio — is nobody to the plugin, so there is nothing of the plugin's to
* protect in such a collection, and its accounts keep managing each other as Payload's default lets them.
* An array: a select, text or relationship with `hasMany` (a relationship to documents with text ids holds those
* ids), json, and any type the plugin does not know.
*/
export function rolesAreAList(collection: Staffish): boolean {
const field = findRolesField(collection.fields as FieldLike[]) as { hasMany?: boolean; type?: string } | undefined
if (!field) {return false}
if (SINGLE_UNLESS_MANY.includes(field.type ?? '')) {return field.hasMany === true}
return !NEVER_A_ROLE_LIST.includes(field.type ?? '')
}
/**
* True when the collection carries the plugin's roles: a `roles` select (at the top level of the data, also inside
* a row or an unnamed tab) with `hasMany` whose values are all the plugin's. Without `hasMany` the value never
* counts as a role (`rolesAreAList`).
*/
export function hasPluginRoles(collection: Staffish): boolean {
return roleValues(collection)?.every((value) => ROLE_HIERARCHY.includes(value as never)) ?? false
return rolesAreAList(collection) && (roleValues(collection)?.every((value) => ROLE_HIERARCHY.includes(value as never)) ?? false)
}
/**
@@ -115,14 +138,16 @@ export function hasPluginRoles(collection: Staffish): boolean {
* The plugin's predicates go by the VALUE on the account (`isAdmin`, `isEditor`, `userMeetsRole`): an account of
* a staff collection whose roles hold `admin` is a plugin admin, also when the select offers `boss` next to it; one
* that holds `editor` edits the site's settings. So the accounts of such a collection must not be able to hand
* those values out to each other, and the admin rules apply:
* those values out to each other, and the admin rules apply. The field must be able to hold a LIST
* (`rolesAreAList`), and then:
* - a `roles` select with `editor` or `admin` among its options (`user, editor, admin, boss`; `viewer, editor`);
* - a `roles` field whose values cannot be listed — a text or json field, a select without options: anything
* can be written there, `admin` included.
* False without a `roles` field, and for a select whose options hold neither value (`lead, member`).
* - a `roles` field whose values cannot be listed — text, json, a relationship (to documents whose ids are text),
* a select without options: anything can be written there, `admin` included.
* False without a `roles` field, for a single-valued one, and for a select whose options hold neither value
* (`lead, member`).
*/
export function canHoldStaffRole(collection: Staffish): boolean {
if (!findRolesField(collection.fields as FieldLike[])) {return false}
if (!rolesAreAList(collection)) {return false}
const values = roleValues(collection)
return values === null || values.some((value) => value === 'editor' || value === 'admin')
}
@@ -347,33 +372,67 @@ export function applyFirstUserRoute(config: Config, option: FirstUserRouteOption
type LivePayload = { collections: Record<string, { config: { access?: { create?: Access; delete?: Access; read?: Access; readVersions?: Access; unlock?: Access; update?: Access }; auth?: unknown; slug: string } }>; config?: unknown }
type CountingPayload = {
collections: Record<string, { config: CollectionConfig }>
count: (args: { collection: string; overrideAccess: boolean; where?: unknown }) => Promise<{ totalDocs: number }>
find: (args: { collection: string; depth: number; limit: number; overrideAccess: boolean; pagination: boolean }) => Promise<{ docs: unknown[]; hasNextPage?: boolean; totalDocs?: number }>
}
/** How many accounts are read to look for an admin where the database cannot be asked. */
const ADMIN_SCAN_LIMIT = 1000
/**
* Whether a staff collection has an account that is a plugin admin: `true`, `false`, or `null` — could not check.
* Asked the way that is right for the field, never guessed:
* - no `roles` field: every account is an admin → is there an account;
* - a `roles` field that cannot hold a list, or a select whose options do not offer `admin`: none, without a query;
* - a select with `hasMany`: a count in the database;
* - anything else (text, json, a relationship): the accounts are READ and the plugin's own test is applied to the
* value (an array that holds `'admin'`) — a query on such a field answers differently on every database.
*/
async function collectionHasAdmin(payload: CountingPayload, collection: CollectionConfig): Promise<boolean | null> {
const field = findRolesField(collection.fields as FieldLike[]) as { type?: string } | undefined
try {
if (!field) {return (await payload.count({ collection: collection.slug, overrideAccess: true })).totalDocs > 0}
if (!rolesAreAList(collection)) {return false}
const values = roleValues(collection)
if (values && !values.includes('admin')) {return false}
if (values) {
try {
return (await payload.count({ collection: collection.slug, overrideAccess: true, where: { roles: { in: ['admin'] } } })).totalDocs > 0
} catch {
// asked in a way this database does not take: read instead
}
}
const { docs, hasNextPage } = await payload.find({ collection: collection.slug, depth: 0, limit: ADMIN_SCAN_LIMIT, overrideAccess: true, pagination: true })
if (docs.some((doc) => Array.isArray((doc as { roles?: unknown }).roles) && ((doc as { roles: unknown[] }).roles).includes('admin'))) {return true}
return hasNextPage ? null : false // more accounts than were read: not known
} catch {
return null
}
}
/**
* For the start-up line: staff collections that run on the plugin's ADMIN rules (other than `except`, the collection
* with the plugin's own roles) while NO account of any staff collection is a plugin admin — then nobody can create,
* delete or unlock accounts there. Returns their slugs; `[]` when an admin exists, when there is no such
* collection, or when the accounts cannot be counted (a `roles` field that cannot be queried).
* delete or unlock accounts there. Counted collection by collection:
* - `stuck`: those collections, when every staff collection could be checked and none has an admin;
* - `unchecked`: staff collections whose accounts could not be checked — then nothing is claimed (`stuck` is empty)
* unless an admin was found elsewhere, in which case both are empty.
*/
export async function staffCollectionsNobodyManages(
payload: { collections: Record<string, { config: CollectionConfig }>; count: (args: { collection: string; overrideAccess: boolean; where?: unknown }) => Promise<{ totalDocs: number }> },
staffSlugs: string[],
except?: string,
): Promise<string[]> {
export async function staffCollectionsNobodyManages(payload: CountingPayload, staffSlugs: string[], except?: string): Promise<{ stuck: string[]; unchecked: string[] }> {
const staff = staffSlugs.map((slug) => payload.collections?.[slug]?.config).filter((c): c is CollectionConfig => Boolean(c?.auth))
const ruled = staff.filter((c) => {
const rules = (c.custom as { ipalAccountRules?: StaffAccountRules } | undefined)?.ipalAccountRules
return c.slug !== except && rules && !rules.ownRoles && rules.applied.includes('create') && Boolean(findRolesField(c.fields as FieldLike[]))
return c.slug !== except && rules && !rules.ownRoles && rules.applied.includes('create') && rolesAreAList(c)
})
if (!ruled.length) {return []}
try {
for (const c of staff) {
// without a `roles` field every account of a staff collection is an admin to the plugin
const where = findRolesField(c.fields as FieldLike[]) ? { roles: { in: ['admin'] } } : undefined
if ((await payload.count({ collection: c.slug, overrideAccess: true, where })).totalDocs > 0) {return []}
}
} catch {
return [] // cannot tell: say nothing
if (!ruled.length) {return { stuck: [], unchecked: [] }}
const unchecked: string[] = []
for (const c of staff) {
const has = await collectionHasAdmin(payload, c)
if (has) {return { stuck: [], unchecked: [] }}
if (has === null) {unchecked.push(c.slug)}
}
return ruled.map((c) => c.slug).sort()
return unchecked.length ? { stuck: [], unchecked: unchecked.sort() } : { stuck: ruled.map((c) => c.slug).sort(), unchecked: [] }
}
/**