diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index f444def..84d8229 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). The logo is a bitmap (JPEG, PNG, WebP, AVIF, GIF; an SVG logo shows the name unless `svgLogo: true`), checked by its bytes before it is printed (`checkLogo`), without a plate (`logoPlate: true` for a logo with dark letters). Options: `accent` (hex), `languages: false`; `signIn: false` = Payload's screens. Name / logo / icon are admin-only with the look (`brandAccess: 'editor'` = as before). 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 6f7e685..de919cd 100644 --- a/docs/agent/reference-site/INDEX.md +++ b/docs/agent/reference-site/INDEX.md @@ -1175,6 +1175,7 @@ Rules: AGENT.md §8a. | `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/routes.snapshot.json` | every public route of the site (REST, GraphQL, Next route files) with one line saying who may use it and why — the judged list `routes:check` compares with | | `e2e/routes.ts` | `routes:check`: the site's public routes against e2e/routes.snapshot.json (`pnpm payload run e2e/routes.ts [update]`; from the repository `pnpm routes:check`) (below) | +| `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 addresses of the second test admin and the test editor (below) | diff --git a/docs/agent/skills/iapl-reference/SKILL.md b/docs/agent/skills/iapl-reference/SKILL.md index e31bb2f..77ec55c 100644 --- a/docs/agent/skills/iapl-reference/SKILL.md +++ b/docs/agent/skills/iapl-reference/SKILL.md @@ -64,6 +64,14 @@ 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: JPEG / PNG / WebP / AVIF / GIF, fetched and checked by its bytes before it is printed, ≤ 512 KB, fits 240 × 72, no 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.logoPlate` | `false` (the logo straight on the dark panel: upload one that works on dark) | `true` = a white plate behind the logo (dark letters) | — | +| `whiteLabel.signIn.checkLogo` | on | the logo's file is fetched as an anonymous visitor gets it and its first bytes read (10-minute memory); a deleted / broken / non-image / > 512 KB file → the site's name; nothing answers → the upload document is believed | `false` = no fetch | +| `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` | `false`: an SVG logo is NOT shown on the sign-in screens (the site's name is) — tell the client to upload a PNG / WebP logo | `true` = shown as a picture (`` runs no script) | — | +| `whiteLabel.brandAccess` | `'admin'` with the sign-in look (else `'editor'`) | field-level `access.update` on the name, logo and icon fields of Site settings: only admins change what the sign-in screens show; editors keep the rest. No schema change | `'editor'` = whoever edits Site settings | | `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 +161,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 500b89e..c27178f 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..a721927 --- /dev/null +++ b/src/modules/branding/signIn/brand.ts @@ -0,0 +1,276 @@ +import type { Payload } from 'payload' + +import { getFromImportMap } from 'payload/shared' + +import { secondFactorPassed } from '../../security/totp/secondFactor.js' +import { PUBLIC_IMAGE_MAX_BYTES, rasterImageType, 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 ``, and only a bitmap: JPEG, PNG, WebP, AVIF or GIF, as the upload says AND as the + * file's first bytes say (the file is looked at before it is printed; a deleted, broken or renamed file + * gives the name, never a broken picture). No SVG unless the project asks (`svgLogo: true`); + * - 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 + /** `false`: the logo's file is not fetched and looked at before it is printed. */ + checkLogo?: false + /** 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 + /** `true`: the logo stands on a white plate (a logo drawn for light grounds). Default: no plate. */ + logoPlate?: true + /** Field of the site's name. Default `'siteName'`. */ + nameField?: string + /** Slug of the settings global. Default `'site-settings'`. */ + settingsSlug?: string + /** `true`: an SVG logo is shown too (as a picture). Default: bitmaps only, an SVG logo gives the name. */ + svgLogo?: true +} + +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; sizes?: unknown; url?: unknown; width?: unknown } + +/** The picture types a logo may have on the sign-in screens: the bitmaps a browser shows. */ +export const SIGN_IN_LOGO_TYPES = ['image/jpeg', 'image/png', 'image/webp', 'image/avif', 'image/gif'] as const + +const usableAddress = (url: unknown): url is string => typeof url === 'string' && /^(?:https?:\/\/|\/(?!\/))/i.test(url.trim()) + +/** 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 address to serve for a logo shown `shownWidth` wide: the smallest generated size (the upload's + * `sizes`) that is at least twice that width, has the picture's own proportions (a cropped size is another + * picture) and an allowed type; else the upload itself. + */ +function servedAddress(m: MediaLike, shownWidth: number): string { + const full = (m.url as string).trim() + if (typeof m.width !== 'number' || typeof m.height !== 'number' || !m.sizes || typeof m.sizes !== 'object') {return full} + let best: { url: string; width: number } | null = null + for (const size of Object.values(m.sizes as Record)) { + if (!size || typeof size.width !== 'number' || typeof size.height !== 'number' || !usableAddress(size.url)) {continue} + if (size.width < 2 * shownWidth || size.width >= m.width || size.height < 1) {continue} + if (Math.abs(size.width / size.height - m.width / m.height) > 0.02) {continue} + if (typeof size.mimeType === 'string' && !(SIGN_IN_LOGO_TYPES as readonly string[]).includes(size.mimeType.toLowerCase())) {continue} + if (!best || size.width < best.width) {best = { url: size.url.trim(), width: size.width }} + } + return best?.url ?? full +} + +/** + * The logo of an upload document, or null when there is nothing to show: no address, an address that is not + * http(s) or site-relative, or a type that is not one of `SIGN_IN_LOGO_TYPES` (SVG only with `svgLogo: true`). + */ +export function signInLogo(media: unknown, look: Pick = {}): null | SignInLogo { + if (!media || typeof media !== 'object') {return null} + const m = media as MediaLike + if (!usableAddress(m.url)) {return null} + if (isSvgUpload(m)) {return look.svgLogo === true ? { src: m.url.trim(), ...(fitLogo(m.width, m.height) ?? {}) } : null} + if (typeof m.mimeType !== 'string' || !(SIGN_IN_LOGO_TYPES as readonly string[]).includes(m.mimeType.toLowerCase())) {return null} + const fit = fitLogo(m.width, m.height) + return { src: fit ? servedAddress(m, fit.width) : m.url.trim(), ...(fit ?? {}) } +} + +export type LogoCheck = 'bad' | 'unknown' | { bytes: Buffer; type: string } + +/** + * Looks at the logo's file the way an anonymous visitor gets it (no cookies, at most 512 KB): + * - the picture itself when it answers and its first bytes are one of the allowed bitmaps (an SVG, allowed + * by `svgLogo: true`, is taken by its `image/svg+xml` type); + * - `'bad'` when the server ANSWERS and it is no such picture: 404, another type, too large, broken bytes; + * - `'unknown'` when nothing answers (the site cannot reach its own address from inside its container, a + * timeout): the upload document is then believed, so a network quirk never takes the logo away. + * A redirect is NEVER followed: the server asks only the address the upload itself has, so a logo address + * that answers "go to http://169.254.169.254/…" (or any internal host) makes the server fetch nothing there. + * Such a logo counts as `'unknown'`: the browser may follow it, the server does not. + */ +export async function checkLogoFile(url: string, base: null | string | undefined, allowSvg = false): Promise { + let target: URL + try { + target = new URL(url, base || undefined) + } catch { + return 'unknown' // a site-relative address and no origin to resolve it against + } + if (target.protocol !== 'http:' && target.protocol !== 'https:') {return 'bad'} + let res: Response + try { + res = await fetch(target, { credentials: 'omit', redirect: 'manual', signal: AbortSignal.timeout(4000) }) + } catch { + return 'unknown' + } + try { + if ((res.status >= 300 && res.status < 400) || res.type === 'opaqueredirect') {return 'unknown'} + if (!res.ok) {return res.status >= 500 ? 'unknown' : 'bad'} + const declared = Number(res.headers.get('content-length')) + if (Number.isFinite(declared) && declared > PUBLIC_IMAGE_MAX_BYTES) {return 'bad'} + const bytes = Buffer.from(await res.arrayBuffer()) + if (!bytes.length || bytes.length > PUBLIC_IMAGE_MAX_BYTES) {return 'bad'} + const declaredType = (res.headers.get('content-type') ?? '').split(';')[0].trim().toLowerCase() + if (allowSvg && declaredType === 'image/svg+xml') {return { type: declaredType, bytes }} + const type = rasterImageType(bytes) + return type && (SIGN_IN_LOGO_TYPES as readonly string[]).includes(type) ? { type, bytes } : 'bad' + } catch { + return 'unknown' + } finally { + await res.body?.cancel().catch(() => undefined) + } +} + +/** What the last look at a logo's file said, kept for ten minutes per address: one fetch, not one per page view. */ +const CHECKED = new Map() +const CHECK_TTL_MS = 10 * 60_000 + +async function checkedLogo(url: string, base: null | string | undefined, allowSvg: boolean): Promise { + const key = `${base ?? ''}|${url}|${allowSvg ? 1 : 0}` + const hit = CHECKED.get(key) + if (hit && Date.now() - hit.at < CHECK_TTL_MS) {return hit.result} + const result = await checkLogoFile(url, base, allowSvg) + if (CHECKED.size > 50) {CHECKED.clear()} + // "nothing answered" is asked again soon; an answer is kept + CHECKED.set(key, { at: result === 'unknown' ? Date.now() - CHECK_TTL_MS + 30_000 : Date.now(), result }) + return result +} + +/** For tests: forget what was checked. */ +export const forgetCheckedLogos = (): void => CHECKED.clear() + +/** 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: it gets the picture itself (the one just looked at), or the name. + const pending = Boolean(user && !secondFactorPassed({ payload, user })) + if (logo && (look.checkLogo !== false || pending) && !(pending && look.inlineImages === false)) { + const checked = await checkedLogo(logo.src, origin, look.svgLogo === true) + if (checked === 'bad') { + logo = null + } else if (pending) { + logo = checked === 'unknown' ? null : { ...logo, src: `data:${checked.type};base64,${checked.bytes.toString('base64')}` } + } + } else if (logo && pending) { + logo = 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 `