diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index 22450ce..94f4466 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -1171,6 +1171,7 @@ project → **plugin gap**, not a copy. | Mail | `email: mailAdapter()` + `serverURL` — mail works with no other setup, through the Intecion mail service; SMTP in the panel only when the client asks; your own mail: `payload.sendEmail` (`withMailKind` when it is account mail); never a second transport in the project. §7.2 | email.md | | Env validation, health | `assertEnv(iaplEnvRules({…}))` (`/env`), `healthRoute` | env.md | | 2FA, white-label, headers | `twoFactor: { issuer, plugin: payloadTotp }`, `whiteLabel`, `buildSecurityHeaders` | security.md, white-label.md | +| Sign-in screens (login, forgot / reset password, first user, logout, the 2FA screens): a dark panel with the client's logo or the site's name beside the form, language links, both themes, phone | on with `whiteLabel` (`signIn`); a NEW site: `whiteLabel: { signIn: { allScreens: true } }` + `pnpm payload generate:importmap` (adds the provider `SignInLook`; without it only login and the 2FA screens get the look, through `AdminLogo` / `SafeTotpView`). Logo and name come from Site settings (no env var, no new field, no migration). Options: `accent` (hex), `logoMadeFor: 'dark'`, `languages: false`, `svgLogo: false`; `signIn: false` = Payload's screens; `brandAccess: 'admin'` = only admins change name / logo / icon. Never build a login page, a custom `graphics.Logo` or login CSS by hand. Check: `curl -s $URL/admin/login \| grep -c iapl-signin__label` ≥ 1; `curl -si "$URL/api/ipal/admin-language?lng=xx"` → 400 | white-label.md → "The sign-in screens" | | Panel link preview + noindex (site name, description, preview image, technology support credit) | on by default (`adminMeta`, `agency`) — do not hand-write `admin.meta` for it; override single keys in `admin.meta` or `adminMeta: { … }` | white-label.md | | Rate limit (forms, MCP, search) | built in; IP from `IAPL_IP_HEADER`; several instances → `setRateLimitStore` | forms.md | diff --git a/docs/agent/reference-site/INDEX.md b/docs/agent/reference-site/INDEX.md index b2e4881..7d957ae 100644 --- a/docs/agent/reference-site/INDEX.md +++ b/docs/agent/reference-site/INDEX.md @@ -1171,6 +1171,7 @@ Rules: AGENT.md §8a. | `e2e/mail-relay-fixture.ts` | test fixture, on only with E2E_MAIL_RELAY_URL: points the mail service's client at the stand-in the spec starts; never in a real site (a real site names no address) (below) | | `e2e/mail-relay-setup.ts` | for the mail-service spec: empties the SMTP fields and the stored token, so the next e-mail enrols and goes through the mail service (local database only) (below) | | `e2e/mail-relay.spec.ts` | the mail service on a built site: the state block in the panel, the first e-mail through the public confirm route, no token in anything the browser receives | +| `e2e/sign-in-look.spec.ts` | browser test of the sign-in look (whiteLabel.signIn): the panel comes with the form, sits above it on a phone in both themes, is on forgot / reset / logout too, the language links work, the 2FA code screen keeps its boxes (now named) | | `e2e/smoke.spec.ts` | the smoke tests every release must pass: pages, showcase, forms (also a file sent by e-mail), sitemap, SEO/GEO, headers, consent, 2FA | | `e2e/smtp-sink.ts` | a local mail sink for the smoke tests: reads what the site really sent (recipients, attachments) | | `e2e/totp.ts` | RFC 6238 code generator for the 2FA sign-in in the smoke test, and the address of the second test admin (below) | diff --git a/docs/agent/skills/iapl-reference/SKILL.md b/docs/agent/skills/iapl-reference/SKILL.md index 6351c4b..360f9b8 100644 --- a/docs/agent/skills/iapl-reference/SKILL.md +++ b/docs/agent/skills/iapl-reference/SKILL.md @@ -64,6 +64,13 @@ description: Complete map of everything @intecion/ipal-kit provides — every ia | `whiteLabel.logoField` / `iconField` / `nameField` | `'logo'` / `'favicon'` / `'siteName'` | fields in Site settings | any upload/text field | | `whiteLabel.titleSuffix` | none | `admin.meta.titleSuffix` (tab title) | — | | `whiteLabel.credit` | on | `IntecionCredit` in `afterLogin` and `afterNavLinks`: "Technology support: Intecion.com" (en/pl, from `agency`) | `false`; `{ text, url }` overrides | +| `whiteLabel.signIn` | on (with `whiteLabel`) | the sign-in look: a dark panel with the client's logo (Site settings → Logo, on a white plate) or the site's name beside the form, "Administration panel", language links; both themes, a band above the form on a phone. Login, the 2FA screens and e-mail verification get it through `AdminLogo` / `SafeTotpView` (already in the import map: an upgrade needs no edit). No env var, no new field, no migration | `false` = Payload's own screens | +| `whiteLabel.signIn.allScreens` | `false` (the starter writes `true`) | the look on forgot / reset password, create first user, logout and "unauthorized" too: adds the provider `SignInLook` — ONE new import-map entry, run `pnpm payload generate:importmap`. Production start: when `importMap.js` on disk lacks it, the provider is left out and the log says `[iapl] The sign-in look covers only the login and 2FA screens …` | `true` | +| `whiteLabel.signIn.accent` | `#0070c0` | hex colour of the button, links and focus ring (anything that is not a hex colour is ignored); or CSS variables `--iapl-signin-*` on `:root` in the admin's `custom.scss` | `'#0b6e4f'` | +| `whiteLabel.signIn.logoMadeFor` | `'light'` | `'dark'` = a logo drawn for dark grounds: no white plate | — | +| `whiteLabel.signIn.languages` | shown with 2+ admin languages | links on the panel; `GET /api/ipal/admin-language?lng=` writes Payload's `payload-lng` cookie and redirects (303) back to the admin path of the `Referer`; unknown language → 400 | `false` = no links, no endpoint | +| `whiteLabel.signIn.svgLogo` | shown as a picture (`` runs no script) | `false` = an SVG logo is not shown on the sign-in screens; the site's name is | — | +| `whiteLabel.brandAccess` | `'editor'` (whoever edits Site settings) | `'admin'` = field-level `access.update` on the name, logo and icon fields: only admins change what the sign-in screens show. No schema change | — | | `agency` | `{ name: 'Intecion.com', url: 'https://intecion.com' }` | the credit line, the panel's link description and preview image | `{ name, url }` = another agency; `false` = none anywhere | | `adminMeta` | on (with or without `whiteLabel`) | panel ``: `robots` noindex/nofollow, `titleSuffix` "— \| Panel", `og:site_name` + description from Site settings (refreshed on save), `og:image` `GET /api/ipal/admin-og` (1200×630 from the logo or name), icon `GET /api/ipal/admin-icon` (favicon or initials); no import map step | `false` = Payload defaults; `{ robots, titleSuffix, description, image, icons, language }` (each `false` or your value; `{site}`, `{agency}` placeholders); your own `admin.meta` keys always win. Check: `curl -s $URL/admin/login \| grep -E 'og:\|robots'` (white-label.md) | | `pages` | none | Site settings → **System pages** (page roles) and **Maintenance** tabs | omit → neither tab | @@ -153,6 +160,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ia |---|---|---| | `AdminLogo`, `AdminIcon` | `graphics.Logo/Icon` | `whiteLabel` | | `IntecionCredit` | `afterLogin`, `afterNavLinks` | `whiteLabel` and `credit !== false` | +| `SignInLook` | `providers` (last) | `whiteLabel.signIn.allScreens` — the only entry the sign-in look adds; without it nothing new is needed | | `StatsNavLink`, `StatsView` (`views.ipalStats`, `/stats`), `StatsWidget` (`beforeDashboard`) | nav, view, dashboard | `stats` (`dashboard: false` without the widget) | | `CookieScanButton` | `beforeListTable` of `cookie-review` (with **Check site** when `crawl` is on) | `cookieScanner` | | `CookieReviewTab`, `CookieSiteCheckTab` | `ui` fields in the `cookie-settings` tabs | `cookieScanner` with `adminLayout !== 'separate'` (Site check: `crawl`) | diff --git a/docs/agent/skills/iapl-reference/resources/api.md b/docs/agent/skills/iapl-reference/resources/api.md index 1791160..36bcd47 100644 --- a/docs/agent/skills/iapl-reference/resources/api.md +++ b/docs/agent/skills/iapl-reference/resources/api.md @@ -38,6 +38,8 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT | `TwoFactorResetButton` | `@intecion/ipal-kit/admin` | Client button inside `TwoFactorStatusField`: `POST /api/ipal/two-factor/reset` `{ userId }`, then reloads the view. Props `{ kind: 'reset' \| 'reopen', userId }`. | | `TwoFactorAlert` | `@intecion/ipal-kit/admin` | Server component on the dashboard (`beforeDashboard`), administrators only: accounts without two-step verification and how many are blocked. Wired by the plugin with `twoFactor.requireSetup`; renders nothing when every account has it. | | `IntecionCredit` | `@intecion/ipal-kit/admin` | The line "Technology support: Intecion.com" (admin language; `agency` prop = the name) below the nav and below the login form (`variant: 'nav' \| 'login'`). Injected by the plugin with `whiteLabel`; turn off: `whiteLabel: { credit: false }` or `agency: false`. | +| `SignInPanel` | `@intecion/ipal-kit/admin` | Server component: the dark sign-in panel with its stylesheet (` +
+

{text('signInPanelLabel')}

+ {brand.logo ? ( + + {brand.name} + + ) : brand.name ? ( + + {brand.name} + + ) : null} + {languages.length ? ( + + ) : null} +
+ + ) +} diff --git a/src/modules/branding/signIn/brand.ts b/src/modules/branding/signIn/brand.ts new file mode 100644 index 0000000..0b82021 --- /dev/null +++ b/src/modules/branding/signIn/brand.ts @@ -0,0 +1,177 @@ +import type { Payload } from 'payload' + +import { getFromImportMap } from 'payload/shared' + +import { secondFactorPassed } from '../../security/totp/secondFactor.js' +import { publicImageDataUri, siteOrigin } from '../publicImage.js' + +/** + * What the sign-in panel shows, read from Site settings: the client's logo or, without one, the site's name. + * Nothing here is new data: the same two fields already drive the panel's logo and the public site. + * + * What may reach a page that anyone can open, before signing in: + * - the name as plain text (React escapes it), one line of at most `SIGN_IN_NAME_MAX` characters: no markup, + * no link, nothing an address inside it could turn into; + * - the logo as an ``: a picture never runs script there, an SVG included. `svgLogo: false` leaves SVG + * out all the same (the name is shown); + * - no account, no e-mail address, no hint whether an account exists: the forms are Payload's own. + */ + +/** Import-map path of the provider that carries the look to every sign-in screen. */ +export const SIGN_IN_LOOK = '@intecion/ipal-kit/admin#SignInLook' + +/** The box the logo fits in on the panel, in CSS pixels (a phone: 192 × 56, in the stylesheet). */ +export const SIGN_IN_LOGO_BOX = { height: 72, width: 240 } as const + +/** The site's name on the panel is cut at this many characters. */ +export const SIGN_IN_NAME_MAX = 80 + +/** `whiteLabel.signIn` as the components receive it (`serverProps`): plain values only. */ +export type SignInLookProps = { + /** Hex colour of the button, the links and the focus ring. */ + accent?: string + /** Upload field of the logo. Default `'logo'`. */ + imageField?: string + /** `whiteLabel.inlineImages: false`: never fetch the logo on the server for the 2FA screens. */ + inlineImages?: false + /** `false`: no language links on the panel. */ + languages?: false + /** `'dark'`: the logo was drawn for dark grounds, so it gets no white plate. */ + logoMadeFor?: 'dark' | 'light' + /** Field of the site's name. Default `'siteName'`. */ + nameField?: string + /** Slug of the settings global. Default `'site-settings'`. */ + settingsSlug?: string + /** `false`: an SVG logo is not shown on the sign-in screens (the name is). */ + svgLogo?: false +} + +export type SignInLogo = { height?: number; src: string; width?: number } +export type SignInBrand = { logo: null | SignInLogo; name: string } + +type MediaLike = { filename?: unknown; height?: unknown; mimeType?: unknown; url?: unknown; width?: unknown } + +/** A localized text field may arrive as a string or a { locale: value } map. */ +function pickText(value: unknown, locale: string | undefined): string { + if (typeof value === 'string') {return value} + if (value && typeof value === 'object') { + const map = value as Record + const preferred = locale ? map[locale] : undefined + if (typeof preferred === 'string') {return preferred} + return Object.values(map).find((v): v is string => typeof v === 'string') ?? '' + } + return '' +} + +/** The name as one line of plain text: control characters and line breaks out, cut at the limit. */ +export function signInName(value: unknown, locale?: string): string { + // eslint-disable-next-line no-control-regex + const text = pickText(value, locale).replace(/[\u0000-\u001f\u007f\u2028\u2029]+/g, ' ').replace(/\s+/g, ' ').trim() + return text.length > SIGN_IN_NAME_MAX ? `${text.slice(0, SIGN_IN_NAME_MAX - 1).trimEnd()}…` : text +} + +/** Whether an upload is an SVG, by what the upload says and by its address. */ +export const isSvgUpload = (media: MediaLike): boolean => + (typeof media.mimeType === 'string' && media.mimeType.toLowerCase().includes('svg')) || + [media.filename, media.url].some((v) => typeof v === 'string' && /\.svgz?(?:[?#]|$)/i.test(v)) + +/** The size a picture is shown at inside `box`: never enlarged, never cropped. */ +export function fitLogo(width: unknown, height: unknown, box: { height: number; width: number } = SIGN_IN_LOGO_BOX): { height: number; width: number } | null { + if (typeof width !== 'number' || typeof height !== 'number' || !(width > 0) || !(height > 0)) {return null} + const scale = Math.min(1, box.width / width, box.height / height) + return { height: Math.max(1, Math.round(height * scale)), width: Math.max(1, Math.round(width * scale)) } +} + +/** The logo of an upload document, or null when there is nothing to show. */ +export function signInLogo(media: unknown, look: Pick = {}): null | SignInLogo { + if (!media || typeof media !== 'object') {return null} + const m = media as MediaLike + if (typeof m.url !== 'string' || !m.url.trim()) {return null} + // An address a browser would not load as a picture of the site: only http(s) and site-relative ones. + if (!/^(?:https?:\/\/|\/(?!\/))/i.test(m.url.trim())) {return null} + if (look.svgLogo === false && isSvgUpload(m)) {return null} + return { src: m.url.trim(), ...(fitLogo(m.width, m.height) ?? {}) } +} + +/** The host of the site, shown when Site settings has no name. */ +function siteHost(serverURL: null | string | undefined): string { + try { + return serverURL ? new URL(serverURL).host : '' + } catch { + return '' + } +} + +type LoadArgs = { + locale?: { code?: string } | string + look: SignInLookProps + payload?: Payload + /** The account looking at the screen, when one has typed its password. */ + user?: null | Record +} + +/** Reads the brand. Never throws: no database, no global, no field → an empty name and no logo. */ +export async function loadSignInBrand({ locale, look, payload, user }: LoadArgs): Promise { + if (!payload) {return { name: '', logo: null }} + const origin = siteOrigin(payload.config?.serverURL) + try { + const code = typeof locale === 'string' ? locale : locale?.code + const settings = (await payload.findGlobal({ + slug: (look.settingsSlug ?? 'site-settings') as never, + depth: 1, + ...(code ? { locale: code as never } : {}), + })) as Record + const name = signInName(settings[look.nameField ?? 'siteName'], code) || siteHost(origin) + let logo = signInLogo(settings[look.imageField ?? 'logo'], look) + // A session that still owes its 2FA code (or has not set 2FA up) is refused `media` like every other + // collection: give it the picture itself, fetched as an anonymous visitor would get it. When that fails, + // the name is shown instead of a broken picture. + if (logo && user && !secondFactorPassed({ payload, user })) { + const data = look.inlineImages === false ? null : await publicImageDataUri(logo.src, origin) + logo = data ? { ...logo, src: data } : null + } + return { name, logo } + } catch (error) { + console.warn('[iapl] sign-in look: Site settings could not be read, the panel shows no brand:', error) + return { name: siteHost(origin), logo: null } + } +} + +/** Names of the languages in their own language; a code that is not here is shown as it is, in capitals. */ +export const LANGUAGE_NAMES: Record = { + ar: 'العربية', bg: 'Български', cs: 'Čeština', da: 'Dansk', de: 'Deutsch', el: 'Ελληνικά', en: 'English', es: 'Español', + et: 'Eesti', fi: 'Suomi', fr: 'Français', he: 'עברית', hr: 'Hrvatski', hu: 'Magyar', it: 'Italiano', ja: '日本語', + ko: '한국어', lt: 'Lietuvių', lv: 'Latviešu', nb: 'Norsk', nl: 'Nederlands', pl: 'Polski', pt: 'Português', ro: 'Română', + ru: 'Русский', sk: 'Slovenčina', sl: 'Slovenščina', sr: 'Српски', sv: 'Svenska', tr: 'Türkçe', uk: 'Українська', zh: '中文', +} + +/** Path of the endpoint that remembers the panel's language, under the API route. */ +export const ADMIN_LANGUAGE_PATH = '/ipal/admin-language' + +export type LanguageLink = { code: string; current: boolean; href: string; name: string } + +/** The panel's languages as links; an empty list when the panel has one language. */ +export function languageLinks(config: { i18n?: { supportedLanguages?: Record }; routes?: { api?: string } } | undefined, current: string | undefined): LanguageLink[] { + const codes = Object.keys(config?.i18n?.supportedLanguages ?? {}).filter((code) => /^[a-z]{2,3}(?:-[a-z0-9]{2,8})*$/i.test(code)) + if (codes.length < 2) {return []} + const api = config?.routes?.api ?? '/api' + return codes.map((code) => ({ + name: LANGUAGE_NAMES[code.toLowerCase()] ?? LANGUAGE_NAMES[code.toLowerCase().split('-')[0]] ?? code.toUpperCase(), + code, + current: code === current, + href: `${api}${ADMIN_LANGUAGE_PATH}?lng=${encodeURIComponent(code)}`, + })) +} + +type ComponentLike = { path?: unknown } | null | string | undefined + +/** + * Whether the provider (`SignInLook`) prints the panel on this site: it is in the config AND in the import map + * the running build uses. The logo and the 2FA wrapper print the panel themselves only when it does not. + */ +export function signInProviderActive(payload: Payload | undefined): boolean { + const providers = (payload?.config?.admin?.components?.providers ?? []) as ComponentLike[] + const listed = providers.some((p) => (typeof p === 'string' ? p : p?.path) === SIGN_IN_LOOK) + if (!listed || !payload?.importMap) {return false} + return Boolean(getFromImportMap({ importMap: payload.importMap, PayloadComponent: SIGN_IN_LOOK, schemaPath: '', silent: true })) +} diff --git a/src/modules/branding/signIn/brandAccess.ts b/src/modules/branding/signIn/brandAccess.ts new file mode 100644 index 0000000..acdb16c --- /dev/null +++ b/src/modules/branding/signIn/brandAccess.ts @@ -0,0 +1,29 @@ +import type { Field, GlobalConfig } from 'payload' + +import { userMeetsRole } from '../../access/index.js' + +/** + * `whiteLabel.brandAccess: 'admin'` — the fields whose values the sign-in screens show (the site's name, the + * logo, the icon) can be changed by admins only. Field-level access: nothing is stored differently, so no + * database change. An access rule the field already has still counts (both must allow). + */ +export function lockBrandFields(globals: GlobalConfig[] | undefined, settingsSlug: string, fieldNames: string[]): GlobalConfig[] { + const names = new Set(fieldNames) + const lock = (fields: Field[]): Field[] => + fields.map((field) => { + if (field.type === 'tabs') { + return { ...field, tabs: field.tabs.map((tab) => ('name' in tab && tab.name ? tab : { ...tab, fields: lock(tab.fields) })) } as Field + } + if (field.type === 'row' || field.type === 'collapsible') {return { ...field, fields: lock(field.fields) } as Field} + if (!('name' in field) || !names.has(field.name)) {return field} + const own = (field as { access?: { update?: (args: never) => boolean | Promise } }).access + return { + ...field, + access: { + ...own, + update: async (args: { req: never }) => userMeetsRole(args.req, 'admin') && (own?.update ? await own.update(args as never) : true), + }, + } as Field + }) + return (globals ?? []).map((global) => (global.slug === settingsSlug ? { ...global, fields: lock(global.fields) } : global)) +} diff --git a/src/modules/branding/signIn/css.ts b/src/modules/branding/signIn/css.ts new file mode 100644 index 0000000..3fcc225 --- /dev/null +++ b/src/modules/branding/signIn/css.ts @@ -0,0 +1,169 @@ +/** + * The stylesheet of the panel's sign-in screens (`whiteLabel.signIn`): a dark panel with the client's logo or + * name beside the form, the look IAPL shares with its WordPress sibling. It styles Payload's minimal template + * (`.template-minimal`: login, forgot and reset password, create first user, logout, the 2FA screens) and the one + * element IAPL prints (`.iapl-signin`). CSS only: no script, no font file, no request to another host. + * + * It is put into the page as a `