Files
ipal-kit/src/modules/access/predicates.ts
T
Radosław SmolińskiandClaude Opus 5.5 de414a81a8 Role checks in client components: export them from /client, fix the docs
access.md and the 1.16.4 upgrade notes led projects to import isAdmin from
'@intecion/ipal-kit' in a client component; with `next build --webpack` that
fails ('server-only' cannot be imported from a Client Component module).
No existing entry had a client-safe one, so '@intecion/ipal-kit/client' now
exports hasMinimumRole, isAdmin, isEditor and the type Role; the main entry
keeps them for server code.

Docs: access.md (snippet with imports, server vs client, useConfig() carries
admin.user only), AGENT.md, ipal-debug, ipal-reference, ipal-upgrade, the
1.16.4 note, an Unreleased changelog entry. Tests: /client reaches no
server-only module, the predicates' answers with a client config, no
client-component example in the docs imports the main entry.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 22:00:27 +01:00

167 lines
7.9 KiB
TypeScript

import type { BasePayload } from 'payload'
import type { Role } from './types.js'
import { secondFactorPassed } from '../security/totp/secondFactor.js'
import { ROLE_HIERARCHY } from './types.js'
/**
* The plugin can't know the client's generated User type, and Payload types
* `req.user` loosely (UntypedUser | null). Predicates therefore accept an
* unknown-ish user and read `roles` defensively — no assumptions about shape
* beyond an optional roles array.
*/
type MaybeUser = { roles?: null | Role[] } | null | Record<string, unknown> | undefined
/**
* Where the staff collections come from: `req.payload` (anything with the
* sanitized `config` on it), a config itself (also the client config from
* `useConfig()` — it has `admin.user`), or the list given outright.
*/
type StaffSource = { admin?: { user?: string }; config?: StaffConfig; custom?: unknown; staffCollections?: string[] } | null | undefined
type StaffConfig = { admin?: { user?: string }; custom?: unknown }
type MaybePayload = Pick<BasePayload, 'config'> | StaffSource
/**
* The staff lists of the configs ipalKit built in this process, by owner: the
* running Payload instance once it exists, a token of the config before that.
* Used when a predicate gets no source (`isAdmin(req.user)` in a hook).
*/
const registered = new Map<object, string[]>()
/**
* Called by ipalKit: at config time with a token, then with the Payload
* instance (`replaces` = that config's token) on init and after every reload.
* Not for projects.
*/
export function registerStaffCollections(owner: object, slugs: string[], replaces?: object): void {
if (replaces) {registered.delete(replaces)}
registered.set(owner, [...new Set(slugs.filter(Boolean))])
}
/** For tests. */
export function clearStaffRegistry(): void {
registered.clear()
}
/** For tests: how many configs / instances have a staff list filed. */
export const staffRegistrySize = (): number => registered.size
/**
* The staff collections every config in this process agrees on, or null when
* ipalKit never ran here (a browser bundle, Next middleware, the edge
* runtime). Two configs with different lists: only what both call staff — a
* call that does not say which config it means must not get the wider answer.
*/
function agreedStaff(): null | string[] {
if (!registered.size) {return null}
const lists = [...registered.values()]
return lists[0].filter((slug) => lists.every((list) => list.includes(slug)))
}
/**
* The auth collections whose accounts are staff: the one the admin panel logs
* in with (`admin.user`), the one that carries the plugin's roles
* (`access.authCollection`) and `access.staffCollections`. Accounts of any
* other auth collection — customers, members — are visitors to the plugin:
* no role and no staff check counts for them, whatever fields they have.
*
* Pass `req.payload` (or a config, or `{ staffCollections: [...] }`). Without
* an argument: what the configs built in this process agree on, `[]` when
* there is none.
*/
export function staffCollectionSlugs(source?: MaybePayload): string[] {
if (!source) {return agreedStaff() ?? []}
const given = (source as { staffCollections?: unknown }).staffCollections
if (Array.isArray(given)) {return given.filter((s): s is string => typeof s === 'string' && s !== '')}
const config = ((source as { config?: StaffConfig }).config ?? source) as StaffConfig
const extra = (config.custom as { ipal?: { staffCollections?: string[] } } | undefined)?.ipal?.staffCollections ?? []
return [...new Set([config.admin?.user, ...extra].filter((s): s is string => typeof s === 'string' && s !== ''))]
}
/**
* Whether this account's roles may count at all: it belongs to a staff
* collection. Checked before any role, and it fails closed:
* - an account without `collection` (a user object built by hand) is not staff;
* - where the staff collections are not known — no source given and ipalKit
* never ran in this bundle (client components, Next middleware, the edge
* runtime) — nobody is staff. Pass the source there: `isAdmin(user, config)`
* with the config from `useConfig()` (client components import from
* '@intecion/ipal-kit/client'), or `isAdmin(user, { staffCollections: ['users'] })`.
*/
function isStaffAccount(user: MaybeUser, source?: MaybePayload): boolean {
if (!user || typeof user !== 'object') {return false}
const slug = (user as { collection?: unknown }).collection
return typeof slug === 'string' && staffCollectionSlugs(source).includes(slug)
}
/** Safely extracts the roles array from a loosely-typed user. */
function getRoles(user: MaybeUser): Role[] {
if (!user || typeof user !== 'object') {return []}
const roles = (user as { roles?: unknown }).roles
if (!Array.isArray(roles)) {return []}
return roles.filter((role): role is Role => ROLE_HIERARCHY.includes(role as Role))
}
/** Highest-privilege role index the user holds, or -1 if none. */
function highestRoleIndex(user: MaybeUser): number {
const roles = getRoles(user)
if (!roles.length) {return -1}
return Math.max(...roles.map((role) => ROLE_HIERARCHY.indexOf(role)))
}
/**
* True if the user is a staff account and holds at least the given role.
* admin satisfies 'editor' and 'user'; editor satisfies 'user'.
*
* Pass `req.payload` as the third argument where you have it (access
* functions, hooks, endpoints); without it the staff collections of the
* config ipalKit built in this process are used — and where there is none
* (a browser bundle, middleware) the answer is false: pass the config from
* `useConfig()` or `{ staffCollections: ['users'] }` there. A client component
* imports it from '@intecion/ipal-kit/client': the main entry does not build there with webpack.
*/
export function hasMinimumRole(user: MaybeUser, minimum: Role, payload?: MaybePayload): boolean {
if (!isStaffAccount(user, payload)) {return false}
return highestRoleIndex(user) >= ROLE_HIERARCHY.indexOf(minimum)
}
/** True if the user is a staff account with the admin role. */
export function isAdmin(user: MaybeUser, payload?: MaybePayload): boolean {
return hasMinimumRole(user, 'admin', payload)
}
/** True if the user is a staff account with the editor role or higher. */
export function isEditor(user: MaybeUser, payload?: MaybePayload): boolean {
return hasMinimumRole(user, 'editor', payload)
}
/**
* Role check for the plugin's own staff features (Site Integrations, the
* e-mail test, stats, consent records, form submissions, the settings
* globals). In this order:
*
* 1. The account must belong to a STAFF collection (staffCollectionSlugs).
* An account of any other auth collection never passes — also when its own
* collection has a `roles` field that says `admin`.
* 2. With 2FA on, an account that has TOTP set up must have entered the code
* in this session (secondFactorPassed).
* 3. It holds at least `minimum` — or its collection has no `roles` field at
* all (the project omitted `access`): then every account of that staff
* collection passes, as in Payload's own default.
*
* Pass `req` (it has `payload` and `user`). A project with its own role scheme
* in another field narrows access through globalOverrides / collection overrides.
*/
export function userMeetsRole({ payload, user }: { payload?: BasePayload; user?: unknown }, minimum: Role): boolean {
if (!user || typeof user !== 'object') {return false}
const slug = (user as { collection?: unknown }).collection
if (typeof slug !== 'string' || !staffCollectionSlugs(payload).includes(slug)) {return false}
if (!secondFactorPassed({ payload, user })) {return false}
if (highestRoleIndex(user as MaybeUser) >= ROLE_HIERARCHY.indexOf(minimum)) {return true}
const collection = payload?.collections?.[slug as never]?.config
const fields = (collection?.flattenedFields ?? collection?.fields) as Array<{ name?: string }> | undefined
if (!fields) {return false}
return !fields.some((f) => f.name === 'roles')
}