import type { Access, CollectionConfig, Config, Endpoint, PayloadRequest } from 'payload' 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' /** * Nobody creates an account for themselves, and nobody takes one over. * * Payload's defaults for a collection without access rules are "any logged-in user" for * `create`, `update` and `delete` — an account of ANY auth collection. On a project's own * staff collection that let a visitor account (`customers`) create a staff account, or change * a staff account's password and roles. And Payload's first-user route * (`POST /api//first-register`) answers for EVERY auth collection while it is empty — * on an empty second staff collection the first visitor became a staff account. * * Defaults now, for the staff collections (`accounts.adminOnlyCreate`, `accounts.adminOnlyWrite`, * `accounts.firstUserRoute`) — a rule the project wrote always stays: * * - a collection whose roles are the plugin's (`roles` with user / editor / admin): * create — an admin; update — an admin, or the account itself; delete — an admin; * - a staff collection with other roles, or none (the plugin cannot tell who its admins * are): an account of that same collection, or a plugin admin of another staff * collection. A visitor account, and an editor of another staff collection, are refused; * - the first-user route answers only for the collection the panel logs in with, unless a * collection's own `create` rule lets an anonymous request through. * * Always "fully signed in": the second factor is part of every one of these rules. They are * put on the collections BEFORE the 2FA package runs, because that package gives every * collection a `create` / `update` / `delete` function of its own (Payload's default, wrapped) * — afterwards a missing rule can no longer be told from one the project wrote. */ type Staffish = Pick 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. */ export const staffCreateAccess: Access = ({ req }) => userMeetsRole(req, 'admin') /** `update` where the roles are the plugin's: an admin, or the account itself (fully signed in). */ export const staffUpdateAccess = (slug: string): Access => ({ req }) => { if (userMeetsRole(req, 'admin')) {return true} if (!req.user || collectionOf(req) !== slug || !secondFactorPassed(req)) {return false} return { id: { equals: req.user.id } } } /** * Any operation on a staff collection whose roles are NOT the plugin's: an account of that same * collection (the project's own roles decide the rest), or a plugin admin of another staff * collection. Never an account of a collection that is not staff. */ export const sameStaffCollectionAccess = (slug: string): Access => ({ req }) => { if (!req.user || !secondFactorPassed(req)) {return false} const from = collectionOf(req) if (from === slug) {return staffCollectionSlugs(req.payload).includes(slug)} 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') /** * `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 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 } /** The values of the collection's `roles` select (at the top level of the data, also inside a row or an unnamed tab), or null when it has none. */ const roleValues = (collection: Staffish): null | unknown[] => { 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 null} return field.options.map((option) => (typeof option === 'string' ? option : (option as { value?: unknown })?.value)) } /** 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 rolesAreAList(collection) && (roleValues(collection)?.every((value) => ROLE_HIERARCHY.includes(value as never)) ?? false) } /** * True when an account of the collection can hold one of the plugin's roles that carry rights — `editor` or * `admin` — whatever else its `roles` field offers. * * 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. 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 — 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 (!rolesAreAList(collection)) {return false} const values = roleValues(collection) return values === null || values.some((value) => value === 'editor' || value === 'admin') } /** * 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 iapl 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 = { /** * The operations that had a rule in the project's config when iapl ran (before Payload and the 2FA package * filled the missing ones). A collection of the config that becomes staff LATER — a plugin listed after iapl * sets `admin.user` to it — keeps exactly those rules; an operation that had none gets the plugin's. */ own?: string[] 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 * that arrives after iapl 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). */ 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 } /** 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(await first(args)) && (typeof second !== 'function' || Boolean(await (second as (a: never) => unknown)(args))) /** * 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'` (iapl 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 — except the operations named in `kept`: * the collection was in the config when iapl ran and had a rule of the project's for them then (the marker's * `own`), so they are left as a rule the project wrote, exactly as at config time; * - `'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, mode: 'config' | 'copied' | 'late' = 'config', kept: string[] = []): 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) // a new object: a copied collection shares the original's const access = { ...collection.access } as Record 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) ['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 iapl finishes (markStaffRules): the 2FA package wraps it first } else if ((mode === 'late' && enabled && !kept.includes(operation)) || mark) { access[operation] = markedStaffRule(bothAllow(rule, there), slug) } else {continue} if (!applied.includes(operation)) {applied.push(operation)} } collection.access = access as CollectionConfig['access'] // 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 (as at config time, not where the project's own `update` // rule was kept); // - 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 && !kept.includes('update')) || 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 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 } /** The operations the plugin has a rule for. */ const OPERATIONS = ['create', 'update', 'delete', 'unlock', 'read', 'readVersions'] /** 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) {return collection} // Which operations have a rule of the project's NOW — later nobody can tell (Payload and the 2FA package fill // the missing ones). Kept in the marker for a collection that becomes staff after iapl ran. const own = OPERATIONS.filter((operation) => Boolean((collection.access as Record | undefined)?.[operation])) if (!staffSlugs.includes(collection.slug)) { return { ...collection, custom: { ...collection.custom, ipalAccounts: { slug: collection.slug, own, staff: false } satisfies AccountsMarker } } } const copy = { ...collection, access: { ...collection.access }, fields: copyToRoles(collection.fields as FieldLike[]) as CollectionConfig['fields'] } ruleStaffCollection(copy, options, 'config') return copy }), } } /** 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 /** The operations whose rule from the project's config was left as it is (a config collection that became staff later). */ kept: string[] /** True when the collection was in the config when iapl ran (and became staff afterwards); false when a later plugin added it. */ known: boolean password: boolean slug: string } /** * Collections that were not in the config when iapl ran — a plugin listed after it added them. * 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( config: { collections?: CollectionConfig[] }, staffSlugs: string[], { access, beforeOperation, firstUserRoute = 'panel' }: { access?: false | StaffAccountAccessOptions; beforeOperation?: unknown; firstUserRoute?: FirstUserRouteOption } = {}, ): LateAdoption[] { const adopted: LateAdoption[] = [] for (const collection of config.collections ?? []) { 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} // In the config when iapl ran, not staff then (a later plugin made it the panel's): the rules it had then stay. const known = marker?.slug === collection.slug const kept = known && Array.isArray(marker.own) ? marker.own : [] const done: LateAdoption = { slug: collection.slug, applied: [], firstUser: false, kept: [], known, password: false } // 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.kept = ruled ? kept : [] done.applied = ruleStaffCollection(collection, access === false || !access ? {} : access, ruled ? 'late' : 'copied', kept).applied collection.custom = { ...collection.custom, ipalAccounts: { slug: collection.slug, ...(kept.length ? { own: kept } : {}), 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 } } 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 } /** * 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 IAPL'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 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 iapl 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) => { if (!c.auth) {return c} // (the rules the project wrote, noted before the 2FA package ran — applyStaffAccountAccess) const before = markerOf(c) const own = before?.slug === c.slug && Array.isArray(before.own) ? { own: before.own } : {} return { ...c, custom: { ...c.custom, ipalAccounts: { slug: c.slug, ...own, staff: staffSlugs.includes(c.slug) } satisfies AccountsMarker } } }), } } /** Slugs named as staff that are not auth collections of the live config. */ 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. */ export type FirstUserRouteOption = 'all' | 'panel' | string[] const FIRST_REGISTER = '/first-register' /** * The plugin's own `POST /first-register` for a collection. It is put in front of Payload's * (a collection's own endpoints are matched before the built-in ones, with the same matcher — * so whatever spelling reaches Payload's route reaches this one first): refuses unless the * collection is allowed, then hands the request to Payload's handler. Nothing is decided * from the request's path. */ export function buildFirstUserEndpoint(option: FirstUserRouteOption = 'panel'): Endpoint { const endpoint: Endpoint = { custom: { ipalFirstUser: true }, handler: async (req) => { const slug = (req.routeParams as { collection?: string } | undefined)?.collection const collection = slug ? req.payload.collections[slug as never] : undefined const refused = () => Response.json({ errors: [{ message: req.t('error:notAllowedToPerformAction' as never) }] }, { status: 403 }) if (!slug || !collection) {return refused()} let allowed = Array.isArray(option) ? option.includes(slug) : slug === req.payload.config.admin?.user if (!allowed) { // a collection that lets a visitor sign up anyway may keep its first-user route try { allowed = Boolean(await collection.config.access?.create?.({ data: req.data, req: { ...req, user: null } } as never)) } catch { allowed = false } } if (!allowed) {return refused()} // Payload's own handler: the built-in endpoint of this collection with the same path and method. const builtIn = (collection.config.endpoints || []).find((e) => e !== endpoint && e.method === 'post' && e.path === FIRST_REGISTER && !(e.custom as { ipalFirstUser?: boolean } | undefined)?.ipalFirstUser) if (!builtIn) {return refused()} // for hooks that need to know (the roles field makes the first account an admin) req.context = { ...req.context, ipalFirstRegister: true } return builtIn.handler(req) }, method: 'post', path: FIRST_REGISTER, } return endpoint } /** Puts the first-user endpoint in front of Payload's on every auth collection. `'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(`[iapl] accounts.firstUserRoute must be 'panel', 'all' or a list of collection slugs, got ${JSON.stringify(option)}.`) } return { ...config, collections: (config.collections ?? []).map((collection) => { if (!collection.auth || collection.endpoints === false) {return collection} const own = (collection.endpoints ?? []).filter((e) => !(e.custom as { ipalFirstUser?: boolean } | undefined)?.ipalFirstUser) return { ...collection, endpoints: [buildFirstUserEndpoint(option), ...own] } }), } } type LivePayload = { collections: Record; config?: unknown } type CountingPayload = { collections: Record 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 { 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. 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: 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') && rolesAreAList(c) }) 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 unchecked.length ? { stuck: [], unchecked: unchecked.sort() } : { stuck: ruled.map((c) => c.slug).sort(), unchecked: [] } } /** * 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: LivePayload): Promise { 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() } /** * 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 { const staff = staffCollectionSlugs(payload as never) const outsider = { id: '__ipal-outsider__', collection: '__ipal-outsider__' } 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', 'readVersions', 'update', 'delete', 'unlock'] as const) { try { const rule = config.access?.[operation] // no rule = Payload's default: any logged-in user if (!rule || (await rule({ id: '__ipal-other__', req: { payload, user: outsider } } as never))) {open.push(`${config.slug}:${operation}`)} } catch { /* closed */ } } } 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[] { 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) .sort() }