Files
ipal-kit/src/plugin.ts
T
Radosław SmolińskiandClaude Opus 5.5 e1431a7c49 Stable admin import map without R2 env, read-only media, Cookie Settings save-button migration
buildR2Storage registered nothing without R2_* env, so `pnpm dev` / generate:importmap in dev
wrote an importMap.js without S3ClientUploadHandler — committed, the production admin (R2 on)
rendered a blank page with no console error (hit vanstev.pl). The injected s3Storage is now
always registered (enabled: false without R2 → local disk); storage-s3 still adds its client
handler, so the import map is identical in every environment. ipal-audit flags an import map
without the handler.

R2_PUBLIC_URL alone (absolute, outside production) = read-only media: URLs from the media
domain, upload/delete refused with 403 — local dev against a production database without
bucket keys. ipalEnvRules allows it in development.

Cookie Settings (MongoDB): the 1.11.1 rename buttons.save → savePreferences lost the texts on
the first save; onInit copies the old value (all locales) when the new field is missing.
getConsentTexts read the old field as a string, Mongo returns the raw { pl, en } map.

Also: context.ipalSkipAutoFill (SKIP_AUTO_FILL) — save without meta / aiSummary auto-fill;
createPageRoute redirects the homepage under its own slug (homeAlias, default 'redirect');
ipal-audit: multi-line tsconfig exclude, numeronyms (a11y) not "numbered fields",
`${prefix}/${slug}` links and slugs typed into links detected, clearer panel-language message.
Docs: fallback-on-save in i18n.md, `pnpm up --latest` and the stale-token 401 in PROGRAMISTA §1.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 16:45:03 +02:00

314 lines
13 KiB
TypeScript

import type { Config, Plugin } from 'payload'
import type { IpalOptions, 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 { buildSiteIntegrations } from './globals/SiteIntegrations/index.js'
import { buildSiteSettings } from './globals/SiteSettings/index.js'
import { injectRoles } from './modules/access/index.js'
import { buildConsentLogCollection, buildConsentLogEndpoint } from './modules/consent/consentLog.js'
import { buildConstructionFields } from './modules/construction/fields.js'
import { buildArchiveFields } from './modules/content/index.js'
import { testEmailEndpoint } from './modules/email/test/testEmailEndpoint.js'
import { emailSettingsFields } from './modules/forms/emailLayout.js'
import { buildFormsPlugin } from './modules/forms/formsPluginConfig.js'
import { buildLocalizationConfig, validateI18nConfig } from './modules/i18n/index.js'
import { buildSystemPagesFields } from './modules/pages/index.js'
import { buildSeoPlugin, injectAutoFillMeta, injectSeoTabs } from './modules/seo/index.js'
import { buildIndexNowHook } from './modules/seo/indexNow.js'
import { buildStatsCollection, buildStatsEndpoint } from './modules/stats/index.js'
/**
* IPAL (Intecion Payload Advanced Library) plugin for Payload CMS 3.
*
* @example
* ```ts
* import { ipalKit } from 'ipal-kit'
*
* export default buildConfig({
* plugins: [
* ipalKit({
* i18n: {
* locales: [
* { code: 'pl', label: 'Polski' },
* { code: 'en', label: 'English' },
* ],
* defaultLocale: 'pl',
* },
* access: { authCollection: 'users' },
* }),
* ],
* })
* ```
*/
export const ipalKit = (options: IpalOptions): Plugin => {
// Validate eagerly — fail fast before Payload boots
validateI18nConfig(options.i18n)
return async (incomingConfig: Config): Promise<Config> => {
// Early return when disabled — schema stays, behavior off
if (options.enabled === false) {
return incomingConfig
}
let config = { ...incomingConfig }
// --- 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'
if (!(config.collections ?? []).some((c) => c.slug === authSlug)) {
config.collections = [
...(config.collections ?? []),
{ slug: authSlug, admin: { useAsTitle: 'email' }, auth: true, 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 — ipal-kit 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.
if (options.twoFactor !== false) {
const tf = options.twoFactor
if (!tf?.issuer) {
throw new Error(
'[ipal] 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(
'[ipal] 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).',
)
}
config = await totp({
collection: tf.collectionSlug ?? 'users',
forceSetup: true, // ENFORCED — every user must set up TOTP; no opt-out
totp: { issuer: tf.issuer },
})(config)
}
// --- 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}
const logoProps = { ...serverProps, ...(wl.logoField ? { imageField: wl.logoField } : {}) }
const iconProps = { ...serverProps, ...(wl.iconField ? { imageField: wl.iconField } : {}) }
// Vendor credit ("Technology by Intecion.com") under the nav — on by
// default, hidden with credit:false, text/url overridable.
const creditOn = wl.credit !== false
const creditProps =
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 } }
: {}),
}
}
// --- i18n ---
config.localization = buildLocalizationConfig(options.i18n)
// --- access: inject roles into the client's auth collection ---
if (options.access) {
config = injectRoles(config, options.access)
}
// --- 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 IPAL 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)
}
// --- forms: apply @payloadcms/plugin-form-builder directly ---
if (options.forms) {
config = await buildFormsPlugin(options.forms)(config)
}
// --- 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)
: []),
]
config.globals = [
...(config.globals ?? []),
buildSiteSettings({
additionalFields: options.siteSettingsFields,
...(options.pages ? { constructionFields: buildConstructionFields(options.pages.slug) } : {}),
...(options.forms?.emailLayout ? { emailFields: emailSettingsFields } : {}),
systemPageFields,
}),
buildSiteIntegrations({ additionalFields: options.integrationsFields }),
buildCookieSettings(),
buildNotifications(),
]
config.endpoints = [...(config.endpoints ?? []), testEmailEndpoint]
// --- consent log: proof of consent (opt-in) ---
if (options.consentLog) {
const logOptions = options.consentLog === true ? {} : options.consentLog
config.collections = [...(config.collections ?? []), buildConsentLogCollection()]
config.endpoints = [...(config.endpoints ?? []), buildConsentLogEndpoint(logOptions)]
}
// --- 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 ?? []), buildStatsCollection()]
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 },
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' },
},
],
},
}
// --- hooks: onInit ---
const incomingOnInit = config.onInit
config.onInit = async (payload) => {
if (incomingOnInit) {await incomingOnInit(payload)}
await migrateCookieSettingsSaveButton(payload)
payload.logger.info('[ipal] Plugin initialized.')
}
return config
}
}