Files
ipal-kit/src/types.ts
T
Radosław SmolińskiandClaude Fable 5.2 0a4f001797 IAPL rename, scripted: preferred names in src, bin, scripts, services, tests; bin files and skill folders moved
Replaced by an explicit list of forms only (ten exported names, runtime env names, project file
names and marks, commands, skill names, the log prefix, the brand in prose). Package name, import
paths, routes, CSS tokens, data attributes, custom keys, context flags, the cookie and kv keys are
not touched. package.json keeps the five old bin names beside the five new ones.
The old names stop working in this commit and come back as aliases in the next; docs follow.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-25 17:24:21 +01:00

422 lines
20 KiB
TypeScript

import type { CollectionSlug, Field, PayloadComponent, PayloadRequest, Plugin } from 'payload'
/**
* Factory shape of @clocklimited/payload-2fa's `payloadTotp` export — injected
* so the plugin never imports the optional peer itself. `collection` is
* `CollectionSlug` (not `string`): payloadTotp requires it, and in a project
* with generated payload-types it's a narrowed union — `string` would make
* `plugin: payloadTotp` fail to type-check.
*/
export type TotpPluginFactory = (options: {
collection: CollectionSlug
forceSetup: boolean
totp: { issuer: string }
}) => Plugin
import type { GlobalOverrides } from './globals/overrides.js'
import type { AccessOption, AccountsOptions } from './modules/access/types.js'
import type { AdminMetaOptions, AgencyOption } from './modules/branding/adminMeta.js'
import type { ConsentLogOptions } from './modules/consent/consentLog.js'
import type { CookieScannerOptions } from './modules/consent/scanner/types.js'
import type { ContentOption } from './modules/content/types.js'
import type { DoctorEndpointOptions } from './modules/doctor/status.js'
import type { FormsOption } from './modules/forms/types.js'
import type { RevalidatePathFn } from './modules/hooks/buildRevalidateHook.js'
import type { I18nConfig } from './modules/i18n/types.js'
import type { PagesOption } from './modules/pages/types.js'
import type { SafeBackRule } from './modules/security/totp/safeBack.js'
import type { RequireSetupOptions } from './modules/security/totp/setupRequired.js'
import type { VerifyLimitOptions } from './modules/security/totp/verifyLimit.js'
import type { SeoOption } from './modules/seo/types.js'
import type { StatsOptions } from './modules/stats/collection.js'
/**
* Configuration options for the IAPL plugin.
* Passed by the client project in payload.config.ts.
*/
export type IaplOptions = {
/**
* Role-based access control. Injects a fixed `roles` field
* (admin > editor > user) into the client's auth collection.
*/
access?: AccessOption
/**
* Rules for the accounts of the staff collection: who may open the panel
* (`panelRole`). `false` = none of them. docs/access.md "Account rules".
*/
accounts?: AccountsOptions | false
/**
* Admin panel <head> for link previews and search engines (default on):
* noindex/nofollow, title suffix "— <site> | Panel", siteName and a short
* description from Site settings, a preview image drawn from the site's logo
* (GET /api/ipal/admin-og) and the site's favicon (GET /api/ipal/admin-icon).
* Keys the project sets in its own `admin.meta` always win. `false` = Payload's defaults.
*/
adminMeta?: AdminMetaOptions | false
/**
* Custom admin panel route, e.g. '/its' instead of the default '/admin'.
* The plugin sets config.routes.admin. IMPORTANT: this alone isn't enough —
* the project must ALSO move its panel folder to match:
* app/(payload)/its/[[...segments]]/page.tsx (and the not-found). The plugin
* can't create files in the project's app/. See docs/security.md.
*
* This is obscurity, not security: it hides the panel from dumb bots scanning
* /admin, but real protection is strong auth + 2FA + rate limiting.
*/
adminRoute?: string
/**
* Who supports the technology, named in the admin credit, the panel's link
* description and its preview image. Default `{ name: 'Intecion.com', url: 'https://intecion.com' }`.
* `false` = no agency anywhere.
*/
agency?: AgencyOption | false
/** Internationalization — locales, default locale, fallback behavior */
/**
* Consent log (proof of consent, GDPR Art. 7(1)): adds the `consent-records`
* collection and POST /api/ipal/consent. Pass `<ConsentProvider logEndpoint="/api/ipal/consent">`.
* Stores a random id, choices, policy version and time — no personal data.
* `true` or `{ retentionDays, collectionOverrides }` (default 1095 days). Default off.
*/
consentLog?: boolean | ConsentLogOptions
/**
* Collections whose entries live under an archive page — blog posts, case
* studies, anything with a listing. Adds an "archive page" assignment per
* collection in SiteSettings; the assigned page's localized slug becomes the
* URL segment (/pl/artykuly/moj-post, /en/articles/my-post). Requires `pages`.
*/
content?: ContentOption
/**
* Cookie scanner (docs/cookie-scanner.md): the `cookie-review` collection, a
* "Scan cookies" action above its list and GET/POST /api/ipal/cookie-scan. A
* scan lists the cookies of the integrations this project switches on, plus
* names looked up in the bundled Open Cookie Database, as drafts an editor
* accepts (→ Cookie Settings → Cookies), edits or rejects. Never deletes,
* never overwrites edited text, never publishes by itself.
* `true` or CookieScannerOptions. Default off.
*/
cookieScanner?: boolean | CookieScannerOptions
/**
* Forms — form-builder collections (forms, form-submissions) plus the
* callable submitForm (Turnstile + persistence + SMTP-from-panel email).
*/
/**
* Who sees the plugin's dashboard alerts. They read data that only some
* roles may read, so each decides for itself:
* `integrations` — who gets WHAT is failing in Site integrations (error text
* and link): `'admin'` (default), `'editor'`, `'all'`; an editor below that
* sees a neutral "an integration needs attention — ask an administrator",
* anyone else nothing. `cookies` — who sees the cookie crawl / approval
* alert: `'editor'` (default) or `'all'`. With a role (`'admin'`,
* `'editor'`) a session that still owes its second factor sees nothing.
* `'all'` = as before, and it checks NOTHING — no role and no second
* factor: whoever the dashboard is drawn for sees the full text.
*/
dashboardAlerts?: { cookies?: 'all' | 'editor'; integrations?: 'admin' | 'all' | 'editor' }
/**
* GET /api/ipal/doctor — read-only counts for `iapl-doctor --url` (users without 2FA, cookies
* waiting for approval, versions). Answers 404 until IAPL_DOCTOR_TOKEN (≥ 32 characters) is set;
* then a `Bearer` token is required. `false` = no endpoint; `{ tokenVar, access }` to adapt it.
* docs/doctor.md.
*/
doctor?: DoctorEndpointOptions | false
/**
* `false` = plugin off without uninstalling: its collections, globals and
* fields stay (DB schema and migrations unchanged), but it adds no endpoints,
* onInit work or admin components.
*/
enabled?: boolean
/**
* Text written in one language fills the same field in every language that is
* still empty; a language with its own text is never overwritten. Default on
* for the cookie list (`cookie-settings`: `cookies.purpose`, `cookies.duration`)
* and the cookie review (`cookie-review`: `purpose`, `retention`). `false` turns
* it off; an object sets the fields per slug (`[]` = off for that slug).
* Building blocks: buildFillEmptyLocalesGlobalHook / …CollectionHook.
*/
fillEmptyLocales?: { 'cookie-review'?: string[]; 'cookie-settings'?: string[] } | boolean
forms?: FormsOption
/**
* Change any of the plugin's globals (site-settings, site-integrations,
* cookie-settings, notifications): an object merges over the plugin's
* (`access` / `admin` / `hooks` key by key, your keys win), a function gets
* the global and returns the one to use. E.g. let any logged-in user edit
* Notifications: `{ notifications: { access: { update: authenticated } } }`.
*/
globalOverrides?: GlobalOverrides
i18n: I18nConfig
/**
* IndexNow (seo/indexNow.ts): on publish, submit the page's URLs in every
* language to Bing & co. (feeds ChatGPT Search / Copilot). Adds the hook to the
* pages collection and every `content` collection. Production only. Needs the
* key file route createIndexNowKeyRoute. Default false.
*/
indexNow?: boolean
/** Additional fields injected into SiteIntegrations global */
integrationsFields?: Field[]
/**
* Image lightbox labels in the Notifications global (a "Lightbox" group:
* close, previous, next, counter, dialog name, trigger name), localized per
* language and read with getNotificationTexts(...).lightbox. Off by default —
* the components work without it on English fallbacks and the `texts` prop;
* turn it on so editors translate the labels. Adds columns: run a migration
* on Postgres. See docs/lightbox.md.
*/
lightbox?: boolean
/**
* System-page assignments (homepage, privacy, cookies) in SiteSettings.
* Provide the slug of the client's Pages collection to enable.
*/
pages?: PagesOption
/**
* next/cache `revalidatePath`, INJECTED (the plugin never imports next/cache).
* When given, saving any of the plugin's globals (Site Settings, Site
* Integrations, Cookie Settings, Notifications) revalidates the whole site
* layout, so logo, menu, consent texts and analytics IDs change at once
* instead of after the ISR window. See buildGlobalRevalidateHook.
*/
revalidatePath?: RevalidatePathFn
/**
* Site Settings → "Search engines" tab (verification codes, AI crawler policy,
* llms.txt intro). On by default; `false` removes it; a function gets the
* plugin's fields and returns the tab's fields. Works without `seo`; wins
* over `seo.searchSettings`.
*/
searchSettings?: ((defaults: Field[]) => Field[]) | false
/**
* SEO — adds meta fields to chosen collections (via @payloadcms/plugin-seo)
* and enables locale-aware metadata helpers.
*/
/**
* Stored secrets. `smtpPassword` and `turnstileSecretKey` (Site integrations)
* are **write-only** by default: REST, GraphQL and the panel get `'********'`
* ("a value is set"), never the value; a save that sends nothing, an empty
* value or the mask keeps what is stored, `'[[clear]]'` removes it. Server
* code reads the real value through the Local API (access control off, the
* default). `{ writeOnly: false }` = the value is returned to whoever may
* read the global, as before 1.16.7.
*
* The SMTP password is bound to its server: a save in the panel that changes
* the server, the port or the user name must send the password again, or
* remove it (whatever the transport says) — otherwise a stolen
* admin session points the server at its own machine and a test e-mail hands
* the password over. `{ reenterOnChange: false }` = the stored password
* follows the new server. docs/security.md "Stored secrets".
*/
secrets?: { reenterOnChange?: false; writeOnly?: false }
seo?: SeoOption
/** Additional fields injected into SiteSettings global */
siteSettingsFields?: Field[]
/**
* Built-in statistics (docs/stats.md): the `stats-visits` collection,
* POST /api/ipal/hit, the /admin/stats view and a 30-day chart on the
* dashboard. The site mounts <PageStats> inside <ConsentProvider>.
* Cookieless and IP-free for everyone; visitors who accept analytics cookies
* also get a history across days. `true` or `{ retentionDays, timeZone,
* dashboard }`. Default off.
*/
stats?: boolean | StatsOptions
/**
* Light / dark theme. `storageKey`: the localStorage key of the visitor's
* choice — default `theme` (the next-themes key and values, so a project using
* next-themes too shares one choice). getSiteShell().theme passes it to
* <ThemeScript>, which puts it on <html> for useTheme / ThemeSwitcher.
*/
theme?: ThemeOptions
/**
* Two-factor authentication (TOTP), ENFORCED for every user. Wires
* @clocklimited/payload-2fa with forceSetup — no per-project opt-out. Every
* user must configure an authenticator app after login; TOTP is checked before
* data access (not just the admin UI). Requires the peer dep installed and an
* issuer name (shown in the authenticator app).
*
* Pass `false` ONLY for a project that genuinely can't use 2FA (rare, discouraged)
* — default is enforced. See docs/security.md.
*/
twoFactor?:
| {
/**
* Let `collectionSlug` differ from the panel's login collection
* (admin.user). Off by default: a mismatch means panel users skip 2FA,
* so the plugin refuses to start. Set true only when you protect a
* second auth collection on purpose.
*/
allowCollectionMismatch?: boolean
/**
* Auth collection TOTP wraps. Default: the panel's login collection —
* admin.user, else the first auth collection (with the one the plugin
* injects). Must be an auth collection.
*/
collectionSlug?: CollectionSlug
/**
* IAPL's own second-factor check on every collection and global —
* also the ones added after the 2FA package ran (IAPL's own, other
* plugins') — and in `userMeetsRole`. On by default. `false` leaves only
* the package's wrapper, which does not cover those: a staff password
* without the TOTP code then reads them over the API. Only for a 2FA
* package version the check does not recognise; docs/security.md.
*/
guard?: false
/**
* Check, at start in production, that the committed admin import map has
* the entry `safeBack` needs (`@intecion/ipal-kit/admin#SafeTotpView`).
* Without it Payload renders the 2FA screens empty and nobody can sign in;
* with the check the server log says so at every start and the 2FA screens
* show a message instead of nothing. On by default; `false` skips the file
* read, the log line and the message.
*/
importMapCheck?: false
/** Name shown in the authenticator app (e.g. company/site name). */
issuer: string
/**
* The 2FA plugin factory, INJECTED from the project:
* `import { payloadTotp } from '@clocklimited/payload-2fa'`. Injecting it
* (the same pattern as NextResponse / revalidatePath) means IAPL never
* imports the optional peer itself — Next can't bundle such an import
* ("Cannot find module '@clocklimited/payload-2fa'", even on public
* pages), and serverExternalPackages is no fix (the package imports its
* own .css). The payload CLI loads the same config, so it gets the
* injected factory too. See docs/security.md.
*/
plugin: TotpPluginFactory
/**
* Admin provider that sends users to the TOTP setup / verify screens.
* Default: IAPL's `@intecion/ipal-kit/admin#TotpRedirectProvider`
* (reads the path in the browser). The package's own provider needs an
* `x-pathname` request header on every /admin request; without it the
* setup screen redirects to itself (`setup-totp?back=null`). Pass your
* own component path (it gets clientProps `forceSetup` and the package's
* serverProps `pluginOptions`), or `false` to keep the package's provider
* (then set `x-pathname` on /admin yourself). Run generate:importmap.
*/
provider?: false | PayloadComponent
/**
* "Setup required", on by default: an account that has not set TOTP up
* reaches nothing at the access level (REST, GraphQL, the panel's data) —
* only the setup screen and its endpoint. It has `windowHours` (default 72)
* from its creation, or from a reset by an admin, to set TOTP up; after that
* it is blocked until an admin reopens setup (the account's page in the
* panel, or POST /api/ipal/two-factor/reset). Accounts that existed before
* the mode get the full window from the first start after the upgrade.
* `{ windowHours: false }` = no time limit; `{ exempt: ({ user }) => … }` =
* accounts that may work without TOTP on purpose (a service account);
* `false` = the 2FA package's rule (the panel redirects, the API is open
* until setup). Needs `guard` on. docs/security.md.
*/
requireSetup?: false | RequireSetupOptions
/** Who may reset another account's TOTP / reopen its setup. Default: a staff admin. The second factor is always required. */
resetAccess?: (args: { req: PayloadRequest }) => boolean | Promise<boolean>
/**
* Check on the `back` query value of the 2FA setup and verify screens. The
* 2FA package sends the browser there after a valid code without looking at
* it, so a crafted link could run script in the panel (`javascript:`) or
* leave the site. On by default: IAPL's `SafeTotpView` goes in front of
* the package's views and passes on a value that stays on the site's origin,
* inside the admin route — anything else becomes the admin root
* (`safeAdminBack`). A function replaces the rule; `false` leaves the
* package's views as they are. Run generate:importmap. docs/security.md.
*/
safeBack?: false | SafeBackRule
/**
* 2FA verify and setup attempts (`POST /api/verify-totp`, `/api/setup-totp`)
* are accepted only from the site's own origin: a request that a browser
* marks as coming from elsewhere (`Origin`, `Sec-Fetch-Site`) is refused
* with 403 and not counted — so another page, a sibling subdomain included,
* cannot burn an account's verify attempts and lock its owner out. Own
* origins: the request's host, `serverURL`, Payload's `csrf` / `cors`
* lists, and `{ origins: ['https://app.example.com'] }` here. Requests
* without those headers (scripts, servers) pass. `false` = off.
*/
sameOrigin?: { origins?: string[] } | false
/**
* Texts of the 2FA screens and user field. Default: IAPL's English and
* Polish (`TOTP_TEXTS`), merged over the package's; your own
* `i18n.translations.<lang>.totpPlugin` still wins. `false` keeps the package's.
*/
texts?: false
/**
* Limit on TOTP verify attempts (`POST /api/verify-totp`), per account: the
* 2FA package never counts tries, and a six-digit code can be guessed by
* whoever holds the password. Default `{ max: 5, windowMinutes: 10 }`: the
* sixth attempt in ten minutes, right or wrong, is refused (429) until the
* window ends. The count is kept in memory and in the database (Payload's
* `payload.kv`), so a restart or a second instance does not reset it;
* `{ store: 'memory' }` = this instance only. `false` = no limit (a limiter
* in front of the site).
*/
verifyLimit?: false | VerifyLimitOptions
}
| false
/**
* White-label the admin panel: show the CLIENT's brand (logo + name) in the
* admin — login screen and nav — pulled from SiteSettings, set by the editor
* in the panel (no brand hardcoded in code). `true` wires it with defaults
* (SiteSettings `logo`/`favicon`/`siteName`); the object form overrides the
* global slug, field names, or the browser-tab title suffix.
*
* Injects admin.components.graphics.Logo/Icon pointing at
* `@intecion/ipal-kit/admin`. After enabling, run `pnpm generate:importmap`
* so Payload can resolve the components. See docs/white-label.md.
*/
whiteLabel?:
| {
/**
* Vendor credit ("Technology support: Intecion.com") at the bottom of the
* admin nav. Default on; `false` hides it, or override text/url.
*/
credit?:
| {
text?: string
url?: string
}
| boolean
/** Upload field for the small nav icon. Default 'favicon'. */
iconField?: string
/**
* On the 2FA screens the panel's logo and icon are fetched by the server
* the way an anonymous visitor gets them and put into the page as a
* `data:` image: the session there is refused every collection, `media`
* included, so the browser could not load them. `false` = never fetch;
* the browser tries the media URL and shows the site name when refused.
*/
inlineImages?: false
/** Upload field for the login/nav logo. Default 'logo'. */
logoField?: string
/** Field with the site name. Default 'siteName'. */
nameField?: string
/** SiteSettings global slug. Default 'site-settings'. */
settingsSlug?: string
/** Static browser-tab title suffix (e.g. ' · Acme Admin'). */
titleSuffix?: string
}
| boolean
}
/** `iapl({ theme })` — every key optional. */
export type ThemeOptions = {
/** localStorage key of the visitor's light / dark choice. Default `'theme'`. */
storageKey?: string
}