M1 review round 2: the transport is no way round, nobody raises its own role, late staff collections

R2-1 the SMTP password is bound to server, port and user whatever the transport says; the transport alone is not bound.
R2-2 where the plugin's update rule is in force the roles field is closed for the account itself
     (the plugin's roles: only an admin; roles of the project's own: never one's own).
R2-3 auth collections a later plugin adds get the account rules, the password rule and the first-user endpoint when
     the config goes live; a staff slug that is not an auth collection stops the start.
R2-4 smtpRequireTls is taken out: the branch adds no field, column or collection.
Also: read (a staff account) and unlock (an admin) defaults on staff collections (accounts.staffOnlyRead);
doctor staff-own-roles and read / unlock in staff-accounts-open; r1 NULL against the default, also inside a row;
r2 bound values compared exactly.

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 a32329fbb4
commit 7002ebbfa6
20 changed files with 519 additions and 122 deletions
+175 -24
View File
@@ -33,13 +33,6 @@ import { ROLE_HIERARCHY } from './types.js'
type Staffish = Pick<CollectionConfig, 'fields' | 'slug'>
/** True when the collection carries the plugin's roles: a top-level `roles` select whose values are all the plugin's. */
export function hasPluginRoles(collection: Staffish): boolean {
const field = (collection.fields ?? []).find((f) => 'name' in f && f.name === 'roles') as { options?: unknown[]; type?: string } | undefined
if (!field || field.type !== 'select' || !Array.isArray(field.options) || !field.options.length) {return false}
return field.options.every((option) => ROLE_HIERARCHY.includes((typeof option === 'string' ? option : (option as { value?: unknown })?.value) as never))
}
const collectionOf = (req: PayloadRequest): string | undefined => (req.user as { collection?: string } | null | undefined)?.collection
/** `create` / `delete` where the roles are the plugin's: an admin, fully signed in. */
@@ -68,28 +61,173 @@ export const sameStaffCollectionAccess =
return userMeetsRole(req, 'admin')
}
/** `read` on a staff collection: a fully signed-in account of a staff collection. Never a visitor account. */
export const staffReadAccess: Access = ({ req }) => {
const from = collectionOf(req)
return Boolean(req.user && from && staffCollectionSlugs(req.payload).includes(from) && secondFactorPassed(req))
}
type FieldAccessArgs = { id?: number | string; req: PayloadRequest }
/** `roles` where the roles are the plugin's: only an admin changes them — nobody raises itself. */
export const rolesByAdminOnly = ({ req }: FieldAccessArgs): boolean => userMeetsRole(req, 'admin')
/**
* Puts the defaults on the named staff collections where the project wrote no rule.
* `pluginRoles`: slugs that will carry the plugin's roles although the field is not there yet
* (`access.authCollection`, whose field is injected later).
* `roles` where the role values are the project's own (the plugin cannot rank them): an account
* never changes its OWN roles. Another account of the collection, or a plugin admin, may.
*/
export function applyStaffAccountAccess(config: Config, staffSlugs: string[], { create = true, pluginRoles = [], write = true }: { create?: boolean; pluginRoles?: string[]; write?: boolean } = {}): Config {
if (!create && !write) {return config}
export const rolesNotOwn =
(slug: string) =>
({ id, req }: FieldAccessArgs): boolean =>
!(req.user && collectionOf(req) === slug && id !== undefined && String(req.user.id) === String(id))
type FieldLike = { access?: { update?: unknown }; fields?: FieldLike[]; name?: string; tabs?: { fields: FieldLike[]; name?: string }[] }
/** The `roles` field of a collection: at the top level of the data (also inside a row, a collapsible or an unnamed tab). */
function findRolesField(fields: FieldLike[] | undefined): FieldLike | undefined {
for (const field of fields ?? []) {
if (field.name === 'roles') {return field}
if (!field.name && field.fields) {
const found = findRolesField(field.fields)
if (found) {return found}
}
for (const tab of field.tabs ?? []) {
const found = tab.name ? undefined : findRolesField(tab.fields)
if (found) {return found}
}
}
return undefined
}
/** 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. */
export function hasPluginRoles(collection: Staffish): boolean {
const field = findRolesField(collection.fields as FieldLike[]) as { options?: unknown[]; type?: string } | undefined
if (!field || field.type !== 'select' || !Array.isArray(field.options) || !field.options.length) {return false}
return field.options.every((option) => ROLE_HIERARCHY.includes((typeof option === 'string' ? option : (option as { value?: unknown })?.value) as never))
}
/** 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')
export type StaffAccountAccessOptions = {
/** `create` (accounts.adminOnlyCreate). */
create?: boolean
/** Slugs that will carry the plugin's roles although the field is not there yet (`access.authCollection`). */
pluginRoles?: string[]
/** `read` (accounts.staffOnlyRead). */
read?: boolean
/** `update`, `delete`, `unlock`, and the `roles` field (accounts.adminOnlyWrite). */
write?: boolean
}
/**
* 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.
*/
function ruleStaffCollection(collection: CollectionConfig, { create = true, pluginRoles = [], read = true, write = true }: StaffAccountAccessOptions): 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
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)}
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')
}
}
// "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
}
/** A copy of the field tree down to the `roles` field, so the project's own objects are not changed. */
const copyToRoles = (fields: FieldLike[] | undefined): FieldLike[] | undefined =>
fields?.map((field) => {
if (field.name === 'roles') {return { ...field }}
if (!field.name && field.fields) {return { ...field, fields: copyToRoles(field.fields) }}
if (field.tabs) {return { ...field, tabs: field.tabs.map((tab) => (tab.name ? tab : { ...tab, fields: copyToRoles(tab.fields)! })) }}
return field
})
/**
* Puts the defaults on the named staff collections where the project wrote no rule: `create`,
* `update`, `delete`, `unlock`, `read`, and `roles` cannot be raised by its own account.
*/
export function applyStaffAccountAccess(config: Config, staffSlugs: string[], options: StaffAccountAccessOptions = {}): Config {
const { create = true, read = true, write = true } = options
if (!create && !write && !read) {return config}
return {
...config,
collections: (config.collections ?? []).map((collection) => {
if (!collection.auth || !staffSlugs.includes(collection.slug)) {return collection}
const ours = pluginRoles.includes(collection.slug) || hasPluginRoles(collection)
const other = sameStaffCollectionAccess(collection.slug)
const access = { ...collection.access }
if (create && !access.create) {access.create = ours ? staffCreateAccess : other}
if (write && !access.update) {access.update = ours ? staffUpdateAccess(collection.slug) : other}
if (write && !access.delete) {access.delete = ours ? staffCreateAccess : other}
return { ...collection, access }
const copy = { ...collection, access: { ...collection.access }, fields: copyToRoles(collection.fields as FieldLike[]) as CollectionConfig['fields'] }
ruleStaffCollection(copy, options)
return copy
}),
}
}
type LiveCollections = Record<string, { config: CollectionConfig }>
/**
* 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.
*/
export function adoptLateAuthCollections(
payload: { collections: LiveCollections },
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 ?? {})}
if (beforeOperation) {
const hooks = (config.hooks ?? {}) as { beforeOperation?: unknown[] }
hooks.beforeOperation = [...(hooks.beforeOperation ?? []), beforeOperation]
config.hooks = hooks as CollectionConfig['hooks']
}
}
if (firstUserRoute !== 'all' && Array.isArray(config.endpoints) && !config.endpoints.some((e) => (e.custom as { ipalFirstUser?: boolean } | undefined)?.ipalFirstUser)) {
config.endpoints.unshift(buildFirstUserEndpoint(firstUserRoute))
}
}
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)) }
}
/** 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)
}
/** `accounts.firstUserRoute`: `'panel'` (default) = the panel's login collection only; slugs = those; `'all'` = Payload's behaviour. */
export type FirstUserRouteOption = 'all' | 'panel' | string[]
@@ -149,7 +287,7 @@ export function applyFirstUserRoute(config: Config, option: FirstUserRouteOption
}
}
type LivePayload = { collections: Record<string, { config: { access?: { create?: Access; delete?: Access; update?: Access }; auth?: unknown; slug: string } }>; config?: unknown }
type LivePayload = { collections: Record<string, { config: { access?: { create?: Access; delete?: Access; read?: Access; unlock?: Access; update?: Access }; auth?: unknown; slug: string } }>; config?: unknown }
/**
* Auth collections whose `create` rule lets an anonymous request through — open sign-up.
@@ -169,9 +307,9 @@ export async function openSignUpCollections(payload: LivePayload): Promise<strin
}
/**
* Staff collections that an account of ANOTHER, non-staff auth collection may create in,
* update or delete from — `'users:update'`. For the doctor. Asked with a made-up account of a
* collection that is not staff; a rule that throws counts as closed.
* Staff collections that an account of ANOTHER, non-staff auth collection may create in, read,
* update, delete from or unlock — `'users:update'`. For the doctor. Asked with a made-up account of
* a collection that is not staff; a rule that throws counts as closed.
*/
export async function staffCollectionsOpenToOthers(payload: LivePayload): Promise<string[]> {
const staff = staffCollectionSlugs(payload as never)
@@ -179,7 +317,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', 'update', 'delete'] as const) {
for (const operation of ['create', 'read', 'update', 'delete', 'unlock'] as const) {
try {
const rule = config.access?.[operation]
// no rule = Payload's default: any logged-in user
@@ -191,3 +329,16 @@ export async function staffCollectionsOpenToOthers(payload: LivePayload): Promis
}
return open.sort()
}
/**
* Staff collections with role values of their OWN that run on the plugin's defaults: inside such a
* collection every account may create, change and delete accounts — the plugin cannot rank the
* project's roles. For the doctor: the project should write its own rules. Slugs only.
*/
export function staffCollectionsOnOwnRoles(payload: LivePayload): string[] {
return Object.values(payload.collections ?? {})
.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)
.sort()
}
+11
View File
@@ -33,6 +33,10 @@ export type AccountsOptions = {
* (a `customers` visitor) change a staff account's password. On a staff
* collection whose roles are not the plugin's: an account of that same
* collection, or a plugin admin. A rule the project wrote stays.
* With it: `unlock` gets the admin rule, and the collection's `roles`
* field (when it has no `access.update` of its own) cannot be raised by
* its own account — with the plugin's roles only an admin changes roles;
* with role values of the project's own, never the account itself.
* `false` = Payload's default on collections without a rule, as before.
*/
adminOnlyWrite?: false
@@ -63,6 +67,13 @@ export type AccountsOptions = {
* logging in. `false` = Payload's own rule (3 characters).
*/
password?: false | PasswordRuleOptions
/**
* `read` on a staff collection without a `read` rule: a fully signed-in
* account of a staff collection. Payload's default let any logged-in
* account — a `customers` visitor — list the staff accounts. A rule the
* project wrote stays. `false` = Payload's default, as before.
*/
staffOnlyRead?: false
}
/**