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
@@ -1171,6 +1171,7 @@ project → **plugin gap**, not a copy.
|
||||
| Mail | `email: mailAdapter()` + `serverURL` — mail works with no other setup, through the Intecion mail service; SMTP in the panel only when the client asks; your own mail: `payload.sendEmail` (`withMailKind` when it is account mail); never a second transport in the project. §7.2 | email.md |
|
||||
| Env validation, health | `assertEnv(iaplEnvRules({…}))` (`/env`), `healthRoute` | env.md |
|
||||
| 2FA, white-label, headers | `twoFactor: { issuer, plugin: payloadTotp }`, `whiteLabel`, `buildSecurityHeaders` | security.md, white-label.md |
|
||||
| Sign-in screens (login, forgot / reset password, first user, logout, the 2FA screens): a dark panel with the client's logo or the site's name beside the form, language links, both themes, phone | on with `whiteLabel` (`signIn`); a NEW site: `whiteLabel: { signIn: { allScreens: true } }` + `pnpm payload generate:importmap` (adds the provider `SignInLook`; without it only login and the 2FA screens get the look, through `AdminLogo` / `SafeTotpView`). Logo and name come from Site settings (no env var, no new field, no migration). Options: `accent` (hex), `logoMadeFor: 'dark'`, `languages: false`, `svgLogo: false`; `signIn: false` = Payload's screens; `brandAccess: 'admin'` = only admins change name / logo / icon. Never build a login page, a custom `graphics.Logo` or login CSS by hand. Check: `curl -s $URL/admin/login \| grep -c iapl-signin__label` ≥ 1; `curl -si "$URL/api/ipal/admin-language?lng=xx"` → 400 | white-label.md → "The sign-in screens" |
|
||||
| Panel link preview + noindex (site name, description, preview image, technology support credit) | on by default (`adminMeta`, `agency`) — do not hand-write `admin.meta` for it; override single keys in `admin.meta` or `adminMeta: { … }` | white-label.md |
|
||||
| Rate limit (forms, MCP, search) | built in; IP from `IAPL_IP_HEADER`; several instances → `setRateLimitStore` | forms.md |
|
||||
|
||||
|
||||
@@ -1171,6 +1171,7 @@ Rules: AGENT.md §8a.
|
||||
| `e2e/mail-relay-fixture.ts` | test fixture, on only with E2E_MAIL_RELAY_URL: points the mail service's client at the stand-in the spec starts; never in a real site (a real site names no address) (below) |
|
||||
| `e2e/mail-relay-setup.ts` | for the mail-service spec: empties the SMTP fields and the stored token, so the next e-mail enrols and goes through the mail service (local database only) (below) |
|
||||
| `e2e/mail-relay.spec.ts` | the mail service on a built site: the state block in the panel, the first e-mail through the public confirm route, no token in anything the browser receives |
|
||||
| `e2e/sign-in-look.spec.ts` | browser test of the sign-in look (whiteLabel.signIn): the panel comes with the form, sits above it on a phone in both themes, is on forgot / reset / logout too, the language links work, the 2FA code screen keeps its boxes (now named) |
|
||||
| `e2e/smoke.spec.ts` | the smoke tests every release must pass: pages, showcase, forms (also a file sent by e-mail), sitemap, SEO/GEO, headers, consent, 2FA |
|
||||
| `e2e/smtp-sink.ts` | a local mail sink for the smoke tests: reads what the site really sent (recipients, attachments) |
|
||||
| `e2e/totp.ts` | RFC 6238 code generator for the 2FA sign-in in the smoke test, and the address of the second test admin (below) |
|
||||
|
||||
@@ -64,6 +64,13 @@ description: Complete map of everything @intecion/ipal-kit provides — every ia
|
||||
| `whiteLabel.logoField` / `iconField` / `nameField` | `'logo'` / `'favicon'` / `'siteName'` | fields in Site settings | any upload/text field |
|
||||
| `whiteLabel.titleSuffix` | none | `admin.meta.titleSuffix` (tab title) | — |
|
||||
| `whiteLabel.credit` | on | `IntecionCredit` in `afterLogin` and `afterNavLinks`: "Technology support: Intecion.com" (en/pl, from `agency`) | `false`; `{ text, url }` overrides |
|
||||
| `whiteLabel.signIn` | on (with `whiteLabel`) | the sign-in look: a dark panel with the client's logo (Site settings → Logo, on a white plate) or the site's name beside the form, "Administration panel", language links; both themes, a band above the form on a phone. Login, the 2FA screens and e-mail verification get it through `AdminLogo` / `SafeTotpView` (already in the import map: an upgrade needs no edit). No env var, no new field, no migration | `false` = Payload's own screens |
|
||||
| `whiteLabel.signIn.allScreens` | `false` (the starter writes `true`) | the look on forgot / reset password, create first user, logout and "unauthorized" too: adds the provider `SignInLook` — ONE new import-map entry, run `pnpm payload generate:importmap`. Production start: when `importMap.js` on disk lacks it, the provider is left out and the log says `[iapl] The sign-in look covers only the login and 2FA screens …` | `true` |
|
||||
| `whiteLabel.signIn.accent` | `#0070c0` | hex colour of the button, links and focus ring (anything that is not a hex colour is ignored); or CSS variables `--iapl-signin-*` on `:root` in the admin's `custom.scss` | `'#0b6e4f'` |
|
||||
| `whiteLabel.signIn.logoMadeFor` | `'light'` | `'dark'` = a logo drawn for dark grounds: no white plate | — |
|
||||
| `whiteLabel.signIn.languages` | shown with 2+ admin languages | links on the panel; `GET /api/ipal/admin-language?lng=<code>` writes Payload's `payload-lng` cookie and redirects (303) back to the admin path of the `Referer`; unknown language → 400 | `false` = no links, no endpoint |
|
||||
| `whiteLabel.signIn.svgLogo` | shown as a picture (`<img>` runs no script) | `false` = an SVG logo is not shown on the sign-in screens; the site's name is | — |
|
||||
| `whiteLabel.brandAccess` | `'editor'` (whoever edits Site settings) | `'admin'` = field-level `access.update` on the name, logo and icon fields: only admins change what the sign-in screens show. No schema change | — |
|
||||
| `agency` | `{ name: 'Intecion.com', url: 'https://intecion.com' }` | the credit line, the panel's link description and preview image | `{ name, url }` = another agency; `false` = none anywhere |
|
||||
| `adminMeta` | on (with or without `whiteLabel`) | panel `<head>`: `robots` noindex/nofollow, `titleSuffix` "— <site> \| Panel", `og:site_name` + description from Site settings (refreshed on save), `og:image` `GET /api/ipal/admin-og` (1200×630 from the logo or name), icon `GET /api/ipal/admin-icon` (favicon or initials); no import map step | `false` = Payload defaults; `{ robots, titleSuffix, description, image, icons, language }` (each `false` or your value; `{site}`, `{agency}` placeholders); your own `admin.meta` keys always win. Check: `curl -s $URL/admin/login \| grep -E 'og:\|robots'` (white-label.md) |
|
||||
| `pages` | none | Site settings → **System pages** (page roles) and **Maintenance** tabs | omit → neither tab |
|
||||
@@ -153,6 +160,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ia
|
||||
|---|---|---|
|
||||
| `AdminLogo`, `AdminIcon` | `graphics.Logo/Icon` | `whiteLabel` |
|
||||
| `IntecionCredit` | `afterLogin`, `afterNavLinks` | `whiteLabel` and `credit !== false` |
|
||||
| `SignInLook` | `providers` (last) | `whiteLabel.signIn.allScreens` — the only entry the sign-in look adds; without it nothing new is needed |
|
||||
| `StatsNavLink`, `StatsView` (`views.ipalStats`, `/stats`), `StatsWidget` (`beforeDashboard`) | nav, view, dashboard | `stats` (`dashboard: false` without the widget) |
|
||||
| `CookieScanButton` | `beforeListTable` of `cookie-review` (with **Check site** when `crawl` is on) | `cookieScanner` |
|
||||
| `CookieReviewTab`, `CookieSiteCheckTab` | `ui` fields in the `cookie-settings` tabs | `cookieScanner` with `adminLayout !== 'separate'` (Site check: `crawl`) |
|
||||
|
||||
@@ -38,6 +38,8 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT
|
||||
| `TwoFactorResetButton` | `@intecion/ipal-kit/admin` | Client button inside `TwoFactorStatusField`: `POST /api/ipal/two-factor/reset` `{ userId }`, then reloads the view. Props `{ kind: 'reset' \| 'reopen', userId }`. |
|
||||
| `TwoFactorAlert` | `@intecion/ipal-kit/admin` | Server component on the dashboard (`beforeDashboard`), administrators only: accounts without two-step verification and how many are blocked. Wired by the plugin with `twoFactor.requireSetup`; renders nothing when every account has it. |
|
||||
| `IntecionCredit` | `@intecion/ipal-kit/admin` | The line "Technology support: Intecion.com" (admin language; `agency` prop = the name) below the nav and below the login form (`variant: 'nav' \| 'login'`). Injected by the plugin with `whiteLabel`; turn off: `whiteLabel: { credit: false }` or `agency: false`. |
|
||||
| `SignInPanel` | `@intecion/ipal-kit/admin` | Server component: the dark sign-in panel with its stylesheet (`<style>` deduplicated by React) — label, the logo or the site's name from Site settings as a link to the site, language links. Props `look` (`SignInLookProps`) plus what Payload injects (`payload`, `i18n`, `locale`, `user`); `SignInPanelProps`. Hidden by its own CSS on any page that is not Payload's minimal template. `AdminLogo` (prop `signIn`) and `SafeTotpView` (prop `iaplSignIn`) render it when the provider does not. |
|
||||
| `SignInLook` | `@intecion/ipal-kit/admin` | Admin provider (`admin.components.providers`, `serverProps: { look }`; `SignInLookProviderProps`): prints `SignInPanel` on every admin page so that every minimal screen has it. Registered by `whiteLabel: { signIn: { allScreens: true } }`. |
|
||||
| `buildAdminMeta({ agency, apiRoute?, defaultLocale?, meta?, options? })` | `@intecion/ipal-kit` | The `adminMeta` step: static panel meta (robots, preview image, icon) without overwriting keys in `meta`; returns `{ meta, resolved }` |
|
||||
| `adminMetaForSite(site, resolved)`, `syncAdminMeta(payload, resolved, { nameField?, settingsSlug? })` | `@intecion/ipal-kit` | Site-name parts (suffix, description, siteName); `syncAdminMeta` writes them into the live config (onInit + Site settings afterChange, never throws) |
|
||||
| `buildAdminImageEndpoints(resolved, { settingsSlug?, nameField?, logoField?, iconField? })` | `@intecion/ipal-kit` | `GET /api/ipal/admin-og` (1200×630 PNG via `next/og`) and `GET /api/ipal/admin-icon` (the favicon itself, or initials) — already added by `adminMeta` |
|
||||
@@ -623,6 +625,11 @@ Server only (`pnpm payload run`); never import it from client code, the Payload
|
||||
| `countAccountsWithoutTotp(payload, collection, setupWindowMs?)` | `@intecion/ipal-kit` | `{ without, blocked }` — accounts of the 2FA collection without TOTP, and how many are past their window. |
|
||||
| `resolveRequireSetup(option)`, `strictExempt(fn)`, `SETUP_FROM_FIELD`, `DEFAULT_SETUP_WINDOW_HOURS` | `@intecion/ipal-kit` | `twoFactor.requireSetup` → `{ requireSetup, setupWindowMs, exempt? }` as the guard reads it (throws on a `windowHours` that is not a number ≥ 0 or `false`, and on an `async` `exempt`); the wrapper that makes an `exempt` function answer `true` only for exactly `true`; the field name `'totpSetupFrom'`; `72`. |
|
||||
| `fetchPublicImage(url, base)`, `publicImageDataUri(url, base)`, `rasterImageType(bytes)`, `siteOrigin(serverURL)`, `PUBLIC_IMAGE_MAX_BYTES` | `@intecion/ipal-kit` | An image fetched the way an anonymous visitor gets it (no cookies; http(s) only; `image/*`; at most 512 KB, reading stops at the limit) as `{ bytes, type }` or a `data:` address, else `null`. Used for the logo and icon on the 2FA screens. `rasterImageType(bytes)` → the media type of a bitmap by its first bytes (PNG, JPEG, GIF, WebP, ICO, AVIF) or `null` — never trust a claimed type before answering a file's bytes from the site's origin; an SVG gives `null`. |
|
||||
| `resolveSignInLook(whiteLabel)` | `@intecion/ipal-kit` | `whiteLabel` option → `null` (white-label or `signIn` off) or `{ allScreens, props }` (`ResolvedSignInLook`; `props` = `SignInLookProps`, the plain values the components get: `accent`, `imageField`, `inlineImages`, `languages`, `logoMadeFor`, `nameField`, `settingsSlug`, `svgLogo`). Option type: `SignInLookOptions`. |
|
||||
| `loadSignInBrand({ payload, look, locale?, user? })`, `signInName(value, locale?)`, `signInLogo(media, { svgLogo? })`, `fitLogo(width, height, box?)`, `isSvgUpload(media)` | `@intecion/ipal-kit` | What the sign-in panel shows: `{ name, logo }` (`SignInBrand`, `SignInLogo = { src, width?, height? }`) read from Site settings, never throwing; the name as one line of plain text (control characters out, cut at `SIGN_IN_NAME_MAX` = 80); the logo of an upload document (only an `http(s)` or site-relative address; `null` for SVG with `svgLogo: false`), fitted into `SIGN_IN_LOGO_BOX` (240 × 72) without enlarging. A session that owes its 2FA code gets the picture inlined (`publicImageDataUri`) or no logo. |
|
||||
| `signInCss({ accent? })`, `isHexColour(value)`, `SIGN_IN_STYLE_ID` | `@intecion/ipal-kit` | The stylesheet of the sign-in look as a string (no `url()`, no font, no other host; every rule needs `.iapl-signin` on the page), the hex check `accent` must pass, and the `href` of its `<style>` (`'iapl-sign-in'`). |
|
||||
| `languageLinks(config, current)`, `LANGUAGE_NAMES`, `buildAdminLanguageEndpoint()`, `adminPathFromReferer(referer, adminRoute)`, `ADMIN_LANGUAGE_PATH` | `@intecion/ipal-kit` | The panel's languages as links (`LanguageLink[]`: `{ code, name, current, href }`; empty with one language; names in their own language, else the code); the public endpoint `GET /api/ipal/admin-language?lng=` (`'/ipal/admin-language'`) that writes `<cookiePrefix>-lng` for a supported language (else 400) and answers 303 to a path inside the admin route taken from the `Referer` (anything else → the admin root, never another host). |
|
||||
| `signInProviderActive(payload)`, `SIGN_IN_LOOK` | `@intecion/ipal-kit` | Whether the provider `'@intecion/ipal-kit/admin#SignInLook'` is in the config AND in the running import map — `AdminLogo` and `SafeTotpView` print the panel themselves only when it is not. |
|
||||
| `UPLOAD_SECURITY_HEADERS` | `@intecion/ipal-kit` | The two headers of `buildUploadSecurityHeaders` (`Content-Security-Policy: default-src 'none'; … sandbox`, `X-Content-Type-Options: nosniff`) for a route of your own that returns an uploaded file's bytes from the site's origin. In a Next project a site-wide `headers()` rule with the same key overrides a header the route sets itself: add a `headers()` rule for the path after the site-wide one (as `buildUploadSecurityHeaders({ collections, adminIcon })` does for the upload routes and `/api/ipal/admin-icon`), and never answer with an SVG. |
|
||||
| `twoFactorSetupState(req)`, `twoFactorSetupDeadline(req)` | `@intecion/ipal-kit` | Where an account stands with TOTP setup, from `{ payload, user }`: `'set-up'`, `'open'` (may set it up now), `'closed'` (the setup window has passed: blocked until an admin reopens it), `'exempt'` (`requireSetup.exempt`, or `requireSetup: false`), `'not-applicable'` (no user, another collection, 2FA off); and the moment setup closes (`Date`, or `null` without a window). Types: `TwoFactorSetupState`, `RequireSetupOptions`. |
|
||||
| `requireSecondFactor(access?)` | `@intecion/ipal-kit` | Wraps an `Access` function: refused while the second factor is owed, otherwise the function itself (Payload's default "logged in" when none). iapl applies it to every collection and global in the config, and to those added by plugins listed after it (in `onInit` and at the start of the first request, so also after a dev hot reload); use it for access functions that are not part of the config. Per-entity opt-out: `custom.ipal.secondFactor: false \| { read: false }` or the package's `custom.totp.disableAccessWrapper`. Wrapping twice is harmless. |
|
||||
|
||||
@@ -188,7 +188,7 @@ export default buildConfig({
|
||||
seo: { collections: ['pages'] },
|
||||
forms: { redirectRelationships: ['pages'] },
|
||||
twoFactor: { issuer: '<Client name>', plugin: payloadTotp },
|
||||
whiteLabel: true,
|
||||
whiteLabel: { signIn: { allScreens: true } }, // client's logo / name on every sign-in screen (white-label.md)
|
||||
indexNow: true,
|
||||
// consentLog is on by default (1.17.0): consent-records + POST /api/ipal/consent; `consentLog: false` turns it off.
|
||||
// Postgres / SQLite: pnpm payload migrate:create consent-log, applied in the same deploy.
|
||||
@@ -207,7 +207,7 @@ are never added to a new site. Local `.env` with `PAYLOAD_SECRET` ≥ 32 charact
|
||||
One language: one entry in `locales`, no `[locale]` folder (i18n.md).
|
||||
|
||||
**Check.** `pnpm payload generate:importmap` (whiteLabel adds admin components) and `pnpm generate:types` without
|
||||
errors (the import map lists `@intecion/ipal-kit/admin#TotpRedirectProvider` and `#SafeTotpView`); `pnpm dev`, `/admin`: first-user screen → after saving, TOTP setup is enforced (`/admin/setup-totp?back=%2Fadmin`, QR, no reloading);
|
||||
errors (the import map lists `@intecion/ipal-kit/admin#TotpRedirectProvider`, `#SafeTotpView` and `#SignInLook`); `pnpm dev`, `/admin`: first-user screen → after saving, TOTP setup is enforced (`/admin/setup-totp?back=%2Fadmin`, QR, no reloading);
|
||||
the panel shows Site settings, Site integrations, Cookies, Form messages, the Forms group, Consent records.
|
||||
`curl -s -o /dev/null -w '%{http_code}' -X POST localhost:3000/api/ipal/consent -H 'content-type: application/json'
|
||||
-d '{"id":"0123456789abcdef","version":1,"state":{"necessary":true,"functional":false,"analytics":false,"marketing":false}}'` → `201`.
|
||||
@@ -294,6 +294,12 @@ the panel shows Site settings, Site integrations, Cookies, Form messages, the Fo
|
||||
win; a function `(global) => global` takes over). Without `revalidatePath` global saves wait for the ISR window.
|
||||
- `whiteLabel: { credit: false, titleSuffix, settingsSlug, logoField, … }`; with `whiteLabel` the plugin overrides
|
||||
`graphics.Logo/Icon` — your own graphics only without it.
|
||||
- Sign-in screens (`whiteLabel.signIn`, on): a dark panel with the client's logo or the site's name beside the
|
||||
form; the logo and name are Site settings fields (no env var, no migration). `allScreens: true` (in the config
|
||||
above) adds the provider `SignInLook` to the import map and covers forgot / reset password, first user and
|
||||
logout. `accent: '#hex'`, `logoMadeFor: 'dark'` (a white logo), `languages: false`, `svgLogo: false`;
|
||||
`signIn: false` = Payload's screens; `brandAccess: 'admin'` = only admins change name, logo and icon.
|
||||
Check: `/admin/login` and `/admin/forgot` show the panel, also at a phone width; do not write login CSS by hand.
|
||||
- Panel link preview (`adminMeta`, on): noindex/nofollow, "— <site> | Panel" suffix, site name, description and
|
||||
preview image (`/api/ipal/admin-og`) from Site settings; `agency` names who supports the technology (default
|
||||
Intecion.com). Turn off: `adminMeta: false`, `agency: false`; your own `admin.meta` keys win. Check:
|
||||
|
||||
@@ -648,6 +648,22 @@ PROGRAMISTA §6, items 73–75; email.md; AGENT.md §7.2) — nothing to run; re
|
||||
**Send test e-mail** names the transport you expect; a form submission arrives. **The service is live at
|
||||
`https://webservices.intecion.net/mail`; while the service runs with enrolment "pending" (from its launch until Intecion switches to open enrolment), every new site waits for approval — keep SMTP until it is approved, or `relay: false`.**
|
||||
|
||||
**→ 1.18.0, the sign-in look (CHANGELOG 1.18.0; white-label.md → "The sign-in screens") — nothing is required:**
|
||||
1. **Sites with `whiteLabel`:** after the update the login screen and the 2FA screens (code, setup) have the new
|
||||
look — a dark panel with the client's logo or the site's name beside the form. No edit, no
|
||||
`generate:importmap`, no migration: the look comes through `AdminLogo` and `SafeTotpView`, which the site's
|
||||
import map already has. **Check:** open `/admin/login` on a desktop and at a phone width, in both themes; sign
|
||||
in through 2FA. A logo that looks wrong on the white plate (a white logo): `signIn: { logoMadeFor: 'dark' }`.
|
||||
2. **Tell the owner the sign-in page looks different** and ask whether to keep it. No: `whiteLabel: { signIn: false }`
|
||||
— Payload's screens with the plain logo, as before (record it in AGENTS.md → Project decisions).
|
||||
3. **Recommended, one edit:** `whiteLabel: { signIn: { allScreens: true } }`, `pnpm payload generate:importmap`,
|
||||
commit `importMap.js` — forgot / reset password, create first user and logout get the same look. Forgetting
|
||||
the import map does not break the panel: at a production start the provider is left out and the log says so.
|
||||
4. **Project CSS for the login screen** (`custom.scss` rules on `.login`, `.template-minimal`, a hand-made
|
||||
`graphics.Logo`): look at the screens after the update; the look's own rules win over Payload's layer but not
|
||||
over the project's later ones. Restyle with the `--iapl-signin-*` variables instead.
|
||||
5. Sites **without** `whiteLabel`: nothing changes.
|
||||
|
||||
## 2. Inventory (no code changes)
|
||||
**What changed for projects** between your old and new plugin version is exactly the reference site's diff —
|
||||
`git diff v<old> v<new> -- reference/` in the IAPL repo (or the two `docs/agent/reference-site/INDEX.md` files):
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
# The panel's sign-in screens: design notes and screenshots
|
||||
|
||||
Design record of `whiteLabel.signIn` (the user-facing page is [white-label.md](../../white-label.md) → "The sign-in
|
||||
screens"). The goal: IAPL's sign-in looks like IAWL's (the WordPress sibling), and both have a place for the client's
|
||||
logo.
|
||||
|
||||
## Files here
|
||||
|
||||
Made with `node scripts/login-page-shots.mjs` (headless Chromium, 1280 × 800 and 390 × 844) against the reference
|
||||
site; `after-*` from a production build with `signIn: { allScreens: true }`, `before-*` from main (1.17.0).
|
||||
|
||||
| Files | What |
|
||||
|---|---|
|
||||
| `before-*.png` | IAPL 1.17.0: login (light, dark, phone, Polish, wrong password), forgot password, 2FA code, 2FA setup; `-logo` = with a logo set |
|
||||
| `after-*-name.png` | the new look with no logo set: the site's name |
|
||||
| `after-*-logo.png` | the new look with a logo (`placeholder-logo.png`, drawn for these pictures) |
|
||||
| `iawl-*.png` | IAWL's sign-in page, copied from its repository (`docs/reviews/white-label/`, made 2026-11-24). Two later changes are not in them: the languages are plain links now (no drop-down with a button), and messages are square boxes with a straight bar |
|
||||
| `placeholder-logo*.png` | the placeholder logos (dark text; white text for `logoMadeFor: 'dark'`) |
|
||||
|
||||
Screens: `login-{light,dark,phone,phone-dark,pl}`, `login-error-{light,phone}`, `forgot-{light,dark,phone}`,
|
||||
`2fa-code-{light,dark,phone}`, `2fa-setup-{light,dark,phone}`. Create-first-user needs a database without users
|
||||
(`--only=first-user`); it uses the same template and was checked by hand, not photographed.
|
||||
|
||||
## What defines IAWL's sign-in page (read from `plugin/assets/sign-in/sign-in.css`, `SignInLook.php`, `Logo.php`, `LanguageSwitcher.php`)
|
||||
|
||||
- **Layout:** two columns, 5 : 6. Left: a dark panel (`#060606`) inset 10 px from the window's edge, 20 px corners,
|
||||
a faint grid (3.5 × 2.5 rem cells, 4 % white lines) and two blue glows (`rgb(0 158 246)`, 22–24 %). Right: a white
|
||||
page with the form, 28 rem wide, centred in its column. No card around the form.
|
||||
- **On the panel**, at the bottom: a label "ADMINISTRATION PANEL" (mono, 14 px, 600, upper case, 0.05 em tracking,
|
||||
`#b2b2b2`, a 5 px blue square before it), then the logo on a white plate (12 px corners, 16 × 20 px padding; the
|
||||
logo fits 240 × 72) or the site's name as text (weight 500, −0.03 em, clamp 36–60 px). Both link to the site.
|
||||
- **Form:** labels above fields, 48 px fields with a 1 px `#80868f` border and 6 px corners, a full-width 50 px blue
|
||||
button (`#0070c0`, hover `#005a9e`, white text), links `#006bb8` underlined, focus ring 2 px `#017bd0`.
|
||||
- **Under the form:** links (lost password, back to the site), the languages as links, a hairline, and the credit
|
||||
"Technology support: Intecion.com" (13 px, muted, centred).
|
||||
- **Messages:** boxes above the form with a 4 px bar on the leading edge: red for errors, green for success.
|
||||
- **Phone (≤ 52 rem):** the panel is a band above the form, bottom corners rounded, the logo 192 × 56.
|
||||
- **Theme:** none: the panel is always dark, the form always light. **Fonts:** Outfit / Inter / Roboto Mono from
|
||||
local files, part of the credit (off with `credit => false`). **Script:** one optional file, the grid light that
|
||||
follows the mouse.
|
||||
- **States:** WordPress's own (errors, lost password, reset with the strength meter, logged out, interim frame);
|
||||
IAWL changes the look only.
|
||||
|
||||
## How IAPL maps it
|
||||
|
||||
| Element | IAPL | Same as IAWL? |
|
||||
|---|---|---|
|
||||
| Split, panel inset and corners, grid, glows, colours | the same numbers (`css.ts`) | yes |
|
||||
| Label, plate, logo box, name as text, link to the site | the same | yes |
|
||||
| Button, link, focus and border colours; field and button heights; 28 rem column | the same | yes |
|
||||
| Phone band at 52 rem | the same | yes |
|
||||
| Languages | links, **on the panel** (top corner; under the brand on a phone), because the form's markup is Payload's and differs per screen | place differs |
|
||||
| Credit line | under the login form, hairline above (login only, as before) | IAWL: every screen |
|
||||
| Dark theme | the form's side follows the admin theme; the panel stays dark | IAWL has no dark form |
|
||||
| Fonts | the admin's own font stack and the system's mono; no font file | differs (no extra request before sign-in) |
|
||||
| Grid light (script) | not built: no script on the sign-in page | differs |
|
||||
| Messages | Payload's own toasts and field errors, unchanged | differs |
|
||||
| Field look | Payload's fields with the shared border colour and height | close |
|
||||
|
||||
## Decisions
|
||||
|
||||
1. **Carried by components every site already has.** A new admin component needs a new import-map entry, and a
|
||||
provider missing from the map blanks the whole panel. So `AdminLogo` prints the panel on the login screen and
|
||||
`SafeTotpView` in front of the 2FA screens; only `allScreens` adds a provider (`SignInLook`), guarded at start.
|
||||
2. **The panel is one self-contained element**, fixed on a desktop and in the flow on a phone, hidden by its own
|
||||
CSS off the minimal template. It therefore works wherever it is printed (inside the login form's wrapper, before
|
||||
a 2FA view, at the top of the body).
|
||||
3. **No new stored data.** Logo and name are Site settings fields that exist since 1.0: no migration. The plate
|
||||
switch (`logoMadeFor`) and the accent are code options; putting them in the panel would add columns on SQL.
|
||||
4. **Payload draws its admin screens in the browser** (the server's HTML body is empty until React runs), so "no
|
||||
flash" means: the panel, its stylesheet and the form appear in the same step. The e2e spec checks that the
|
||||
form's template is never in the page without them.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Changelog draft — the sign-in look (for the next minor, written as 1.18.0)
|
||||
|
||||
To be placed in `docs/CHANGELOG.md` by the release; the version number is the integration session's call.
|
||||
|
||||
## Read before upgrading
|
||||
|
||||
**The panel's sign-in page looks different on every site with `whiteLabel`.** After the update the login screen and
|
||||
the 2FA screens (code, setup) show a dark panel with the client's logo — or the site's name — beside the form, the
|
||||
look IAPL now shares with IAWL. No edit, no `generate:importmap`, no migration, no new env var.
|
||||
Keep Payload's screens: `whiteLabel: { signIn: false }`. Sites without `whiteLabel`: nothing changes.
|
||||
|
||||
## Added
|
||||
|
||||
- **Sign-in look (`whiteLabel.signIn`, on with `whiteLabel`).** A dark panel with the label "Administration panel",
|
||||
the client's logo on a white plate (Site settings → Logo) or the site's name, and the panel's languages as links;
|
||||
the form beside it, in both admin themes; a band above the form on a phone. Logo and name come from Site settings:
|
||||
no env var, **no new field, no schema change** (MongoDB, Postgres, SQLite alike). With nothing set the panel shows
|
||||
the label and the site's host — no Payload or Intecion mark.
|
||||
- **`signIn: { allScreens: true }`** — the same look on forgot / reset password, create first user, logout and
|
||||
"unauthorized". Adds the provider `SignInLook` (one import-map entry: `pnpm payload generate:importmap`). The
|
||||
project starter writes it for new sites. A production start that does not find the entry in `importMap.js`
|
||||
leaves the provider out and logs what to run; the panel keeps working.
|
||||
- **Options:** `signIn.accent` (hex colour of the button, links and focus ring), `signIn.logoMadeFor: 'dark'` (a
|
||||
white logo: no plate), `signIn.languages: false`, `signIn.svgLogo: false` (an SVG logo is not shown on the sign-in
|
||||
screens), `whiteLabel.brandAccess: 'admin'` (only admins change the name, logo and icon in Site settings;
|
||||
field-level access, no schema change). CSS variables `--iapl-signin-*` for a project's `custom.scss`.
|
||||
- **Language links before sign-in:** `GET /api/ipal/admin-language?lng=<code>` writes Payload's language cookie for
|
||||
a supported language and returns to the admin page it was opened from (public; 400 for an unknown language;
|
||||
never redirects off the admin route). Registered only with the sign-in look and `languages !== false`.
|
||||
- **The 2FA code boxes have names** for screen readers ("Digit 2 of 6") and ask a phone for the numeric keyboard
|
||||
(with the sign-in look).
|
||||
- Exports: `SignInPanel`, `SignInLook` (`/admin`); `resolveSignInLook`, `loadSignInBrand`, `signInLogo`,
|
||||
`signInName`, `fitLogo`, `isSvgUpload`, `languageLinks`, `LANGUAGE_NAMES`, `signInCss`, `isHexColour`,
|
||||
`signInProviderActive`, `buildAdminLanguageEndpoint`, `adminPathFromReferer`, `SIGN_IN_LOOK`, `SIGN_IN_STYLE_ID`,
|
||||
`SIGN_IN_LOGO_BOX`, `SIGN_IN_NAME_MAX`, `ADMIN_LANGUAGE_PATH` and their types.
|
||||
|
||||
## Changed
|
||||
|
||||
- `AdminLogo` prints the sign-in panel when the plugin gives it `signIn` (the default with `whiteLabel`); wired by
|
||||
hand without that prop it is the plain logo as before. The logo on the login screen is now shown inside
|
||||
240 × 72 px (it was up to 420 × 120).
|
||||
- The credit line under the login form: full-strength muted colour and a hairline above it (it was 60 % opacity).
|
||||
- The reference site and the starter use `whiteLabel: { signIn: { allScreens: true } }`.
|
||||
|
||||
## Requires project changes
|
||||
|
||||
None. Recommended: `allScreens` (one config line, regenerate the import map). A project with its own CSS for the
|
||||
login screen looks at the result after the update.
|
||||
+125
-9
@@ -1,6 +1,6 @@
|
||||
# white-label — admin panel branding from the admin panel
|
||||
|
||||
The admin panel shows the **client's brand** (logo + name) on the login screen and in
|
||||
The admin panel shows the **client's brand** (logo + name) on the sign-in screens and in
|
||||
the navigation, taken from **SiteSettings** — i.e. set by the editor in the admin panel,
|
||||
not hard-coded. Each client logs in to "their own" panel.
|
||||
|
||||
@@ -45,6 +45,8 @@ whiteLabel: {
|
||||
| `iconField` | `'favicon'` | `graphics.Icon` → `AdminIcon` (max 28×28 px) |
|
||||
| `titleSuffix` | none (`adminMeta` builds one from the site name) | static `admin.meta.titleSuffix`, wins over `adminMeta` |
|
||||
| `credit` | `true` | `false` or `{ text?, url? }` |
|
||||
| `signIn` | `true` | the look of the sign-in screens (below); `false` = Payload's own screens; `{ allScreens, accent, logoMadeFor, languages, svgLogo }` |
|
||||
| `brandAccess` | `'editor'` | who may change the name, logo and icon fields: `'admin'` = admins only (field-level access, no schema change) |
|
||||
|
||||
The plugin overrides `admin.components.graphics.Logo` / `Icon` from the project config (its
|
||||
values win over yours); `afterLogin` / `afterNavLinks` are appended.
|
||||
@@ -109,12 +111,123 @@ image. The plugin now fills the panel's `<head>` from Site settings, **with or w
|
||||
`og:site_name` = the site name, `og:image` = `/api/ipal/admin-og`; open `$URL/api/ipal/admin-og` → the
|
||||
preview image; paste the link in Slack → the site's name and image.
|
||||
|
||||
## Logo on the login screen
|
||||
## The sign-in screens — `whiteLabel.signIn` (on by default with `whiteLabel`)
|
||||
|
||||
`AdminLogo` is the LARGE logo on the login screen (Payload uses `graphics.Icon` for
|
||||
the small icon in the navigation). It renders quite a bit larger (`maxHeight 120 / maxWidth
|
||||
420`), so the client's brand is clear at login. The small nav icon is `favicon`
|
||||
through `AdminIcon`.
|
||||
One look for every screen a person passes before the panel: **a dark panel with the client's logo — or the site's
|
||||
name — beside the form**, the same look as the WordPress sibling (IAWL). On a phone the panel is a band above the
|
||||
form. The panel is dark in both themes; the form's side follows the admin theme (light or dark).
|
||||
|
||||
| On the panel | From | When it is missing |
|
||||
|---|---|---|
|
||||
| Label "Administration panel" (pl: "Panel administracyjny") | the plugin's texts (`ipal:signInPanelLabel`) | — |
|
||||
| The client's logo, a link to the site | Site settings → **Logo** (`logoField`) | the site's name |
|
||||
| The site's name, a link to the site | Site settings → **Site name** (`nameField`) | the site's host, then nothing |
|
||||
| Languages of the panel, as links | `i18n.supportedLanguages` (IAPL turns on English and Polish) | hidden with one language |
|
||||
|
||||
**Nothing is set in `.env` or in code: the logo and the name are the two fields of Site settings the public site
|
||||
uses too.** No new field, collection or global — so **no migration on Postgres / SQLite** and no change for MongoDB.
|
||||
With nothing set, the panel shows the label and the site's host: no Intecion and no Payload mark is put on a
|
||||
client's sign-in page (the credit line under the form is separate: `credit: false`).
|
||||
|
||||
**The logo.** Shown inside 240 × 72 px (192 × 56 on a phone), never enlarged or cropped, with its `width` and
|
||||
`height` set (no layout shift). It stands **on a white plate**, so any ordinary logo works on the dark panel; a
|
||||
logo drawn for dark grounds (a white logo) sets `signIn: { logoMadeFor: 'dark' }` and the plate is left out.
|
||||
Recommended upload: PNG or WebP, 480 px wide or more, without empty margins.
|
||||
|
||||
### Which screens
|
||||
|
||||
| Screens | How they get the look | What the project does |
|
||||
|---|---|---|
|
||||
| Login; the 2FA code, 2FA setup and "2FA setup required" screens; e-mail verification | through `AdminLogo` and `SafeTotpView` — components **already in the import map** of every site with `whiteLabel` / 2FA | nothing: an upgrade needs no edit and no `generate:importmap` |
|
||||
| Forgot password, reset password, create first user, logout, "unauthorized" | one admin provider, `SignInLook` | `whiteLabel: { signIn: { allScreens: true } }`, then `pnpm payload generate:importmap` and commit the map |
|
||||
|
||||
```ts
|
||||
iapl({
|
||||
whiteLabel: { signIn: { allScreens: true } }, // the project starter writes this for new sites
|
||||
})
|
||||
```
|
||||
|
||||
**Every sign-in screen (`allScreens`).** It adds `@intecion/ipal-kit/admin#SignInLook` to `admin.components.providers`
|
||||
— the one new import-map entry of this feature, which is why it is not on by default: a site must upgrade without
|
||||
touching its map. A provider the map lacks would render nothing, the whole panel included, so in production the
|
||||
plugin looks for the entry in `importMap.js` on disk at start and **leaves the provider out when it is not there**:
|
||||
the login and 2FA screens keep the look, and the log says `[iapl] The sign-in look covers only the login and 2FA
|
||||
screens … Run "pnpm payload generate:importmap"`. Without `allScreens` the other screens are Payload's own.
|
||||
|
||||
### Options
|
||||
|
||||
| `signIn:` | Default | Meaning |
|
||||
|---|---|---|
|
||||
| `false` | — | Payload's own sign-in screens; `AdminLogo` is the plain logo, as before |
|
||||
| `allScreens` | `false` | the look on every sign-in screen (above) |
|
||||
| `accent` | the shared blue `#0070c0` | a hex colour for the button, the links and the focus ring; it carries white text, so check its contrast (4.5:1) |
|
||||
| `logoMadeFor` | `'light'` | `'dark'`: no white plate behind the logo |
|
||||
| `languages` | shown when the panel has 2+ languages | `false`: no language links, and no `/api/ipal/admin-language` endpoint |
|
||||
| `svgLogo` | shown (as a picture) | `false`: an SVG logo is not shown on the sign-in screens; the site's name is |
|
||||
|
||||
**Language links.** Plain links, no script: `GET /api/ipal/admin-language?lng=pl` writes Payload's own language
|
||||
cookie (`payload-lng`, one year) and sends the browser back to the admin page it came from. Public, because nobody
|
||||
is signed in yet; it accepts only a language the panel supports (else `400`) and returns only to a path inside the
|
||||
admin route (taken from the `Referer`; anything else → the admin root), so it cannot be used to send someone to
|
||||
another site.
|
||||
|
||||
### What a public page may show — the security rules
|
||||
|
||||
The sign-in page is open to anyone, so what reaches it is narrow on purpose:
|
||||
|
||||
- **Text:** the site's name only, as plain text (escaped; one line, at most 80 characters). No description, no
|
||||
rich text, no link an editor can write: the panel's only links are the site's own root and the language links.
|
||||
- **Pictures:** the logo as an `<img>` — a picture in `<img>` never runs script, an SVG included. `svgLogo: false`
|
||||
leaves SVG out anyway. Only an `http(s)` or site-relative address is used. The plugin serves **no new file** for
|
||||
it: the logo is the media file at its own address, with the media collection's own headers and cache rules. On
|
||||
the 2FA screens (the session is refused `media`) the server fetches it as an anonymous visitor would — images
|
||||
only, at most 512 KB — and inlines it; when that fails the name is shown (`inlineImages`, above).
|
||||
- **Who can change it:** whoever may edit Site settings — editors and admins by default, as for the public site's
|
||||
name and logo. `whiteLabel: { brandAccess: 'admin' }` makes the three brand fields (name, logo, icon)
|
||||
admin-only with field-level access; other Site settings stay with editors.
|
||||
- **Accounts:** the forms, their messages and their limits are Payload's and the 2FA package's own, untouched.
|
||||
The look adds no text that depends on an account, so nothing new says whether an account exists.
|
||||
- **The stylesheet** is inline, has no `url()`, no font file and no request to another host; `accent` is accepted
|
||||
only as a hex colour. No script is added to the login screen. On the 2FA screens one small client component
|
||||
gives the six code boxes a name for screen readers ("Digit 2 of 6") and the numeric keyboard; it changes
|
||||
attributes only.
|
||||
|
||||
### Accessibility
|
||||
|
||||
Label and name contrast on the panel ≥ 7:1; text, links and the button on the form's side ≥ 4.5:1 in both themes;
|
||||
a visible focus ring on every control; no animation except the button's colour change, and none with
|
||||
`prefers-reduced-motion`; Windows high-contrast keeps the panel's edge; no sideways scroll from 320 px; the logo's
|
||||
alternative text is the site's name; the language links are a `<nav>` named "Language" with the current one marked
|
||||
(`aria-current`). The stylesheet and the panel come in the page's own response and are put on the page in the same
|
||||
step as the form: no flash of Payload's plain screen and no layout shift.
|
||||
A browser without `:has()` (Firefox before 121) shows Payload's plain layout.
|
||||
|
||||
### Restyle it
|
||||
|
||||
Set the custom properties on `:root` in the admin's `custom.scss` (the defaults have no specificity):
|
||||
`--iapl-signin-primary`, `--iapl-signin-primary-hover`, `--iapl-signin-primary-text`, `--iapl-signin-link`,
|
||||
`--iapl-signin-focus`, `--iapl-signin-bg`, `--iapl-signin-text`, `--iapl-signin-muted`, `--iapl-signin-border`,
|
||||
`--iapl-signin-field-border`, `--iapl-signin-panel`, `--iapl-signin-panel-text`, `--iapl-signin-panel-label`,
|
||||
`--iapl-signin-panel-glow` (three numbers, `R G B`), `--iapl-signin-panel-radius`, `--iapl-signin-panel-inset`,
|
||||
`--iapl-signin-split` (the panel's share of the width), `--iapl-signin-radius`. Classes you may rely on:
|
||||
`iapl-signin` (with `iapl-signin--logo` or `iapl-signin--name`), `iapl-signin__label`, `iapl-signin__brand`
|
||||
(`--plate`, `--name`), `iapl-signin__languages`, `iapl-credit--login`.
|
||||
|
||||
### Your own screens, or none
|
||||
|
||||
- **Off:** `whiteLabel: { signIn: false }` — Payload's screens with the plain logo; nothing else changes.
|
||||
- **Your own logo in code:** set `admin.components.graphics.Logo` yourself and do not use `whiteLabel` (the plugin's
|
||||
`Logo` wins while `whiteLabel` is on); or keep `whiteLabel` and filter what Site settings holds.
|
||||
- **Your own panel:** `SignInPanel` (the panel with its stylesheet) and `SignInLook` (the provider) are exported
|
||||
from `@intecion/ipal-kit/admin`; wire them in `admin.components` with `serverProps: { look: { … } }`
|
||||
(`SignInLookProps`). From the main entry: `resolveSignInLook`, `loadSignInBrand`, `signInLogo`, `signInName`,
|
||||
`fitLogo`, `isSvgUpload`, `languageLinks`, `LANGUAGE_NAMES`, `signInCss`, `isHexColour`, `signInProviderActive`,
|
||||
`buildAdminLanguageEndpoint`, `adminPathFromReferer`, and the constants `SIGN_IN_LOOK`, `SIGN_IN_STYLE_ID`,
|
||||
`SIGN_IN_LOGO_BOX`, `SIGN_IN_NAME_MAX`, `ADMIN_LANGUAGE_PATH`; types `SignInLookOptions`, `ResolvedSignInLook`,
|
||||
`SignInLookProps`, `SignInBrand`, `SignInLogo`, `LanguageLink`, `SignInPanelProps`, `SignInLookProviderProps`.
|
||||
- **Verify:** `curl -s $URL/admin/login | grep -c 'class="iapl-signin'` → `1`; open `/admin/login` at a phone
|
||||
width; with `allScreens`, `curl -s $URL/admin/forgot | grep -c 'class="iapl-signin'` → `1`;
|
||||
`curl -si "$URL/api/ipal/admin-language?lng=xx"` → `400`.
|
||||
|
||||
## How it works
|
||||
|
||||
@@ -141,15 +254,18 @@ through `AdminIcon`.
|
||||
|
||||
- [ ] `iapl({ whiteLabel: true })`
|
||||
- [ ] The editor uploaded `logo` and `favicon` in SiteSettings (+ `siteName`)
|
||||
- [ ] `signIn: { allScreens: true }` for the look on every sign-in screen (new sites: yes)
|
||||
- [ ] `pnpm generate:importmap`
|
||||
- [ ] Restart dev / rebuild → the panel shows the client's brand on login and in the nav
|
||||
|
||||
## Turn off, override, extend
|
||||
|
||||
- **Turn off:** without `whiteLabel` (default) the panel has Payload branding; `credit: false` hides the credit;
|
||||
- **Turn off:** without `whiteLabel` (default) the panel has Payload branding; `signIn: false` keeps Payload's
|
||||
sign-in screens; `credit: false` hides the credit;
|
||||
`agency: false` removes the agency everywhere; `adminMeta: false` restores Payload's link preview.
|
||||
- **Override:** other fields / global (`settingsSlug`, `nameField`, `logoField`, `iconField`), credit text and URL,
|
||||
`titleSuffix`. With `whiteLabel` on, the plugin overrides `graphics.Logo` / `Icon` from the project
|
||||
config — set your own graphics components without `whiteLabel`.
|
||||
- **Extend:** `AdminLogo`, `AdminIcon`, `IntecionCredit` (props `agency`, `text`, `url`, `variant`) from
|
||||
`@intecion/ipal-kit/admin` can be wired manually into `admin.components` with your own `serverProps`.
|
||||
- **Extend:** `AdminLogo`, `AdminIcon`, `IntecionCredit` (props `agency`, `text`, `url`, `variant`), `SignInPanel`
|
||||
and `SignInLook` from `@intecion/ipal-kit/admin` can be wired manually into `admin.components` with your own
|
||||
`serverProps`.
|
||||
|
||||
@@ -64,6 +64,13 @@ description: Complete map of everything @intecion/ipal-kit provides — every ia
|
||||
| `whiteLabel.logoField` / `iconField` / `nameField` | `'logo'` / `'favicon'` / `'siteName'` | fields in Site settings | any upload/text field |
|
||||
| `whiteLabel.titleSuffix` | none | `admin.meta.titleSuffix` (tab title) | — |
|
||||
| `whiteLabel.credit` | on | `IntecionCredit` in `afterLogin` and `afterNavLinks`: "Technology support: Intecion.com" (en/pl, from `agency`) | `false`; `{ text, url }` overrides |
|
||||
| `whiteLabel.signIn` | on (with `whiteLabel`) | the sign-in look: a dark panel with the client's logo (Site settings → Logo, on a white plate) or the site's name beside the form, "Administration panel", language links; both themes, a band above the form on a phone. Login, the 2FA screens and e-mail verification get it through `AdminLogo` / `SafeTotpView` (already in the import map: an upgrade needs no edit). No env var, no new field, no migration | `false` = Payload's own screens |
|
||||
| `whiteLabel.signIn.allScreens` | `false` (the starter writes `true`) | the look on forgot / reset password, create first user, logout and "unauthorized" too: adds the provider `SignInLook` — ONE new import-map entry, run `pnpm payload generate:importmap`. Production start: when `importMap.js` on disk lacks it, the provider is left out and the log says `[iapl] The sign-in look covers only the login and 2FA screens …` | `true` |
|
||||
| `whiteLabel.signIn.accent` | `#0070c0` | hex colour of the button, links and focus ring (anything that is not a hex colour is ignored); or CSS variables `--iapl-signin-*` on `:root` in the admin's `custom.scss` | `'#0b6e4f'` |
|
||||
| `whiteLabel.signIn.logoMadeFor` | `'light'` | `'dark'` = a logo drawn for dark grounds: no white plate | — |
|
||||
| `whiteLabel.signIn.languages` | shown with 2+ admin languages | links on the panel; `GET /api/ipal/admin-language?lng=<code>` writes Payload's `payload-lng` cookie and redirects (303) back to the admin path of the `Referer`; unknown language → 400 | `false` = no links, no endpoint |
|
||||
| `whiteLabel.signIn.svgLogo` | shown as a picture (`<img>` runs no script) | `false` = an SVG logo is not shown on the sign-in screens; the site's name is | — |
|
||||
| `whiteLabel.brandAccess` | `'editor'` (whoever edits Site settings) | `'admin'` = field-level `access.update` on the name, logo and icon fields: only admins change what the sign-in screens show. No schema change | — |
|
||||
| `agency` | `{ name: 'Intecion.com', url: 'https://intecion.com' }` | the credit line, the panel's link description and preview image | `{ name, url }` = another agency; `false` = none anywhere |
|
||||
| `adminMeta` | on (with or without `whiteLabel`) | panel `<head>`: `robots` noindex/nofollow, `titleSuffix` "— <site> \| Panel", `og:site_name` + description from Site settings (refreshed on save), `og:image` `GET /api/ipal/admin-og` (1200×630 from the logo or name), icon `GET /api/ipal/admin-icon` (favicon or initials); no import map step | `false` = Payload defaults; `{ robots, titleSuffix, description, image, icons, language }` (each `false` or your value; `{site}`, `{agency}` placeholders); your own `admin.meta` keys always win. Check: `curl -s $URL/admin/login \| grep -E 'og:\|robots'` (white-label.md) |
|
||||
| `pages` | none | Site settings → **System pages** (page roles) and **Maintenance** tabs | omit → neither tab |
|
||||
@@ -153,6 +160,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ia
|
||||
|---|---|---|
|
||||
| `AdminLogo`, `AdminIcon` | `graphics.Logo/Icon` | `whiteLabel` |
|
||||
| `IntecionCredit` | `afterLogin`, `afterNavLinks` | `whiteLabel` and `credit !== false` |
|
||||
| `SignInLook` | `providers` (last) | `whiteLabel.signIn.allScreens` — the only entry the sign-in look adds; without it nothing new is needed |
|
||||
| `StatsNavLink`, `StatsView` (`views.ipalStats`, `/stats`), `StatsWidget` (`beforeDashboard`) | nav, view, dashboard | `stats` (`dashboard: false` without the widget) |
|
||||
| `CookieScanButton` | `beforeListTable` of `cookie-review` (with **Check site** when `crawl` is on) | `cookieScanner` |
|
||||
| `CookieReviewTab`, `CookieSiteCheckTab` | `ui` fields in the `cookie-settings` tabs | `cookieScanner` with `adminLayout !== 'separate'` (Site check: `crawl`) |
|
||||
|
||||
@@ -38,6 +38,8 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT
|
||||
| `TwoFactorResetButton` | `@intecion/ipal-kit/admin` | Client button inside `TwoFactorStatusField`: `POST /api/ipal/two-factor/reset` `{ userId }`, then reloads the view. Props `{ kind: 'reset' \| 'reopen', userId }`. |
|
||||
| `TwoFactorAlert` | `@intecion/ipal-kit/admin` | Server component on the dashboard (`beforeDashboard`), administrators only: accounts without two-step verification and how many are blocked. Wired by the plugin with `twoFactor.requireSetup`; renders nothing when every account has it. |
|
||||
| `IntecionCredit` | `@intecion/ipal-kit/admin` | The line "Technology support: Intecion.com" (admin language; `agency` prop = the name) below the nav and below the login form (`variant: 'nav' \| 'login'`). Injected by the plugin with `whiteLabel`; turn off: `whiteLabel: { credit: false }` or `agency: false`. |
|
||||
| `SignInPanel` | `@intecion/ipal-kit/admin` | Server component: the dark sign-in panel with its stylesheet (`<style>` deduplicated by React) — label, the logo or the site's name from Site settings as a link to the site, language links. Props `look` (`SignInLookProps`) plus what Payload injects (`payload`, `i18n`, `locale`, `user`); `SignInPanelProps`. Hidden by its own CSS on any page that is not Payload's minimal template. `AdminLogo` (prop `signIn`) and `SafeTotpView` (prop `iaplSignIn`) render it when the provider does not. |
|
||||
| `SignInLook` | `@intecion/ipal-kit/admin` | Admin provider (`admin.components.providers`, `serverProps: { look }`; `SignInLookProviderProps`): prints `SignInPanel` on every admin page so that every minimal screen has it. Registered by `whiteLabel: { signIn: { allScreens: true } }`. |
|
||||
| `buildAdminMeta({ agency, apiRoute?, defaultLocale?, meta?, options? })` | `@intecion/ipal-kit` | The `adminMeta` step: static panel meta (robots, preview image, icon) without overwriting keys in `meta`; returns `{ meta, resolved }` |
|
||||
| `adminMetaForSite(site, resolved)`, `syncAdminMeta(payload, resolved, { nameField?, settingsSlug? })` | `@intecion/ipal-kit` | Site-name parts (suffix, description, siteName); `syncAdminMeta` writes them into the live config (onInit + Site settings afterChange, never throws) |
|
||||
| `buildAdminImageEndpoints(resolved, { settingsSlug?, nameField?, logoField?, iconField? })` | `@intecion/ipal-kit` | `GET /api/ipal/admin-og` (1200×630 PNG via `next/og`) and `GET /api/ipal/admin-icon` (the favicon itself, or initials) — already added by `adminMeta` |
|
||||
@@ -623,6 +625,11 @@ Server only (`pnpm payload run`); never import it from client code, the Payload
|
||||
| `countAccountsWithoutTotp(payload, collection, setupWindowMs?)` | `@intecion/ipal-kit` | `{ without, blocked }` — accounts of the 2FA collection without TOTP, and how many are past their window. |
|
||||
| `resolveRequireSetup(option)`, `strictExempt(fn)`, `SETUP_FROM_FIELD`, `DEFAULT_SETUP_WINDOW_HOURS` | `@intecion/ipal-kit` | `twoFactor.requireSetup` → `{ requireSetup, setupWindowMs, exempt? }` as the guard reads it (throws on a `windowHours` that is not a number ≥ 0 or `false`, and on an `async` `exempt`); the wrapper that makes an `exempt` function answer `true` only for exactly `true`; the field name `'totpSetupFrom'`; `72`. |
|
||||
| `fetchPublicImage(url, base)`, `publicImageDataUri(url, base)`, `rasterImageType(bytes)`, `siteOrigin(serverURL)`, `PUBLIC_IMAGE_MAX_BYTES` | `@intecion/ipal-kit` | An image fetched the way an anonymous visitor gets it (no cookies; http(s) only; `image/*`; at most 512 KB, reading stops at the limit) as `{ bytes, type }` or a `data:` address, else `null`. Used for the logo and icon on the 2FA screens. `rasterImageType(bytes)` → the media type of a bitmap by its first bytes (PNG, JPEG, GIF, WebP, ICO, AVIF) or `null` — never trust a claimed type before answering a file's bytes from the site's origin; an SVG gives `null`. |
|
||||
| `resolveSignInLook(whiteLabel)` | `@intecion/ipal-kit` | `whiteLabel` option → `null` (white-label or `signIn` off) or `{ allScreens, props }` (`ResolvedSignInLook`; `props` = `SignInLookProps`, the plain values the components get: `accent`, `imageField`, `inlineImages`, `languages`, `logoMadeFor`, `nameField`, `settingsSlug`, `svgLogo`). Option type: `SignInLookOptions`. |
|
||||
| `loadSignInBrand({ payload, look, locale?, user? })`, `signInName(value, locale?)`, `signInLogo(media, { svgLogo? })`, `fitLogo(width, height, box?)`, `isSvgUpload(media)` | `@intecion/ipal-kit` | What the sign-in panel shows: `{ name, logo }` (`SignInBrand`, `SignInLogo = { src, width?, height? }`) read from Site settings, never throwing; the name as one line of plain text (control characters out, cut at `SIGN_IN_NAME_MAX` = 80); the logo of an upload document (only an `http(s)` or site-relative address; `null` for SVG with `svgLogo: false`), fitted into `SIGN_IN_LOGO_BOX` (240 × 72) without enlarging. A session that owes its 2FA code gets the picture inlined (`publicImageDataUri`) or no logo. |
|
||||
| `signInCss({ accent? })`, `isHexColour(value)`, `SIGN_IN_STYLE_ID` | `@intecion/ipal-kit` | The stylesheet of the sign-in look as a string (no `url()`, no font, no other host; every rule needs `.iapl-signin` on the page), the hex check `accent` must pass, and the `href` of its `<style>` (`'iapl-sign-in'`). |
|
||||
| `languageLinks(config, current)`, `LANGUAGE_NAMES`, `buildAdminLanguageEndpoint()`, `adminPathFromReferer(referer, adminRoute)`, `ADMIN_LANGUAGE_PATH` | `@intecion/ipal-kit` | The panel's languages as links (`LanguageLink[]`: `{ code, name, current, href }`; empty with one language; names in their own language, else the code); the public endpoint `GET /api/ipal/admin-language?lng=` (`'/ipal/admin-language'`) that writes `<cookiePrefix>-lng` for a supported language (else 400) and answers 303 to a path inside the admin route taken from the `Referer` (anything else → the admin root, never another host). |
|
||||
| `signInProviderActive(payload)`, `SIGN_IN_LOOK` | `@intecion/ipal-kit` | Whether the provider `'@intecion/ipal-kit/admin#SignInLook'` is in the config AND in the running import map — `AdminLogo` and `SafeTotpView` print the panel themselves only when it is not. |
|
||||
| `UPLOAD_SECURITY_HEADERS` | `@intecion/ipal-kit` | The two headers of `buildUploadSecurityHeaders` (`Content-Security-Policy: default-src 'none'; … sandbox`, `X-Content-Type-Options: nosniff`) for a route of your own that returns an uploaded file's bytes from the site's origin. In a Next project a site-wide `headers()` rule with the same key overrides a header the route sets itself: add a `headers()` rule for the path after the site-wide one (as `buildUploadSecurityHeaders({ collections, adminIcon })` does for the upload routes and `/api/ipal/admin-icon`), and never answer with an SVG. |
|
||||
| `twoFactorSetupState(req)`, `twoFactorSetupDeadline(req)` | `@intecion/ipal-kit` | Where an account stands with TOTP setup, from `{ payload, user }`: `'set-up'`, `'open'` (may set it up now), `'closed'` (the setup window has passed: blocked until an admin reopens it), `'exempt'` (`requireSetup.exempt`, or `requireSetup: false`), `'not-applicable'` (no user, another collection, 2FA off); and the moment setup closes (`Date`, or `null` without a window). Types: `TwoFactorSetupState`, `RequireSetupOptions`. |
|
||||
| `requireSecondFactor(access?)` | `@intecion/ipal-kit` | Wraps an `Access` function: refused while the second factor is owed, otherwise the function itself (Payload's default "logged in" when none). iapl applies it to every collection and global in the config, and to those added by plugins listed after it (in `onInit` and at the start of the first request, so also after a dev hot reload); use it for access functions that are not part of the config. Per-entity opt-out: `custom.ipal.secondFactor: false \| { read: false }` or the package's `custom.totp.disableAccessWrapper`. Wrapping twice is harmless. |
|
||||
|
||||
@@ -188,7 +188,7 @@ export default buildConfig({
|
||||
seo: { collections: ['pages'] },
|
||||
forms: { redirectRelationships: ['pages'] },
|
||||
twoFactor: { issuer: '<Client name>', plugin: payloadTotp },
|
||||
whiteLabel: true,
|
||||
whiteLabel: { signIn: { allScreens: true } }, // client's logo / name on every sign-in screen (white-label.md)
|
||||
indexNow: true,
|
||||
// consentLog is on by default (1.17.0): consent-records + POST /api/ipal/consent; `consentLog: false` turns it off.
|
||||
// Postgres / SQLite: pnpm payload migrate:create consent-log, applied in the same deploy.
|
||||
@@ -207,7 +207,7 @@ are never added to a new site. Local `.env` with `PAYLOAD_SECRET` ≥ 32 charact
|
||||
One language: one entry in `locales`, no `[locale]` folder (i18n.md).
|
||||
|
||||
**Check.** `pnpm payload generate:importmap` (whiteLabel adds admin components) and `pnpm generate:types` without
|
||||
errors (the import map lists `@intecion/ipal-kit/admin#TotpRedirectProvider` and `#SafeTotpView`); `pnpm dev`, `/admin`: first-user screen → after saving, TOTP setup is enforced (`/admin/setup-totp?back=%2Fadmin`, QR, no reloading);
|
||||
errors (the import map lists `@intecion/ipal-kit/admin#TotpRedirectProvider`, `#SafeTotpView` and `#SignInLook`); `pnpm dev`, `/admin`: first-user screen → after saving, TOTP setup is enforced (`/admin/setup-totp?back=%2Fadmin`, QR, no reloading);
|
||||
the panel shows Site settings, Site integrations, Cookies, Form messages, the Forms group, Consent records.
|
||||
`curl -s -o /dev/null -w '%{http_code}' -X POST localhost:3000/api/ipal/consent -H 'content-type: application/json'
|
||||
-d '{"id":"0123456789abcdef","version":1,"state":{"necessary":true,"functional":false,"analytics":false,"marketing":false}}'` → `201`.
|
||||
@@ -294,6 +294,12 @@ the panel shows Site settings, Site integrations, Cookies, Form messages, the Fo
|
||||
win; a function `(global) => global` takes over). Without `revalidatePath` global saves wait for the ISR window.
|
||||
- `whiteLabel: { credit: false, titleSuffix, settingsSlug, logoField, … }`; with `whiteLabel` the plugin overrides
|
||||
`graphics.Logo/Icon` — your own graphics only without it.
|
||||
- Sign-in screens (`whiteLabel.signIn`, on): a dark panel with the client's logo or the site's name beside the
|
||||
form; the logo and name are Site settings fields (no env var, no migration). `allScreens: true` (in the config
|
||||
above) adds the provider `SignInLook` to the import map and covers forgot / reset password, first user and
|
||||
logout. `accent: '#hex'`, `logoMadeFor: 'dark'` (a white logo), `languages: false`, `svgLogo: false`;
|
||||
`signIn: false` = Payload's screens; `brandAccess: 'admin'` = only admins change name, logo and icon.
|
||||
Check: `/admin/login` and `/admin/forgot` show the panel, also at a phone width; do not write login CSS by hand.
|
||||
- Panel link preview (`adminMeta`, on): noindex/nofollow, "— <site> | Panel" suffix, site name, description and
|
||||
preview image (`/api/ipal/admin-og`) from Site settings; `agency` names who supports the technology (default
|
||||
Intecion.com). Turn off: `adminMeta: false`, `agency: false`; your own `admin.meta` keys win. Check:
|
||||
|
||||
@@ -648,6 +648,22 @@ PROGRAMISTA §6, items 73–75; email.md; AGENT.md §7.2) — nothing to run; re
|
||||
**Send test e-mail** names the transport you expect; a form submission arrives. **The service is live at
|
||||
`https://webservices.intecion.net/mail`; while the service runs with enrolment "pending" (from its launch until Intecion switches to open enrolment), every new site waits for approval — keep SMTP until it is approved, or `relay: false`.**
|
||||
|
||||
**→ 1.18.0, the sign-in look (CHANGELOG 1.18.0; white-label.md → "The sign-in screens") — nothing is required:**
|
||||
1. **Sites with `whiteLabel`:** after the update the login screen and the 2FA screens (code, setup) have the new
|
||||
look — a dark panel with the client's logo or the site's name beside the form. No edit, no
|
||||
`generate:importmap`, no migration: the look comes through `AdminLogo` and `SafeTotpView`, which the site's
|
||||
import map already has. **Check:** open `/admin/login` on a desktop and at a phone width, in both themes; sign
|
||||
in through 2FA. A logo that looks wrong on the white plate (a white logo): `signIn: { logoMadeFor: 'dark' }`.
|
||||
2. **Tell the owner the sign-in page looks different** and ask whether to keep it. No: `whiteLabel: { signIn: false }`
|
||||
— Payload's screens with the plain logo, as before (record it in AGENTS.md → Project decisions).
|
||||
3. **Recommended, one edit:** `whiteLabel: { signIn: { allScreens: true } }`, `pnpm payload generate:importmap`,
|
||||
commit `importMap.js` — forgot / reset password, create first user and logout get the same look. Forgetting
|
||||
the import map does not break the panel: at a production start the provider is left out and the log says so.
|
||||
4. **Project CSS for the login screen** (`custom.scss` rules on `.login`, `.template-minimal`, a hand-made
|
||||
`graphics.Logo`): look at the screens after the update; the look's own rules win over Payload's layer but not
|
||||
over the project's later ones. Restyle with the `--iapl-signin-*` variables instead.
|
||||
5. Sites **without** `whiteLabel`: nothing changes.
|
||||
|
||||
## 2. Inventory (no code changes)
|
||||
**What changed for projects** between your old and new plugin version is exactly the reference site's diff —
|
||||
`git diff v<old> v<new> -- reference/` in the IAPL repo (or the two `docs/agent/reference-site/INDEX.md` files):
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
import { expect, type Page, test } from '@playwright/test'
|
||||
|
||||
/**
|
||||
* The sign-in look (whiteLabel.signIn, white-label.md): the dark panel with the site's name or logo beside the
|
||||
* form, on every sign-in screen (this site sets `allScreens`), in the page's first HTML, on a phone above the
|
||||
* form, with working language links; and the 2FA code screen behind it, unchanged in what it does.
|
||||
* No 2FA code is entered here: the account's verify attempts are left for the other specs.
|
||||
* E2E_BASE_URL=http://localhost:3310 pnpm exec playwright test e2e/sign-in-look.spec.ts
|
||||
*/
|
||||
const { E2E_ADMIN_EMAIL: email, E2E_ADMIN_PASSWORD: password } = process.env
|
||||
|
||||
const PHONE = { height: 844, width: 390 }
|
||||
const panel = (page: Page) => page.locator('.iapl-signin')
|
||||
const box = async (page: Page, selector: string) => {
|
||||
const b = await page.locator(selector).first().boundingBox()
|
||||
if (!b) {throw new Error(`${selector} is not on the page`)}
|
||||
return b
|
||||
}
|
||||
/** Nothing is wider than the window: no sideways scroll. */
|
||||
const noSidewaysScroll = async (page: Page) => expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)).toBe(true)
|
||||
|
||||
test('sign-in look — login: the look comes with the form (no flash of the plain screen), one panel, the form beside it', async ({ page, request }) => {
|
||||
// the stylesheet and the panel are in the page's own response: no second request brings the look
|
||||
const html = await (await request.get('/admin/login')).text()
|
||||
expect(html).toContain('iapl-sign-in')
|
||||
expect(html).toContain('iapl-signin__label')
|
||||
|
||||
const errors: string[] = []
|
||||
page.on('console', (m) => m.type() === 'error' && errors.push(m.text()))
|
||||
// Payload draws its screens in the browser. Whenever the form's template is in the page, the panel and its
|
||||
// stylesheet must be there too — checked after every change of the page, before the browser paints it.
|
||||
await page.addInitScript(() => {
|
||||
const seen = { plain: 0, styled: 0 }
|
||||
;(window as unknown as { iaplLook: typeof seen }).iaplLook = seen
|
||||
new MutationObserver(() => {
|
||||
if (!document.querySelector('.template-minimal')) {return}
|
||||
const styled = document.querySelector('.iapl-signin') && document.querySelector('style[data-href="iapl-sign-in"]')
|
||||
seen[styled ? 'styled' : 'plain'] += 1
|
||||
}).observe(document, { childList: true, subtree: true })
|
||||
})
|
||||
await page.goto('/admin/login')
|
||||
await page.locator('#field-email').waitFor()
|
||||
const seen = await page.evaluate(() => (window as unknown as { iaplLook: { plain: number; styled: number } }).iaplLook)
|
||||
expect(seen.plain).toBe(0)
|
||||
expect(seen.styled).toBeGreaterThan(0)
|
||||
await expect(panel(page)).toHaveCount(1)
|
||||
await expect(panel(page)).toBeVisible()
|
||||
await expect(panel(page).locator('.iapl-signin__label')).toHaveText(/Administration panel|Panel administracyjny/)
|
||||
// the site's name (no logo in the seed) is a link to the site; nothing else on the panel leaves the admin
|
||||
await expect(panel(page).locator('.iapl-signin__brand')).toHaveText('Example Studio')
|
||||
await expect(panel(page).locator('.iapl-signin__brand')).toHaveAttribute('href', '/')
|
||||
const p = await box(page, '.iapl-signin')
|
||||
const form = await box(page, '#field-email')
|
||||
expect(p.x + p.width).toBeLessThanOrEqual(form.x)
|
||||
expect(p.height).toBeGreaterThan(600)
|
||||
await noSidewaysScroll(page)
|
||||
// the button carries the accent, the fields their labels
|
||||
await expect(page.locator('.form-submit button')).toHaveCSS('background-color', 'rgb(0, 112, 192)')
|
||||
await expect(page.getByLabel(/^(Email|E-mail)/)).toBeVisible()
|
||||
expect(errors).toEqual([])
|
||||
})
|
||||
|
||||
test('sign-in look — login on a phone: the panel is a band above the form, in both themes', async ({ baseURL, browser }) => {
|
||||
for (const theme of ['light', 'dark'] as const) {
|
||||
const context = await browser.newContext({ baseURL, viewport: PHONE })
|
||||
await context.addCookies([{ name: 'payload-theme', url: baseURL!, value: theme }])
|
||||
const page = await context.newPage()
|
||||
await page.goto('/admin/login')
|
||||
const p = await box(page, '.iapl-signin')
|
||||
const form = await box(page, '#field-email')
|
||||
expect(p.y).toBe(0)
|
||||
expect(Math.round(p.width)).toBe(PHONE.width)
|
||||
expect(p.y + p.height).toBeLessThanOrEqual(form.y)
|
||||
await noSidewaysScroll(page)
|
||||
await expect(page.locator('html')).toHaveAttribute('data-theme', theme)
|
||||
// the page behind the form follows the theme; the panel is dark in both
|
||||
const bg = await page.locator('.template-minimal').evaluate((el) => getComputedStyle(el).backgroundColor)
|
||||
expect(bg === 'rgb(255, 255, 255)').toBe(theme === 'light')
|
||||
await expect(panel(page)).toHaveCSS('background-color', 'rgb(6, 6, 6)')
|
||||
await context.close()
|
||||
}
|
||||
})
|
||||
|
||||
test('sign-in look — the other sign-in screens carry the same panel; the rest of the admin does not show it', async ({ page }) => {
|
||||
for (const path of ['/admin/forgot', '/admin/reset/not-a-real-token', '/admin/logout']) {
|
||||
await page.goto(path)
|
||||
await page.waitForLoadState('networkidle')
|
||||
await expect(panel(page), path).toHaveCount(1)
|
||||
await expect(panel(page), path).toBeVisible()
|
||||
await noSidewaysScroll(page)
|
||||
}
|
||||
await page.goto('/admin/forgot')
|
||||
const p = await box(page, '.iapl-signin')
|
||||
const form = await box(page, '#field-email')
|
||||
expect(p.x + p.width).toBeLessThanOrEqual(form.x)
|
||||
})
|
||||
|
||||
test('sign-in look — language links: one click changes the panel\'s language and comes back to the same screen', async ({ baseURL, browser, request }) => {
|
||||
const context = await browser.newContext({ baseURL, locale: 'en-US' })
|
||||
const page = await context.newPage()
|
||||
await page.goto('/admin/forgot')
|
||||
await expect(panel(page).locator('.iapl-signin__label')).toHaveText('Administration panel')
|
||||
await expect(panel(page).locator('[aria-current="true"]')).toHaveText('English')
|
||||
// a plain link: the endpoint sets the cookie and redirects, no script of the page takes part
|
||||
await expect(panel(page).getByRole('link', { name: 'Polski' })).toHaveAttribute('href', '/api/ipal/admin-language?lng=pl')
|
||||
await panel(page).getByRole('link', { name: 'Polski' }).click()
|
||||
await expect(page).toHaveURL(/\/admin\/forgot$/)
|
||||
await expect(panel(page).locator('.iapl-signin__label')).toHaveText('Panel administracyjny')
|
||||
await expect(panel(page).locator('[aria-current="true"]')).toHaveText('Polski')
|
||||
await expect(page.locator('html')).toHaveAttribute('lang', 'pl')
|
||||
await context.close()
|
||||
|
||||
// the endpoint writes a supported language only, and never sends the browser off the admin
|
||||
const unknown = await request.get('/api/ipal/admin-language?lng=xx', { maxRedirects: 0 })
|
||||
expect(unknown.status()).toBe(400)
|
||||
expect(unknown.headers()['set-cookie']).toBeUndefined()
|
||||
const away = await request.get('/api/ipal/admin-language?lng=pl', { headers: { referer: 'https://evil.example/phish' }, maxRedirects: 0 })
|
||||
expect(away.status()).toBe(303)
|
||||
expect(away.headers().location).toBe('/admin')
|
||||
expect(away.headers()['set-cookie']).toMatch(/^payload-lng=pl; Path=\/; Max-Age=31536000; SameSite=Lax/)
|
||||
})
|
||||
|
||||
test('sign-in look — the 2FA code screen: the panel beside it, the code boxes named, the brand without a media request', async ({ page }) => {
|
||||
test.skip(!email || !password, 'E2E_* test admin not configured')
|
||||
const media: string[] = []
|
||||
page.on('request', (r) => r.url().includes('/api/media/') && media.push(r.url()))
|
||||
await page.goto('/admin/login')
|
||||
await page.fill('#field-email', email!)
|
||||
await page.fill('#field-password', password!)
|
||||
await page.click('.form-submit button')
|
||||
await page.waitForURL(/verify-totp/)
|
||||
await expect(panel(page)).toHaveCount(1)
|
||||
await expect(panel(page)).toBeVisible()
|
||||
const p = await box(page, '.iapl-signin')
|
||||
const first = await box(page, '.template-minimal form input[type="text"]')
|
||||
expect(p.x + p.width).toBeLessThanOrEqual(first.x)
|
||||
// six boxes, each with a name a screen reader can say, the first one focused as before
|
||||
const boxes = page.getByRole('textbox')
|
||||
await expect(boxes).toHaveCount(6)
|
||||
await expect(boxes.first()).toHaveAttribute('aria-label', /^(Digit 1 of 6|Cyfra 1 z 6)$/)
|
||||
await expect(boxes.nth(5)).toHaveAttribute('aria-label', /^(Digit 6 of 6|Cyfra 6 z 6)$/)
|
||||
await expect(boxes.first()).toBeFocused()
|
||||
// a session that owes its code is refused `media`: the page asks for none
|
||||
expect(media).toEqual([])
|
||||
await noSidewaysScroll(page)
|
||||
})
|
||||
@@ -512,6 +512,8 @@ test('admin: sign in through 2FA, agency credit, panel link preview', async ({ p
|
||||
}
|
||||
await expect(page).toHaveTitle(/Dashboard|Pulpit/, { timeout: 20_000 })
|
||||
await expect(page.getByText(/Intecion/).first()).toBeVisible()
|
||||
// the sign-in panel belongs to the sign-in screens: inside the panel it is not shown
|
||||
await expect(page.locator('.iapl-signin')).toBeHidden()
|
||||
})
|
||||
|
||||
// 2FA covers what the plugin adds, over the API too (REST and GraphQL): a correct password without the code
|
||||
|
||||
@@ -44,6 +44,7 @@ import { TwoFactorAlert as TwoFactorAlert_7568fe47d582ff15ce85d2e1873c2c23 } fro
|
||||
import { CookieCrawlAlert as CookieCrawlAlert_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
|
||||
import { IntegrationAlerts as IntegrationAlerts_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
|
||||
import { TotpRedirectProvider as TotpRedirectProvider_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
|
||||
import { SignInLook as SignInLook_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
|
||||
import { SafeTotpView as SafeTotpView_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
|
||||
import { CookieApprovalView as CookieApprovalView_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
|
||||
import { CollectionCards as CollectionCards_f9c02e79a4aed9a3924487c0cd4cafb1 } from '@payloadcms/next/rsc'
|
||||
@@ -99,6 +100,7 @@ export const importMap = {
|
||||
"@intecion/ipal-kit/admin#CookieCrawlAlert": CookieCrawlAlert_7568fe47d582ff15ce85d2e1873c2c23,
|
||||
"@intecion/ipal-kit/admin#IntegrationAlerts": IntegrationAlerts_7568fe47d582ff15ce85d2e1873c2c23,
|
||||
"@intecion/ipal-kit/admin#TotpRedirectProvider": TotpRedirectProvider_7568fe47d582ff15ce85d2e1873c2c23,
|
||||
"@intecion/ipal-kit/admin#SignInLook": SignInLook_7568fe47d582ff15ce85d2e1873c2c23,
|
||||
"@intecion/ipal-kit/admin#SafeTotpView": SafeTotpView_7568fe47d582ff15ce85d2e1873c2c23,
|
||||
"@intecion/ipal-kit/admin#CookieApprovalView": CookieApprovalView_7568fe47d582ff15ce85d2e1873c2c23,
|
||||
"@payloadcms/next/rsc#CollectionCards": CollectionCards_f9c02e79a4aed9a3924487c0cd4cafb1,
|
||||
|
||||
@@ -100,7 +100,8 @@ export default buildConfig({
|
||||
//: twoFactor: false, // turned off by the owner — AGENTS.md → Project decisions, iapl-doctor.json
|
||||
// @starter:endif
|
||||
// @starter:if whiteLabel
|
||||
whiteLabel: true,
|
||||
// the sign-in look on every sign-in screen: one admin provider, in the import map (white-label.md)
|
||||
whiteLabel: { signIn: { allScreens: true } },
|
||||
// @starter:endif
|
||||
// @starter:if !adminMeta
|
||||
//: adminMeta: false, // turned off by the owner — AGENTS.md → Project decisions
|
||||
|
||||
@@ -10,8 +10,9 @@
|
||||
* 2. no package manifest under .next/static (checked on disk, before anything is started);
|
||||
* 3. Playwright against `next start`: e2e/late-staff.spec.ts, e2e/mail-relay.spec.ts (the mail service: the confirm
|
||||
* route under Next, the state block in the panel's production bundle) and the smoke tests "no package.json is published",
|
||||
* "client hints" (Payload's colour-scheme headers on the admin only; a public page is requested once) and every
|
||||
* "consent" test (banner at first paint, Global Privacy Control, equal prominence, withdrawal, the consent log).
|
||||
* "client hints" (Payload's colour-scheme headers on the admin only; a public page is requested once), every
|
||||
* "consent" test (banner at first paint, Global Privacy Control, equal prominence, withdrawal, the consent log)
|
||||
* and e2e/sign-in-look.spec.ts (the sign-in panel in the first HTML, on a phone, the language links, the 2FA screen).
|
||||
*
|
||||
* Needs what the reference site's "Production check" needs (reference/README.md): reference/.env with a local,
|
||||
* seeded database and the E2E_* test admin. The test admins are reset by Playwright's global setup.
|
||||
@@ -83,7 +84,7 @@ for (const bundler of bundlers) {
|
||||
process.exit(1)
|
||||
}
|
||||
console.log(`[e2e:built] ✓ ${bundler}: no package manifest among ${files.length} public files`)
|
||||
run(`${bundler}: the built site — late-staff spec, the mail service, the published-files check, the client hints and consent`, 'pnpm', ['exec', 'playwright', 'test', 'late-staff', 'mail-relay', 'smoke', '--grep', 'late staff collection|the mail service|no package.json is published|client hints|consent'], site, { ALLOW_LOCAL_MEDIA: process.env.ALLOW_LOCAL_MEDIA ?? '1', E2E_LATE_STAFF: '1' })
|
||||
run(`${bundler}: the built site — late-staff spec, the mail service, the published-files check, the client hints, consent and the sign-in look`, 'pnpm', ['exec', 'playwright', 'test', 'late-staff', 'mail-relay', 'smoke', 'sign-in-look', '--grep', 'late staff collection|the mail service|no package.json is published|client hints|consent|sign-in look'], site, { ALLOW_LOCAL_MEDIA: process.env.ALLOW_LOCAL_MEDIA ?? '1', E2E_LATE_STAFF: '1' })
|
||||
passed.push(bundler)
|
||||
}
|
||||
console.log(`\n[e2e:built] passed: ${passed.join(' and ')}. (The reference site's .next now holds the ${passed.at(-1)} build WITH the fixture: rebuild with \`pnpm build\` there before other checks.)`)
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Screenshots of the panel's sign-in screens, for docs/dev/login-page/ (design review, before / after).
|
||||
*
|
||||
* node scripts/login-page-shots.mjs --prefix=after --base=http://localhost:3310 [--only=login,forgot] [--logo=keep|none]
|
||||
*
|
||||
* Needs the reference site running at --base with a seeded local database and the E2E_* test admin of
|
||||
* reference/.env (reference/README.md). Writes docs/dev/login-page/<prefix>-<screen>-<variant>.png:
|
||||
* login (light, dark, phone, Polish), login with a wrong password, forgot password, the 2FA code screen,
|
||||
* the 2FA setup screen (a throw-away editor, removed at the end).
|
||||
* --logo=none takes the logo out of Site settings for the run and puts it back (the "no logo" pictures);
|
||||
* --logo=<file.png> uploads that picture, sets it as the logo for the run and puts the old value back.
|
||||
* Dark pictures set Payload's theme cookie; the development indicator of Next is hidden.
|
||||
* create-first-user needs a database without users: point --base at such a site and pass --only=first-user.
|
||||
*/
|
||||
import { createHmac } from 'node:crypto'
|
||||
import { mkdirSync, readFileSync } from 'node:fs'
|
||||
import { createRequire } from 'node:module'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
|
||||
const require = createRequire(path.join(root, 'reference/package.json'))
|
||||
const { chromium, request } = require('@playwright/test')
|
||||
try {
|
||||
process.loadEnvFile(path.join(root, 'reference/.env'))
|
||||
} catch {
|
||||
/* values come from the environment */
|
||||
}
|
||||
|
||||
const arg = (name, fallback) => process.argv.find((a) => a.startsWith(`--${name}=`))?.slice(name.length + 3) ?? fallback
|
||||
const base = arg('base', process.env.E2E_BASE_URL ?? 'http://localhost:3310')
|
||||
const prefix = arg('prefix', 'after')
|
||||
const only = arg('only')?.split(',')
|
||||
const logoMode = arg('logo', 'keep')
|
||||
const suffix = arg('suffix', logoMode === 'none' ? '-name' : logoMode === 'keep' ? '' : '-logo')
|
||||
const out = path.join(root, 'docs/dev/login-page')
|
||||
mkdirSync(out, { recursive: true })
|
||||
const want = (name) => !only || only.includes(name)
|
||||
|
||||
const admin = { email: process.env.E2E_ADMIN_EMAIL, password: process.env.E2E_ADMIN_PASSWORD, secret: process.env.E2E_TOTP_SECRET }
|
||||
|
||||
function totp(secret, now = Date.now()) {
|
||||
const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'
|
||||
let bits = ''
|
||||
for (const ch of secret.replace(/=+$/, '').toUpperCase()) {bits += alphabet.indexOf(ch).toString(2).padStart(5, '0')}
|
||||
const key = Buffer.from((bits.match(/.{8}/g) ?? []).map((b) => parseInt(b, 2)))
|
||||
const counter = Buffer.alloc(8)
|
||||
counter.writeBigUInt64BE(BigInt(Math.floor(now / 1000 / 30)))
|
||||
const hmac = createHmac('sha1', key).update(counter).digest()
|
||||
const offset = hmac[hmac.length - 1] & 0xf
|
||||
return ((hmac.readUInt32BE(offset) & 0x7fffffff) % 1_000_000).toString().padStart(6, '0')
|
||||
}
|
||||
|
||||
const DESKTOP = { height: 800, width: 1280 }
|
||||
const PHONE = { height: 844, width: 390 }
|
||||
const browser = await chromium.launch()
|
||||
|
||||
async function shot(name, { colorScheme = 'light', locale = 'en-US', viewport = DESKTOP } = {}, steps) {
|
||||
const context = await browser.newContext({ baseURL: base, colorScheme, deviceScaleFactor: 1, locale, reducedMotion: 'reduce', viewport })
|
||||
if (colorScheme === 'dark') {await context.addCookies([{ name: 'payload-theme', url: base, value: 'dark' }])}
|
||||
const page = await context.newPage()
|
||||
try {
|
||||
await steps(page)
|
||||
await page.addStyleTag({ content: 'nextjs-portal{display:none!important}' })
|
||||
await page.waitForLoadState('networkidle').catch(() => undefined)
|
||||
await page.waitForTimeout(400)
|
||||
const file = path.join(out, `${prefix}-${name}${suffix}.png`)
|
||||
await page.screenshot({ fullPage: true, path: file })
|
||||
console.log(`wrote ${path.relative(root, file)}`)
|
||||
} finally {
|
||||
await context.close()
|
||||
}
|
||||
}
|
||||
|
||||
const signIn = async (page, who) => {
|
||||
await page.goto('/admin/login')
|
||||
await page.waitForLoadState('networkidle')
|
||||
await page.locator('#field-email').pressSequentially(who.email)
|
||||
await page.locator('#field-password').pressSequentially(who.password)
|
||||
await page.click('.form-submit button')
|
||||
}
|
||||
|
||||
/**
|
||||
* ONE fully signed-in API session for the whole run, of the second test admin: a 2FA code counts against the
|
||||
* account's verify limit (5 in 10 minutes), and the first admin's screens are the ones photographed.
|
||||
*/
|
||||
let session = null
|
||||
async function adminApi() {
|
||||
if (session) {return session}
|
||||
const api = await request.newContext({ baseURL: base, extraHTTPHeaders: { origin: base } })
|
||||
const login = await api.post('/api/users/login', { data: { email: admin.email.replace('@', '-2@'), password: admin.password } })
|
||||
if (login.status() !== 200) {throw new Error(`test admin cannot sign in (${login.status()})`)}
|
||||
const verify = await (await api.post('/api/verify-totp', { data: { token: totp(admin.secret) } })).json()
|
||||
if (!verify.ok) {throw new Error('test admin: the 2FA code was refused (verify limit? run the reference site\'s e2e/create-test-admin.ts)')}
|
||||
session = api
|
||||
return api
|
||||
}
|
||||
|
||||
let restoreLogo = null
|
||||
if (logoMode !== 'keep') {
|
||||
const api = await adminApi()
|
||||
const settings = await (await api.get('/api/globals/site-settings?depth=0')).json()
|
||||
let logo = null
|
||||
let uploaded = null
|
||||
if (logoMode !== 'none') {
|
||||
const file = path.resolve(logoMode)
|
||||
const res = await api.post('/api/media', {
|
||||
multipart: { _payload: JSON.stringify({ alt: 'Placeholder logo' }), file: { buffer: readFileSync(file), mimeType: 'image/png', name: path.basename(file) } },
|
||||
})
|
||||
uploaded = (await res.json())?.doc?.id
|
||||
if (!uploaded) {throw new Error(`the logo was not uploaded (${res.status()})`)}
|
||||
logo = uploaded
|
||||
}
|
||||
await api.post('/api/globals/site-settings', { data: { logo } })
|
||||
restoreLogo = async () => {
|
||||
await api.post('/api/globals/site-settings', { data: { logo: settings.logo ?? null } })
|
||||
if (uploaded) {await api.delete(`/api/media/${uploaded}`)}
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
if (want('login')) {
|
||||
await shot('login-light', {}, (page) => page.goto('/admin/login'))
|
||||
await shot('login-dark', { colorScheme: 'dark' }, (page) => page.goto('/admin/login'))
|
||||
await shot('login-phone', { viewport: PHONE }, (page) => page.goto('/admin/login'))
|
||||
await shot('login-phone-dark', { colorScheme: 'dark', viewport: PHONE }, (page) => page.goto('/admin/login'))
|
||||
await shot('login-pl', { locale: 'pl-PL' }, (page) => page.goto('/admin/login'))
|
||||
}
|
||||
if (want('error')) {
|
||||
const wrong = async (page) => {
|
||||
await signIn(page, { email: '[email protected]', password: 'wrong-password-1' })
|
||||
await page.locator('.payload-toast-container li, .toast-error').first().waitFor({ timeout: 10_000 }).catch(() => undefined)
|
||||
}
|
||||
await shot('login-error-light', {}, wrong)
|
||||
await shot('login-error-phone', { viewport: PHONE }, wrong)
|
||||
}
|
||||
if (want('forgot')) {
|
||||
await shot('forgot-light', {}, (page) => page.goto('/admin/forgot'))
|
||||
await shot('forgot-dark', { colorScheme: 'dark' }, (page) => page.goto('/admin/forgot'))
|
||||
await shot('forgot-phone', { viewport: PHONE }, (page) => page.goto('/admin/forgot'))
|
||||
}
|
||||
if (want('verify') && admin.email) {
|
||||
const verify = async (page) => {
|
||||
await signIn(page, admin)
|
||||
await page.waitForURL(/verify-totp/, { timeout: 20_000 })
|
||||
}
|
||||
await shot('2fa-code-light', {}, verify)
|
||||
await shot('2fa-code-dark', { colorScheme: 'dark' }, verify)
|
||||
await shot('2fa-code-phone', { viewport: PHONE }, verify)
|
||||
}
|
||||
if (want('setup') && admin.email) {
|
||||
const api = await adminApi()
|
||||
const editor = { email: `shots-editor-${Date.now()}@example.com`, password: `shots-${Date.now()}-Qm48xZr` }
|
||||
const created = await (await api.post('/api/users', { data: { ...editor, roles: ['editor'] } })).json()
|
||||
const id = created?.doc?.id
|
||||
try {
|
||||
const setup = async (page) => {
|
||||
await signIn(page, editor)
|
||||
await page.waitForURL(/setup-totp/, { timeout: 20_000 })
|
||||
}
|
||||
await shot('2fa-setup-light', {}, setup)
|
||||
await shot('2fa-setup-dark', { colorScheme: 'dark' }, setup)
|
||||
await shot('2fa-setup-phone', { viewport: PHONE }, setup)
|
||||
} finally {
|
||||
if (id) {await api.delete(`/api/users/${id}`)}
|
||||
}
|
||||
}
|
||||
if (only?.includes('first-user')) {
|
||||
const first = async (page) => {
|
||||
await page.goto('/admin/create-first-user')
|
||||
await page.locator('#field-confirm-password').waitFor({ timeout: 20_000 })
|
||||
}
|
||||
await shot('first-user-light', {}, first)
|
||||
await shot('first-user-dark', { colorScheme: 'dark' }, first)
|
||||
await shot('first-user-phone', { viewport: PHONE }, first)
|
||||
}
|
||||
} finally {
|
||||
await restoreLogo?.()
|
||||
await session?.dispose()
|
||||
await browser.close()
|
||||
}
|
||||
@@ -69,6 +69,7 @@ export const DESCRIPTIONS = {
|
||||
'e2e/mail-relay-setup.ts': 'for the mail-service spec: empties the SMTP fields and the stored token, so the next e-mail enrols and goes through the mail service (local database only)',
|
||||
'e2e/mail-relay.spec.ts': 'the mail service on a built site: the state block in the panel, the first e-mail through the public confirm route, no token in anything the browser receives',
|
||||
'e2e/smtp-sink.ts': 'a local mail sink for the smoke tests: reads what the site really sent (recipients, attachments)',
|
||||
'e2e/sign-in-look.spec.ts': 'browser test of the sign-in look (whiteLabel.signIn): the panel comes with the form, sits above it on a phone in both themes, is on forgot / reset / logout too, the language links work, the 2FA code screen keeps its boxes (now named)',
|
||||
'e2e/two-factor-back.spec.ts': 'browser test of the 2FA screens\' `back` link (twoFactor.safeBack): a prepared link — script or another host — ends on the admin root, an ordinary one is followed',
|
||||
'e2e/totp.ts': 'RFC 6238 code generator for the 2FA sign-in in the smoke test, and the address of the second test admin',
|
||||
'iapl-doctor.json': 'the production domain and launch state for iapl-doctor',
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -0,0 +1,347 @@
|
||||
import type { Config, Endpoint, GlobalConfig, Payload, PayloadRequest } from 'payload'
|
||||
|
||||
import { payloadTotp } from '@clocklimited/payload-2fa'
|
||||
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
import { describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { adminTexts } from '../src/modules/admin-i18n/index.js'
|
||||
import { AdminLogo } from '../src/modules/branding/adminGraphics.js'
|
||||
import { fitLogo, languageLinks, loadSignInBrand, SIGN_IN_LOOK, SIGN_IN_NAME_MAX, signInLogo, signInName, signInProviderActive } from '../src/modules/branding/signIn/brand.js'
|
||||
import { lockBrandFields } from '../src/modules/branding/signIn/brandAccess.js'
|
||||
import { signInCss } from '../src/modules/branding/signIn/css.js'
|
||||
import { adminPathFromReferer, buildAdminLanguageEndpoint } from '../src/modules/branding/signIn/languageEndpoint.js'
|
||||
import { resolveSignInLook } from '../src/modules/branding/signIn/options.js'
|
||||
import { SignInPanel } from '../src/modules/branding/signIn/SignInPanel.js'
|
||||
import { iapl } from '../src/plugin.js'
|
||||
|
||||
/**
|
||||
* The sign-in look (`whiteLabel.signIn`): what is on by default, what an existing site's import map needs
|
||||
* (nothing new), and what may reach a page that anyone can open before signing in.
|
||||
*/
|
||||
|
||||
const i18n = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }, { code: 'en', label: 'English' }] }
|
||||
const build = (options: Record<string, unknown> = {}, extra: Partial<Config> = {}) =>
|
||||
iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false, ...options } as never)({
|
||||
collections: [{ slug: 'users', auth: true, fields: [] }],
|
||||
secret: 'x',
|
||||
...extra,
|
||||
} as unknown as Config)
|
||||
|
||||
const paths = (config: Config): string[] => JSON.stringify(config.admin?.components ?? {}).match(/@intecion\/ipal-kit\/admin#\w+/g) ?? []
|
||||
const logo = (config: Config) => config.admin?.components?.graphics?.Logo as { path: string; serverProps?: { signIn?: unknown } }
|
||||
const t = (key: string) => (adminTexts.en as Record<string, string>)[key.replace('ipal:', '')] ?? key
|
||||
/** The panel's own markup, without the stylesheet in front of it. */
|
||||
const panel = async (props: Parameters<typeof SignInPanel>[0]) => {
|
||||
const html = renderToStaticMarkup(await SignInPanel(props))
|
||||
return html.slice(html.indexOf('<header'))
|
||||
}
|
||||
const fakePayload = (settings: Record<string, unknown>, extra: Record<string, unknown> = {}) =>
|
||||
({
|
||||
config: { i18n: { supportedLanguages: { en: {}, pl: {} } }, routes: { api: '/api' }, serverURL: 'https://site.test', ...extra },
|
||||
findGlobal: vi.fn(() => Promise.resolve(settings)),
|
||||
}) as unknown as Payload
|
||||
|
||||
describe('whiteLabel.signIn: the option', () => {
|
||||
test('off without whiteLabel, on with it, off with signIn: false', () => {
|
||||
expect(resolveSignInLook(undefined)).toBeNull()
|
||||
expect(resolveSignInLook(false)).toBeNull()
|
||||
expect(resolveSignInLook(true)).toEqual({ allScreens: false, props: {} })
|
||||
expect(resolveSignInLook({ signIn: false })).toBeNull()
|
||||
expect(resolveSignInLook({ signIn: true })).toEqual({ allScreens: false, props: {} })
|
||||
})
|
||||
|
||||
test('the fields of whiteLabel and the options of the look reach the components as plain values', () => {
|
||||
expect(
|
||||
resolveSignInLook({
|
||||
inlineImages: false,
|
||||
logoField: 'brandLogo',
|
||||
nameField: 'brandName',
|
||||
settingsSlug: 'settings',
|
||||
signIn: { accent: '#0B6E4F', allScreens: true, languages: false, logoMadeFor: 'dark', svgLogo: false },
|
||||
}),
|
||||
).toEqual({
|
||||
allScreens: true,
|
||||
props: { accent: '#0B6E4F', imageField: 'brandLogo', inlineImages: false, languages: false, logoMadeFor: 'dark', nameField: 'brandName', settingsSlug: 'settings', svgLogo: false },
|
||||
})
|
||||
})
|
||||
|
||||
test('an accent that is not a hex colour never reaches the stylesheet', () => {
|
||||
for (const accent of ['red', 'url(https://evil.test/x)', '#12', '#0070c0;} body{display:none', 'var(--x)', 7, null]) {
|
||||
expect(resolveSignInLook({ signIn: { accent: accent as never } })?.props.accent).toBeUndefined()
|
||||
expect(signInCss({ accent: accent as never })).toBe(signInCss())
|
||||
}
|
||||
expect(signInCss({ accent: '#0b6e4f' })).toContain('--iapl-signin-primary:#0b6e4f')
|
||||
})
|
||||
})
|
||||
|
||||
describe('whiteLabel.signIn: the config an existing site gets', () => {
|
||||
test('whiteLabel: true adds NO component path a 1.16 import map lacks', async () => {
|
||||
const config = await build({ whiteLabel: true })
|
||||
// the same component paths as with the look off — which is what 1.16 registered for whiteLabel: true
|
||||
expect([...new Set(paths(config))].sort()).toEqual([...new Set(paths(await build({ whiteLabel: { signIn: false } })))].sort())
|
||||
expect(paths(config)).toEqual(expect.arrayContaining(['@intecion/ipal-kit/admin#AdminIcon', '@intecion/ipal-kit/admin#AdminLogo', '@intecion/ipal-kit/admin#IntecionCredit']))
|
||||
expect(JSON.stringify(config.admin)).not.toContain('SignIn')
|
||||
expect(logo(config).serverProps?.signIn).toEqual({})
|
||||
expect(config.admin?.components?.providers ?? []).toEqual([])
|
||||
})
|
||||
|
||||
test('signIn: false is the logo as before: no look, no endpoint', async () => {
|
||||
const config = await build({ whiteLabel: { signIn: false } })
|
||||
expect(logo(config).serverProps?.signIn).toBeUndefined()
|
||||
expect((config.endpoints ?? []).some((e) => e.path === '/ipal/admin-language')).toBe(false)
|
||||
})
|
||||
|
||||
test('without whiteLabel nothing of the look is registered', async () => {
|
||||
const config = await build()
|
||||
expect(JSON.stringify(config.admin?.components ?? {})).not.toMatch(/SignIn|AdminLogo/)
|
||||
expect((config.endpoints ?? []).some((e) => e.path === '/ipal/admin-language')).toBe(false)
|
||||
})
|
||||
|
||||
test('allScreens adds the provider after the project\'s own; languages: false leaves the endpoint out', async () => {
|
||||
const config = await build({ whiteLabel: { signIn: { allScreens: true, languages: false } } }, { admin: { components: { providers: ['mine#Provider'] } } } as never)
|
||||
expect(config.admin?.components?.providers).toEqual(['mine#Provider', { path: SIGN_IN_LOOK, serverProps: { look: { languages: false } } }])
|
||||
expect((config.endpoints ?? []).some((e) => e.path === '/ipal/admin-language')).toBe(false)
|
||||
})
|
||||
|
||||
test('production: a provider the import map on disk lacks is left out (the panel must not go blank), and comes back with the entry', async () => {
|
||||
const dir = await mkdtemp(path.join(os.tmpdir(), 'iapl-sign-in-'))
|
||||
const file = path.join(dir, 'app/(payload)/admin/importMap.js')
|
||||
await mkdir(path.dirname(file), { recursive: true })
|
||||
vi.stubEnv('NODE_ENV', 'production')
|
||||
try {
|
||||
const withMap = () => build({ whiteLabel: { signIn: { allScreens: true } } }, { admin: { importMap: { baseDir: dir } } } as never)
|
||||
await writeFile(file, 'export const importMap = { "@intecion/ipal-kit/admin#AdminLogo": AdminLogo }')
|
||||
const stale = await withMap()
|
||||
expect(stale.admin?.components?.providers ?? []).toEqual([])
|
||||
expect(logo(stale).serverProps?.signIn).toEqual({}) // the login and 2FA screens keep the look
|
||||
const error = vi.fn()
|
||||
await Promise.resolve(stale.onInit?.({ config: stale, logger: { error, info: vi.fn(), warn: vi.fn() } } as never)).catch(() => undefined)
|
||||
expect(error.mock.calls.flat().join(' ')).toContain('The sign-in look covers only the login and 2FA screens')
|
||||
await writeFile(file, `export const importMap = { "${SIGN_IN_LOOK}": SignInLook }`)
|
||||
expect((await withMap()).admin?.components?.providers).toEqual([{ path: SIGN_IN_LOOK, serverProps: { look: {} } }])
|
||||
} finally {
|
||||
vi.unstubAllEnvs()
|
||||
await rm(dir, { force: true, recursive: true })
|
||||
}
|
||||
})
|
||||
|
||||
test('the 2FA screens: IAPL\'s wrapper gets the look, the views and their order stay', async () => {
|
||||
const withLook = await build({ twoFactor: { issuer: 'E', plugin: payloadTotp }, whiteLabel: true }, { collections: [] })
|
||||
const plain = await build({ twoFactor: { issuer: 'E', plugin: payloadTotp }, whiteLabel: { signIn: false } }, { collections: [] })
|
||||
const views = (config: Config) => config.admin?.components?.views as Record<string, { Component: { path?: string; serverProps?: Record<string, unknown> }; path: string }>
|
||||
expect(Object.keys(views(withLook))).toEqual(Object.keys(views(plain)))
|
||||
const wrapped = Object.values(views(withLook)).filter((v) => v.Component?.path === '@intecion/ipal-kit/admin#SafeTotpView')
|
||||
expect(wrapped.length).toBe(Object.values(views(plain)).filter((v) => v.Component?.path === '@intecion/ipal-kit/admin#SafeTotpView').length)
|
||||
expect(wrapped.length).toBeGreaterThan(0)
|
||||
for (const view of wrapped) {
|
||||
expect(view.Component.serverProps?.iaplSignIn).toEqual({})
|
||||
expect(view.Component.serverProps?.ipalTotpView).toBeTruthy()
|
||||
}
|
||||
for (const view of Object.values(views(plain))) {expect(view.Component?.serverProps?.iaplSignIn).toBeUndefined()}
|
||||
// nothing new for the import map here either
|
||||
expect(paths(withLook)).not.toContain(SIGN_IN_LOOK)
|
||||
})
|
||||
|
||||
test('the provider counts only when the config lists it AND the running import map has it', () => {
|
||||
const provider = { path: SIGN_IN_LOOK }
|
||||
const component = () => null
|
||||
expect(signInProviderActive(undefined)).toBe(false)
|
||||
expect(signInProviderActive({ config: { admin: { components: { providers: [provider] } } }, importMap: {} } as never)).toBe(false)
|
||||
expect(signInProviderActive({ config: { admin: { components: { providers: [] } } }, importMap: { [SIGN_IN_LOOK]: component } } as never)).toBe(false)
|
||||
expect(signInProviderActive({ config: { admin: { components: { providers: [provider] } } }, importMap: { [SIGN_IN_LOOK]: component } } as never)).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('what the public sign-in page may show', () => {
|
||||
test('the name is one line of plain text, cut at the limit', () => {
|
||||
expect(signInName(' Acme\n\tStudio
Ltd ')).toBe('Acme Studio Ltd')
|
||||
expect(signInName({ en: 'Acme', pl: 'Akme' }, 'pl')).toBe('Akme')
|
||||
expect(signInName({ en: 'Acme' }, 'pl')).toBe('Acme')
|
||||
expect(signInName(undefined)).toBe('')
|
||||
const long = signInName('x'.repeat(500))
|
||||
expect(long.length).toBe(SIGN_IN_NAME_MAX)
|
||||
expect(long.endsWith('…')).toBe(true)
|
||||
})
|
||||
|
||||
test('the logo: only an http(s) or site-relative address; SVG out when asked; never enlarged', () => {
|
||||
expect(signInLogo({ height: 100, url: '/api/media/file/logo.png', width: 400 })).toEqual({ height: 60, src: '/api/media/file/logo.png', width: 240 })
|
||||
expect(signInLogo({ height: 20, url: 'https://cdn.test/logo.webp', width: 60 })).toEqual({ height: 20, src: 'https://cdn.test/logo.webp', width: 60 })
|
||||
expect(signInLogo({ url: '/logo.png' })).toEqual({ src: '/logo.png' })
|
||||
for (const url of ['javascript:alert(1)', 'data:text/html,<script>1</script>', '//evil.test/x.png', 'file:///etc/passwd', '', ' ']) {
|
||||
expect(signInLogo({ url })).toBeNull()
|
||||
}
|
||||
expect(signInLogo('64f0…id-only')).toBeNull()
|
||||
expect(signInLogo(null)).toBeNull()
|
||||
const svg = { mimeType: 'image/svg+xml', url: '/api/media/file/logo.svg' }
|
||||
expect(signInLogo(svg)).toEqual({ src: svg.url })
|
||||
expect(signInLogo(svg, { svgLogo: false })).toBeNull()
|
||||
expect(signInLogo({ mimeType: 'image/png', url: '/api/media/file/renamed.SVG?v=2' }, { svgLogo: false })).toBeNull()
|
||||
expect(fitLogo(1000, 100)).toEqual({ height: 24, width: 240 })
|
||||
expect(fitLogo(0, 10)).toBeNull()
|
||||
})
|
||||
|
||||
test('markup in the name is text; the only links are the site, and the language endpoint', async () => {
|
||||
const payload = fakePayload({ siteName: '<script>alert(1)</script> <a href="https://evil.test">reset</a> https://evil.test' })
|
||||
const html = await panel({ i18n: { language: 'en', t: t as never }, look: {}, payload })
|
||||
expect(html).not.toContain('<script')
|
||||
expect(html).toContain('<script>alert(1)</script>')
|
||||
const hrefs = [...html.matchAll(/ href="([^"]*)"/g)].map((m) => m[1])
|
||||
expect(hrefs.sort()).toEqual(['/', '/api/ipal/admin-language?lng=pl'])
|
||||
expect(html).toContain('Administration panel')
|
||||
expect(html).toContain('aria-label="Language"')
|
||||
expect(html).toContain('<span aria-current="true" lang="en">English</span>')
|
||||
})
|
||||
|
||||
test('a logo: an <img> with the name as its text and its size, on a plate unless made for dark grounds', async () => {
|
||||
const payload = fakePayload({ logo: { height: 160, mimeType: 'image/png', url: '/api/media/file/logo.png', width: 560 }, siteName: 'Acme' })
|
||||
const html = await panel({ look: { languages: false }, payload })
|
||||
expect(html).toContain('<img alt="Acme" decoding="async" height="69" src="/api/media/file/logo.png" width="240"/>')
|
||||
expect(html).toContain('iapl-signin__brand--plate')
|
||||
expect(html).not.toContain('<nav')
|
||||
const dark = await panel({ look: { logoMadeFor: 'dark' }, payload })
|
||||
expect(dark).not.toContain('iapl-signin__brand--plate')
|
||||
})
|
||||
|
||||
test('nothing set, or no database: the label only — no vendor, no Payload', async () => {
|
||||
const empty = await panel({ look: {}, payload: fakePayload({}, { i18n: {}, serverURL: '' }) })
|
||||
expect(empty).toContain('Administration panel')
|
||||
expect(empty).not.toMatch(/Intecion|Payload|<img|<a /i)
|
||||
const failing = { config: { serverURL: 'https://site.test' }, findGlobal: vi.fn(() => Promise.reject(new Error('no database'))) } as unknown as Payload
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
|
||||
const down = await panel({ look: {}, payload: failing })
|
||||
warn.mockRestore()
|
||||
expect(down).toContain('site.test')
|
||||
expect(await panel({})).toContain('Administration panel')
|
||||
})
|
||||
|
||||
test('a session that owes its 2FA code never gets the media address: the picture itself, or the name', async () => {
|
||||
const settings = { logo: { url: 'https://site.test/api/media/file/logo.png' }, siteName: 'Acme' }
|
||||
const payload = fakePayload(settings, { custom: {} })
|
||||
const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(new Uint8Array([1, 2, 3]), { headers: { 'content-type': 'image/png' } }))
|
||||
// no 2FA guard configured in this fake: a signed-in user counts as passed, the address is used
|
||||
expect((await loadSignInBrand({ look: {}, payload, user: { id: 1, collection: 'users' } })).logo?.src).toBe(settings.logo.url)
|
||||
fetchSpy.mockRestore()
|
||||
expect((await loadSignInBrand({ look: {}, payload })).logo?.src).toBe(settings.logo.url)
|
||||
})
|
||||
|
||||
test('the stylesheet: no file, no font, no other host, no script; honours reduced motion and forced colours', () => {
|
||||
const css = signInCss()
|
||||
expect(css).not.toMatch(/url\(|@import|@font-face|https?:|expression\(|javascript:/i)
|
||||
expect(css).toContain('@media (prefers-reduced-motion:no-preference)')
|
||||
expect(css).toContain('@media (forced-colors:active)')
|
||||
expect(css).toContain('@media (max-width:52rem)')
|
||||
expect(css).toContain(':where(html[data-theme=dark])')
|
||||
// every rule needs the panel on the page: the stylesheet can be on any admin page
|
||||
const rules = css.split('}').map((r) => r.split('{')[0]).filter((s) => s && !s.startsWith('@') && !s.startsWith(':where('))
|
||||
expect(rules.filter((selector) => !selector.includes('.iapl-signin') && !selector.includes('/*'))).toEqual([])
|
||||
})
|
||||
|
||||
test('the logo component: the panel with signIn, nothing when the provider prints it, the plain logo without', async () => {
|
||||
const payload = fakePayload({ siteName: 'Acme' })
|
||||
const withLook = (await AdminLogo({ payload, signIn: { languages: false } })) as { props: Record<string, unknown>; type: unknown }
|
||||
expect(withLook.type).toBe(SignInPanel)
|
||||
expect(withLook.props).toMatchObject({ look: { languages: false }, payload })
|
||||
const withProvider = { ...payload, config: { ...payload.config, admin: { components: { providers: [{ path: SIGN_IN_LOOK }] } } }, importMap: { [SIGN_IN_LOOK]: () => null } } as unknown as Payload
|
||||
expect(await AdminLogo({ payload: withProvider, signIn: {} })).toBeNull()
|
||||
expect(renderToStaticMarkup((await AdminLogo({ payload })) as never)).toBe('<div style="font-size:2rem;font-weight:600">Acme</div>')
|
||||
})
|
||||
})
|
||||
|
||||
describe('the language links', () => {
|
||||
test('one language: no links; more: one link each, the current one marked', () => {
|
||||
expect(languageLinks({ i18n: { supportedLanguages: { pl: {} } } }, 'pl')).toEqual([])
|
||||
expect(languageLinks({ i18n: { supportedLanguages: { de: {}, xx: {}, 'x y': {} } }, routes: { api: '/cms' } }, 'de')).toEqual([
|
||||
{ name: 'Deutsch', code: 'de', current: true, href: '/cms/ipal/admin-language?lng=de' },
|
||||
{ name: 'XX', code: 'xx', current: false, href: '/cms/ipal/admin-language?lng=xx' },
|
||||
])
|
||||
})
|
||||
|
||||
test('the way back is a path inside the admin, whatever the Referer says', () => {
|
||||
expect(adminPathFromReferer('https://site.test/admin/forgot?x=1', '/admin')).toBe('/admin/forgot?x=1')
|
||||
expect(adminPathFromReferer('https://evil.test/admin/login', '/admin')).toBe('/admin/login') // a path only: the host is never used
|
||||
for (const referer of [undefined, null, '', 'not a url', 'https://site.test/', 'https://site.test/administrator', 'https://site.test//evil.test/admin', 'javascript:alert(1)', 'https://site.test/admin\\..\\x']) {
|
||||
expect(adminPathFromReferer(referer, '/admin')).toBe('/admin')
|
||||
}
|
||||
expect(adminPathFromReferer('https://site.test/its/login', '/its/')).toBe('/its/login')
|
||||
})
|
||||
|
||||
const endpoint = buildAdminLanguageEndpoint() as { handler: (req: PayloadRequest) => Response } & Endpoint
|
||||
const request = (lng: unknown, headers: Record<string, string> = {}) =>
|
||||
({
|
||||
headers: new Headers(headers),
|
||||
payload: { config: { cookiePrefix: 'acme', i18n: { supportedLanguages: { en: {}, pl: {} } }, routes: { admin: '/admin' } } },
|
||||
query: { lng },
|
||||
url: 'http://localhost:3000/api/ipal/admin-language',
|
||||
}) as unknown as PayloadRequest
|
||||
|
||||
test('a supported language: Payload\'s own cookie and a redirect back; nothing else can be written', () => {
|
||||
const res = endpoint.handler(request('pl', { referer: 'https://site.test/admin/login?redirect=%2Fadmin', 'x-forwarded-proto': 'https' }))
|
||||
expect(res.status).toBe(303)
|
||||
expect(res.headers.get('location')).toBe('/admin/login?redirect=%2Fadmin')
|
||||
expect(res.headers.get('set-cookie')).toBe('acme-lng=pl; Path=/; Max-Age=31536000; SameSite=Lax; Secure')
|
||||
expect(res.headers.get('cache-control')).toBe('no-store')
|
||||
for (const lng of ['de', '', undefined, ['pl'], 'pl; Domain=evil.test', 'pl\r\nSet-Cookie: x=1']) {
|
||||
const refused = endpoint.handler(request(lng))
|
||||
expect(refused.status).toBe(400)
|
||||
expect(refused.headers.get('set-cookie')).toBeNull()
|
||||
}
|
||||
expect(endpoint.method).toBe('get')
|
||||
})
|
||||
})
|
||||
|
||||
describe('whiteLabel.brandAccess', () => {
|
||||
const settings = (): GlobalConfig => ({
|
||||
slug: 'site-settings',
|
||||
fields: [
|
||||
{
|
||||
type: 'tabs',
|
||||
tabs: [
|
||||
{ fields: [{ name: 'siteName', type: 'text' }, { name: 'siteDescription', type: 'text' }, { name: 'logo', type: 'upload', relationTo: 'media' }], label: 'General' },
|
||||
],
|
||||
},
|
||||
],
|
||||
})
|
||||
const fieldsOf = (global: GlobalConfig) => (global.fields[0] as { tabs: { fields: { access?: { update?: (a: unknown) => Promise<boolean> }; name: string }[] }[] }).tabs[0].fields
|
||||
|
||||
test('the default leaves the fields as they are; "admin" locks the brand fields only, without a new field', async () => {
|
||||
const config = await build({ whiteLabel: true })
|
||||
const plain = config.globals!.find((g) => g.slug === 'site-settings')!
|
||||
expect(JSON.stringify(plain.fields)).toBe(JSON.stringify((await build()).globals!.find((g) => g.slug === 'site-settings')!.fields))
|
||||
|
||||
const locked = lockBrandFields([settings(), { slug: 'other', fields: [{ name: 'siteName', type: 'text' }] }], 'site-settings', ['siteName', 'logo', 'favicon'])
|
||||
const [siteName, description, logoField] = fieldsOf(locked[0])
|
||||
expect(description.access).toBeUndefined()
|
||||
expect((locked[1].fields[0] as { access?: unknown }).access).toBeUndefined()
|
||||
const staff = { collections: {}, config: { custom: { ipal: { staffCollections: ['users'] } } } }
|
||||
for (const field of [siteName, logoField]) {
|
||||
expect(await field.access!.update!({ req: { payload: staff, user: null } })).toBe(false)
|
||||
}
|
||||
expect(fieldsOf(locked[0]).map((f) => f.name)).toEqual(['siteName', 'siteDescription', 'logo'])
|
||||
})
|
||||
|
||||
test('through the plugin: an editor may not change the name, an admin may', async () => {
|
||||
const config = await build({ whiteLabel: { brandAccess: 'admin' } }, { collections: [{ slug: 'users', auth: true, fields: [] }, { slug: 'media', fields: [], upload: true }] } as never)
|
||||
const global = config.globals!.find((g) => g.slug === 'site-settings')!
|
||||
const find = (fields: unknown[], name: string): { access?: { update?: (a: unknown) => Promise<boolean> } } | undefined => {
|
||||
for (const f of fields as { fields?: unknown[]; name?: string; tabs?: { fields: unknown[] }[] }[]) {
|
||||
if (f.name === name) {return f as never}
|
||||
const inner = f.tabs ? f.tabs.flatMap((tab) => tab.fields) : f.fields
|
||||
const hit = inner ? find(inner, name) : undefined
|
||||
if (hit) {return hit}
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
const payload = { collections: { users: { config: { fields: [{ name: 'roles' }] } } }, config }
|
||||
const as = (roles: string[]) => ({ req: { payload, user: { id: 1, collection: 'users', roles } } })
|
||||
for (const name of ['siteName', 'logo', 'favicon']) {
|
||||
const update = find(global.fields, name)?.access?.update
|
||||
expect(update, name).toBeTypeOf('function')
|
||||
expect(await update!(as(['editor'])), name).toBe(false)
|
||||
expect(await update!(as(['admin'])), name).toBe(true)
|
||||
}
|
||||
expect(find(global.fields, 'siteDescription')?.access?.update).toBeUndefined()
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user