Copied staff collections: the plugin's rule goes in front, nothing is replaced (a rule that cannot widen)

A plugin listed after ipalKit that copies a staff collection under a new slug, or reuses its access object, brings
rules the plugin wrote for the ORIGINAL. On 1.16.7 the copy also carried the boolean 'seen' marker and was left
alone: 'the account itself' then meant an account of the original — with numeric ids the original's account with
the same id changed the copy's account (17 of 40 measured shapes).
Design: the plugin never replaces and never rewrites a rule on such a collection. It puts its rule for the copy's
own slug in front, and both must allow: on a copy named as staff in front of every rule; on a copy that is not
staff or keeps its own rules (custom.ipal.accountRules: false) in front of the rules marked as the plugin's for
another collection. The roles field of every copy is guarded. The mark on the plugin's functions says only
{ slug, self }; custom.ipalAccounts says { slug, staff } (a collection named as staff during next dev is handled
on the reload). The plugin's rules are marked before its 2FA guard, which carries the mark.
Accepted cost: a copy's own account cannot edit itself through a copied rule (as on 1.16.7); the copy writes
access.update — one documented line.
Proof: test/accountCopyTableSuite.ts — 40 shapes x accounts x operations, each row not wider than the measurement
taken on 1.16.7 (test/fixtures/copyRulesBaseline.json) and not wider than the plugin's rule; 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:48:09 +01:00
co-authored by Claude Fable 5.2
parent 4c7b722aed
commit 8dcc123b99
14 changed files with 2745 additions and 62 deletions
+4 -1
View File
@@ -3,6 +3,7 @@ import type { CollectionBeforeOperationHook, Config } from 'payload'
import { ValidationError } from 'payload'
import { serverText } from '../integrations/texts.js'
import { markPasswordRule } from './ruleMark.js'
/**
* A password rule for staff accounts.
@@ -47,7 +48,7 @@ export function checkPassword(password: string, { email, minLength = DEFAULT_PAS
* (`create`, `update`, `resetPassword`). Login, refresh and every other operation pass untouched.
*/
export function buildPasswordRuleHook({ minLength = DEFAULT_PASSWORD_MIN_LENGTH }: PasswordRuleOptions = {}): CollectionBeforeOperationHook {
return async ({ args, collection, operation, req }) => {
const hook: CollectionBeforeOperationHook = async ({ args, collection, operation, req }) => {
if (operation !== 'create' && operation !== 'update' && operation !== 'resetPassword') {return args}
const data = (args as { data?: { email?: unknown; password?: unknown } }).data
const password = data?.password
@@ -88,6 +89,8 @@ export function buildPasswordRuleHook({ minLength = DEFAULT_PASSWORD_MIN_LENGTH
if (problem) {return refuse(problem)}
return args
}
// marked on the function itself: a copied collection brings the hook along, and it is not put there twice
return markPasswordRule(hook)
}
/** Adds the rule to the named auth collections that log in with a password. */
+72
View File
@@ -0,0 +1,72 @@
/**
* The plugin's mark on an access function it put on a staff collection: "this is the plugin's
* rule, written for the collection `slug`".
*
* A later plugin may copy a collection (`{ ...staff, slug: 'copy' }`) or reuse its access object:
* the functions travel along, and a rule written for the original — "an account of `staff`",
* "the account itself" = one of the original's — then sits on a collection it does not speak of.
* The mark lets the plugin see that. It is on the function itself, so it:
* - travels with every copy (it is the same function object);
* - is on the function that ends up on the collection (set after the 2FA package wrapped the
* rule; ipal-kit's own 2FA guard gets a mark of its own for its wrapper);
* - is the same for every instance of this module (`Symbol.for`): after a `next dev` reload the
* config was built by one instance and is adopted by another.
* It counts only on the very function it was made for (`self`): a Proxy around a marked rule, a
* function with the rule as its prototype, a function that got the rule's property descriptors
* copied answer with the same property but are somebody's own rule.
*
* What the plugin DOES with a rule marked for another collection: it never replaces it. It puts
* its rule for this collection in front, and both must allow (selfRegistration.ts). So the mark
* says nothing about what the rule is — no operation, no kind: nothing is decided from it but
* "this rule speaks of another collection".
*/
const STAFF_RULE = Symbol.for('ipal.staffRule')
const PASSWORD_RULE = Symbol.for('ipal.passwordRule')
export type StaffRuleMark = {
/** The function the mark was made for. */
self: unknown
/** The collection the rule was written for. */
slug: string
}
type Marked = { [PASSWORD_RULE]?: { self: unknown }; [STAFF_RULE]?: StaffRuleMark }
const settable = (value: unknown): value is Marked => typeof value === 'function' && Object.isExtensible(value)
const setMark = (rule: Marked, slug: string): void => {
Object.defineProperty(rule, STAFF_RULE, { configurable: true, value: { slug, self: rule } satisfies StaffRuleMark })
}
/**
* A NEW function that does what `rule` does and carries the mark. Always a new one: the plugin's
* exported rules are shared (`adminOnly`), and a mark on a shared function would follow it into
* collections where the project itself used it. Not exported from the package.
*/
export function markedStaffRule<T extends (...args: never[]) => unknown>(rule: T, slug: string): T {
const marked = ((...args: never[]) => rule(...args)) as unknown as Marked & T
setMark(marked, slug)
return marked
}
/**
* The plugin's mark on a function, or undefined: then it is not a rule the plugin put there.
* Only a mark that is the function's OWN property and was made for this very function counts.
*/
export const staffRuleOf = (rule: unknown): StaffRuleMark | undefined => {
if (typeof rule !== 'function' || !Object.hasOwn(rule, STAFF_RULE)) {return undefined}
const mark = (rule as Marked)[STAFF_RULE]
return mark && typeof mark === 'object' && typeof mark.slug === 'string' && mark.self === rule ? mark : undefined
}
/** For a wrapper the PLUGIN puts around an access function (its 2FA guard): the wrapper answers for the same rule and gets a mark of its own. */
export function carryStaffRule(from: unknown, to: unknown): void {
const mark = staffRuleOf(from)
if (mark && settable(to)) {setMark(to, mark.slug)}
}
/** Marks a `beforeOperation` hook as the plugin's password rule (so it is not put on a collection twice). */
export function markPasswordRule<T>(hook: T): T {
if (settable(hook)) {Object.defineProperty(hook, PASSWORD_RULE, { configurable: true, value: { self: hook } })}
return hook
}
/** True for a hook made by `buildPasswordRuleHook` — in any instance of the module; only the hook itself, not a wrapper around it. */
export const isPasswordRuleHook = (hook: unknown): boolean => typeof hook === 'function' && Object.hasOwn(hook, PASSWORD_RULE) && (hook as Marked)[PASSWORD_RULE]?.self === hook
+167 -45
View File
@@ -2,6 +2,7 @@ import type { Access, CollectionConfig, Config, Endpoint, PayloadRequest } from
import { secondFactorPassed } from '../security/totp/secondFactor.js'
import { staffCollectionSlugs, userMeetsRole } from './predicates.js'
import { isPasswordRuleHook, markedStaffRule, staffRuleOf } from './ruleMark.js'
import { ROLE_HIERARCHY } from './types.js'
/**
@@ -152,8 +153,23 @@ export function canHoldStaffRole(collection: Staffish): boolean {
return values === null || values.some((value) => value === 'editor' || value === 'admin')
}
/** What the plugin put on a staff collection (`custom.ipalAccountRules`) — for the doctor and for late collections. */
export type StaffAccountRules = { applied: string[]; ownRoles: boolean }
/**
* What the plugin put on a collection (`custom.ipalAccountRules`) — for the doctor and the log. `slug`: the
* collection the record was written for (a copy of the collection carries the original's record along).
*/
export type StaffAccountRules = { applied: string[]; ownRoles: boolean; slug?: string }
/**
* The "seen" marker (`custom.ipalAccounts`): which collection ipalKit handled, and whether as a staff
* collection. Not a plain `true`: a later plugin may spread a collection into a new slug
* (`{ ...staff, slug: 'copy' }`) and the marker travels with it; and in `next dev` a collection object can
* outlive a reload in which it became staff.
*/
export type AccountsMarker = { slug: string; staff: boolean }
const markerOf = (collection: { custom?: unknown }): AccountsMarker | undefined => {
const marker = (collection.custom as { ipalAccounts?: unknown } | undefined)?.ipalAccounts
return marker && typeof marker === 'object' && typeof (marker as AccountsMarker).slug === 'string' ? (marker as AccountsMarker) : undefined
}
/**
* BOTH rules must allow: the plugin's and the one the collection already has. For a collection
@@ -188,50 +204,116 @@ export type StaffAccountAccessOptions = {
write?: boolean
}
/** Field access: both must allow (a `roles` field's own rule and the plugin's guard). */
const bothAllowField =
(first: (args: never) => unknown, second: unknown) =>
async (args: never): Promise<boolean> =>
Boolean(await first(args)) && (typeof second !== 'function' || Boolean(await (second as (a: never) => unknown)(args)))
/**
* Puts the defaults on ONE staff collection, in place: the operations without a rule, and the
* `roles` field when the plugin's `update` rule is the one in force. Returns what it applied.
* `late`: the collection's config is already sanitized (see `bothAllow`) — the plugin's rule is
* combined with whatever is there instead of only filling gaps.
* Puts the plugin's rules on ONE collection, in place, and returns what it put.
*
* **A rule that cannot widen.** The plugin fills an operation that has NO rule (config time), or puts its rule
* in FRONT of the rule that is there, so that both must allow (`bothAllow`). It never replaces a rule and never
* rewrites one. Whatever is on the collection — the project's rule, Payload's default, a rule the plugin wrote for
* ANOTHER collection that a copy brought along — still has to allow. So the result is never wider than what was
* there and never wider than the plugin's rule for this collection, whatever role values, operations or wrappers
* are involved.
*
* `mode`:
* - `'config'` (ipalKit is running, nothing is sanitized): an operation without a rule gets the plugin's;
* - `'late'` (a staff collection a later plugin added; the config is sanitized, so Payload's default cannot be
* told from a written rule): the plugin's rule in front of every rule;
* - `'copied'` (a late collection that is not staff, or that keeps its own rules — `custom.ipal.accountRules:
* false`): the plugin's rule goes in front ONLY of a rule the plugin wrote for another collection (its mark,
* ruleMark.ts). Such a rule says "an account of the original", "the account itself" = one of the original's;
* with this collection's rule in front, the original's namesake with the same id is not "itself" here.
* Accepted cost: where a copied rule says "itself" for the ORIGINAL's accounts, the copy's own account cannot
* edit itself (as before this change) — the copying plugin writes the copy's `access.update`.
*/
function ruleStaffCollection(collection: CollectionConfig, { create = true, pluginRoles = [], read = true, write = true }: StaffAccountAccessOptions, late = false): StaffAccountRules {
function ruleStaffCollection(collection: CollectionConfig, { create = true, pluginRoles = [], read = true, write = true }: StaffAccountAccessOptions, mode: 'config' | 'copied' | 'late' = 'config'): StaffAccountRules {
const slug = collection.slug
// the admin rules: where the roles are the plugin's, and wherever an account can hold `editor` or `admin` (canHoldStaffRole)
const ours = pluginRoles.includes(slug) || hasPluginRoles(collection) || canHoldStaffRole(collection)
const other = sameStaffCollectionAccess(slug)
const access = (collection.access ?? {}) as Record<string, unknown>
const applied: string[] = []
const put = (operation: string, rule: Access) => {
if (late) {access[operation] = bothAllow(rule, access[operation])}
else if (!access[operation]) {access[operation] = rule}
else {return} // a rule the project wrote
applied.push(operation)
}
if (create) {put('create', ours ? staffCreateAccess : other)}
if (write) {
put('update', ours ? staffUpdateAccess(slug) : other)
put('delete', ours ? staffCreateAccess : other)
put('unlock', ours ? staffCreateAccess : other)
}
if (read) {
put('read', staffReadAccess)
// a new object: a copied collection shares the original's
const access = { ...collection.access } as Record<string, unknown>
const before = (collection.custom as { ipalAccountRules?: StaffAccountRules } | undefined)?.ipalAccountRules
// what the plugin put there earlier for THIS slug (the injected collection's own rules, plugin.ts)
const applied: string[] = before?.slug === slug ? [...before.applied] : []
// The plugin's rule for each operation of THIS collection, and whether that default is switched on.
const rules: [operation: string, rule: Access, enabled: boolean][] = [
['create', ours ? staffCreateAccess : other, create],
['update', ours ? staffUpdateAccess(slug) : other, write],
['delete', ours ? staffCreateAccess : other, write],
['unlock', ours ? staffCreateAccess : other, write],
['read', staffReadAccess, read],
// versions of an account hold what the account holds (e-mail addresses, roles)
put('readVersions', staffReadAccess)
['readVersions', staffReadAccess, read],
]
/** A rule of ANOTHER collection is on this one: it is a copy, or it reuses another collection's access. */
let copied = Boolean(before?.slug && before.slug !== slug) || Boolean(markerOf(collection) && markerOf(collection)?.slug !== slug)
for (const [operation, rule, enabled] of rules) {
const there = access[operation]
// A mark — for another collection, or one that claims this one — only ever ADDS the plugin's rule in front; a
// function is never left alone because of what its mark says (whether a collection was handled is the marker's
// business, not the function's).
const mark = staffRuleOf(there)
if (mark && mark.slug !== slug) {copied = true}
if (mode === 'config') {
if (there || !enabled) {continue} // a rule the project wrote
access[operation] = rule // marked when ipalKit finishes (markStaffRules): the 2FA package wraps it first
} else if ((mode === 'late' && enabled) || mark) {
access[operation] = markedStaffRule(bothAllow(rule, there), slug)
} else {continue}
if (!applied.includes(operation)) {applied.push(operation)}
}
collection.access = access as CollectionConfig['access']
// The plugin's `update` rule lets an account change itself (or, with roles of its own, every account of
// the collection change every other): a `roles` field without access of its own would let it raise itself.
const roles = findRolesField(collection.fields as FieldLike[])
if (applied.includes('update')) {
if (roles && !roles.access?.update) {
roles.access = { ...roles.access, update: ours ? rolesByAdminOnly : rolesNotOwn(slug) }
applied.push('roles')
// The `roles` field. An account that may update itself would raise itself through a `roles` field without access of
// its own. The guard (the plugin's roles: only an admin changes them; others: never one's own) is put:
// - config: where the plugin's `update` rule is the one in force (it says "the account itself");
// - late: on every staff collection the plugin rules;
// - on every COPY, whatever the mode — also one that keeps its own rules and one that is not staff: its field came
// without a rule of its own, and its accounts must not write their own roles because the original's could not.
// A rule the field has is kept: the guard goes in front of it only when it is the plugin's rule for another collection.
let roles = findRolesField(collection.fields as FieldLike[])
if (roles) {
const guard = (ours ? rolesByAdminOnly : rolesNotOwn(slug)) as (args: never) => unknown
const there = roles.access?.update
const fieldMark = staffRuleOf(there)
const foreign = Boolean(fieldMark) && mode !== 'config'
const wanted = mode === 'config' ? write && applied.includes('update') : (mode === 'late' && write) || copied
if (foreign || (!there && wanted)) {
// the field object may be shared with the collection this one was copied from — give this one its own
if (mode !== 'config') {roles = ownCopyOfField(collection, roles)}
roles.access = { ...roles.access, update: markedStaffRule(foreign ? bothAllowField(guard, there) : guard, slug) as never }
if (!applied.includes('roles')) {applied.push('roles')}
}
}
// "roles of its own": a roles field whose values are not the plugin's (a collection without the field has no roles to rank)
const rules: StaffAccountRules = { applied, ownRoles: !ours && Boolean(roles) }
collection.custom = { ...collection.custom, ipalAccountRules: rules }
return rules
const record: StaffAccountRules = { slug, applied, ownRoles: !ours && Boolean(roles) }
// (a late collection that is not staff and brought nothing of the plugin's along gets no record)
if (applied.length || before || mode !== 'copied') {collection.custom = { ...collection.custom, ipalAccountRules: record }}
return record
}
/**
* Gives a (sanitized) collection its OWN copy of one field object, in `fields` and `flattenedFields`, and returns
* the copy: a collection made by spreading another shares the field objects — and the arrays — with it.
*/
function ownCopyOfField(collection: CollectionConfig, field: FieldLike): FieldLike {
const copy = { ...field }
const rebuild = (list: FieldLike[]): FieldLike[] =>
list.map((entry) => {
if (entry === field) {return copy}
if (!entry.name && entry.fields) {return { ...entry, fields: rebuild(entry.fields) }}
if (entry.tabs) {return { ...entry, tabs: entry.tabs.map((tab) => (tab.name ? tab : { ...tab, fields: rebuild(tab.fields) })) }}
return entry
})
const own = collection as unknown as { fields?: FieldLike[]; flattenedFields?: FieldLike[] }
if (Array.isArray(own.fields)) {own.fields = rebuild(own.fields)}
if (Array.isArray(own.flattenedFields)) {own.flattenedFields = own.flattenedFields.map((entry) => (entry === field ? copy : entry))}
return copy
}
/** A copy of the field tree down to the `roles` field, so the project's own objects are not changed. */
@@ -255,7 +337,7 @@ export function applyStaffAccountAccess(config: Config, staffSlugs: string[], op
collections: (config.collections ?? []).map((collection) => {
if (!collection.auth || !staffSlugs.includes(collection.slug)) {return collection}
const copy = { ...collection, access: { ...collection.access }, fields: copyToRoles(collection.fields as FieldLike[]) as CollectionConfig['fields'] }
ruleStaffCollection(copy, options)
ruleStaffCollection(copy, options, 'config')
return copy
}),
}
@@ -279,14 +361,23 @@ export function adoptLateAuthCollections(
): LateAdoption[] {
const adopted: LateAdoption[] = []
for (const collection of config.collections ?? []) {
const custom = collection.custom as { ipal?: { accountRules?: unknown }; ipalAccounts?: boolean } | undefined
if (!collection.auth || custom?.ipalAccounts) {continue}
collection.custom = { ...collection.custom, ipalAccounts: true }
if (!collection.auth) {continue}
const custom = collection.custom as { ipal?: { accountRules?: unknown } } | undefined
const staff = staffSlugs.includes(collection.slug)
// Handled already: under THIS slug, and as staff if it is staff now. A marker for another slug came along with
// a copy; a marker that says "not staff" on a collection that is staff now was made before it was named as one.
const marker = markerOf(collection)
if (marker?.slug === collection.slug && (marker.staff || !staff)) {continue}
const done: LateAdoption = { slug: collection.slug, applied: [], firstUser: false, password: false }
if (staffSlugs.includes(collection.slug)) {
if (access !== false && custom?.ipal?.accountRules !== false) {done.applied = ruleStaffCollection(collection, access ?? {}, true).applied}
if (beforeOperation) {
const hooks = (collection.hooks ?? {}) as { beforeOperation?: unknown[] }
// A staff collection gets the plugin's rules in front of its own. Any other late collection — not staff, or one
// that keeps its own rules — only where it carries a rule the plugin wrote for another collection (a copy).
const ruled = staff && access !== false && custom?.ipal?.accountRules !== false
done.applied = ruleStaffCollection(collection, access === false || !access ? {} : access, ruled ? 'late' : 'copied').applied
collection.custom = { ...collection.custom, ipalAccounts: { slug: collection.slug, staff } satisfies AccountsMarker }
if (staff) {
const hooks = (collection.hooks ?? {}) as { beforeOperation?: unknown[] }
// (a copied collection brings the original's hooks along: the password rule is put once)
if (beforeOperation && !(hooks.beforeOperation ?? []).some(isPasswordRuleHook)) {
hooks.beforeOperation = [...(hooks.beforeOperation ?? []), beforeOperation]
collection.hooks = hooks as CollectionConfig['hooks']
done.password = true
@@ -301,9 +392,38 @@ export function adoptLateAuthCollections(
return adopted
}
/** Marks the auth collections ipalKit has seen at config time, so `adoptLateAuthCollections` leaves them alone. */
export function markSeenAuthCollections(config: Config): Config {
return { ...config, collections: (config.collections ?? []).map((c) => (c.auth ? { ...c, custom: { ...c.custom, ipalAccounts: true } } : c)) }
/**
* Puts the plugin's mark on the rules it filled in during this run (`custom.ipalAccountRules.applied`, for the
* collection's own slug). Called AFTER the 2FA package has wrapped them — the mark must be on the function that is
* on the collection — and BEFORE ipal-kit's own 2FA guard, which carries the mark to its wrapper. Already marked
* functions are left, so it can run more than once.
*/
export function markStaffRules(config: Config): Config {
return {
...config,
collections: (config.collections ?? []).map((c) => {
const record = (c.custom as { ipalAccountRules?: StaffAccountRules } | undefined)?.ipalAccountRules
if (!c.auth || !c.access || record?.slug !== c.slug) {return c}
const access = { ...c.access } as Record<string, unknown>
for (const operation of record.applied) {
const rule = access[operation]
if (typeof rule === 'function' && !staffRuleOf(rule)) {access[operation] = markedStaffRule(rule as Access, c.slug)}
}
return { ...c, access: access as CollectionConfig['access'] }
}),
}
}
/**
* Marks the auth collections ipalKit has seen at config time — with their slug and whether they are staff — so
* `adoptLateAuthCollections` leaves exactly those alone.
*/
export function markSeenAuthCollections(config: Config, staffSlugs: string[] = []): Config {
const marked = markStaffRules(config) // (a no-op where the plugin marked them before its 2FA guard)
return {
...marked,
collections: (marked.collections ?? []).map((c) => (c.auth ? { ...c, custom: { ...c.custom, ipalAccounts: { slug: c.slug, staff: staffSlugs.includes(c.slug) } satisfies AccountsMarker } } : c)),
}
}
/** Slugs named as staff that are not auth collections of the live config. */
@@ -482,7 +602,9 @@ export async function staffCollectionsOpenToOthers(payload: LivePayload): Promis
* project's roles. For the doctor: the project should write its own rules. Slugs only.
*/
export function staffCollectionsOnOwnRoles(payload: LivePayload): string[] {
const staff = staffCollectionSlugs(payload as never)
return Object.values(payload.collections ?? {})
.filter(({ config }) => staff.includes(config.slug))
.map(({ config }) => ({ slug: config.slug, rules: (config as { custom?: { ipalAccountRules?: StaffAccountRules } }).custom?.ipalAccountRules }))
.filter(({ rules }) => rules?.ownRoles && rules.applied.some((operation) => operation === 'create' || operation === 'update' || operation === 'delete'))
.map(({ slug }) => slug)
@@ -1,5 +1,7 @@
import type { BasePayload, CollectionConfig, Config, GlobalConfig } from 'payload'
import { carryStaffRule } from '../../access/ruleMark.js'
/**
* ipal-kit's own second-factor check, next to the access wrapper of
* @clocklimited/payload-2fa.
@@ -150,6 +152,8 @@ export function requireSecondFactor<T extends AnyAccess>(access?: T): T {
return access ? access(args as never) : Boolean(args.req?.user)
}) as unknown as Guarded
wrapped[GUARDED] = true
// the wrapper answers for the same rule: the plugin's mark on a staff account rule goes with it (access/ruleMark.ts)
carryStaffRule(access, wrapped)
return wrapped as unknown as T
}