Files
ipal-kit/src/plugin.ts
T
Radosław SmolińskiandClaude Opus 5.5 99036eb70c Consent compliance: Global Privacy Control honoured, equal choice by default, withdrawal that stops running tools, consent log on by default
- GPC (gpc.ts): read in the browser before the first paint (consentBannerScript) and in the consent store; pages stay
  static. 'honour' (default): no banner, analytics and marketing off, no request to Google or a pixel; an explicit
  choice on the site wins; a grant made without the signal gives way when it appears. 'ask' and false as opt-outs.
- equalChoice defaults to true; a development warning when the banner has no 'reject'.
- Withdrawal: Meta / TikTok / Clarity told at once, listed localStorage / sessionStorage keys removed.
- Clarity gets consentv2 when it loads; ads_data_redaction with the Consent Mode default.
- consentLog on by default (consentLog: false turns it off); SiteProviders posts to it by itself; a missing SQL table
  answers 503 with one log line.
- Default banner text: one sentence on changing the choice and browser settings; the GPC line (PL / EN).
- Doctor: consent-log-migration, consent-banner rules.
- Stats: Sec-GPC over a choice made without it keeps the visitor id out.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 13:38:39 +01:00

1044 lines
58 KiB
TypeScript

import type { BasePayload, Config, PayloadRequest, Plugin } from 'payload'
import { deepMergeSimple } from 'payload/shared'
import type { AccountsOptions, Role } from './modules/access/types.js'
import type { ResolvedAdminMeta } from './modules/branding/adminMeta.js'
import type { IaplOptions, TotpPluginFactory } from './types.js'
import { buildCookieSettings } from './globals/CookieSettings/index.js'
import { migrateCookieSettingsSaveButton } from './globals/CookieSettings/migrateSaveButton.js'
import { buildNotifications } from './globals/Notifications/index.js'
import { applyGlobalOverrides } from './globals/overrides.js'
import { buildSiteIntegrations } from './globals/SiteIntegrations/index.js'
import { buildSiteSettings } from './globals/SiteSettings/index.js'
import { adminOnly, adminOrSelfIn, injectRoles, registerStaffCollections, staffCollectionSlugs } from './modules/access/index.js'
import { applyPanelRole, countBelowPanelRole, resolvePanelRole } from './modules/access/panelRole.js'
import { applyPasswordRule, buildPasswordRuleHook, resolvePasswordRule } from './modules/access/passwordRule.js'
import { adoptLateAuthCollections, applyFirstUserRoute, applyStaffAccountAccess, markSeenAuthCollections, markStaffRules, staffCollectionsNobodyManages, unknownStaffCollections } from './modules/access/selfRegistration.js'
import { ROLE_HIERARCHY } from './modules/access/types.js'
import { applyAdminI18n } from './modules/admin-i18n/apply.js'
import { buildAdminImageEndpoints } from './modules/branding/adminImages.js'
import { buildAdminMeta, DEFAULT_AGENCY, syncAdminMeta } from './modules/branding/adminMeta.js'
import { buildConsentLogCollection, buildConsentLogEndpoint } from './modules/consent/consentLog.js'
import { addCookieScannerTabs } from './modules/consent/scanner/adminTabs.js'
import { buildCookieApprovalEndpoints, COOKIE_APPROVAL_VIEW_PATH } from './modules/consent/scanner/approval.js'
import { buildCookieReviewCollection } from './modules/consent/scanner/collection.js'
import { buildCookieCrawlEndpoints } from './modules/consent/scanner/crawl/endpoints.js'
import { buildCookieCrawlGlobal } from './modules/consent/scanner/crawl/global.js'
import { buildCookieScanEndpoints } from './modules/consent/scanner/endpoint.js'
import { mergeCookieScanLabels } from './modules/consent/scanner/labels.js'
import { buildConstructionFields } from './modules/construction/fields.js'
import { buildArchiveFields } from './modules/content/index.js'
import { defaultConnectionReserve, poolSize, watchTransactions } from './modules/database/transactions.js'
import { buildDoctorEndpoint } from './modules/doctor/status.js'
import { withAccountMailAfterCommit } from './modules/email/accountMailAfterCommit.js'
import { GRAPH_DEPRECATION_NOTICE, graphAvailable } from './modules/email/mailAdapter.js'
import { withAccountMailMark } from './modules/email/relay/accountMail.js'
import { relayConfirmEndpoint } from './modules/email/relay/confirm.js'
import { relayPanelEndpoints } from './modules/email/relay/panel.js'
import { testEmailEndpoint } from './modules/email/test/testEmailEndpoint.js'
import { emailSettingsFields } from './modules/forms/emailLayout.js'
import { buildFormsPlugin } from './modules/forms/formsPluginConfig.js'
import { buildGlobalRevalidateHook } from './modules/hooks/buildRevalidateHook.js'
import { withFillLocales } from './modules/hooks/fillEmptyLocales.js'
import { buildLocalizationConfig, validateI18nConfig } from './modules/i18n/index.js'
import { serverText } from './modules/integrations/texts.js'
import { buildSystemPagesFields } from './modules/pages/index.js'
import { missingImportMapEntries } from './modules/security/totp/importMapCheck.js'
import { changedViewKeys, copyViews, SAFE_TOTP_VIEW, wrapTotpViews } from './modules/security/totp/safeBack.js'
import { reportRefusedOrigin, requestFromOwnOrigin } from './modules/security/totp/sameOrigin.js'
import {
buildGuardStrategy,
ensurePayloadGuarded,
guardConfigAccess,
guardNewEntityEndpoints,
guardTotpEndpoint,
missingTotpParts,
passOptOutsToPackage,
watchPayloadConfig,
} from './modules/security/totp/secondFactor.js'
import { backfillSetupFrom, buildSetupFields, buildTwoFactorResetEndpoint, resolveRequireSetup, stampSetupFrom } from './modules/security/totp/setupRequired.js'
import { TOTP_TEXTS, TOTP_VIEW_TITLE } from './modules/security/totp/totpTexts.js'
import { buildVerifyLimit } from './modules/security/totp/verifyLimit.js'
import { buildSeoPlugin, injectAutoFillMeta, injectSeoTabs } from './modules/seo/index.js'
import { buildIndexNowHook } from './modules/seo/indexNow.js'
import { searchSettingsFields } from './modules/seo/searchSettings.js'
import { migrateTitleSeparator } from './modules/seo/titleSeparator.js'
import { applyCollectionOverride } from './modules/shared/collectionOverride.js'
import { assertDevelopmentHosts } from './modules/shared/developmentHosts.js'
import { buildStatsCollection, buildStatsEndpoint } from './modules/stats/index.js'
import { visitorCookieFor } from './modules/stats/visitorCookie.js'
/** The admin provider @clocklimited/payload-2fa registers; IAPL swaps it (twoFactor.provider). */
const TOTP_PACKAGE_PROVIDER = '@clocklimited/payload-2fa/rsc#TOTPProvider'
/** IAPL's own redirect provider (twoFactor.provider default). */
const TOTP_REDIRECT_PROVIDER = '@intecion/ipal-kit/admin#TotpRedirectProvider'
/**
* IAPL (Intecion Advanced Payload Library) plugin for Payload CMS 3.
*
* @example
* ```ts
* import { iapl } from '@intecion/ipal-kit'
*
* export default buildConfig({
* plugins: [
* iapl({
* i18n: {
* locales: [
* { code: 'pl', label: 'Polski' },
* { code: 'en', label: 'English' },
* ],
* defaultLocale: 'pl',
* },
* access: { authCollection: 'users' },
* }),
* ],
* })
* ```
*/
export const iapl = (options: IaplOptions): Plugin => {
// Validate eagerly — fail fast before Payload boots
validateI18nConfig(options.i18n)
return async (incomingConfig: Config): Promise<Config> => {
const config = await transform(incomingConfig)
// Disabled: schema stays (collections, globals, fields — so a Postgres
// migration doesn't drop the plugin's tables), behaviour goes: no plugin
// endpoints, onInit work or admin components. Returning the incoming
// config untouched used to drop the plugin's collections and globals.
if (options.enabled === false) {
return {
...config,
admin: { ...config.admin, components: incomingConfig.admin?.components, dependencies: incomingConfig.admin?.dependencies },
endpoints: incomingConfig.endpoints,
onInit: incomingConfig.onInit,
}
}
return config
}
async function transform(incomingConfig: Config): Promise<Config> {
let config = { ...incomingConfig }
// Text written in one language fills the empty languages of the same field (cookie list, cookie review).
const fillDefaults = { 'cookie-review': ['purpose', 'retention'], 'cookie-settings': ['cookies.purpose', 'cookies.duration'] }
const fillLocales: Record<keyof typeof fillDefaults, string[]> =
options.fillEmptyLocales === false
? { 'cookie-review': [], 'cookie-settings': [] }
: { ...fillDefaults, ...(typeof options.fillEmptyLocales === 'object' ? options.fillEmptyLocales : {}) }
// --- auth collection: Payload adds its default `users` only AFTER plugins
// run (config sanitize), so roles and 2FA would have nothing to attach to,
// and a project without it crashes ("users is not a valid admin user
// collection"). Inject a plain auth collection when the project defines
// none — a project's own collection with that slug always wins.
const authSlug =
options.access?.authCollection ??
(options.twoFactor ? options.twoFactor.collectionSlug : undefined) ??
config.admin?.user ??
'users'
// With roles on it (access.authCollection), the injected collection is
// locked down: Payload's default lets ANY logged-in account read, edit
// (email, password), unlock or delete every other account — a plain 'user'
// could take over an admin. Admins manage everyone; others only themselves.
// access.authAccess overrides any of it; a project's own collection wins whole.
if (!(config.collections ?? []).some((c) => c.slug === authSlug)) {
const hasRoles = options.access?.authCollection === authSlug
config.collections = [
...(config.collections ?? []),
{
slug: authSlug,
...(hasRoles
? {
access: {
create: adminOnly,
delete: adminOnly,
// "self" = an account of THIS collection: with numeric ids a customer
// account no. 5 must not match staff account no. 5.
read: adminOrSelfIn(authSlug),
unlock: adminOnly,
update: adminOrSelfIn(authSlug),
...options.access?.authAccess,
},
}
: {}),
admin: { useAsTitle: 'email' },
auth: true,
// these rules are the plugin's, written for this slug (marked as such when iapl finishes) — not the ones
// the project passed in access.authAccess
...(hasRoles
? { custom: { ipalAccountRules: { slug: authSlug, applied: ['create', 'delete', 'read', 'unlock', 'update'].filter((k) => !(k in (options.access?.authAccess ?? {}))), ownRoles: false } } }
: {}),
fields: [],
},
]
}
// --- custom admin route (e.g. '/its' instead of '/admin') ---
// Sets config.routes.admin; the project must move its app/(payload)/<route>/
// folder to match (plugin can't create files in the project's app/).
if (options.adminRoute) {
config.routes = { ...(config.routes ?? {}), admin: options.adminRoute }
}
// --- enforced 2FA (TOTP) via @clocklimited/payload-2fa ---
// Enforced by default (forceSetup) unless twoFactor is explicitly false. The
// package is an optional PEER the project injects — IAPL doesn't bundle
// or import it, so projects that opt out (twoFactor: false) needn't install it.
// Wrapping access control (not just admin UI) means TOTP gates data access —
// no API bypass.
// IAPL's own second-factor check (secondFactor.ts) covers what the 2FA
// package cannot: everything added to the config after the package ran.
let secondFactorGuard = false
/** The 2FA collection, when 2FA is on. */
let twoFactorCollection: null | string = null
/** Set when the committed admin import map lacks the 2FA view wrapper (production). */
let staleImportMap: null | string = null
/** This config's entry in the staff registry until a Payload instance takes it over. */
const staffToken = {}
/**
* A config has gone live on this instance (start, or a dev hot reload): guard what plugins
* listed after iapl added, and file its staff collections under the instance.
*/
const adoptConfig = (payload: BasePayload) => {
const token = (payload.config.custom as { ipal?: { staffToken?: object } } | undefined)?.ipal?.staffToken
registerStaffCollections(payload, staffCollectionSlugs(payload), token)
// Auth collections a plugin listed after iapl added: the account rules for them too — BEFORE the
// 2FA guard below wraps their access (it needs the rule inside its wrapper).
if (accounts) {
const rule = resolvePasswordRule(accounts.password)
// `payload.config`, not `payload.collections`: on a dev reload Payload swaps the config first, and
// `payload.collections` still holds the old one at this moment.
const lateAccounts = adoptLateAuthCollections(payload.config as never, staffCollectionSlugs(payload), {
access: { ...accountAccess, pluginRoles: [] },
beforeOperation: rule ? buildPasswordRuleHook(rule) : undefined,
firstUserRoute: accounts.firstUserRoute,
})
// said exactly: what was put, on which collection
for (const late of lateAccounts) {
const parts = [late.applied.length ? `access rules for ${late.applied.join(', ')}` : '', late.password ? 'the password rule' : '', late.firstUser ? 'the first-user endpoint' : ''].filter(Boolean)
const kept = late.kept.length ? ` Its own rules for ${late.kept.join(', ')} are kept as written.` : ''
payload.logger.info(`[iapl] "${late.slug}" ${late.known ? 'became a staff collection after iapl ran' : 'was added after iapl'}: put on it — ${parts.join('; ')}.${kept}`)
}
}
if (!secondFactorGuard) {return}
const late = ensurePayloadGuarded(payload)
if (late?.length) {payload.logger.info(`[iapl] 2FA also enforced on entities added after iapl: ${late.join(', ')}.`)}
}
/** 2FA collection when "setup required" is on — its existing accounts get their setup window in onInit. */
let setupRequiredFor: null | string = null
let setupWindowHours = 0
/** accounts.panelRole in force: the collection and the role, for the start-up line. */
let panelRoleFor: { role: Role; slug: string } | null = null
/** Why the default panel role was not applied (said once at start). */
let panelRoleSkipped: null | string = null
/** `accounts: false` turns every account rule off. */
const accounts: AccountsOptions | null = options.accounts === false ? null : (options.accounts ?? {})
/** Which of the staff defaults are on (accounts.adminOnlyCreate / adminOnlyWrite / staffOnlyRead). */
const accountAccess = { create: accounts?.adminOnlyCreate !== false, read: accounts?.staffOnlyRead !== false, write: accounts?.adminOnlyWrite !== false }
/** requireSetup.setupNotice / statusField (on unless switched off). */
let setupNotice = true
let statusField = false
// Account rules (accounts.*): nobody creates an account for themselves, or takes one over.
// BEFORE the 2FA package: it gives every collection a create / update / delete function of
// its own, and afterwards a missing rule cannot be told from one the project wrote.
if (accounts) {
const panelSlug = config.admin?.user ?? (config.collections ?? []).find((c) => c.auth)?.slug
const staffSlugs = [...new Set([panelSlug, options.access?.authCollection, ...(options.access?.staffCollections ?? [])].filter((s): s is string => Boolean(s)))]
config = applyStaffAccountAccess(config, staffSlugs, { ...accountAccess, pluginRoles: options.access?.authCollection ? [options.access.authCollection] : [] })
}
if (options.twoFactor !== false) {
const tf = options.twoFactor
if (!tf?.issuer) {
throw new Error(
'[iapl] twoFactor.issuer is required (name shown in the authenticator ' +
'app). Pass twoFactor: { issuer: "Your Site" }, or twoFactor: false to ' +
'opt out (discouraged).',
)
}
// The project INJECTS the factory (twoFactor.plugin = payloadTotp) — the
// plugin never imports the optional peer itself, so Next has nothing it
// can't bundle. See TotpPluginFactory / docs/security.md.
const totp: TotpPluginFactory | undefined = tf.plugin
if (typeof totp !== 'function') {
throw new Error(
'[iapl] 2FA is enforced but no 2FA plugin was injected. Add ' +
'`import { payloadTotp } from "@clocklimited/payload-2fa"` and pass ' +
'`twoFactor: { issuer, plugin: payloadTotp }`. Or set twoFactor: false ' +
'to opt out (discouraged).',
)
}
// TOTP must wrap the collection people log in to the panel with
// (admin.user, else Payload's pick: the first auth collection). Wrapping
// another slug leaves the real one without TOTP fields, and the TOTP
// access wrapper lets users without those fields through — 2FA silently
// off. So: default to it, and refuse a target that isn't an auth
// collection, or differs from it unless allowCollectionMismatch says so.
const authSlugs = (config.collections ?? []).filter((c) => c.auth).map((c) => c.slug)
const adminSlug = config.admin?.user ?? authSlugs[0] ?? authSlug
const target = tf.collectionSlug ?? adminSlug
if (!authSlugs.includes(target)) {
throw new Error(
`[iapl] twoFactor: "${target}" is not an auth collection, so 2FA would protect nothing. ` +
`Auth collections: ${authSlugs.join(', ') || 'none'}. Fix twoFactor.collectionSlug.`,
)
}
if (target !== adminSlug && !tf.allowCollectionMismatch) {
throw new Error(
`[iapl] twoFactor wraps "${target}" but the admin panel logs in with "${adminSlug}" ` +
'(admin.user) — those accounts would skip 2FA. Point twoFactor.collectionSlug at ' +
`"${adminSlug}", or pass twoFactor.allowCollectionMismatch: true if that is deliberate.`,
)
}
const endpointsBefore = new Set(config.endpoints ?? [])
// Copies, so that a view the 2FA factory hands back is told apart from one it left alone
// even when the factory returns the very same objects on every call.
const viewsBefore = copyViews(config.admin?.components?.views)
if (config.admin?.components?.views) {
config.admin = { ...config.admin, components: { ...config.admin.components, views: viewsBefore as never } }
}
const entityEndpointsBefore = new Map<string, Set<unknown>>(
[...(config.collections ?? []), ...(config.globals ?? [])].map((e) => [e.slug, new Set<unknown>(Array.isArray(e.endpoints) ? e.endpoints : [])]),
)
// custom.ipal.secondFactor (IAPL's per-entity opt-out) → the package's own key
config = passOptOutsToPackage(config)
config = await totp({
collection: target,
forceSetup: true, // ENFORCED — every user must set up TOTP; no opt-out
totp: { issuer: tf.issuer },
})(config)
// The package's endpoints (setup, verify, remove, admin reset / remove) take
// `req.user` from ANY auth collection and act on the 2FA collection by id.
// Only accounts of the 2FA collection may use them (guardTotpEndpoint) —
// whatever the package registered, also paths a later version adds.
const limitVerify = tf.verifyLimit === false ? undefined : buildVerifyLimit(target, { ...tf.verifyLimit, keyPrefix: (typeof tf.verifyLimit?.keyPrefix === 'string' && tf.verifyLimit.keyPrefix.trim()) || (options.storageNames === 'iapl' ? 'iapl' : 'ipal') })
const extraOrigins = typeof tf.sameOrigin === 'object' ? (tf.sameOrigin.origins ?? []) : []
const guards = {
...(limitVerify ? { limitVerify: (req: PayloadRequest) => limitVerify(req) } : {}),
...(tf.sameOrigin === false
? {}
: {
ownOrigin: (req: PayloadRequest) => {
if (requestFromOwnOrigin(req as never, extraOrigins)) {return true}
reportRefusedOrigin(req as never, extraOrigins) // never in silence: once per origin, with the ways to allow it
return false
},
}),
onSetupClosed: (req: PayloadRequest) =>
Response.json({ message: serverText(req.i18n as never, 'twoFactorSetupClosed'), ok: false }, { status: 403 }),
}
config.endpoints = (config.endpoints ?? []).map((e) => (endpointsBefore.has(e) ? e : guardTotpEndpoint(e, target, guards as never)))
// …and the same for endpoints it may put on a collection or a global.
config.collections = guardNewEntityEndpoints(config.collections, entityEndpointsBefore, target, guards as never)
config.globals = guardNewEntityEndpoints(config.globals, entityEndpointsBefore, target, guards as never)
twoFactorCollection = target
// The window-start field is part of the 2FA collection whenever 2FA is on — the schema must
// not depend on requireSetup / guard (setupRequired.ts, buildSetupFields). The panel's status
// field joins it below, when the mode is on. Validates requireSetup at start either way.
if (tf.requireSetup !== false) {resolveRequireSetup(tf.requireSetup)}
// The views the 2FA package registered, by object: it REPLACES a view the project (or an
// earlier run of the package, or of iapl) already had under its keys, so a key that
// existed before is no sign that the view is the project's own. Taken here, before the
// texts step below re-creates those objects.
const viewsFromPackage = changedViewKeys(viewsBefore, { ...config.admin?.components?.views })
// The package wraps only what is in the config right now. IAPL's own
// globals and collections come later, so they get IAPL's guard at the
// end of this function (and other plugins' in onInit). The guard reads the
// package's `totp` strategy and `hasTotp` field: when those are not there,
// this is a version it was not written for — refuse to start rather than
// run with a second factor that may protect nothing.
if (tf.guard !== false) {
const missing = missingTotpParts(config, target)
if (missing.length) {
throw new Error(
`[iapl] twoFactor: the injected 2FA plugin did not add ${missing.join(', ')} to "${target}". ` +
'IAPL enforces the second factor on its own globals and collections through them, so it ' +
'cannot do that with this version of @clocklimited/payload-2fa. Use a supported version, or pass ' +
'twoFactor.guard: false to rely on the package alone (docs/security.md — not recommended).',
)
}
secondFactorGuard = true
// "Setup required" (default): an account without TOTP reaches nothing but the setup
// screen, and only within the window; requireSetup: false = the package's rule.
const setup = resolveRequireSetup(tf.requireSetup)
const setupParts = tf.requireSetup && typeof tf.requireSetup === 'object' ? tf.requireSetup : {} // null = the default, like undefined
config.custom = { ...config.custom, ipal: { ...config.custom?.ipal, twoFactor: { collection: target, ...setup } } }
if (setup.requireSetup) {
setupRequiredFor = target
setupWindowHours = setup.setupWindowMs / 3_600_000
setupNotice = setupParts.setupNotice !== false
statusField = setupParts.statusField !== false
// The stamp hook only while the mode is on: an account made while it is off gets its
// window when the mode is switched on (the start-up step), not a creation date long past.
config.collections = (config.collections ?? []).map((c) =>
c.slug === target ? { ...c, hooks: { ...c.hooks, beforeChange: [...(c.hooks?.beforeChange ?? []), stampSetupFrom] } } : c,
)
if (setupParts.dashboardNotice !== false) {
config.admin = {
...config.admin,
components: {
...config.admin?.components,
beforeDashboard: [
...(config.admin?.components?.beforeDashboard ?? []),
{ path: '@intecion/ipal-kit/admin#TwoFactorAlert', serverProps: { adminRoute: options.adminRoute ?? '/admin' } },
],
},
}
}
}
// An admin resets an account's TOTP (lost phone) / reopens its setup window.
config.endpoints = [...(config.endpoints ?? []), buildTwoFactorResetEndpoint(target, { access: tf.resetAccess })]
// Called by Payload on every request before any access function: guards whatever
// the live config has that was added after iapl (start, dev hot reload).
const sweep = buildGuardStrategy(adoptConfig)
config.collections = (config.collections ?? []).map((c) =>
c.slug === target && typeof c.auth === 'object'
? { ...c, auth: { ...c.auth, strategies: [sweep as never, ...(c.auth.strategies ?? [])] } } // first: a strategy that finds a user ends the round
: c,
)
}
// The window start (data) whenever 2FA is on; the status / reset control when the mode is.
config.collections = (config.collections ?? []).map((c) =>
c.slug === target ? { ...c, fields: [...c.fields, ...buildSetupFields({ statusField })] } : c,
)
// The package's texts are long and informal: IAPL's (admin-ux.md) go over
// them, the project's own i18n.translations over both. The 2FA screens get a
// tab title instead of "Payload" (view meta is a plain string: the site's language).
if (tf.texts !== false) {
config.i18n = {
...config.i18n,
translations: deepMergeSimple(
deepMergeSimple((config.i18n?.translations ?? {}) as Record<string, unknown>, TOTP_TEXTS),
(incomingConfig.i18n?.translations ?? {}) as Record<string, unknown>,
),
}
const title = TOTP_VIEW_TITLE[options.i18n.defaultLocale.toLowerCase().startsWith('pl') ? 'pl' : 'en']
const views = config.admin?.components?.views ?? {}
config.admin = {
...config.admin,
components: {
...config.admin?.components,
views: Object.fromEntries(
Object.entries(views).map(([key, view]) =>
/^(?:Setup|Verify)TOTP/.test(key) && view && !view.meta?.title
? [key, { ...view, meta: { ...view.meta, title } }]
: [key, view],
),
),
},
}
}
// The package's TOTPProvider reads the path from an `x-pathname` header
// no proxy sets on /admin, so it redirected the setup screen to itself
// (`setup-totp?back=null`). Swap in IAPL's client-side provider, or
// the project's (`provider`); `provider: false` keeps the package's.
if (tf.provider !== false) {
const custom = tf.provider
const ours =
typeof custom === 'object' ? custom : { path: custom ?? TOTP_REDIRECT_PROVIDER }
const providers = config.admin?.components?.providers ?? []
config.admin = {
...config.admin,
components: {
...config.admin?.components,
providers: providers.map((p) =>
p && (typeof p === 'string' ? p : p.path) === TOTP_PACKAGE_PROVIDER
? {
...ours,
clientProps: { forceSetup: true, ...(setupRequiredFor && setupNotice ? { requireSetup: true, setupWindowHours } : {}), ...ours.clientProps },
serverProps: { ...(typeof p === 'object' ? p.serverProps : {}), ...ours.serverProps },
}
: p,
),
},
}
}
// The package's setup and verify screens send the browser to the `back` query
// value after a valid code, unchecked: a crafted link runs script in the panel
// or leaves the site (safeBack.ts). IAPL's view goes in front of them and
// hands the package's view a checked value. `safeBack: false` leaves them as
// the package registered them; a function replaces the rule.
if (tf.safeBack !== false) {
const wrapped = wrapTotpViews(
(config.admin?.components?.views ?? {}) as Record<string, { Component?: unknown; path?: string }>,
(key) => viewsFromPackage.has(key),
typeof tf.safeBack === 'function' ? tf.safeBack : undefined,
)
if (Object.keys(wrapped.dependencies).length) {
config.admin = {
...config.admin,
components: { ...config.admin?.components, views: wrapped.views as never },
// keeps the package's own views in the import map: the wrapper renders them from there
dependencies: { ...config.admin?.dependencies, ...wrapped.dependencies },
}
// A production build with the import map of the previous version shows an EMPTY 2FA
// screen (Payload renders nothing for a path the map lacks): say so, in the log at
// start and on the screen itself (importMapCheck.ts). Development regenerates the map.
// The check reads the file on disk, which need not be the map in the bundle — so it
// only ever ADDS a notice; the screen itself is rendered as usual.
if (tf.importMapCheck !== false && process.env.NODE_ENV === 'production') {
const stale = await missingImportMapEntries(config, [SAFE_TOTP_VIEW])
if (stale.missing.length) {
staleImportMap = `${stale.missing.join(', ')} was not found in ${stale.file}`
const providers = config.admin?.components?.providers ?? []
config.admin = {
...config.admin,
components: {
...config.admin?.components,
providers: providers.map((p) =>
p && typeof p === 'object' && p.path === TOTP_REDIRECT_PROVIDER // IAPL's own provider only
? { ...p, clientProps: { ...p.clientProps, staleImportMap: true } }
: p,
),
},
}
}
}
}
}
}
const agency = options.agency === undefined ? DEFAULT_AGENCY : options.agency
// --- white-label admin branding ---
// Inject admin.components.graphics.Logo/Icon pointing at the plugin's
// /admin export. The components read SiteSettings at render, so each client
// sees their own brand from the panel (no brand in code). Project must run
// `pnpm generate:importmap` so Payload resolves the component paths.
if (options.whiteLabel) {
const wl = options.whiteLabel === true ? {} : options.whiteLabel
const serverProps: Record<string, unknown> = {}
if (wl.settingsSlug) {serverProps.settingsSlug = wl.settingsSlug}
if (wl.nameField) {serverProps.nameField = wl.nameField}
if (wl.inlineImages === false) {serverProps.inlineImages = false}
const logoProps = { ...serverProps, ...(wl.logoField ? { imageField: wl.logoField } : {}) }
const iconProps = { ...serverProps, ...(wl.iconField ? { imageField: wl.iconField } : {}) }
// Vendor credit ("Technology support: Intecion.com") under the nav — on by
// default, hidden with credit:false, text/url overridable.
const creditOn = wl.credit !== false && agency !== false
const creditProps = {
...(agency ? { agency: agency.name, url: agency.url } : {}),
...(wl.credit && typeof wl.credit === 'object'
? {
...(wl.credit.text ? { text: wl.credit.text } : {}),
...(wl.credit.url ? { url: wl.credit.url } : {}),
}
: {}),
}
config.admin = {
...(config.admin ?? {}),
components: {
...(config.admin?.components ?? {}),
graphics: {
...(config.admin?.components?.graphics ?? {}),
Icon: { path: '@intecion/ipal-kit/admin#AdminIcon', serverProps: iconProps },
Logo: { path: '@intecion/ipal-kit/admin#AdminLogo', serverProps: logoProps },
},
...(creditOn
? {
afterLogin: [
...(config.admin?.components?.afterLogin ?? []),
{
path: '@intecion/ipal-kit/admin#IntecionCredit',
serverProps: { ...creditProps, variant: 'login' },
},
],
afterNavLinks: [
...(config.admin?.components?.afterNavLinks ?? []),
{
path: '@intecion/ipal-kit/admin#IntecionCredit',
serverProps: { ...creditProps, variant: 'nav' },
},
],
}
: {}),
},
...(wl.titleSuffix
? { meta: { ...(config.admin?.meta ?? {}), titleSuffix: wl.titleSuffix } }
: {}),
}
}
// --- admin <head>: link previews + noindex (default on) ---
// Static parts now; the site name parts come from Site settings in onInit
// and after every save (syncAdminMeta). The project's own admin.meta keys win.
let adminMeta: null | ResolvedAdminMeta = null
const brandFields = options.whiteLabel && options.whiteLabel !== true ? options.whiteLabel : {}
const settingsSlug = brandFields.settingsSlug ?? 'site-settings'
if (options.adminMeta !== false) {
const built = buildAdminMeta({
agency,
apiRoute: config.routes?.api,
defaultLocale: options.i18n.defaultLocale,
meta: config.admin?.meta,
options: options.adminMeta ?? {},
})
adminMeta = built.resolved
config.admin = { ...(config.admin ?? {}), meta: built.meta }
config.endpoints = [
...(config.endpoints ?? []),
...buildAdminImageEndpoints(built.resolved, {
iconField: brandFields.iconField,
logoField: brandFields.logoField,
nameField: brandFields.nameField,
serveIcon: options.adminMeta?.serveIcon,
settingsSlug,
}),
]
}
// --- i18n ---
config.localization = buildLocalizationConfig(options.i18n)
// Admin languages (en + pl unless the project set its own) and the plugin's texts.
config = applyAdminI18n(config)
// --- access: inject roles into the client's auth collection ---
if (options.access) {
config = injectRoles(config, options.access)
// Staff collections besides the panel's login collection: the one that carries
// the roles, and the ones the project names. Roles and staff checks count only
// for accounts of a staff collection (staffCollectionSlugs).
const staff = [...new Set([options.access.authCollection, ...(options.access.staffCollections ?? [])])]
config.custom = { ...config.custom, ipal: { ...config.custom?.ipal, staffCollections: staff } }
// Account rules (accounts.*): the lowest role stays out of the panel.
let panelRole = accounts ? resolvePanelRole(accounts.panelRole) : null
const rolesSlug = options.access.authCollection
// With firstUserAdmin: false the first account gets the default role. Below the panel
// role, a fresh site would have nobody who can open the panel — and nobody to raise a role.
const firstRole = options.access.defaultRole ?? 'user'
if (panelRole && options.access.firstUserAdmin === false && ROLE_HIERARCHY.indexOf(firstRole) < ROLE_HIERARCHY.indexOf(panelRole)) {
if (accounts?.panelRole !== undefined) {
throw new Error(
`[iapl] access.firstUserAdmin: false with accounts.panelRole: '${panelRole}' leaves a fresh site with nobody who can open the panel: ` +
`the first account gets the role '${firstRole}', which is below the panel role. Set access.defaultRole to '${panelRole}' or higher, ` +
"or accounts: { panelRole: false }, or drop access.firstUserAdmin: false (docs/access.md \"Account rules\").",
)
}
panelRoleSkipped = `access.firstUserAdmin is false and the first account gets the role '${firstRole}'`
panelRole = null
}
// the project's own access.admin (or access.authAccess.admin) wins
if (panelRole && !(config.collections ?? []).find((c) => c.slug === rolesSlug)?.access?.admin) {
config = applyPanelRole(config, rolesSlug, panelRole)
panelRoleFor = { slug: rolesSlug, role: panelRole }
}
}
// Account rules (accounts.*): nobody creates an account for themselves.
if (accounts) {
const panelSlug = config.admin?.user ?? (config.collections ?? []).find((c) => c.auth)?.slug
const staffSlugs = [...new Set([panelSlug, options.access?.authCollection, ...(options.access?.staffCollections ?? [])].filter((s): s is string => Boolean(s)))]
config = applyFirstUserRoute(config, accounts.firstUserRoute)
const passwordRule = resolvePasswordRule(accounts.password)
if (passwordRule) {config = applyPasswordRule(config, staffSlugs, passwordRule)}
}
// For predicates called without `req.payload` (isAdmin(req.user) in a hook): what this config
// says now, under a token; the Payload instance takes the entry over when the config goes live
// (adoptConfig), with `admin.user` as Payload resolved it.
{
const panel = config.admin?.user ?? (config.collections ?? []).find((c) => c.auth)?.slug
config.custom = { ...config.custom, ipal: { ...config.custom?.ipal, staffToken } }
registerStaffCollections(staffToken, staffCollectionSlugs({ admin: { user: panel }, custom: config.custom }))
}
// --- seo: apply @payloadcms/plugin-seo directly ---
// NOTE: apply the plugin function to the config immediately rather than
// pushing it onto config.plugins. Payload has already iterated the plugins
// array by the time IAPL runs, so nested plugins added to that list are
// never executed. Calling the plugin as (config) => config applies its
// transform now.
if (options.seo) {
config = await buildSeoPlugin({ seo: options.seo })(config)
// Auto-fill empty meta from document content on save
config = injectAutoFillMeta(config, options.seo)
// Wrap fields into Content + SEO tabs (replaces plugin-seo's tabbedUI,
// which breaks when other fields already exist in the collection)
config = injectSeoTabs(config, options.seo)
}
// --- theme: the localStorage key of the visitor's choice reaches getSiteShell() through config.custom ---
if (options.theme?.storageKey) {
config.custom = { ...config.custom, ipal: { ...config.custom?.ipal, themeStorageKey: options.theme.storageKey } }
}
// --- forms: apply @payloadcms/plugin-form-builder directly ---
if (options.forms) {
config = await buildFormsPlugin(options.forms)(config)
// submitForm reads it from payload.config when the call doesn't pass one
if (options.forms.consentFieldName) {
config.custom = { ...config.custom, ipal: { ...config.custom?.ipal, consentFieldName: options.forms.consentFieldName } }
}
// what a form does while Turnstile cannot check — read by passTurnstile when the call site gives none
if (options.forms.turnstileOnConfigError) {
const ipal = (config.custom?.ipal ?? {}) as { forms?: object }
config.custom = { ...config.custom, ipal: { ...ipal, forms: { ...ipal.forms, turnstileOnConfigError: options.forms.turnstileOnConfigError } } }
}
}
// --- globals ---
// The System Pages tab collects every "which page plays this role"
// assignment. Composing it here keeps SiteSettings unaware of which modules
// are enabled — it just renders the fields it's given.
const systemPageFields = [
...(options.pages ? buildSystemPagesFields(options.pages) : []),
...(options.content && options.pages
? buildArchiveFields(options.content, options.pages.slug)
: []),
]
// Top-level option first (works without `seo`), then the older seo.searchSettings.
const searchSettings = options.searchSettings ?? options.seo?.searchSettings
const pluginGlobals = [
buildSiteSettings({
additionalFields: options.siteSettingsFields,
...(options.pages ? { constructionFields: buildConstructionFields(options.pages.slug) } : {}),
...(options.forms?.emailLayout ? { emailFields: emailSettingsFields } : {}),
...(searchSettings === false
? {}
: { searchFields: typeof searchSettings === 'function' ? searchSettings(searchSettingsFields) : searchSettingsFields }),
systemPageFields,
}),
buildSiteIntegrations({
additionalFields: options.integrationsFields,
mailRelay: options.mail?.relay !== false,
reenterSecretOnChange: options.secrets?.reenterOnChange !== false,
writeOnlySecrets: options.secrets?.writeOnly !== false,
}),
withFillLocales('global', buildCookieSettings(), fillLocales['cookie-settings']),
buildNotifications({ lightbox: options.lightbox === true }),
]
// A global feeds every page's layout — revalidate the site on save.
const revalidateGlobal = options.revalidatePath ? buildGlobalRevalidateHook({ revalidatePath: options.revalidatePath }) : null
const withRevalidate = revalidateGlobal
? pluginGlobals.map((g) => ({ ...g, hooks: { ...g.hooks, afterChange: [...(g.hooks?.afterChange ?? []), revalidateGlobal] } }))
: pluginGlobals
// The project's globalOverrides win (access, admin, hooks merged; a function = full control).
config.globals = [...(config.globals ?? []), ...applyGlobalOverrides(withRevalidate, options.globalOverrides)]
// A new site name refreshes the panel's link preview texts.
if (adminMeta) {
const resolved = adminMeta
config.globals = config.globals.map((g) =>
g.slug === settingsSlug
? {
...g,
hooks: {
...g.hooks,
afterChange: [
...(g.hooks?.afterChange ?? []),
async ({ doc, req }) => {
if (req?.payload) {await syncAdminMeta(req.payload, resolved, { nameField: brandFields.nameField, settingsSlug })}
return doc
},
],
},
}
: g,
)
}
config.endpoints = [...(config.endpoints ?? []), testEmailEndpoint]
// --- e-mail: the Intecion Notifications Webservice (docs/email.md; off with mail: { relay: false }) ---
// What mailAdapter() reads at send time; born under the new name (`custom.iapl`).
const relay = options.mail?.relay
if (relay && relay.developmentHosts !== undefined) {assertDevelopmentHosts(relay.developmentHosts, 'iapl({ mail: { relay: { developmentHosts } } })')}
const iaplCustom = (config.custom?.iapl ?? {}) as object
config.custom = {
...config.custom,
iapl: { ...iaplCustom, ...(options.developmentHosts !== undefined ? { developmentHosts: [...assertDevelopmentHosts(options.developmentHosts, 'iapl({ developmentHosts })')] } : {}), mail: { ...(options.mail?.graphDeprecationWarning === false ? { graphDeprecationWarning: false } : {}), relay: relay === false ? false : (relay ?? {}) } },
}
// "Forgot password" and "verify your e-mail" through mailAdapter(): sent right after their transaction
// commits, not inside it (mail.accountMailAfterCommit; docs/deployment.md §4.3a).
if (options.mail?.accountMailAfterCommit !== false) {
config.collections = (config.collections ?? []).map((c) => (c.auth ? withAccountMailAfterCommit(c) : c))
}
if (relay !== false) {
// The public route the service calls a site back at (404 unless this site just started an
// enrolment), and the admin-only routes of the state block on the e-mail tab.
config.endpoints = [...config.endpoints, relayConfirmEndpoint(relay ?? {}), ...relayPanelEndpoints()]
// "Forgot password" and "verify your e-mail" are Payload's own mail: say what they are.
config.collections = (config.collections ?? []).map((c) => (c.auth ? withAccountMailMark(c) : c))
}
// --- iapl-doctor status (404 until IAPL_DOCTOR_TOKEN is set; docs/doctor.md) ---
if (options.doctor !== false) {
config.endpoints = [...(config.endpoints ?? []), buildDoctorEndpoint(options.doctor ?? {})]
}
// --- consent log: proof of consent (on by default since 1.17.0; `consentLog: false` turns it off) ---
if (options.consentLog !== false) {
const logOptions = options.consentLog === true || options.consentLog === undefined ? {} : options.consentLog
config.collections = [...(config.collections ?? []), applyCollectionOverride(buildConsentLogCollection(), logOptions.collectionOverrides)]
config.endpoints = [...(config.endpoints ?? []), buildConsentLogEndpoint(logOptions)]
}
// --- cookie scanner: review list + "Scan cookies" (opt-in) ---
if (options.cookieScanner) {
const scannerOptions = options.cookieScanner === true ? {} : options.cookieScanner
const adminRoute = options.adminRoute ?? '/admin'
const labels = mergeCookieScanLabels(scannerOptions.labels)
// One "Cookies" entry by default: the review list and the site check leave the navigation
// (their pages and API stay) and appear as tabs of the Cookies global.
const combined = scannerOptions.adminLayout !== 'separate'
const hideFromNav = <T extends { admin?: object }>(entity: T): T => (combined ? { ...entity, admin: { ...entity.admin, group: false } } : entity)
config.collections = [
...(config.collections ?? []),
applyCollectionOverride(hideFromNav(withFillLocales('collection', buildCookieReviewCollection(scannerOptions), fillLocales['cookie-review'])), scannerOptions.collectionOverrides),
]
const scanPlugin = { localeCount: options.i18n.locales.length, stats: Boolean(options.stats), visitorCookie: visitorCookieFor(options.storageNames), ...(options.theme?.storageKey ? { themeStorageKey: options.theme.storageKey } : {}) }
config.endpoints = [...(config.endpoints ?? []), ...buildCookieScanEndpoints(scannerOptions, scanPlugin)]
// One approval for everything found (default on): the "Approve cookies" view and its endpoint.
const approval = scannerOptions.approval === false ? null : (scannerOptions.approval ?? {})
if (approval) {
config.endpoints = [...(config.endpoints ?? []), ...buildCookieApprovalEndpoints(scannerOptions)]
config.admin = {
...(config.admin ?? {}),
components: {
...(config.admin?.components ?? {}),
views: {
...(config.admin?.components?.views ?? {}),
ipalCookieApproval: {
Component: {
path: '@intecion/ipal-kit/admin#CookieApprovalView',
serverProps: { adminRoute, labels, ...(approval.unknownCategory ? { unknownCategory: approval.unknownCategory } : {}) },
},
meta: { title: 'Approve cookies' },
path: COOKIE_APPROVAL_VIEW_PATH,
},
},
},
}
}
// Browser crawl through the scanner service (opt-in): latest-result global, endpoints.
const crawl = scannerOptions.crawl ? (scannerOptions.crawl === true ? {} : scannerOptions.crawl) : null
if (crawl) {
const crawlGlobal = hideFromNav(buildCookieCrawlGlobal(labels))
const override = crawl.globalOverride
config.globals = [
...(config.globals ?? []),
override ? applyGlobalOverrides([crawlGlobal], { [crawlGlobal.slug]: override } as never)[0] : crawlGlobal,
]
config.endpoints = [...(config.endpoints ?? []), ...buildCookieCrawlEndpoints({ labels, options: scannerOptions, plugin: scanPlugin })]
}
if (combined) {
config.globals = (config.globals ?? []).map((g) =>
g.slug === 'cookie-settings'
? addCookieScannerTabs(g, { approval: Boolean(approval), crawl: Boolean(crawl), labels, unknownCategory: approval?.unknownCategory })
: g,
)
}
// Dashboard warning: cookies waiting for approval, crawl violations or a failed crawl.
const alertApproval = Boolean(approval && approval.dashboard !== false)
const alertCrawl = Boolean(crawl && crawl.dashboard !== false)
if (alertApproval || alertCrawl) {
config.admin = {
...(config.admin ?? {}),
components: {
...(config.admin?.components ?? {}),
beforeDashboard: [
...(config.admin?.components?.beforeDashboard ?? []),
{ path: '@intecion/ipal-kit/admin#CookieCrawlAlert', serverProps: { adminRoute, approval: alertApproval, crawl: alertCrawl, labels, ...(options.dashboardAlerts?.cookies ? { audience: options.dashboardAlerts.cookies } : {}) } },
],
},
}
}
}
// --- built-in statistics: cookieless visits + consented history (opt-in) ---
if (options.stats) {
const statsOptions = options.stats === true ? {} : options.stats
const adminRoute = options.adminRoute ?? '/admin'
const viewProps = { adminRoute, ...(statsOptions.timeZone ? { timeZone: statsOptions.timeZone } : {}) }
config.collections = [...(config.collections ?? []), applyCollectionOverride(buildStatsCollection(), statsOptions.collectionOverrides)]
config.endpoints = [...(config.endpoints ?? []), buildStatsEndpoint(statsOptions)]
config.admin = {
...(config.admin ?? {}),
components: {
...(config.admin?.components ?? {}),
afterNavLinks: [
...(config.admin?.components?.afterNavLinks ?? []),
{ path: '@intecion/ipal-kit/admin#StatsNavLink', serverProps: { adminRoute } },
],
beforeDashboard: [
...(config.admin?.components?.beforeDashboard ?? []),
...(statsOptions.dashboard === false
? []
: [{ path: '@intecion/ipal-kit/admin#StatsWidget', serverProps: viewProps }]),
],
views: {
...(config.admin?.components?.views ?? {}),
ipalStats: {
Component: { path: '@intecion/ipal-kit/admin#StatsView', serverProps: viewProps },
meta: { title: 'Statistics' },
path: '/stats',
},
},
},
}
}
// --- IndexNow: submit published URLs (opt-in) ---
if (options.indexNow) {
const pagesSlug = options.pages?.slug ?? 'pages'
const contentSlugs = new Set((options.content?.collections ?? []).map((c) => c.slug))
config.collections = (config.collections ?? []).map((collection) => {
const isPages = collection.slug === pagesSlug
if (!isPages && !contentSlugs.has(collection.slug)) {return collection}
const hook = buildIndexNowHook({
config: options.i18n,
...(isPages ? {} : { contentCollection: collection.slug }),
})
return {
...collection,
hooks: { ...collection.hooks, afterChange: [...(collection.hooks?.afterChange ?? []), hook] },
}
})
}
// --- integration alerts on the dashboard (Turnstile status, …) ---
// Renders nothing while everything works; never throws.
config.admin = {
...(config.admin ?? {}),
components: {
...(config.admin?.components ?? {}),
beforeDashboard: [
...(config.admin?.components?.beforeDashboard ?? []),
{
path: '@intecion/ipal-kit/admin#IntegrationAlerts',
serverProps: { adminRoute: options.adminRoute ?? '/admin', ...(options.dashboardAlerts?.integrations ? { details: options.dashboardAlerts.integrations } : {}) },
},
],
},
}
// --- second factor on everything in the config by now: the project's
// collections (wrapped by the package already; twice is harmless), the
// plugin's globals and collections, the form builder's.
if (secondFactorGuard) {
// the plugin's account rules get their mark first (the 2FA package has wrapped them by now): the guard carries it over
config = markStaffRules(config)
config = guardConfigAccess(config)
}
// --- hooks: onInit ---
const incomingOnInit = config.onInit
config.onInit = async (payload) => {
if (incomingOnInit) {await incomingOnInit(payload)}
// A staff collection that does not exist protects nothing and hides a typo: its accounts would not be staff,
// or — worse — a collection of that name added later would be, without anyone having decided it.
const unknownStaff = unknownStaffCollections(payload.config as never, [...new Set([options.access?.authCollection, ...(options.access?.staffCollections ?? [])].filter((s): s is string => Boolean(s)))])
if (unknownStaff.length) {
throw new Error(
`[iapl] access names ${unknownStaff.map((s) => `"${s}"`).join(', ')} as a staff collection, but this config has no auth collection with that slug ` +
`(auth collections: ${payload.config.collections.filter((c) => c.auth).map((c) => c.slug).join(', ') || 'none'}). ` +
'Fix the slug in access.authCollection / access.staffCollections, or add the collection (docs/access.md "Who is staff").',
)
}
adoptConfig(payload)
// Postgres: keep a few pool connections free of transactions (connectionReserve), and watch commits so
// that form e-mails go out after the submission's transaction (forms.emailsInTransaction).
watchTransactions(payload, options.connectionReserve === false ? false : (options.connectionReserve ?? defaultConnectionReserve(poolSize(payload) ?? 10)))
// Microsoft Graph is deprecated (removed in 2.0): one warning per start while its variables are set.
if (graphAvailable() && options.mail?.graphDeprecationWarning !== false) {payload.logger.warn(GRAPH_DEPRECATION_NOTICE)}
// Payload's dev reload swaps `payload.config` and runs no onInit: adopt the new config at once.
watchPayloadConfig(payload, adoptConfig)
if (staleImportMap) {
payload.logger.error(
`[iapl] The admin import map may be out of date: ${staleImportMap}. If the 2FA setup and verify screens are ` +
'EMPTY (no code form), nobody can sign in to the panel: run `pnpm payload generate:importmap`, commit ' +
'importMap.js, rebuild and redeploy. If the screens work, the file on disk is not the map the build used — ' +
'set twoFactor.importMapCheck: false (docs/security.md "A stale import map").',
)
}
// Staff whose collection is not the 2FA collection log in without a second factor: say so.
if (twoFactorCollection) {
const uncovered = staffCollectionSlugs(payload).filter((slug) => slug !== twoFactorCollection)
if (uncovered.length) {
payload.logger.warn(
`[iapl] 2FA covers "${twoFactorCollection}" only. Staff accounts of ${uncovered.map((s) => `"${s}"`).join(', ')} ` +
'pass the staff checks with a password alone (docs/access.md "Who is staff").',
)
}
}
if (panelRoleSkipped) {
payload.logger.warn(
`[iapl] The panel role (accounts.panelRole, 'editor' by default) is NOT applied: ${panelRoleSkipped}, so nobody could open the panel on a fresh site. ` +
'Every account of the login collection can open the panel. To keep the lowest role out, set access.defaultRole to \'editor\' or drop access.firstUserAdmin: false (docs/access.md "Account rules").',
)
}
// Staff collections on the admin rules while no staff account is an admin: nobody can manage their accounts.
if (accounts) {
const { stuck, unchecked } = await staffCollectionsNobodyManages(payload as never, staffCollectionSlugs(payload), options.access?.authCollection)
if (stuck.length) {
payload.logger.warn(
`[iapl] No staff account holds the role "admin", so NOBODY can create, delete or unlock accounts in ${stuck.map((s) => `"${s}"`).join(', ')} ` +
"(only an admin does there: the collection's roles can hold \"editor\" or \"admin\"). Give one account the role with a script " +
'(payload.update, Local API), or write the collection\'s own access.create / update / delete rules (docs/access.md "Account rules").',
)
} else if (unchecked.length) {
payload.logger.warn(
`[iapl] Could not check whether an account of ${unchecked.map((s) => `"${s}"`).join(', ')} holds the role "admin" (no other staff account does). ` +
'If none does, nobody can create, delete or unlock accounts in the staff collections that are managed by admins only (docs/access.md "Account rules").',
)
}
}
// The panel role: tell a site how many of its accounts the rule keeps out of the panel.
if (panelRoleFor) {
try {
const { all, below } = await countBelowPanelRole(payload, panelRoleFor.slug, panelRoleFor.role)
if (all && below === all) {
payload.logger.error(
`[iapl] No account of "${panelRoleFor.slug}" has the role "${panelRoleFor.role}" or higher, so NOBODY can open the admin panel ` +
'(accounts.panelRole). Give an account the role with a script (payload.update, Local API), or set accounts: { panelRole: false } and redeploy (docs/access.md "Account rules").',
)
} else if (below) {
payload.logger.warn(
`[iapl] ${below} account(s) of "${panelRoleFor.slug}" are below the role "${panelRoleFor.role}" and cannot open the admin panel ` +
'(accounts.panelRole). Give them a higher role, or set accounts: { panelRole: \'user\' } (docs/access.md "Account rules").',
)
}
} catch {
/* a database that is not ready must not stop the start */
}
}
// Accounts from before "setup required": their window starts now, not at their creation date.
if (setupRequiredFor) {
const started = await backfillSetupFrom(payload, setupRequiredFor)
if (started) {
payload.logger.warn(
`[iapl] 2FA: ${started} existing account(s) without two-step verification. ` +
(setupWindowHours ? `They have ${setupWindowHours} h from now to set it up; after that an administrator must reopen setup.` : 'They cannot use the panel until they set it up.'),
)
}
}
await migrateCookieSettingsSaveButton(payload)
await migrateTitleSeparator(payload, settingsSlug)
if (adminMeta) {await syncAdminMeta(payload, adminMeta, { nameField: brandFields.nameField, settingsSlug })}
payload.logger.info('[iapl] Plugin initialized.')
}
// Every auth collection of this config has been seen: what appears later is a late one (adoptConfig).
if (accounts) {
const panel = config.admin?.user ?? (config.collections ?? []).find((c) => c.auth)?.slug
config = markSeenAuthCollections(config, staffCollectionSlugs({ admin: { user: panel }, custom: config.custom }))
}
return config
}
}
/** @deprecated The name before 1.17.0; the same function as `iapl`. Removed in 2.0. */
export const ipalKit = iapl