M1 review round 3: late staff collections without guessing Payload's default; rules survive a dev reload

R3-1 nothing is decided by a function's name any more (a production build renames it): on a collection that
     arrives after ipalKit the plugin's rule is put in FRONT of the rule that is there and both must allow
     (bothAllow). unlock follows the same table. The log says exactly what was put.
R3-2 the adoption walks the live config (payload.config), which Payload swaps first on a dev reload.
R3-3 readVersions gets the read rule on staff collections.
R3-5 a secret that is not text is refused.
Also: the async check of requireSetup.exempt compares the constructor, not its name.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-25 00:39:24 +01:00
co-authored by Claude Fable 5.2
parent 3e44863c98
commit 6e0ad26b2c
13 changed files with 288 additions and 72 deletions
+61 -28
View File
@@ -106,8 +106,27 @@ export function hasPluginRoles(collection: Staffish): boolean {
/** What the plugin put on a staff collection (`custom.ipalAccountRules`) — for the doctor and for late collections. */
export type StaffAccountRules = { applied: string[]; ownRoles: boolean }
/** Payload's own default ("any logged-in user"), as a sanitized config holds it where the project wrote no rule. */
const isPayloadDefault = (rule: unknown): boolean => !rule || (typeof rule === 'function' && rule.name === 'defaultAccess')
/**
* BOTH rules must allow: the plugin's and the one the collection already has. For a collection
* that arrives after ipalKit ran (a later plugin), whose config is already sanitized: Payload has
* filled every missing rule with its default by then, and that default cannot be told from a
* rule somebody wrote — not by its name (a production build minifies it away) and not safely by
* identity. So nothing is guessed: the plugin's rule is put in FRONT of whatever is there. With
* Payload's default behind it the result is the plugin's rule; with a rule of the collection's
* own the result is the narrower of the two. Never wider than the plugin's rule: fail closed.
*/
export function bothAllow(first: Access, second: unknown): Access {
if (typeof second !== 'function') {return first}
return async (args) => {
const a = await first(args)
if (!a) {return false}
const b = await (second as Access)(args)
if (!b) {return false}
if (a === true) {return b}
if (b === true) {return a}
return { and: [a, b] }
}
}
export type StaffAccountAccessOptions = {
/** `create` (accounts.adminOnlyCreate). */
@@ -123,16 +142,19 @@ export type StaffAccountAccessOptions = {
/**
* 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.
*/
function ruleStaffCollection(collection: CollectionConfig, { create = true, pluginRoles = [], read = true, write = true }: StaffAccountAccessOptions): StaffAccountRules {
function ruleStaffCollection(collection: CollectionConfig, { create = true, pluginRoles = [], read = true, write = true }: StaffAccountAccessOptions, late = false): StaffAccountRules {
const slug = collection.slug
const ours = pluginRoles.includes(slug) || hasPluginRoles(collection)
const other = sameStaffCollectionAccess(slug)
const access = (collection.access ?? {}) as Record<string, unknown>
const applied: string[] = []
const put = (operation: string, rule: unknown) => {
if (!isPayloadDefault(access[operation])) {return}
access[operation] = rule
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)}
@@ -141,7 +163,11 @@ function ruleStaffCollection(collection: CollectionConfig, { create = true, plug
put('delete', ours ? staffCreateAccess : other)
put('unlock', ours ? staffCreateAccess : other)
}
if (read) {put('read', staffReadAccess)}
if (read) {
put('read', staffReadAccess)
// versions of an account hold what the account holds (e-mail addresses, roles)
put('readVersions', staffReadAccess)
}
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.
@@ -185,35 +211,42 @@ export function applyStaffAccountAccess(config: Config, staffSlugs: string[], op
}
}
type LiveCollections = Record<string, { config: CollectionConfig }>
/** What was put on one late auth collection: for the log, which says only what was really done. */
export type LateAdoption = { applied: string[]; firstUser: boolean; password: boolean; slug: string }
/**
* Collections that were not in the config when ipalKit ran — a plugin listed after it added them.
* Called when a config goes live (start, dev reload): a late STAFF collection gets the same
* defaults, and every late auth collection the first-user endpoint. Changes the live config in
* place; returns the slugs it adopted. `beforeOperation`: the password rule's hook for staff.
* Called when a config goes live (start, dev reload) with THAT config: a late STAFF collection
* gets the account rules (in front of whatever rules it has — `bothAllow`), the roles-field rule
* and the password hook; every late auth collection gets the first-user endpoint. Changes the
* config in place; returns what it put where. A late collection that wants its own rules exactly
* as they are says so: `custom: { ipal: { accountRules: false } }`.
*/
export function adoptLateAuthCollections(
payload: { collections: LiveCollections },
config: { collections?: CollectionConfig[] },
staffSlugs: string[],
{ access, beforeOperation, firstUserRoute = 'panel' }: { access?: false | StaffAccountAccessOptions; beforeOperation?: unknown; firstUserRoute?: FirstUserRouteOption } = {},
): string[] {
const adopted: string[] = []
for (const { config } of Object.values(payload.collections ?? {})) {
if (!config.auth || (config.custom as { ipalAccounts?: boolean } | undefined)?.ipalAccounts) {continue}
config.custom = { ...config.custom, ipalAccounts: true }
adopted.push(config.slug)
if (staffSlugs.includes(config.slug)) {
if (access !== false) {ruleStaffCollection(config, access ?? {})}
): 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 }
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 = (config.hooks ?? {}) as { beforeOperation?: unknown[] }
const hooks = (collection.hooks ?? {}) as { beforeOperation?: unknown[] }
hooks.beforeOperation = [...(hooks.beforeOperation ?? []), beforeOperation]
config.hooks = hooks as CollectionConfig['hooks']
collection.hooks = hooks as CollectionConfig['hooks']
done.password = true
}
}
if (firstUserRoute !== 'all' && Array.isArray(config.endpoints) && !config.endpoints.some((e) => (e.custom as { ipalFirstUser?: boolean } | undefined)?.ipalFirstUser)) {
config.endpoints.unshift(buildFirstUserEndpoint(firstUserRoute))
if (firstUserRoute !== 'all' && Array.isArray(collection.endpoints) && !collection.endpoints.some((e) => (e.custom as { ipalFirstUser?: boolean } | undefined)?.ipalFirstUser)) {
collection.endpoints.unshift(buildFirstUserEndpoint(firstUserRoute))
done.firstUser = true
}
if (done.applied.length || done.firstUser || done.password) {adopted.push(done)}
}
return adopted
}
@@ -224,8 +257,8 @@ export function markSeenAuthCollections(config: Config): Config {
}
/** Slugs named as staff that are not auth collections of the live config. */
export function unknownStaffCollections(payload: { collections: LiveCollections }, staffSlugs: string[]): string[] {
return staffSlugs.filter((slug) => !payload.collections?.[slug]?.config?.auth)
export function unknownStaffCollections(config: { collections?: CollectionConfig[] }, staffSlugs: string[]): string[] {
return staffSlugs.filter((slug) => !(config.collections ?? []).some((c) => c.slug === slug && c.auth))
}
/** `accounts.firstUserRoute`: `'panel'` (default) = the panel's login collection only; slugs = those; `'all'` = Payload's behaviour. */
@@ -287,7 +320,7 @@ export function applyFirstUserRoute(config: Config, option: FirstUserRouteOption
}
}
type LivePayload = { collections: Record<string, { config: { access?: { create?: Access; delete?: Access; read?: Access; unlock?: Access; update?: Access }; auth?: unknown; slug: string } }>; config?: unknown }
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 }
/**
* Auth collections whose `create` rule lets an anonymous request through — open sign-up.
@@ -317,7 +350,7 @@ export async function staffCollectionsOpenToOthers(payload: LivePayload): Promis
const open: string[] = []
for (const { config } of Object.values(payload.collections ?? {})) {
if (!config.auth || !staff.includes(config.slug)) {continue}
for (const operation of ['create', 'read', 'update', 'delete', 'unlock'] as const) {
for (const operation of ['create', 'read', 'readVersions', 'update', 'delete', 'unlock'] as const) {
try {
const rule = config.access?.[operation]
// no rule = Payload's default: any logged-in user
@@ -16,6 +16,7 @@ export const integrationsTexts = defineTexts({
maskedRemoved: 'The stored value will be removed when you save.',
maskedSet: 'A value is set. It is not shown; type a new one to replace it.',
maskedShow: 'Show',
secretNotText: 'Enter the value as text.',
secretReenter: 'Enter the password again: the server, port or user name changed. To use the server without a password, remove the stored value.',
// Status banner on an integration's tab (IntegrationStatusBanner)
@@ -75,6 +76,7 @@ export const integrationsTexts = defineTexts({
maskedRemoved: 'Zapisana wartość zostanie usunięta po zapisaniu.',
maskedSet: 'Wartość jest ustawiona. Nie jest wyświetlana; wpisz nową, aby ją zastąpić.',
maskedShow: 'Pokaż',
secretNotText: 'Wpisz wartość jako tekst.',
secretReenter: 'Wpisz hasło ponownie: zmienił się serwer, port lub nazwa użytkownika. Aby używać serwera bez hasła, usuń zapisaną wartość.',
statusCode: 'Kod: {{code}}.',
+4 -2
View File
@@ -194,14 +194,16 @@ export const securityRules: DoctorRule[] = [
const what: Record<string, string> = {
create: ': it can make itself a staff account',
read: ': it can list the staff accounts (addresses, roles)',
readVersions: ': it can read the versions of staff accounts (addresses, roles)',
unlock: ': it can lift the lock after failed logins, which helps guessing a password',
update: ": it can change a staff account's password",
}
const option = operation === 'create' ? 'adminOnlyCreate' : operation === 'read' ? 'staffOnlyRead' : 'adminOnlyWrite'
const reads = operation === 'read' || operation === 'readVersions'
const option = operation === 'create' ? 'adminOnlyCreate' : reads ? 'staffOnlyRead' : 'adminOnlyWrite'
return {
fix: `give "${slug}" an access.${operation} rule that asks for a staff account (staffCreateAccess, staffUpdateAccess('${slug}'), staffReadAccess, adminOrSelfIn('${slug}')), or drop accounts: false / accounts.${option}: false`,
message: `an account of another auth collection may ${operation} in the staff collection "${slug}"${what[operation] ?? ''}`,
severity: operation === 'read' ? ('warning' as const) : ('error' as const),
severity: reads ? ('warning' as const) : ('error' as const),
}
}),
docs: 'docs/access.md',
+9 -5
View File
@@ -97,7 +97,14 @@ export function buildKeepSecret({ appliesWhen, boundTo = [] }: WriteOnlySecretOp
const name = (field as { name?: string } | undefined)?.name
const value = siblingData && name ? (siblingData as Record<string, unknown>)[name] : given
if (value === SECRET_CLEAR) {return null}
if (!(value === undefined || value === null || value === '' || value === SECRET_MASK)) {return value}
const refuse = (key: 'secretNotText' | 'secretReenter', fallback: string): never => {
const message = req?.t ? ipalT(req.t as never, key) : fallback
throw new ValidationError({ collection: collection?.slug, errors: [{ message, path: path.join('.') }], global: global?.slug }, req?.t)
}
const nothing = value === undefined || value === null || value === '' || value === SECRET_MASK
// a secret is text: `false`, `0`, a list or an object is refused, not stored as typed
if (!nothing && typeof value !== 'string') {return refuse('secretNotText', 'Enter the value as text.')}
if (!nothing) {return value}
const stored = storedSecret(originalDoc, path)
if (stored && boundTo.length && overrideAccess !== true && (!appliesWhen || appliesWhen((siblingData ?? {}) as Record<string, unknown>))) {
const before = dig(originalDoc, path.slice(0, -1)) as Record<string, unknown> | undefined
@@ -110,10 +117,7 @@ export function buildKeepSecret({ appliesWhen, boundTo = [] }: WriteOnlySecretOp
const byDefault = typeof fallback === 'function' ? undefined : fallback
return !sameSetting(next ?? byDefault, before?.[name] ?? byDefault)
})
if (changed.length) {
const message = req?.t ? ipalT(req.t as never, 'secretReenter') : 'Enter the password again: the settings it belongs to have changed.'
throw new ValidationError({ collection: collection?.slug, errors: [{ message, path: path.join('.') }], global: global?.slug }, req?.t)
}
if (changed.length) {return refuse('secretReenter', 'Enter the password again: the settings it belongs to have changed.')}
}
return stored
}
+5 -1
View File
@@ -73,6 +73,9 @@ export function resolveRequireSetup(option: false | RequireSetupOptions | undefi
/** What was already said about a wrong `exempt` answer: each kind is logged once per process. */
const exemptComplaints = new Set<string>()
/** The constructor of async functions (there is no global for it). */
const ASYNC_FUNCTION: unknown = (async () => {}).constructor
/**
* The project's `exempt`, made safe to call from an access check: only an answer of exactly
* `true` exempts. An async function is refused at start (its Promise would be truthy for every
@@ -83,7 +86,8 @@ export function strictExempt(exempt: unknown): NonNullable<RequireSetupOptions['
if (typeof exempt !== 'function') {
throw new Error('[ipal] twoFactor.requireSetup.exempt must be a function: ({ user }) => boolean.')
}
if (exempt.constructor?.name === 'AsyncFunction') {
// by the constructor itself, not by its name
if (exempt.constructor === ASYNC_FUNCTION) {
throw new Error(
'[ipal] twoFactor.requireSetup.exempt must not be async: it is called in access checks, which cannot wait, and a Promise ' +
'would count as "exempt" for every account. Return true or false at once (decide from the fields on `user`).',