Merge claude/login-page-whitelabel-616f3d: the panel's sign-in look (whiteLabel.signIn), the client's logo, hardened brand image fetch

Conflicts kept both sides: the 2FA texts (twoFactorBusy from A, twoFactorCodeDigit here), the reference index rows,
and the e2e:built line (closed doors from C and the sign-in look here). routes.snapshot.json judges the new public
GET /api/ipal/admin-language.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-26 22:04:30 +01:00
co-authored by Claude Opus 5.5
126 changed files with 2283 additions and 46 deletions
+4
View File
@@ -11,6 +11,10 @@ export { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmai
export { DocumentTitle } from '../modules/admin-i18n/DocumentTitle.js'
export { RowLabel } from '../modules/admin-ui/RowLabelComponent.js'
export { AdminIcon, AdminLogo, IntecionCredit } from '../modules/branding/index.js'
export { SignInLook } from '../modules/branding/signIn/SignInLook.js'
export type { SignInLookProviderProps } from '../modules/branding/signIn/SignInLook.js'
export { SignInPanel } from '../modules/branding/signIn/SignInPanel.js'
export type { SignInPanelProps } from '../modules/branding/signIn/SignInPanel.js'
export { CookieApprovalForm } from '../modules/consent/scanner/CookieApprovalForm.js'
export { CookieApprovalView } from '../modules/consent/scanner/CookieApprovalView.js'
export { CookieReviewTab } from '../modules/consent/scanner/CookieReviewTab.js'
+25 -1
View File
@@ -70,7 +70,31 @@ export type { SectionHeaderFieldOptions, SectionSettingsFieldOptions } from './m
export { buildAdminImageEndpoints } from './modules/branding/adminImages.js'
export { ADMIN_META_TEXTS, adminMetaForSite, buildAdminMeta, DEFAULT_AGENCY, syncAdminMeta } from './modules/branding/adminMeta.js'
export type { AdminMetaOptions, AgencyOption, ResolvedAdminMeta } from './modules/branding/adminMeta.js'
export { fetchPublicImage, PUBLIC_IMAGE_MAX_BYTES, publicImageDataUri, rasterImageType, siteOrigin } from './modules/branding/publicImage.js'
export { fetchPublicImage, PUBLIC_IMAGE_MAX_BYTES, PUBLIC_IMAGE_TIMEOUT_MS, publicImageDataUri, rasterImageType, siteOrigin } from './modules/branding/publicImage.js'
export {
ADMIN_LANGUAGE_PATH,
adminPathFromReferer,
buildAdminLanguageEndpoint,
checkLogoFile,
fitLogo,
isHexColour,
isSvgUpload,
LANGUAGE_NAMES,
languageLinks,
loadSignInBrand,
SIGN_IN_LOGO_BOX,
SIGN_IN_LOGO_TYPES,
SIGN_IN_LOOK,
SIGN_IN_NAME_MAX,
SIGN_IN_STYLE_ID,
signInCss,
signInLogo,
signInName,
signInProviderActive,
} from './modules/branding/signIn/index.js'
export type { LanguageLink, LogoCheck, SignInBrand, SignInLogo, SignInLookProps } from './modules/branding/signIn/index.js'
export { resolveSignInLook } from './modules/branding/signIn/options.js'
export type { ResolvedSignInLook, SignInLookOptions } from './modules/branding/signIn/options.js'
export {
ACCEPT_ALL_CONSENT,
buildConsentLogCollection,
+2
View File
@@ -10,6 +10,7 @@ export const securityTexts = defineTexts({
twoFactorAlertPending: 'Accounts without two-step verification: {{count}}. Until it is set up, such an account cannot use the panel.',
twoFactorAlertTitle: 'Two-step verification',
twoFactorBusy: 'Another code for this account is being checked right now. Try again in a moment.',
twoFactorCodeDigit: 'Digit {{n}} of {{total}}',
twoFactorReopen: 'Reopen setup',
twoFactorReset: 'Reset two-step verification',
twoFactorResetConfirm: 'This account will have to set up two-step verification again before it can use the panel. Continue?',
@@ -35,6 +36,7 @@ export const securityTexts = defineTexts({
twoFactorAlertPending: 'Konta bez weryfikacji dwuetapowej: {{count}}. Dopóki nie zostanie ustawiona, takie konto nie może korzystać z panelu.',
twoFactorAlertTitle: 'Weryfikacja dwuetapowa',
twoFactorBusy: 'Właśnie sprawdzamy inny kod dla tego konta. Spróbuj ponownie za chwilę.',
twoFactorCodeDigit: 'Cyfra {{n}} z {{total}}',
twoFactorReopen: 'Otwórz konfigurację ponownie',
twoFactorReset: 'Zresetuj weryfikację dwuetapową',
twoFactorResetConfirm: 'To konto będzie musiało ponownie ustawić weryfikację dwuetapową, zanim skorzysta z panelu. Kontynuować?',
+4
View File
@@ -6,10 +6,14 @@ export const settingsTexts = defineTexts({
brandingCredit: 'Technology support: {{agency}}',
faviconNotSquare: 'The icon is not square ({{width}}×{{height}} px), so it may be cropped in tabs and search results.',
faviconTooSmall: 'The icon is {{width}}×{{height}} px. Google shows icons of at least 48×48 px; upload a larger one.',
signInLanguage: 'Language',
signInPanelLabel: 'Administration panel',
},
pl: {
brandingCredit: 'Wsparcie technologiczne: {{agency}}',
faviconNotSquare: 'Ikona nie jest kwadratowa ({{width}}×{{height}} px), więc może być przycięta na kartach i w wynikach wyszukiwania.',
faviconTooSmall: 'Ikona ma {{width}}×{{height}} px. Google pokazuje ikony od 48×48 px; wgraj większą.',
signInLanguage: 'Język',
signInPanelLabel: 'Panel administracyjny',
},
})
+18 -1
View File
@@ -4,6 +4,8 @@ import { iaplT } from '../admin-i18n/t.js'
import { settingsTexts } from '../admin-i18n/texts/settings.js'
import { secondFactorPassed } from '../security/totp/secondFactor.js'
import { publicImageDataUri, siteOrigin } from './publicImage.js'
import { type SignInLookProps, signInProviderActive } from './signIn/brand.js'
import { SignInPanel } from './signIn/SignInPanel.js'
/**
* White-label admin branding: the Payload admin panel's logo (login + nav) and
@@ -25,6 +27,8 @@ import { publicImageDataUri, siteOrigin } from './publicImage.js'
*/
type BrandingProps = {
/** Injected by Payload into admin server components. */
i18n?: { language?: string; t: (key: never, vars?: Record<string, unknown>) => string }
/** Upload field to render as the image. Default 'logo' (Logo) / 'favicon' (Icon). */
imageField?: string
/** `whiteLabel.inlineImages: false` — never fetch the image on the server for the 2FA screens. */
@@ -37,6 +41,11 @@ type BrandingProps = {
payload?: Payload
/** SiteSettings global slug. Default 'site-settings'. */
settingsSlug?: string
/**
* `whiteLabel.signIn`, set by the plugin on `graphics.Logo`: the logo's place on the login screen then holds
* the sign-in panel (docs/white-label.md). Not set: the plain logo, as before.
*/
signIn?: SignInLookProps
/** Injected by Payload into admin server components — the account looking at the panel. */
user?: null | Record<string, unknown>
}
@@ -94,9 +103,17 @@ async function loadBranding(
* Admin panel logo — this is the LARGE logo on the login / unauthorized screens
* (Payload uses `graphics.Icon` for the small nav glyph). SiteSettings `logo`,
* falls back to `siteName` text. Sized generously for the login screen.
*
* With `signIn` (the sign-in look, on by default with `whiteLabel`) it prints the sign-in panel instead: this
* component is in the import map of every white-label site, so the look needs no new entry. When the provider
* `SignInLook` already prints the panel (`signIn.allScreens`), it prints nothing.
*/
export async function AdminLogo(props: BrandingProps = {}) {
const { imageField = 'logo', nameField = 'siteName', settingsSlug = 'site-settings' } = props
if (props.signIn) {
if (signInProviderActive(props.payload)) {return null}
return <SignInPanel i18n={props.i18n} locale={props.locale} look={props.signIn} payload={props.payload} user={props.user} />
}
const { name, url } = await loadBranding(props, settingsSlug, nameField, imageField)
if (url) {
return (
@@ -178,7 +195,7 @@ export function IntecionCredit(
textDecoration: 'none',
}
return (
<a href={url} rel="noopener noreferrer" style={style} target="_blank">
<a className={`iapl-credit iapl-credit--${variant}`} href={url} rel="noopener noreferrer" style={style} target="_blank">
{text}
</a>
)
+31 -15
View File
@@ -4,7 +4,7 @@ import type { AgencyOption, ResolvedAdminMeta } from './adminMeta.js'
import { UPLOAD_SECURITY_HEADERS } from '../security/buildSecurityHeaders.js'
import { ADMIN_ICON_PATH, ADMIN_META_TEXTS, ADMIN_OG_PATH } from './adminMeta.js'
import { fetchPublicImage, rasterImageType } from './publicImage.js'
import { fetchPublicImage, rasterImageType, siteOrigin } from './publicImage.js'
/**
* The panel's link-preview image (1200×630) and icon, drawn from SiteSettings:
@@ -33,24 +33,40 @@ async function loadBranding(req: PayloadRequest, f: Required<Omit<Fields, 'serve
}
}
/** Absolute URL of an upload, resolved against the request (uploads are often relative). */
const absolute = (url: string, req: PayloadRequest) => new URL(url, req.url ?? `http://localhost`).toString()
/**
* The site's own origin for resolving a site-relative upload address: what the CONFIG says (`serverURL`, else
* `NEXT_PUBLIC_SERVER_URL`), never the request. These endpoints are public, and a request names its own host
* (`Host`, `X-Forwarded-Host`): resolving against it would let anyone point the server's fetch at a host of
* their choice. No configured origin: a relative address is not fetched at all.
*/
const origin = (req: PayloadRequest): null | string => siteOrigin(req.payload.config?.serverURL)
/** The image as a data URI, so the renderer needs no network access of its own. */
async function inline(url: null | string, req: PayloadRequest): Promise<null | string> {
if (!url) {return null}
/** The upload's address as the browser is sent to it: absolute when the site's origin is known, else as stored. */
function publicAddress(url: string, req: PayloadRequest): string {
try {
const res = await fetch(absolute(url, req))
if (!res.ok) {return null}
const type = res.headers.get('content-type') ?? 'image/png'
// The renderer can't draw WebP/AVIF; the site name is shown instead.
if (!/png|jpe?g|gif|svg/.test(type)) {return null}
return `data:${type};base64,${Buffer.from(await res.arrayBuffer()).toString('base64')}`
return new URL(url, origin(req) || undefined).toString()
} catch {
return null
return url
}
}
/** What the preview image's renderer can draw, by the file's first bytes. */
const DRAWABLE = ['image/png', 'image/jpeg', 'image/gif']
/**
* The image as a data URI, so the renderer needs no network access of its own. Fetched like every public
* brand image (publicImage.ts: one address, no redirect, a timeout, at most 512 KB read). PNG, JPEG and GIF
* by their bytes; an SVG by its declared type, as before (drawn by the renderer on the server, not by a
* browser); WebP / AVIF cannot be drawn: the site name is shown instead.
*/
async function inline(url: null | string, req: PayloadRequest): Promise<null | string> {
const image = await fetchPublicImage(url, origin(req))
if (!image) {return null}
const raster = rasterImageType(image.bytes)
const type = raster && DRAWABLE.includes(raster) ? raster : !raster && image.type === 'image/svg+xml' ? image.type : null
return type ? `data:${type};base64,${image.bytes.toString('base64')}` : null
}
// Loaded on first use, so the Payload CLI (which reads this config outside Next) never loads it;
// '.js' because next has no exports map (plain Node ESM can't resolve 'next/og').
const imageResponse = async () => (await import('next/og.js')).ImageResponse
@@ -111,7 +127,7 @@ export function buildAdminImageEndpoints(resolved: ResolvedAdminMeta, fields: Fi
// media file: a panel session that still owes its 2FA code is refused that file (it is
// refused every collection), and a cached redirect would send it there anyway. The answer
// is the same for everyone, so it can be cached like the redirect was.
const image = fields.serveIcon === false ? null : await fetchPublicImage(absolute(brand.icon, req), null)
const image = fields.serveIcon === false ? null : await fetchPublicImage(brand.icon, origin(req))
// Only a bitmap is answered from here, recognised by its first bytes — never an SVG, which
// is a document that can run script in the site's origin. The headers below are the upload
// routes' (sandbox, no sniffing), but a Next project's site-wide CSP rule overrides a
@@ -124,7 +140,7 @@ export function buildAdminImageEndpoints(resolved: ResolvedAdminMeta, fields: Fi
}
// An SVG favicon, or not fetchable from here (too large, media is not public): the browser
// goes to the media file itself, where the upload route's own headers apply.
return new Response(null, { headers: { 'Cache-Control': CACHE, Location: absolute(brand.icon, req) }, status: 302 })
return new Response(null, { headers: { 'Cache-Control': CACHE, Location: publicAddress(brand.icon, req) }, status: 302 })
}
const ImageResponse = await imageResponse()
return new ImageResponse(
+20 -3
View File
@@ -5,11 +5,24 @@
* set 2FA up) is refused every collection, `media` included, although the
* same file is public. Serving the bytes from here opens nothing: only what
* answers an anonymous request comes back, and only an image of a sane size.
*
* The server asks ONE address and nothing else: a redirect is never followed
* (an answer "go to http://169.254.169.254/…" or to any internal host makes
* the server fetch nothing there — it counts as "no image"), the whole
* exchange has `PUBLIC_IMAGE_TIMEOUT_MS`, and reading stops at
* `PUBLIC_IMAGE_MAX_BYTES` whatever the server says about the length.
*/
export const PUBLIC_IMAGE_MAX_BYTES = 512 * 1024
const MAX_BYTES = PUBLIC_IMAGE_MAX_BYTES
/** Headers and body together: a server that never answers, or never ends, is given up on. */
export const PUBLIC_IMAGE_TIMEOUT_MS = 5000
export async function fetchPublicImage(url: null | string | undefined, base: null | string | undefined): Promise<{ bytes: Buffer; type: string } | null> {
export async function fetchPublicImage(
url: null | string | undefined,
base: null | string | undefined,
/** `timeoutMs`: another limit for the whole exchange (default `PUBLIC_IMAGE_TIMEOUT_MS`). */
options: { timeoutMs?: number } = {},
): Promise<{ bytes: Buffer; type: string } | null> {
if (!url) {return null}
let target: URL
try {
@@ -19,8 +32,12 @@ export async function fetchPublicImage(url: null | string | undefined, base: nul
}
if (target.protocol !== 'http:' && target.protocol !== 'https:') {return null}
try {
const res = await fetch(target, { credentials: 'omit', redirect: 'follow', signal: AbortSignal.timeout(5000) })
if (!res.ok) {return null}
const res = await fetch(target, { credentials: 'omit', redirect: 'manual', signal: AbortSignal.timeout(options.timeoutMs ?? PUBLIC_IMAGE_TIMEOUT_MS) })
// `!res.ok` covers a redirect too (3xx, or the opaque answer `redirect: 'manual'` gives): never followed.
if (!res.ok || res.type === 'opaqueredirect') {
await res.body?.cancel().catch(() => undefined)
return null
}
const type = (res.headers.get('content-type') ?? '').split(';')[0].trim()
if (!type.startsWith('image/')) {return null}
// Too large is known before reading when the server says so; otherwise stop reading at the limit.
@@ -0,0 +1,23 @@
import type React from 'react'
import { SignInPanel, type SignInPanelProps } from './SignInPanel.js'
export type SignInLookProviderProps = { children?: React.ReactNode } & SignInPanelProps
/**
* Admin provider that puts the sign-in panel on EVERY screen of Payload's minimal template: login, forgot and
* reset password, create first user, logout, "unauthorized", e-mail verification and the 2FA screens. The
* stylesheet shows the panel only there; on the other admin pages it is not displayed.
*
* Registered by `whiteLabel: { signIn: { allScreens: true } }` — a new import-map entry, so run
* `pnpm payload generate:importmap`. Without it the login screen and the 2FA screens still get the look,
* through components every site already has in its map (`AdminLogo`, `SafeTotpView`).
*/
export function SignInLook({ children, ...panel }: SignInLookProviderProps): React.ReactElement {
return (
<>
<SignInPanel {...panel} />
{children}
</>
)
}
@@ -0,0 +1,78 @@
import type { Payload } from 'payload'
import type React from 'react'
import { iaplT } from '../../admin-i18n/t.js'
import { settingsTexts } from '../../admin-i18n/texts/settings.js'
import { languageLinks, loadSignInBrand, type SignInLookProps } from './brand.js'
import { SIGN_IN_STYLE_ID, signInCss } from './css.js'
export type SignInPanelProps = {
/** Injected by Payload into admin server components. */
i18n?: { language?: string; t: (key: never, vars?: Record<string, unknown>) => string }
/** Injected by Payload — the panel's content locale (object or code). */
locale?: { code?: string } | string
/** `whiteLabel.signIn`, as the plugin resolved it. */
look?: SignInLookProps
/** Injected by Payload into admin server components. */
payload?: Payload
/** Injected by Payload — the account looking at the screen, if any. */
user?: null | Record<string, unknown>
}
/**
* The dark panel of the sign-in screens with its stylesheet: the label "Administration panel", the client's
* logo (straight on the panel; on a white plate with `logoPlate`) or the site's name, and the panel's languages
* as links. A Server Component; it reads Site settings with the `payload` Payload hands it and never throws.
*
* The stylesheet hides it wherever the page is not one of Payload's minimal screens, so the same element can
* be printed by the provider on every admin page (`SignInLook`), by the logo on the login screen (`AdminLogo`)
* or in front of the 2FA screens (`SafeTotpView`). Wire it yourself the same way for a screen of your own.
*/
export async function SignInPanel(props: SignInPanelProps = {}): Promise<React.ReactElement> {
const { i18n, look = {}, payload } = props
const text = (key: 'signInLanguage' | 'signInPanelLabel') => (i18n ? iaplT(i18n.t, key) : settingsTexts.en[key])
const brand = await loadSignInBrand({ locale: props.locale, look, payload, user: props.user })
const languages = look.languages === false ? [] : languageLinks(payload?.config, i18n?.language)
const plate = brand.logo && look.logoPlate === true
return (
<>
{/* React keeps one copy by `href` and puts it into <head> before the page is shown. */}
<style href={SIGN_IN_STYLE_ID} precedence="iapl">
{signInCss({ accent: look.accent })}
</style>
<header className={`iapl-signin iapl-signin--${brand.logo ? 'logo' : 'name'}`} data-iapl-sign-in="">
<p className="iapl-signin__label">{text('signInPanelLabel')}</p>
{brand.logo ? (
<a className={`iapl-signin__brand${plate ? ' iapl-signin__brand--plate' : ''}`} href="/">
<img alt={brand.name} decoding="async" height={brand.logo.height} src={brand.logo.src} width={brand.logo.width} />
</a>
) : brand.name ? (
<a className="iapl-signin__brand iapl-signin__brand--name" href="/">
{brand.name}
</a>
) : null}
{languages.length ? (
<nav aria-label={text('signInLanguage')} className="iapl-signin__languages">
<ul>
{languages.map((l) => (
<li key={l.code}>
{l.current ? (
<span aria-current="true" lang={l.code}>
{l.name}
</span>
) : (
// A plain link: the endpoint sets the cookie and sends the browser back, without script.
<a href={l.href} hrefLang={l.code} lang={l.code} rel="nofollow">
{l.name}
</a>
)}
</li>
))}
</ul>
</nav>
) : null}
</header>
</>
)
}
+276
View File
@@ -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 `<img>`, 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<string, unknown>
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<string, MediaLike | null>)) {
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<SignInLookProps, 'svgLogo'> = {}): 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<LogoCheck> {
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<string, { at: number; result: LogoCheck }>()
const CHECK_TTL_MS = 10 * 60_000
async function checkedLogo(url: string, base: null | string | undefined, allowSvg: boolean): Promise<LogoCheck> {
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<string, unknown>
}
/** 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<SignInBrand> {
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<string, unknown>
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<string, string> = {
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<string, unknown> }; 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 }))
}
@@ -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<boolean> } }).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))
}
+169
View File
@@ -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 `<style>` by the component that prints the panel, so it exists only where the
* panel does; every rule needs `.iapl-signin` on the page. Payload's own rules sit in `@layer payload-default`,
* so these win without `!important`; the few `!important`s answer inline styles and the 2FA package's own.
*
* Projects: set the custom properties on `:root` in the admin's `custom.scss` (the defaults below have no
* specificity), or pass `whiteLabel.signIn.accent`.
*/
/** A colour a project may pass as the accent: a hex value only, so nothing else can reach the stylesheet. */
export const isHexColour = (value: unknown): value is string => typeof value === 'string' && /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i.test(value)
/** Id of the `<style>`: React keeps one copy however many components print it. */
export const SIGN_IN_STYLE_ID = 'iapl-sign-in'
const TOKENS = (accent: string | undefined) => `
:where(:root){
--iapl-signin-split:45.4545%;
--iapl-signin-bg:#ffffff;
--iapl-signin-text:#060606;
--iapl-signin-muted:#5f6368;
--iapl-signin-border:#e5e7eb;
--iapl-signin-field-border:#80868f;
--iapl-signin-primary:${accent ?? '#0070c0'};
--iapl-signin-primary-hover:${accent ? 'color-mix(in srgb,var(--iapl-signin-primary) 82%,#000)' : '#005a9e'};
--iapl-signin-primary-text:#ffffff;
--iapl-signin-link:${accent ? 'var(--iapl-signin-primary)' : '#006bb8'};
--iapl-signin-focus:${accent ? 'var(--iapl-signin-primary)' : '#017bd0'};
--iapl-signin-panel:#060606;
--iapl-signin-panel-text:#fbfbfb;
--iapl-signin-panel-label:#b2b2b2;
--iapl-signin-panel-glow:0 158 246;
--iapl-signin-panel-inset:0.625rem;
--iapl-signin-panel-radius:1.25rem;
--iapl-signin-radius:0.375rem;
}
:where(html[data-theme=dark]){
--iapl-signin-bg:var(--theme-bg,#141414);
--iapl-signin-text:#f3f3f3;
--iapl-signin-muted:#a8adb4;
--iapl-signin-border:#2f3338;
--iapl-signin-field-border:#6b7178;
--iapl-signin-link:${accent ? 'color-mix(in srgb,var(--iapl-signin-primary) 55%,#fff)' : '#74bdf2'};
--iapl-signin-focus:${accent ? 'color-mix(in srgb,var(--iapl-signin-primary) 55%,#fff)' : '#4aa8f0'};
}`
const RULES = `
.iapl-signin{display:none}
body:has(.template-minimal) .iapl-signin{
box-sizing:border-box;position:fixed;z-index:1;inset-block:var(--iapl-signin-panel-inset);inset-inline-start:var(--iapl-signin-panel-inset);
width:calc(var(--iapl-signin-split) - var(--iapl-signin-panel-inset));margin:0;padding:clamp(2rem,4vw,4rem);overflow:hidden;
display:flex;flex-direction:column;justify-content:flex-end;align-items:flex-start;gap:1.25rem;
background:var(--iapl-signin-panel);border-radius:var(--iapl-signin-panel-radius);color:var(--iapl-signin-panel-text);text-align:start;
}
.iapl-signin *{box-sizing:border-box}
.iapl-signin::before{
content:"";position:absolute;inset:0;pointer-events:none;
background:
linear-gradient(rgb(255 255 255 / .04) 1px,transparent 1px) 0 0 / 3.5rem 2.5rem,
linear-gradient(90deg,rgb(255 255 255 / .04) 1px,transparent 1px) 0 0 / 3.5rem 2.5rem;
}
.iapl-signin::after{
content:"";position:absolute;inset:0;pointer-events:none;
background:
radial-gradient(circle 24rem at 0% 62%,rgb(var(--iapl-signin-panel-glow) / .24),transparent),
radial-gradient(circle 22rem at 100% 8%,rgb(var(--iapl-signin-panel-glow) / .22),transparent);
}
.iapl-signin>*{position:relative;z-index:1}
.iapl-signin__label{
display:flex;align-items:center;gap:.625rem;margin:0;padding:0;
font:600 .875rem/1.25rem ui-monospace,"SFMono-Regular",Menlo,Consolas,"Liberation Mono",monospace;
letter-spacing:.05em;text-transform:uppercase;color:var(--iapl-signin-panel-label);
}
.iapl-signin__label::before{content:"";flex:none;width:.3125rem;height:.3125rem;background:rgb(var(--iapl-signin-panel-glow))}
.iapl-signin__brand{display:block;max-width:100%;color:inherit;text-decoration:none}
.iapl-signin__brand--plate{padding:1rem 1.25rem;background:#fff;border-radius:.75rem}
.iapl-signin__brand img{display:block;width:auto;height:auto;max-width:min(15rem,100%);max-height:4.5rem}
.iapl-signin__brand--name{
margin:0;font-family:inherit;font-weight:500;font-size:clamp(2.25rem,1.4rem + 2.4vw,3.75rem);line-height:1.12;letter-spacing:-.03em;
text-wrap:balance;overflow-wrap:anywhere;
}
.iapl-signin a:hover{color:inherit}
.iapl-signin a:focus-visible{outline:2px solid #fff;outline-offset:3px;border-radius:.25rem}
.iapl-signin__languages{position:absolute;inset-block-start:clamp(1.25rem,2.5vw,2rem);inset-inline-end:clamp(1.25rem,2.5vw,2rem);max-width:calc(100% - 2.5rem);font-size:.8125rem;line-height:1.25rem;color:var(--iapl-signin-panel-label)}
.iapl-signin__languages ul{display:flex;flex-wrap:wrap;justify-content:flex-end;gap:0 .125rem;margin:0;padding:0;list-style:none}
.iapl-signin__languages li{display:flex;align-items:center;margin:0;padding:0}
.iapl-signin__languages li+li::before{content:"";width:1px;height:.875rem;margin-inline-end:.125rem;background:rgb(255 255 255 / .22)}
.iapl-signin__languages :is(a,span){display:block;padding:.375rem .5rem;color:inherit;text-decoration:none;border-radius:.25rem}
.iapl-signin__languages a:hover{color:#fff;text-decoration:underline}
.iapl-signin__languages [aria-current]{color:#fff;font-weight:600}
/* The form column: Payload's minimal template. */
html:has(.iapl-signin) body .template-minimal{
box-sizing:border-box;width:calc(100% - var(--iapl-signin-split));min-height:100vh;min-height:100svh;height:auto;
margin-inline:var(--iapl-signin-split) 0;padding:clamp(1.5rem,4vw,3.5rem) clamp(1.25rem,4vw,2rem);
background:var(--iapl-signin-bg);color:var(--iapl-signin-text);
}
html:has(.iapl-signin) body:has(.template-minimal){background:var(--iapl-signin-bg)}
html:has(.iapl-signin) .template-minimal--width-normal .template-minimal__wrap{max-width:28rem}
/* The logo's own place on the login screen: the panel carries the brand. */
html:has(.iapl-signin) .login__brand{display:block;margin:0}
html:has(.iapl-signin) .login__brand:not(:has(.iapl-signin)){display:none}
html:has(.iapl-signin) .template-minimal h1{font-size:1.75rem;line-height:1.2;letter-spacing:-.02em;font-weight:500}
html:has(.iapl-signin) .template-minimal a:not(.btn):not(.iapl-signin *){color:var(--iapl-signin-link);text-underline-offset:.25em}
html:has(.iapl-signin) .template-minimal :is(a,button,input,select,textarea):not(.iapl-signin *):focus-visible{outline:2px solid var(--iapl-signin-focus);outline-offset:2px}
html:has(.iapl-signin) .template-minimal .field-type :is(input[type=text],input[type=email],input[type=password]){
min-height:3rem;border-color:var(--iapl-signin-field-border);border-radius:var(--iapl-signin-radius);
}
/* The 2FA code boxes are white with a soft shadow: on a white page they need an edge. */
html:has(.iapl-signin) .template-minimal form input[type=text]:not(.field-type *){box-shadow:inset 0 0 0 1px var(--iapl-signin-field-border)}
html:has(.iapl-signin) .template-minimal .form-submit{display:block;width:100%;margin:1.375rem 0 0}
html:has(.iapl-signin) .template-minimal :is(.form-submit .btn,.btn--style-primary):not(.btn--disabled){
--bg-color:var(--iapl-signin-primary);--hover-bg:var(--iapl-signin-primary-hover);--color:var(--iapl-signin-primary-text);--hover-color:var(--iapl-signin-primary-text);
}
html:has(.iapl-signin) .template-minimal .form-submit .btn{display:block;width:100%;min-height:3.125rem;margin-block:0;border-radius:var(--iapl-signin-radius)}
html:has(.iapl-signin) .template-minimal .forgot-password__form__actions{gap:1rem}
html:has(.iapl-signin) .template-minimal .forgot-password__form__actions .form-submit{margin-top:.375rem}
html:has(.iapl-signin) .template-minimal .reset-password__wrap>a{display:inline-block;margin-top:1rem}
/* The credit line under the login form (its own inline styles are answered here). */
html:has(.iapl-signin) .template-minimal .iapl-credit--login{
margin-top:1.5rem!important;padding:1rem 0 0!important;border-top:1px solid var(--iapl-signin-border);
color:var(--iapl-signin-muted)!important;opacity:1!important;font-size:.8125rem!important;
}
/* The 2FA setup notice is a bar over the page: it stays over the form column. */
html:has(.iapl-signin) body:has(.template-minimal) #ipal-two-factor-notice{margin-inline-start:var(--iapl-signin-split)}
/* A phone: the panel is a band above the form. */
@media (max-width:52rem){
body:has(.template-minimal) .iapl-signin{
position:relative;inset:auto;width:100vw;max-width:none;margin-inline-start:calc(50% - 50vw);
justify-content:flex-start;gap:.625rem;padding:1.75rem 1.25rem 2rem;
border-radius:0 0 var(--iapl-signin-panel-radius) var(--iapl-signin-panel-radius);
}
.iapl-signin::after{
background:
radial-gradient(circle 12rem at 0% 100%,rgb(var(--iapl-signin-panel-glow) / .2),transparent),
radial-gradient(circle 12rem at 100% 0%,rgb(var(--iapl-signin-panel-glow) / .22),transparent);
}
.iapl-signin__brand img{max-width:min(12rem,100%);max-height:3.5rem}
.iapl-signin__brand--plate{padding:.75rem 1rem}
.iapl-signin__brand--name{font-size:1.875rem}
.iapl-signin__languages{position:static;order:3;max-width:100%;margin:.375rem 0 -.5rem -.5rem}
.iapl-signin__languages ul{justify-content:flex-start}
html:has(.iapl-signin) body .template-minimal{
width:100%;min-height:0;margin-inline:0;align-items:flex-start;padding:1.75rem 1.25rem 2rem;
}
html:has(.iapl-signin) body .template-minimal:has(.iapl-signin){padding-top:0}
html:has(.iapl-signin) .login__brand:has(.iapl-signin){margin-bottom:1.75rem}
html:has(.iapl-signin) .template-minimal--width-normal .template-minimal__wrap{max-width:30rem}
html:has(.iapl-signin) body:has(.template-minimal) #ipal-two-factor-notice{margin-inline-start:0}
}
@media (prefers-reduced-motion:no-preference){
html:has(.iapl-signin) .template-minimal .form-submit .btn{transition:background-color 120ms ease}
}
@media (forced-colors:active){
body:has(.template-minimal) .iapl-signin{border:1px solid CanvasText}
.iapl-signin__brand--plate{border:1px solid CanvasText}
}`
/** The whole stylesheet. `accent`: a hex colour for the button, the links and the focus ring. */
export function signInCss(options: { accent?: string } = {}): string {
const accent = isHexColour(options.accent) ? options.accent : undefined
return `${TOKENS(accent)}${RULES}`.replace(/\n\s*/g, '')
}
+19
View File
@@ -0,0 +1,19 @@
export {
ADMIN_LANGUAGE_PATH,
checkLogoFile,
fitLogo,
isSvgUpload,
LANGUAGE_NAMES,
languageLinks,
loadSignInBrand,
SIGN_IN_LOGO_BOX,
SIGN_IN_LOGO_TYPES,
SIGN_IN_LOOK,
SIGN_IN_NAME_MAX,
signInLogo,
signInName,
signInProviderActive,
} from './brand.js'
export type { LanguageLink, LogoCheck, SignInBrand, SignInLogo, SignInLookProps } from './brand.js'
export { isHexColour, SIGN_IN_STYLE_ID, signInCss } from './css.js'
export { adminPathFromReferer, buildAdminLanguageEndpoint } from './languageEndpoint.js'
@@ -0,0 +1,53 @@
import type { Endpoint, PayloadRequest } from 'payload'
import { ADMIN_LANGUAGE_PATH } from './brand.js'
/**
* `GET /api/ipal/admin-language?lng=pl` — remembers the panel's language for this browser and sends it back to
* the admin page it came from. It is what makes the language links of the sign-in panel work without script.
*
* Public on purpose (nobody is signed in on the sign-in screen), and it can do one thing only: write Payload's
* own language cookie with a language the panel supports. The way back is a PATH inside the admin taken from
* the Referer, never a host: a crafted link can choose which admin page opens, nothing else.
*/
/** The admin path a Referer points at, or the admin root: only a path of this site's panel is ever returned. */
export function adminPathFromReferer(referer: null | string | undefined, adminRoute: string): string {
const admin = adminRoute.startsWith('/') ? adminRoute.replace(/\/+$/, '') || '/' : '/admin'
if (!referer) {return admin}
let url: URL
try {
url = new URL(referer)
} catch {
return admin
}
const path = url.pathname
const inside = admin === '/' || path === admin || path.startsWith(`${admin}/`)
if (!inside || path.startsWith('//') || path.includes('\\')) {return admin}
return `${path}${url.search}`
}
export function buildAdminLanguageEndpoint(): Endpoint {
return {
handler: (req: PayloadRequest) => {
const config = req.payload.config
const admin = config.routes?.admin ?? '/admin'
const lng = typeof req.query?.lng === 'string' ? req.query.lng : ''
const supported = Object.keys(config.i18n?.supportedLanguages ?? {})
if (!supported.includes(lng)) {
return Response.json({ error: 'Unknown language.' }, { headers: { 'Cache-Control': 'no-store' }, status: 400 })
}
const secure = (req.headers.get('x-forwarded-proto') ?? new URL(req.url ?? 'http://localhost').protocol.replace(':', '')) === 'https'
const headers = new Headers({
'Cache-Control': 'no-store',
Location: adminPathFromReferer(req.headers.get('referer'), admin),
'Referrer-Policy': 'no-referrer',
'X-Robots-Tag': 'noindex, nofollow',
})
headers.append('Set-Cookie', `${config.cookiePrefix || 'payload'}-lng=${encodeURIComponent(lng)}; Path=/; Max-Age=31536000; SameSite=Lax${secure ? '; Secure' : ''}`)
return new Response(null, { headers, status: 303 })
},
method: 'get',
path: ADMIN_LANGUAGE_PATH,
}
}
+63
View File
@@ -0,0 +1,63 @@
import type { SignInLookProps } from './brand.js'
import { isHexColour } from './css.js'
/** `whiteLabel.signIn` as a project writes it. */
export type SignInLookOptions = {
/**
* Hex colour (`'#0b6e4f'`) of the button, the links and the focus ring on the sign-in screens. Check its
* contrast against white: it carries the button's white text. Default: the shared blue.
*/
accent?: string
/**
* Put the look on EVERY sign-in screen (forgot and reset password, create first user, logout, …), not only
* on the login screen and the 2FA screens. Adds one admin provider (`SignInLook`), so the import map gains
* an entry: run `pnpm payload generate:importmap` and commit it. Default `false`, so that a site upgrades
* without touching its import map; the project starter turns it on.
*/
allScreens?: boolean
/**
* `false`: the logo's file is not fetched and looked at before it is printed (its type by its first bytes,
* at most 512 KB; a deleted or broken file gives the site's name). Default: checked, remembered ten minutes.
*/
checkLogo?: false
/** `false`: no language links on the panel. Default: shown when the panel has more than one language. */
languages?: false
/**
* `true`: the logo stands on a white plate — for a logo drawn for light grounds (dark letters). Default:
* no plate, the logo straight on the dark panel, so the panel's logo should be one made for dark grounds.
*/
logoPlate?: boolean
/**
* `true`: an SVG logo is shown too (as a picture, where it cannot run script). Default: only JPEG, PNG,
* WebP, AVIF and GIF are shown; with an SVG logo the sign-in screens show the site's name.
*/
svgLogo?: boolean
}
export type ResolvedSignInLook = { allScreens: boolean; props: SignInLookProps }
type WhiteLabelFields = { inlineImages?: false; logoField?: string; nameField?: string; settingsSlug?: string; signIn?: boolean | SignInLookOptions }
/**
* The sign-in look of a `whiteLabel` option: null when white-label or the look is off, otherwise the plain
* values the components receive. On by default with `whiteLabel`; `signIn: false` keeps Payload's screens.
*/
export function resolveSignInLook(whiteLabel: boolean | undefined | WhiteLabelFields): null | ResolvedSignInLook {
if (!whiteLabel) {return null}
const wl = whiteLabel === true ? {} : whiteLabel
if (wl.signIn === false) {return null}
const signIn = typeof wl.signIn === 'object' && wl.signIn ? wl.signIn : {}
const props: SignInLookProps = {
...(isHexColour(signIn.accent) ? { accent: signIn.accent } : {}),
...(wl.logoField ? { imageField: wl.logoField } : {}),
...(wl.inlineImages === false ? { inlineImages: false as const } : {}),
...(signIn.languages === false ? { languages: false as const } : {}),
...(signIn.checkLogo === false ? { checkLogo: false as const } : {}),
...(signIn.logoPlate === true ? { logoPlate: true as const } : {}),
...(wl.nameField ? { nameField: wl.nameField } : {}),
...(wl.settingsSlug ? { settingsSlug: wl.settingsSlug } : {}),
...(signIn.svgLogo === true ? { svgLogo: true as const } : {}),
}
return { allScreens: signIn.allScreens === true, props }
}
@@ -0,0 +1,22 @@
'use client'
import { useEffect } from 'react'
/**
* Names for the boxes of the 2FA code. The package draws one text box per digit without a label, so a screen
* reader announces six unnamed fields. After the page is live each box gets `aria-label` ("Digit 2 of 6") and
* the numeric keyboard on a phone. Attributes only: no value, handler or focus is touched, and a box that
* already has a name keeps it. Rendered by `SafeTotpView` together with the sign-in look.
*/
export function CodeInputNames({ label }: { label: string }) {
useEffect(() => {
const boxes = document.querySelectorAll<HTMLInputElement>('.template-minimal form input[type="text"][maxlength="1"]')
boxes.forEach((box, index) => {
if (!box.hasAttribute('aria-label') && !box.hasAttribute('aria-labelledby')) {
box.setAttribute('aria-label', label.replace('%n', String(index + 1)).replace('%t', String(boxes.length)))
}
if (!box.hasAttribute('inputmode')) {box.setAttribute('inputmode', 'numeric')}
})
}, [label])
return null
}
+35 -2
View File
@@ -4,9 +4,21 @@ import type React from 'react'
import { RenderServerComponent } from '@payloadcms/ui/elements/RenderServerComponent'
import { getFromImportMap } from 'payload/shared'
import type { SignInLookProps } from '../../branding/signIn/brand.js'
import { iaplT } from '../../admin-i18n/t.js'
import { securityTexts } from '../../admin-i18n/texts/security.js'
import { signInProviderActive } from '../../branding/signIn/brand.js'
import { SignInPanel } from '../../branding/signIn/SignInPanel.js'
import { CodeInputNames } from './CodeInputNames.js'
import { safeAdminBack, type SafeBackRule, type TotpViewComponent, totpViewImportKey } from './safeBack.js'
export type SafeTotpViewProps = {
/**
* `whiteLabel.signIn`, set by the plugin: the sign-in panel is printed in front of the 2FA screen when the
* provider (`SignInLook`) does not print it. Not set: the screen as the package draws it.
*/
iaplSignIn?: SignInLookProps
/** `twoFactor.safeBack` as a function: replaces the default rule. */
ipalSafeBack?: SafeBackRule
/** `clientProps` of the view's own registration; passed on to it. */
@@ -42,7 +54,7 @@ const CLIENT_PROPS = ['browseByFolderSlugs', 'clientConfig', 'collectionSlug', '
* `admin.dependencies`.
*/
export function SafeTotpView(props: SafeTotpViewProps): React.ReactNode {
const { ipalSafeBack, ipalTotpClientProps, ipalTotpView, ...rest } = props
const { iaplSignIn, ipalSafeBack, ipalTotpClientProps, ipalTotpView, ...rest } = props
const config = props.initPageResult?.req?.payload?.config ?? props.payload?.config
const query = (props.searchParams ?? {}) as Record<string, unknown>
const back = (ipalSafeBack ?? safeAdminBack)(typeof query.back === 'string' ? query.back : undefined, {
@@ -61,10 +73,31 @@ export function SafeTotpView(props: SafeTotpViewProps): React.ReactNode {
for (const key of CLIENT_PROPS) {
if (key in rest) {clientProps[key] = (rest as Record<string, unknown>)[key]}
}
return RenderServerComponent({
const view = RenderServerComponent({
clientProps,
Component: ipalTotpView,
importMap: props.importMap,
serverProps: { ...rest, searchParams },
})
const req = props.initPageResult?.req
const payload = req?.payload ?? props.payload
// The look only: the panel is a sibling in front of the screen, the screen itself is rendered as above.
if (!iaplSignIn) {return view}
const i18n = (req?.i18n ?? props.i18n) as { t: (key: never, vars?: Record<string, unknown>) => string } | undefined
const digit = i18n ? iaplT(i18n.t, 'twoFactorCodeDigit', { n: '%n', total: '%t' }) : securityTexts.en.twoFactorCodeDigit.replace('{{n}}', '%n').replace('{{total}}', '%t')
return (
<>
{signInProviderActive(payload) ? null : (
<SignInPanel
i18n={i18n as never}
locale={(props.initPageResult?.locale ?? props.locale) as never}
look={iaplSignIn}
payload={payload}
user={(req?.user ?? props.user) as never}
/>
)}
{view}
<CodeInputNames label={digit} />
</>
)
}
+61 -1
View File
@@ -20,6 +20,10 @@ 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 { SIGN_IN_LOOK } from './modules/branding/signIn/brand.js'
import { lockBrandFields } from './modules/branding/signIn/brandAccess.js'
import { buildAdminLanguageEndpoint } from './modules/branding/signIn/languageEndpoint.js'
import { resolveSignInLook } from './modules/branding/signIn/options.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'
@@ -200,6 +204,8 @@ export const iapl = (options: IaplOptions): Plugin => {
let twoFactorCollection: null | string = null
/** Set when the committed admin import map lacks the 2FA view wrapper (production). */
let staleImportMap: null | string = null
/** `whiteLabel.signIn.allScreens` asked for a provider the import map on disk lacks: left out, said in the log. */
let staleSignInLook: null | string = null
/** This config's entry in the staff registry until a Payload instance takes it over. */
const staffToken = {}
/**
@@ -525,7 +531,10 @@ export const iapl = (options: IaplOptions): Plugin => {
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 } : {}) }
// The sign-in look (on by default with whiteLabel; `signIn: false` keeps Payload's screens). The logo
// component and the 2FA wrapper print the panel: both are in the import map of every site already.
const look = resolveSignInLook(wl)
const logoProps = { ...serverProps, ...(wl.logoField ? { imageField: wl.logoField } : {}), ...(look ? { signIn: look.props } : {}) }
const iconProps = { ...serverProps, ...(wl.iconField ? { imageField: wl.iconField } : {}) }
// Vendor credit ("Technology support: Intecion.com") under the nav — on by
@@ -573,6 +582,44 @@ export const iapl = (options: IaplOptions): Plugin => {
? { meta: { ...(config.admin?.meta ?? {}), titleSuffix: wl.titleSuffix } }
: {}),
}
if (look) {
// In front of the 2FA screens: IAPL's own wrapper gets the look (a project's own screens are left alone).
const views = (config.admin?.components?.views ?? {}) as Record<string, { Component?: unknown }>
const withLook = Object.fromEntries(
Object.entries(views).map(([key, view]) => {
const component = view?.Component as { path?: string; serverProps?: object } | undefined
return component && typeof component === 'object' && component.path === SAFE_TOTP_VIEW
? [key, { ...view, Component: { ...component, serverProps: { ...component.serverProps, iaplSignIn: look.props } } }]
: [key, view]
}),
)
if (Object.keys(withLook).length) {
config.admin = { ...config.admin, components: { ...config.admin?.components, views: withLook as never } }
}
// The language links of the panel: a public endpoint that writes Payload's own language cookie.
if (look.props.languages !== false) {
config.endpoints = [...(config.endpoints ?? []), buildAdminLanguageEndpoint()]
}
// Every other minimal screen (forgot / reset password, first user, logout): one provider, one new
// import-map entry — asked for with `allScreens`. A provider the import map lacks renders NOTHING,
// the whole panel included, so a production start checks the file on disk and leaves the provider
// out when it is not there: the login and 2FA screens keep the look, the log says what to run.
if (look.allScreens) {
const stale = process.env.NODE_ENV === 'production' ? await missingImportMapEntries(config, [SIGN_IN_LOOK]) : { file: null, missing: [] }
if (stale.missing.length) {
staleSignInLook = `${SIGN_IN_LOOK} was not found in ${stale.file}`
} else {
config.admin = {
...config.admin,
components: {
...config.admin?.components,
providers: [...(config.admin?.components?.providers ?? []), { path: SIGN_IN_LOOK, serverProps: { look: look.props } }],
},
}
}
}
}
}
// --- admin <head>: link previews + noindex (default on) ---
@@ -729,6 +776,13 @@ export const iapl = (options: IaplOptions): Plugin => {
: pluginGlobals
// The project's globalOverrides win (access, admin, hooks merged; a function = full control).
config.globals = [...(config.globals ?? []), ...applyGlobalOverrides(withRevalidate, options.globalOverrides)]
// The brand the sign-in screens show (name, logo, icon) is changed by admins only — with the sign-in look,
// unless the project says `brandAccess: 'editor'`; without the look only when it says `'admin'`.
const brandWl = options.whiteLabel === true ? {} : options.whiteLabel
if (brandWl && (brandWl.brandAccess === 'admin' || (brandWl.brandAccess !== 'editor' && resolveSignInLook(brandWl)))) {
const wl = brandWl
config.globals = lockBrandFields(config.globals, wl.settingsSlug ?? 'site-settings', [wl.nameField ?? 'siteName', wl.logoField ?? 'logo', wl.iconField ?? 'favicon'])
}
// A new site name refreshes the panel's link preview texts.
if (adminMeta) {
@@ -958,6 +1012,12 @@ export const iapl = (options: IaplOptions): Plugin => {
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 (staleSignInLook) {
payload.logger.error(
`[iapl] The sign-in look covers only the login and 2FA screens: ${staleSignInLook}. Run "pnpm payload generate:importmap", ` +
'commit importMap.js, rebuild and redeploy (docs/white-label.md "Every sign-in screen").',
)
}
if (staleImportMap) {
payload.logger.error(
`[iapl] The admin import map may be out of date: ${staleImportMap}. If the 2FA setup and verify screens are ` +
+20
View File
@@ -1,5 +1,7 @@
import type { CollectionSlug, Field, PayloadComponent, PayloadRequest, Plugin } from 'payload'
import type { SignInLookOptions } from './modules/branding/signIn/options.js'
/**
* Factory shape of @clocklimited/payload-2fa's `payloadTotp` export — injected
* so the plugin never imports the optional peer itself. `collection` is
@@ -443,6 +445,14 @@ export type IaplOptions = {
*/
whiteLabel?:
| {
/**
* Who may change the brand the sign-in screens show (the name, logo and
* icon fields of Site settings). Default with the sign-in look: `'admin'`
* (field-level access, admins only; no schema change). `'editor'`: whoever
* may edit Site settings, as before 1.17.1. With `signIn: false` the default
* is `'editor'`.
*/
brandAccess?: 'admin' | 'editor'
/**
* Vendor credit ("Technology support: Intecion.com") at the bottom of the
* admin nav. Default on; `false` hides it, or override text/url.
@@ -469,6 +479,16 @@ export type IaplOptions = {
nameField?: string
/** SiteSettings global slug. Default 'site-settings'. */
settingsSlug?: string
/**
* The look of the panel's sign-in screens: a dark panel with the client's
* logo (or the site's name) beside the form, in both themes and on a phone.
* On by default with `whiteLabel`: the login screen and the 2FA screens get
* it through components every white-label site already has in its import
* map. `{ allScreens: true }` adds one provider (one new import-map entry)
* and covers forgot / reset password, create first user and logout too.
* `false` keeps Payload's own screens. See docs/white-label.md.
*/
signIn?: boolean | SignInLookOptions
/** Static browser-tab title suffix (e.g. ' · Acme Admin'). */
titleSuffix?: string
}