Sign-in look: the client's logo or the site's name on a dark panel beside the form (whiteLabel.signIn)
On by default with whiteLabel. The login screen and the 2FA screens get the look through AdminLogo and SafeTotpView, which every site already has in its import map: an upgrade needs no edit. allScreens adds one provider (SignInLook) for forgot / reset password, first user and logout; a production start leaves it out when the import map on disk lacks it. Logo and name come from Site settings: no new field, no migration. Language links through GET /api/ipal/admin-language (Payload's own cookie, back to an admin path only). Options: accent, logoMadeFor, languages, svgLogo; whiteLabel.brandAccess 'admin'. The 2FA code boxes get names for screen readers. Reference site and starter: allScreens on. Docs, agent guide, skills, tests. Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
co-authored by
Claude Fable 5.2
parent
e821d52d19
commit
b6c91a3a11
@@ -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'
|
||||
|
||||
@@ -70,6 +70,28 @@ 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 {
|
||||
ADMIN_LANGUAGE_PATH,
|
||||
adminPathFromReferer,
|
||||
buildAdminLanguageEndpoint,
|
||||
fitLogo,
|
||||
isHexColour,
|
||||
isSvgUpload,
|
||||
LANGUAGE_NAMES,
|
||||
languageLinks,
|
||||
loadSignInBrand,
|
||||
SIGN_IN_LOGO_BOX,
|
||||
SIGN_IN_LOOK,
|
||||
SIGN_IN_NAME_MAX,
|
||||
SIGN_IN_STYLE_ID,
|
||||
signInCss,
|
||||
signInLogo,
|
||||
signInName,
|
||||
signInProviderActive,
|
||||
} from './modules/branding/signIn/index.js'
|
||||
export type { LanguageLink, 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,
|
||||
|
||||
@@ -9,6 +9,7 @@ export const securityTexts = defineTexts({
|
||||
twoFactorAlertLink: 'Open the user list',
|
||||
twoFactorAlertPending: 'Accounts without two-step verification: {{count}}. Until it is set up, such an account cannot use the panel.',
|
||||
twoFactorAlertTitle: 'Two-step verification',
|
||||
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?',
|
||||
@@ -33,6 +34,7 @@ export const securityTexts = defineTexts({
|
||||
twoFactorAlertLink: 'Otwórz listę użytkowników',
|
||||
twoFactorAlertPending: 'Konta bez weryfikacji dwuetapowej: {{count}}. Dopóki nie zostanie ustawiona, takie konto nie może korzystać z panelu.',
|
||||
twoFactorAlertTitle: 'Weryfikacja dwuetapowa',
|
||||
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ć?',
|
||||
|
||||
@@ -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',
|
||||
},
|
||||
})
|
||||
|
||||
@@ -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>
|
||||
)
|
||||
|
||||
@@ -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 (on a white plate unless it was made for dark grounds) 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.logoMadeFor !== 'dark'
|
||||
|
||||
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>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -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 `<img>`: 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<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 logo of an upload document, or null when there is nothing to show. */
|
||||
export function signInLogo(media: unknown, look: Pick<SignInLookProps, 'svgLogo'> = {}): 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<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: 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<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))
|
||||
}
|
||||
@@ -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, '')
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
export {
|
||||
ADMIN_LANGUAGE_PATH,
|
||||
fitLogo,
|
||||
isSvgUpload,
|
||||
LANGUAGE_NAMES,
|
||||
languageLinks,
|
||||
loadSignInBrand,
|
||||
SIGN_IN_LOGO_BOX,
|
||||
SIGN_IN_LOOK,
|
||||
SIGN_IN_NAME_MAX,
|
||||
signInLogo,
|
||||
signInName,
|
||||
signInProviderActive,
|
||||
} from './brand.js'
|
||||
export type { LanguageLink, 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,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
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`: no language links on the panel. Default: shown when the panel has more than one language. */
|
||||
languages?: false
|
||||
/** `'dark'`: the logo was made for dark grounds (a white logo) and gets no white plate. Default `'light'`. */
|
||||
logoMadeFor?: 'dark' | 'light'
|
||||
/** `false`: an SVG logo is not shown on the sign-in screens; the site's name is. Default: shown as a picture. */
|
||||
svgLogo?: false
|
||||
}
|
||||
|
||||
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.logoMadeFor === 'dark' ? { logoMadeFor: 'dark' as const } : {}),
|
||||
...(wl.nameField ? { nameField: wl.nameField } : {}),
|
||||
...(wl.settingsSlug ? { settingsSlug: wl.settingsSlug } : {}),
|
||||
...(signIn.svgLogo === false ? { svgLogo: false 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
|
||||
}
|
||||
@@ -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} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
+59
-1
@@ -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'
|
||||
@@ -197,6 +201,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 = {}
|
||||
/**
|
||||
@@ -522,7 +528,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
|
||||
@@ -570,6 +579,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) ---
|
||||
@@ -726,6 +773,11 @@ 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)]
|
||||
// `whiteLabel.brandAccess: 'admin'`: the brand the sign-in screens show is changed by admins only.
|
||||
if (options.whiteLabel && options.whiteLabel !== true && options.whiteLabel.brandAccess === 'admin') {
|
||||
const wl = options.whiteLabel
|
||||
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) {
|
||||
@@ -955,6 +1007,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 ` +
|
||||
|
||||
@@ -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,12 @@ export type IaplOptions = {
|
||||
*/
|
||||
whiteLabel?:
|
||||
| {
|
||||
/**
|
||||
* Who may change the brand the sign-in screens show (the name, logo and
|
||||
* icon fields of Site settings). Default `'editor'`: whoever may edit Site
|
||||
* settings, as before. `'admin'`: field-level access, admins only.
|
||||
*/
|
||||
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 +477,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
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user