diff --git a/dev/app/(payload)/admin/importMap.js b/dev/app/(payload)/admin/importMap.js index e61ab42..6e0cbe8 100644 --- a/dev/app/(payload)/admin/importMap.js +++ b/dev/app/(payload)/admin/importMap.js @@ -1,4 +1,3 @@ -import { TOTPField as TOTPField_3eb2cc20d1a2569c2ccbafcee15bd128 } from '@clocklimited/payload-2fa/rsc' import { OverviewComponent as OverviewComponent_a8a977ebc872c5d5ea7ee689724c0860 } from '@payloadcms/plugin-seo/client' import { MetaTitleComponent as MetaTitleComponent_a8a977ebc872c5d5ea7ee689724c0860 } from '@payloadcms/plugin-seo/client' import { MetaDescriptionComponent as MetaDescriptionComponent_a8a977ebc872c5d5ea7ee689724c0860 } from '@payloadcms/plugin-seo/client' @@ -34,22 +33,21 @@ import { IntegrationStatusBanner as IntegrationStatusBanner_7568fe47d582ff15ce85 import { MaskedField as MaskedField_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin' import { TestEmailButton as TestEmailButton_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin' import { RowLabel as RowLabel_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin' +import { CookieReviewTab as CookieReviewTab_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin' +import { CookieSiteCheckTab as CookieSiteCheckTab_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin' +import { AdminIcon as AdminIcon_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin' +import { AdminLogo as AdminLogo_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin' +import { IntecionCredit as IntecionCredit_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin' import { StatsNavLink as StatsNavLink_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin' import { CookieCrawlAlert as CookieCrawlAlert_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin' import { StatsWidget as StatsWidget_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 { TOTPSetup as TOTPSetup_3eb2cc20d1a2569c2ccbafcee15bd128 } from '@clocklimited/payload-2fa/rsc' -import { TOTPVerify as TOTPVerify_3eb2cc20d1a2569c2ccbafcee15bd128 } from '@clocklimited/payload-2fa/rsc' import { CookieApprovalView as CookieApprovalView_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin' -import { CookieReviewTab as CookieReviewTab_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin' -import { CookieSiteCheckTab as CookieSiteCheckTab_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin' import { StatsView as StatsView_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin' import { CollectionCards as CollectionCards_f9c02e79a4aed9a3924487c0cd4cafb1 } from '@payloadcms/next/rsc' /** @type import('payload').ImportMap */ export const importMap = { - "@clocklimited/payload-2fa/rsc#TOTPField": TOTPField_3eb2cc20d1a2569c2ccbafcee15bd128, "@payloadcms/plugin-seo/client#OverviewComponent": OverviewComponent_a8a977ebc872c5d5ea7ee689724c0860, "@payloadcms/plugin-seo/client#MetaTitleComponent": MetaTitleComponent_a8a977ebc872c5d5ea7ee689724c0860, "@payloadcms/plugin-seo/client#MetaDescriptionComponent": MetaDescriptionComponent_a8a977ebc872c5d5ea7ee689724c0860, @@ -85,16 +83,16 @@ export const importMap = { "@intecion/ipal-kit/admin#MaskedField": MaskedField_7568fe47d582ff15ce85d2e1873c2c23, "@intecion/ipal-kit/admin#TestEmailButton": TestEmailButton_7568fe47d582ff15ce85d2e1873c2c23, "@intecion/ipal-kit/admin#RowLabel": RowLabel_7568fe47d582ff15ce85d2e1873c2c23, + "@intecion/ipal-kit/admin#CookieReviewTab": CookieReviewTab_7568fe47d582ff15ce85d2e1873c2c23, + "@intecion/ipal-kit/admin#CookieSiteCheckTab": CookieSiteCheckTab_7568fe47d582ff15ce85d2e1873c2c23, + "@intecion/ipal-kit/admin#AdminIcon": AdminIcon_7568fe47d582ff15ce85d2e1873c2c23, + "@intecion/ipal-kit/admin#AdminLogo": AdminLogo_7568fe47d582ff15ce85d2e1873c2c23, + "@intecion/ipal-kit/admin#IntecionCredit": IntecionCredit_7568fe47d582ff15ce85d2e1873c2c23, "@intecion/ipal-kit/admin#StatsNavLink": StatsNavLink_7568fe47d582ff15ce85d2e1873c2c23, "@intecion/ipal-kit/admin#CookieCrawlAlert": CookieCrawlAlert_7568fe47d582ff15ce85d2e1873c2c23, "@intecion/ipal-kit/admin#StatsWidget": StatsWidget_7568fe47d582ff15ce85d2e1873c2c23, "@intecion/ipal-kit/admin#IntegrationAlerts": IntegrationAlerts_7568fe47d582ff15ce85d2e1873c2c23, - "@intecion/ipal-kit/admin#TotpRedirectProvider": TotpRedirectProvider_7568fe47d582ff15ce85d2e1873c2c23, - "@clocklimited/payload-2fa/rsc#TOTPSetup": TOTPSetup_3eb2cc20d1a2569c2ccbafcee15bd128, - "@clocklimited/payload-2fa/rsc#TOTPVerify": TOTPVerify_3eb2cc20d1a2569c2ccbafcee15bd128, "@intecion/ipal-kit/admin#CookieApprovalView": CookieApprovalView_7568fe47d582ff15ce85d2e1873c2c23, - "@intecion/ipal-kit/admin#CookieReviewTab": CookieReviewTab_7568fe47d582ff15ce85d2e1873c2c23, - "@intecion/ipal-kit/admin#CookieSiteCheckTab": CookieSiteCheckTab_7568fe47d582ff15ce85d2e1873c2c23, "@intecion/ipal-kit/admin#StatsView": StatsView_7568fe47d582ff15ce85d2e1873c2c23, "@payloadcms/next/rsc#CollectionCards": CollectionCards_f9c02e79a4aed9a3924487c0cd4cafb1 } diff --git a/dev/payload.config.ts b/dev/payload.config.ts index 617aba1..3262408 100644 --- a/dev/payload.config.ts +++ b/dev/payload.config.ts @@ -76,6 +76,8 @@ export default buildConfig({ // 2FA is enforced by default; the dev sandbox opts out so it boots without an authenticator. // IPAL_DEV_2FA=1 turns it on (first-login setup and verify screens). twoFactor: process.env.IPAL_DEV_2FA ? { issuer: 'ipal-kit dev', plugin: payloadTotp } : false, + // Panel logo/icon from Site settings and the technology support credit. + whiteLabel: true, }), ], secret: process.env.PAYLOAD_SECRET || 'test-secret_key', diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index 53baefd..ea6da13 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -954,6 +954,7 @@ project → **plugin gap**, not a copy. | Mail | `email: mailAdapter()`, `sendEmail` | email.md | | Env validation, health | `assertEnv(ipalEnvRules({…}))` (`/env`), `healthRoute` | env.md | | 2FA, white-label, headers | `twoFactor: { issuer, plugin: payloadTotp }`, `whiteLabel`, `buildSecurityHeaders` | security.md, white-label.md | +| 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 `IPAL_IP_HEADER`; several instances → `setRateLimitStore` | forms.md | **Compliance (PL/EU) — the mechanism from the plugin, the content from the client:** policy pages diff --git a/docs/agent/skills/ipal-reference/SKILL.md b/docs/agent/skills/ipal-reference/SKILL.md index bb0c1b7..6b6d133 100644 --- a/docs/agent/skills/ipal-reference/SKILL.md +++ b/docs/agent/skills/ipal-reference/SKILL.md @@ -39,7 +39,9 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip | `whiteLabel.settingsSlug` | `'site-settings'` | global it reads the logo/name from | — | | `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` | `false`; `{ text, url }` overrides | +| `whiteLabel.credit` | on | `IntecionCredit` in `afterLogin` and `afterNavLinks`: "Technology support: Intecion.com" (en/pl, from `agency`) | `false`; `{ text, url }` overrides | +| `agency` | `{ name: 'Intecion.com', url: 'https://intecion.com' }` | the credit line, the panel's link description and preview image | `{ name, url }` = another agency; `false` = none anywhere | +| `adminMeta` | on (with or without `whiteLabel`) | panel ``: `robots` noindex/nofollow, `titleSuffix` "— \| Panel", `og:site_name` + description from Site settings (refreshed on save), `og:image` `GET /api/ipal/admin-og` (1200×630 from the logo or name), icon `GET /api/ipal/admin-icon` (favicon or initials); no import map step | `false` = Payload defaults; `{ robots, titleSuffix, description, image, icons, language }` (each `false` or your value; `{site}`, `{agency}` placeholders); your own `admin.meta` keys always win. Check: `curl -s $URL/admin/login \| grep -E 'og:\|robots'` (white-label.md) | | `pages` | none | Site settings → **System pages** (page roles) and **Maintenance** tabs | omit → neither tab | | `pages.slug` | — (required in `pages`) | the project's pages collection (System pages relations, construction, IndexNow) | — | | `pages.roles` | all: `homepage`, `notFound`, `privacyPolicy`, `cookiePolicy`, `termsOfService` | which assignments to show | subset of the array | diff --git a/docs/agent/skills/ipal-reference/resources/api.md b/docs/agent/skills/ipal-reference/resources/api.md index 03ab209..03afd3e 100644 --- a/docs/agent/skills/ipal-reference/resources/api.md +++ b/docs/agent/skills/ipal-reference/resources/api.md @@ -32,7 +32,11 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT | `CookieCrawlAlert` | `@intecion/ipal-kit/admin` | Server Component: dashboard warning — "Waiting for approval: N" with a link to the approval view, and with the crawl violations or a failed crawl; renders nothing otherwise. Props `approval`, `crawl`. Injected with `cookieScanner` (`approval.dashboard: false` / `crawl.dashboard: false` drop its parts); after turning it on, `pnpm generate:importmap`. | | `CookieScanButton` | `@intecion/ipal-kit/admin` | "Scan cookies" box above the *Cookie review* list: integrations in use, optional extra names, runs `POST /api/ipal/cookie-scan`. Injected by the plugin with `cookieScanner`; after turning it on, `pnpm generate:importmap`. | | `TotpRedirectProvider` | `@intecion/ipal-kit/admin` | Client admin provider: sends a user without TOTP to `/admin/setup-totp?back=…` and a user whose session has not passed TOTP to `/admin/verify-totp?back=…` (path read in the browser; never redirects away from those screens or logout; renders nothing while redirecting). Injected by the plugin with `twoFactor` in place of the package's header-based provider; swap with `twoFactor.provider`. After upgrading, `pnpm generate:importmap`. Check: a new admin lands on `setup-totp?back=%2Fadmin` with the QR code. Props type `TotpRedirectProviderProps` (`forceSetup`) | -| `IntecionCredit` | `@intecion/ipal-kit/admin` | The line "Technology supported by Intecion.com" below the nav and below the login form (`variant: 'nav' \| 'login'`). Injected by the plugin with `whiteLabel`; turn off: `whiteLabel: { credit: false }`. | +| `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`. | +| `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` (favicon redirect or initials) — already added by `adminMeta` | +| `DEFAULT_AGENCY`, `ADMIN_META_TEXTS` | `@intecion/ipal-kit` | Default agency `{ name: 'Intecion.com', url }`; en/pl meta texts (`{site}`, `{agency}`). Types `AdminMetaOptions`, `AgencyOption`, `ResolvedAdminMeta` | ## Readable array rows in the panel (`admin-ui`) — details: `node_modules/@intecion/ipal-kit/docs/links.md` diff --git a/docs/agent/skills/ipal-setup/SKILL.md b/docs/agent/skills/ipal-setup/SKILL.md index 33819e4..7a26c1d 100644 --- a/docs/agent/skills/ipal-setup/SKILL.md +++ b/docs/agent/skills/ipal-setup/SKILL.md @@ -163,6 +163,10 @@ the panel shows Site settings, Site integrations, Cookie banner, Notifications, 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. +- Panel link preview (`adminMeta`, on): noindex/nofollow, "— | 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: + `curl -s localhost:3000/admin/login | grep -E 'og:|robots'` → `noindex, nofollow`, `og:site_name` = Site settings name. - Mail: any Payload adapter instead of `mailAdapter()`; `mailAdapter({ fallbackFromAddress, smtp, graph })`. - R2: other storage-s3 options (prefix, clientUploads) → call `s3Storage` yourself instead of `buildR2Storage`. - `forms: { adminGroup, fields, formOverrides, formSubmissionOverrides, beforeEmail, emailLayout }` (forms.md). diff --git a/docs/agent/skills/ipal-upgrade/SKILL.md b/docs/agent/skills/ipal-upgrade/SKILL.md index 273fcea..cadc205 100644 --- a/docs/agent/skills/ipal-upgrade/SKILL.md +++ b/docs/agent/skills/ipal-upgrade/SKILL.md @@ -159,6 +159,11 @@ Cookies in every language; the dashboard shows the reminder while cookies wait. **Check:** one **Cookies** entry in the admin navigation; its tabs list the review entries and the site check; type a cookie purpose in one language and save → the other languages show it, and a language with its own text keeps it. +**→ panel link preview (`adminMeta`, `agency`):** remove a hand-written `admin.meta` that only set +the panel title, description, `openGraph` or `robots: noindex` — the plugin now fills them from Site settings +(keep any key you really want: your `admin.meta` keys win). The credit reads "Technology support: Intecion.com". +Check: `curl -s $URL/admin/login | grep -E 'og:|robots'` and paste an `/admin` link in Slack. + ## 2. Inventory (no code changes) For **every** item in the PROGRAMISTA §6 table show evidence (grep / file) of whether it applies to the project. Run the **ipal-audit** skill (`--quick`) and attach the result. diff --git a/docs/white-label.md b/docs/white-label.md index bdd75b4..bd320dc 100644 --- a/docs/white-label.md +++ b/docs/white-label.md @@ -43,29 +43,66 @@ whiteLabel: { | `nameField` | `'siteName'` | text fallback (localized → current locale, then the first available) | | `logoField` | `'logo'` | `graphics.Logo` → `AdminLogo` | | `iconField` | `'favicon'` | `graphics.Icon` → `AdminIcon` (max 28×28 px) | -| `titleSuffix` | none | `admin.meta.titleSuffix` | +| `titleSuffix` | none (`adminMeta` builds one from the site name) | static `admin.meta.titleSuffix`, wins over `adminMeta` | | `credit` | `true` | `false` or `{ text?, url? }` | The plugin overrides `admin.components.graphics.Logo` / `Icon` from the project config (its values win over yours); `afterLogin` / `afterNavLinks` are appended. -## Vendor credit — "Technology supported by Intecion.com" +## Technology support credit — "Technology support: Intecion.com" -A discreet credit **"Technology supported by Intecion.com"** (a link to -`https://intecion.com`) appears in **two places**: +A discreet line **"Technology support: Intecion.com"** (pl `Wsparcie technologiczne: Intecion.com`, +a link to `https://intecion.com`) appears in **two places**: - **under the panel navigation** (`afterNavLinks`, variant `nav` — left-aligned), - **at the bottom of the login screen** (`afterLogin`, variant `login` — centered). -It is a credit for the technology VENDOR (Intecion provides the ipal-kit framework) — the client's -brand still owns the logo and name; this is just a "who supports the technology" line. +It credits who supports the technology — the client's brand still owns the logo and name. +The agency comes from the top-level `agency` option (default `{ name: 'Intecion.com', url: 'https://intecion.com' }`), +the same one the panel's link preview uses (below). On by default with `whiteLabel`. Control: ```ts -whiteLabel: { credit: false } // hide (both places) -whiteLabel: { credit: { text: 'Powered by Intecion', url: 'https://intecion.com' } } // custom text/url +ipalKit({ agency: { name: 'Studio X', url: 'https://studio.example' } }) // another agency, everywhere +ipalKit({ agency: false }) // no agency anywhere +whiteLabel: { credit: false } // hide the line (both places) +whiteLabel: { credit: { text: 'Powered by Intecion', url: 'https://intecion.com' } } // own text/url ``` +The default text follows the admin language (key `brandingCredit`, `{{agency}}` placeholder); +override it per language in `i18n.translations..ipal.brandingCredit`. + +## Link previews and search engines — `adminMeta` (on by default) + +A pasted `/admin` link (Slack, Messenger, Teams…) used to show "Payload App" and Payload's generic +image. The plugin now fills the panel's `` from Site settings, **with or without `whiteLabel`**: + +| Piece | Default | Turn off / override | +|---|---|---| +| robots | `noindex, nofollow` on every panel page | `adminMeta: { robots: false }` or `{ robots: { index, follow } }`; your `admin.meta.robots` wins | +| title suffix | `— \| Panel` | `adminMeta: { titleSuffix: '· {site} admin' }` or `false`; `whiteLabel.titleSuffix` / your `admin.meta.titleSuffix` win | +| `og:site_name` | the site name | your `admin.meta.openGraph.siteName` wins | +| description | "Administration panel of . Built on Payload CMS, technology support: Intecion.com." (Polish when the site's default locale is `pl`) | `adminMeta: { description: 'Panel of {site}' }` (string or `{ en, pl }`), `false`; `language: 'en' \| 'pl'`; your `admin.meta.description` wins | +| preview image | `GET /api/ipal/admin-og` — 1200×630 PNG: the site's logo (or name), "Administration panel", "Technology support: Intecion.com" | `adminMeta: { image: '/my-og.png' }` or `false`; your `admin.meta.openGraph.images` wins | +| icon | `GET /api/ipal/admin-icon` — redirects to the site's favicon, or draws the initials | `adminMeta: { icons: false }`; your `admin.meta.icons` win | +| everything | on | `adminMeta: false` = Payload's defaults | + +- **How:** Payload builds every panel page's metadata from `config.admin.meta`. The plugin sets the + static parts at config time and fills the site-name parts on start and after every Site settings save + (`syncAdminMeta`). Keys you set in `admin.meta` are never touched. +- **The image** is drawn on the server with `next/og` (no external service, cached 1 h). The logo is + read from the upload itself: PNG, JPG, GIF or SVG; a WebP/AVIF logo falls back to the site name. + The image endpoints are public (link previews fetch without a session) and show only the logo and + name the site shows anyway. Fields: `whiteLabel.settingsSlug` / `nameField` / `logoField` / `iconField`. +- **No import map step** — no new admin components (endpoints only). +- **Search engines:** besides the `noindex, nofollow` meta, `getRobots()` already disallows `/admin` + (and `/api`) in robots.txt; `IPAL_NOINDEX=1` adds `X-Robots-Tag` to every response on staging. +- **Building blocks:** `buildAdminMeta`, `adminMetaForSite`, `syncAdminMeta`, `buildAdminImageEndpoints`, + `DEFAULT_AGENCY`, `ADMIN_META_TEXTS`; types `AdminMetaOptions`, `AgencyOption`, `ResolvedAdminMeta`. +- **Verify:** `curl -s $URL/admin/login | grep -E 'og:|robots|) => string }; text?: string; url?: string; variant?: 'login' | 'nav' } = {}, + props: { + /** Agency name in the default text (`agency` option). Default "Intecion.com". */ + agency?: string + i18n?: { t: (key: never, vars?: Record) => string } + text?: string + url?: string + variant?: 'login' | 'nav' + } = {}, ) { - const { i18n, url = 'https://intecion.com', variant = 'nav' } = props + const { agency = 'Intecion.com', i18n, url = 'https://intecion.com', variant = 'nav' } = props // A project's own text wins; otherwise the plugin's text in the admin language. - const text = props.text ?? (i18n ? ipalT(i18n.t, 'brandingCredit') : settingsTexts.en.brandingCredit) + const text = + props.text ?? + (i18n ? ipalT(i18n.t, 'brandingCredit', { agency }) : settingsTexts.en.brandingCredit.replace('{{agency}}', agency)) const style = variant === 'login' ? { diff --git a/src/modules/branding/adminImages.tsx b/src/modules/branding/adminImages.tsx new file mode 100644 index 0000000..26a67e1 --- /dev/null +++ b/src/modules/branding/adminImages.tsx @@ -0,0 +1,125 @@ +import type { Endpoint, PayloadRequest } from 'payload' + +import type { AgencyOption, ResolvedAdminMeta } from './adminMeta.js' + +import { ADMIN_ICON_PATH, ADMIN_META_TEXTS, ADMIN_OG_PATH } from './adminMeta.js' + +/** + * The panel's link-preview image (1200×630) and icon, drawn from SiteSettings: + * logo (or the site name), "Administration panel" and a small technology + * support line. Rendered on the server with next/og — no external service. + * Public (link previews fetch without a session); they show only what the site + * already shows publicly. Never throw: a missing logo or setting falls back to + * the site name, then to initials. + */ + +type Fields = { iconField?: string; logoField?: string; nameField?: string; settingsSlug?: string } + +type Branding = { icon: null | string; logo: null | string; name: string } + +const CACHE = 'public, max-age=3600, s-maxage=3600' + +async function loadBranding(req: PayloadRequest, f: Required): Promise { + try { + const locale = req.payload.config.localization ? req.payload.config.localization.defaultLocale : undefined + const s = (await req.payload.findGlobal({ slug: f.settingsSlug as never, depth: 1, ...(locale ? { locale: locale as never } : {}), req })) as Record + const url = (v: unknown) => (v && typeof v === 'object' && typeof (v as { url?: unknown }).url === 'string' ? (v as { url: string }).url : null) + const name = typeof s[f.nameField] === 'string' ? (s[f.nameField] as string).trim() : '' + return { name, icon: url(s[f.iconField]), logo: url(s[f.logoField]) } + } catch { + return { name: '', icon: null, logo: null } + } +} + +/** Absolute URL of an upload, resolved against the request (uploads are often relative). */ +const absolute = (url: string, req: PayloadRequest) => new URL(url, req.url ?? `http://localhost`).toString() + +/** The image as a data URI, so the renderer needs no network access of its own. */ +async function inline(url: null | string, req: PayloadRequest): Promise { + if (!url) {return null} + try { + const res = await fetch(absolute(url, req)) + if (!res.ok) {return null} + const type = res.headers.get('content-type') ?? 'image/png' + // The renderer can't draw WebP/AVIF; the site name is shown instead. + if (!/png|jpe?g|gif|svg/.test(type)) {return null} + return `data:${type};base64,${Buffer.from(await res.arrayBuffer()).toString('base64')}` + } catch { + return null + } +} + +// Loaded on first use, so the Payload CLI (which reads this config outside Next) never loads it; +// '.js' because next has no exports map (plain Node ESM can't resolve 'next/og'). +const imageResponse = async () => (await import('next/og.js')).ImageResponse + +const initials = (name: string) => + name + .split(/\s+/) + .filter(Boolean) + .slice(0, 2) + .map((w) => w[0].toUpperCase()) + .join('') || 'A' + +export function buildAdminImageEndpoints(resolved: ResolvedAdminMeta, fields: Fields = {}): Endpoint[] { + const f: Required = { + iconField: fields.iconField ?? 'favicon', + logoField: fields.logoField ?? 'logo', + nameField: fields.nameField ?? 'siteName', + settingsSlug: fields.settingsSlug ?? 'site-settings', + } + const texts = ADMIN_META_TEXTS[resolved.language] + const agency: AgencyOption | false = resolved.agency + + const og: Endpoint = { + handler: async (req) => { + const brand = await loadBranding(req, f) + const logo = await inline(brand.logo, req) + const ImageResponse = await imageResponse() + const image = new ImageResponse( + ( +
+ {logo ? ( + // Rendered by next/og, not the browser. + + ) : ( +
{brand.name || texts.imageTitle}
+ )} +
{texts.imageTitle}
+ {agency ? ( +
+ {texts.imageLine.replace('{agency}', agency.name)} +
+ ) : null} +
+ ), + { headers: { 'Cache-Control': CACHE }, height: 630, width: 1200 }, + ) + return image + }, + method: 'get', + path: ADMIN_OG_PATH, + } + + const icon: Endpoint = { + handler: async (req) => { + const brand = await loadBranding(req, f) + if (brand.icon) { + return new Response(null, { headers: { 'Cache-Control': CACHE, Location: absolute(brand.icon, req) }, status: 302 }) + } + const ImageResponse = await imageResponse() + return new ImageResponse( + ( +
+ {initials(brand.name)} +
+ ), + { headers: { 'Cache-Control': CACHE }, height: 64, width: 64 }, + ) + }, + method: 'get', + path: ADMIN_ICON_PATH, + } + + return [og, icon] +} diff --git a/src/modules/branding/adminMeta.ts b/src/modules/branding/adminMeta.ts new file mode 100644 index 0000000..017d26e --- /dev/null +++ b/src/modules/branding/adminMeta.ts @@ -0,0 +1,190 @@ +import type { Config, Payload } from 'payload' + +import type { AdminText } from '../admin-i18n/index.js' + +/** + * Admin panel for link previews and search engines: what Slack, + * Messenger and similar show for a pasted /admin link, and noindex for robots. + * + * Payload builds every admin page's metadata from `config.admin.meta` on each + * request, so the plugin + * - sets static defaults at config time (robots, preview image and icon + * pointing at the plugin's own endpoints), and + * - fills the site-dependent parts (title suffix, description, siteName) + * from SiteSettings on start and after every Site settings save. + * Next may load the config more than once per process (dev recompiles, route + * bundles), so the site name lives in a process-wide store and the meta reads + * it through getters: `openGraph` keeps its object reference through Payload's + * sanitize, so its getters run on every request; the top-level `titleSuffix` + * and `description` are read when a config is loaded, and the live config is + * updated in place as well. + * A key the project set in its own `admin.meta` is never touched. + */ + +/** Who supports the technology: named in the credit, the description and the preview image. */ +export type AgencyOption = { name: string; url: string } + +export const DEFAULT_AGENCY: AgencyOption = { name: 'Intecion.com', url: 'https://intecion.com' } + +export type AdminMetaOptions = { + /** Description for link previews; `{site}` and `{agency}` are replaced. `false` = Payload's own. */ + description?: AdminText | false | string + /** Favicon of the panel from SiteSettings (`/api/ipal/admin-icon`). `false` = Payload's own. */ + icons?: boolean + /** Preview image: generated from the site's logo (`/api/ipal/admin-og`), your own URL, or `false` = Payload's own. */ + image?: false | string + /** Language of the description and suffix. Default: the site's default locale when it is `pl`, else `en`. */ + language?: 'en' | 'pl' + /** Robots meta. Default noindex, nofollow. `false` = none. */ + robots?: { follow?: boolean; index?: boolean } | false + /** Browser-tab suffix; `{site}` is replaced. Default "— {site} | Panel". `false` = none. */ + titleSuffix?: false | string +} + +export const ADMIN_META_TEXTS = { + en: { + description: 'Administration panel of {site}. Built on Payload CMS, technology support: {agency}.', + descriptionNoAgency: 'Administration panel of {site}. Built on Payload CMS.', + imageLine: 'Technology support: {agency}', + imageTitle: 'Administration panel', + titleSuffix: '— {site} | Panel', + titleSuffixNoSite: '| Panel', + }, + pl: { + description: 'Panel administracyjny witryny {site}. Zbudowany na Payload CMS, wsparcie technologiczne: {agency}.', + descriptionNoAgency: 'Panel administracyjny witryny {site}. Zbudowany na Payload CMS.', + imageLine: 'Wsparcie technologiczne: {agency}', + imageTitle: 'Panel administracyjny', + titleSuffix: '— {site} | Panel', + titleSuffixNoSite: '| Panel', + }, +} + +type Store = { site?: string } +const STORE_KEY = Symbol.for('ipal.adminMeta') +/** Process-wide: the site name the meta getters read. */ +export const adminMetaStore = (): Store => { + const g = globalThis as unknown as Record + return (g[STORE_KEY] ??= {}) +} + +export const ADMIN_OG_PATH = '/ipal/admin-og' +export const ADMIN_ICON_PATH = '/ipal/admin-icon' + +type Meta = NonNullable['meta']> + +const fill = (template: string, site: string, agency: AgencyOption | false) => + template.replaceAll('{site}', site).replaceAll('{agency}', agency ? agency.name : '').trim() + +export type ResolvedAdminMeta = { + agency: AgencyOption | false + language: 'en' | 'pl' + options: AdminMetaOptions + /** Keys the project set itself in admin.meta — never overwritten. */ + own: { description: boolean; icons: boolean; images: boolean; robots: boolean; siteName: boolean; titleSuffix: boolean } +} + +/** Static defaults at config time. Returns the new meta and what the runtime sync may fill. */ +export function buildAdminMeta({ + agency, + apiRoute = '/api', + defaultLocale, + meta = {}, + options = {}, +}: { + agency: AgencyOption | false + apiRoute?: string + defaultLocale?: string + meta?: Meta + options?: AdminMetaOptions +}): { meta: Meta; resolved: ResolvedAdminMeta } { + const og = (meta.openGraph ?? {}) as Record + const own = { + description: meta.description !== undefined || og.description !== undefined, + icons: meta.icons !== undefined, + images: og.images !== undefined, + robots: meta.robots !== undefined, + siteName: og.siteName !== undefined, + titleSuffix: meta.titleSuffix !== undefined, + } + const language = options.language ?? (defaultLocale?.toLowerCase().startsWith('pl') ? 'pl' : 'en') + const api = apiRoute.replace(/\/$/, '') + const next: Meta = { ...meta } + const openGraph: Record = { ...og } + const resolved: ResolvedAdminMeta = { agency, language, options, own } + const current = () => { + const site = adminMetaStore().site + return site ? adminMetaForSite(site, resolved) : null + } + const getter = (target: object, key: string, read: () => unknown) => + Object.defineProperty(target, key, { configurable: true, enumerable: true, get: read }) + + if (!own.titleSuffix && options.titleSuffix !== false) { + getter(next, 'titleSuffix', () => current()?.titleSuffix ?? ADMIN_META_TEXTS[language].titleSuffixNoSite) + } + if (!own.description && options.description !== false) { + getter(next, 'description', () => current()?.description) + getter(openGraph, 'description', () => current()?.description) + } + if (!own.siteName) {getter(openGraph, 'siteName', () => current()?.siteName)} + + if (!own.robots && options.robots !== false) { + next.robots = { follow: false, index: false, ...(options.robots ?? {}) } as Meta['robots'] + } + if (!own.images && options.image !== false) { + openGraph.images = [{ height: 630, url: options.image ?? `${api}${ADMIN_OG_PATH}`, width: 1200 }] + } + if (!own.icons && options.icons !== false) { + next.icons = [{ rel: 'icon', url: `${api}${ADMIN_ICON_PATH}` }] as Meta['icons'] + } + if (Object.keys(openGraph).length) {next.openGraph = openGraph as Meta['openGraph']} + return { meta: next, resolved } +} + +/** Site-dependent parts of the meta for a given site name. */ +export function adminMetaForSite(site: string, { agency, language, options }: ResolvedAdminMeta) { + const texts = ADMIN_META_TEXTS[language] + const description = + options.description === false + ? undefined + : fill( + typeof options.description === 'string' + ? options.description + : options.description + ? options.description[language] + : agency + ? texts.description + : texts.descriptionNoAgency, + site, + agency, + ) + const titleSuffix = options.titleSuffix === false ? undefined : fill(options.titleSuffix ?? texts.titleSuffix, site, agency) + return { description, siteName: site, titleSuffix } +} + +/** + * Writes the site-dependent parts into the live config Payload reads for every + * admin page. Never throws; skips keys the project set itself. + */ +export async function syncAdminMeta( + payload: Payload, + resolved: ResolvedAdminMeta, + { nameField = 'siteName', settingsSlug = 'site-settings' }: { nameField?: string; settingsSlug?: string } = {}, +): Promise { + try { + const locale = payload.config.localization ? payload.config.localization.defaultLocale : undefined + const settings = (await payload.findGlobal({ slug: settingsSlug as never, depth: 0, ...(locale ? { locale: locale as never } : {}) })) as Record + const raw = settings[nameField] + const site = typeof raw === 'string' ? raw.trim() : '' + if (!site) {return} + adminMetaStore().site = site + // The live config was sanitized before this ran: its top-level values are plain copies. + const { description, titleSuffix } = adminMetaForSite(site, resolved) + const meta = payload.config.admin.meta as (Meta & Record) | undefined + if (!meta) {return} + if (!resolved.own.description && resolved.options.description !== false && description) {meta.description = description} + if (!resolved.own.titleSuffix && resolved.options.titleSuffix !== false && titleSuffix) {meta.titleSuffix = titleSuffix} + } catch (error) { + payload.logger.warn({ err: error, msg: '[ipal] admin meta: could not read Site settings; Payload defaults stay.' }) + } +} diff --git a/src/plugin.ts b/src/plugin.ts index 81e1410..29711f4 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -1,5 +1,6 @@ import type { Config, Plugin } from 'payload' +import type { ResolvedAdminMeta } from './modules/branding/adminMeta.js' import type { IpalOptions, TotpPluginFactory } from './types.js' import { buildCookieSettings } from './globals/CookieSettings/index.js' @@ -10,6 +11,8 @@ import { buildSiteIntegrations } from './globals/SiteIntegrations/index.js' import { buildSiteSettings } from './globals/SiteSettings/index.js' import { adminOnly, adminOrSelf, injectRoles } from './modules/access/index.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 { 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' @@ -222,6 +225,8 @@ export const ipalKit = (options: IpalOptions): Plugin => { } } + const agency = options.agency === undefined ? DEFAULT_AGENCY : options.agency + // --- white-label admin branding --- // Inject admin.components.graphics.Logo/Icon pointing at the plugin's // /admin export. The components read SiteSettings at render, so each client @@ -237,14 +242,16 @@ export const ipalKit = (options: IpalOptions): Plugin => { // Vendor credit ("Technology by Intecion.com") under the nav — on by // default, hidden with credit:false, text/url overridable. - const creditOn = wl.credit !== false - const creditProps = - wl.credit && typeof wl.credit === 'object' + const creditOn = wl.credit !== false && agency !== false + const creditProps = { + ...(agency ? { agency: agency.name, url: agency.url } : {}), + ...(wl.credit && typeof wl.credit === 'object' ? { ...(wl.credit.text ? { text: wl.credit.text } : {}), ...(wl.credit.url ? { url: wl.credit.url } : {}), } - : {} + : {}), + } config.admin = { ...(config.admin ?? {}), @@ -280,6 +287,33 @@ export const ipalKit = (options: IpalOptions): Plugin => { } } + // --- admin : link previews + noindex (default on) --- + // Static parts now; the site name parts come from Site settings in onInit + // and after every save (syncAdminMeta). The project's own admin.meta keys win. + let adminMeta: null | ResolvedAdminMeta = null + const brandFields = options.whiteLabel && options.whiteLabel !== true ? options.whiteLabel : {} + const settingsSlug = brandFields.settingsSlug ?? 'site-settings' + if (options.adminMeta !== false) { + const built = buildAdminMeta({ + agency, + apiRoute: config.routes?.api, + defaultLocale: options.i18n.defaultLocale, + meta: config.admin?.meta, + options: options.adminMeta ?? {}, + }) + adminMeta = built.resolved + config.admin = { ...(config.admin ?? {}), meta: built.meta } + config.endpoints = [ + ...(config.endpoints ?? []), + ...buildAdminImageEndpoints(built.resolved, { + iconField: brandFields.iconField, + logoField: brandFields.logoField, + nameField: brandFields.nameField, + settingsSlug, + }), + ] + } + // --- i18n --- config.localization = buildLocalizationConfig(options.i18n) // Admin languages (en + pl unless the project set its own) and the plugin's texts. @@ -349,6 +383,28 @@ export const ipalKit = (options: IpalOptions): Plugin => { // The project's globalOverrides win (access, admin, hooks merged; a function = full control). config.globals = [...(config.globals ?? []), ...applyGlobalOverrides(withRevalidate, options.globalOverrides)] + // A new site name refreshes the panel's link preview texts. + if (adminMeta) { + const resolved = adminMeta + config.globals = config.globals.map((g) => + g.slug === settingsSlug + ? { + ...g, + hooks: { + ...g.hooks, + afterChange: [ + ...(g.hooks?.afterChange ?? []), + async ({ doc, req }) => { + await syncAdminMeta(req.payload, resolved, { nameField: brandFields.nameField, settingsSlug }) + return doc + }, + ], + }, + } + : g, + ) + } + config.endpoints = [...(config.endpoints ?? []), testEmailEndpoint] // --- consent log: proof of consent (opt-in) --- @@ -502,6 +558,7 @@ export const ipalKit = (options: IpalOptions): Plugin => { config.onInit = async (payload) => { if (incomingOnInit) {await incomingOnInit(payload)} await migrateCookieSettingsSaveButton(payload) + if (adminMeta) {await syncAdminMeta(payload, adminMeta, { nameField: brandFields.nameField, settingsSlug })} payload.logger.info('[ipal] Plugin initialized.') } diff --git a/src/types.ts b/src/types.ts index fc8eba5..d0be10f 100644 --- a/src/types.ts +++ b/src/types.ts @@ -14,6 +14,7 @@ export type TotpPluginFactory = (options: { }) => Plugin import type { GlobalOverrides } from './globals/overrides.js' import type { AccessOption } from './modules/access/types.js' +import type { AdminMetaOptions, AgencyOption } from './modules/branding/adminMeta.js' import type { ConsentLogOptions } from './modules/consent/consentLog.js' import type { CookieScannerOptions } from './modules/consent/scanner/types.js' import type { ContentOption } from './modules/content/types.js' @@ -35,6 +36,15 @@ export type IpalOptions = { */ access?: AccessOption + /** + * Admin panel for link previews and search engines (default on): + * noindex/nofollow, title suffix "— | Panel", siteName and a short + * description from Site settings, a preview image drawn from the site's logo + * (GET /api/ipal/admin-og) and the site's favicon (GET /api/ipal/admin-icon). + * Keys the project sets in its own `admin.meta` always win. `false` = Payload's defaults. + */ + adminMeta?: AdminMetaOptions | false + /** * Custom admin panel route, e.g. '/its' instead of the default '/admin'. * The plugin sets config.routes.admin. IMPORTANT: this alone isn't enough — @@ -47,6 +57,13 @@ export type IpalOptions = { */ adminRoute?: string + /** + * Who supports the technology, named in the admin credit, the panel's link + * description and its preview image. Default `{ name: 'Intecion.com', url: 'https://intecion.com' }`. + * `false` = no agency anywhere. + */ + agency?: AgencyOption | false + /** Internationalization — locales, default locale, fallback behavior */ /** * Consent log (proof of consent, GDPR Art. 7(1)): adds the `consent-records` diff --git a/test/adminMeta.test.ts b/test/adminMeta.test.ts new file mode 100644 index 0000000..46f2e9e --- /dev/null +++ b/test/adminMeta.test.ts @@ -0,0 +1,155 @@ +import type { Config, Endpoint, Payload, PayloadRequest } from 'payload' + +import { beforeEach, describe, expect, test, vi } from 'vitest' + +import { buildAdminImageEndpoints } from '../src/modules/branding/adminImages.js' +import { adminMetaForSite, adminMetaStore, buildAdminMeta, DEFAULT_AGENCY, syncAdminMeta } from '../src/modules/branding/adminMeta.js' +import { ipalKit } from '../src/plugin.js' + +const i18n = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }, { code: 'en', label: 'English' }] } +const base = (meta?: Record): Config => + ({ admin: meta ? { meta } : {}, collections: [{ slug: 'users', auth: true, fields: [] }], secret: 'test' }) as unknown as Config + +describe('admin meta defaults', () => { + beforeEach(() => { + delete adminMetaStore().site + }) + + test('noindex, generated preview image and icon by default', () => { + const { meta } = buildAdminMeta({ agency: DEFAULT_AGENCY }) + expect(meta.robots).toEqual({ follow: false, index: false }) + expect((meta.openGraph as { images: { url: string }[] }).images[0]).toMatchObject({ height: 630, url: '/api/ipal/admin-og', width: 1200 }) + expect(meta.icons).toEqual([{ rel: 'icon', url: '/api/ipal/admin-icon' }]) + }) + + test("the project's own admin.meta keys win", () => { + const own = { icons: [{ url: '/mine.png' }], openGraph: { images: [{ url: '/og.png' }], siteName: 'Mine' }, robots: 'all', titleSuffix: ' · Mine' } + const { meta, resolved } = buildAdminMeta({ agency: DEFAULT_AGENCY, meta: own as never }) + expect(meta).toMatchObject(own) + expect(resolved.own).toMatchObject({ icons: true, images: true, robots: true, siteName: true, titleSuffix: true }) + }) + + test('options turn each piece off or replace it', () => { + const { meta } = buildAdminMeta({ agency: DEFAULT_AGENCY, options: { icons: false, image: '/brand.png', robots: false } }) + expect(meta.robots).toBeUndefined() + expect(meta.icons).toBeUndefined() + expect((meta.openGraph as { images: { url: string }[] }).images[0].url).toBe('/brand.png') + }) + + test('texts follow the site language and name the agency', () => { + const pl = buildAdminMeta({ agency: DEFAULT_AGENCY, defaultLocale: 'pl' }).resolved + expect(adminMetaForSite('Architekt Imprez', pl)).toEqual({ + description: 'Panel administracyjny witryny Architekt Imprez. Zbudowany na Payload CMS, wsparcie technologiczne: Intecion.com.', + siteName: 'Architekt Imprez', + titleSuffix: '— Architekt Imprez | Panel', + }) + const en = buildAdminMeta({ agency: false, defaultLocale: 'en' }).resolved + expect(adminMetaForSite('Acme', en).description).toBe('Administration panel of Acme. Built on Payload CMS.') + const own = buildAdminMeta({ agency: DEFAULT_AGENCY, options: { description: 'Panel {site}', titleSuffix: false } }).resolved + expect(adminMetaForSite('Acme', own)).toMatchObject({ description: 'Panel Acme', titleSuffix: undefined }) + }) + + test('sync writes the site name parts into the live config, keeping project keys', async () => { + const { meta, resolved } = buildAdminMeta({ agency: DEFAULT_AGENCY, defaultLocale: 'en', meta: { titleSuffix: ' · Mine' } as never }) + const payload = { + config: { admin: { meta }, localization: { defaultLocale: 'en' } }, + findGlobal: vi.fn(async () => ({ siteName: 'Acme' })), + logger: { warn: vi.fn() }, + } as unknown as Payload + await syncAdminMeta(payload, resolved) + expect(payload.config.admin.meta).toMatchObject({ + description: 'Administration panel of Acme. Built on Payload CMS, technology support: Intecion.com.', + openGraph: { siteName: 'Acme' }, + robots: { follow: false, index: false }, + titleSuffix: ' · Mine', + }) + }) + + test('before the site name is known: a neutral suffix, no site name', () => { + const { meta } = buildAdminMeta({ agency: DEFAULT_AGENCY, defaultLocale: 'pl' }) + expect(meta.titleSuffix).toBe('| Panel') + expect((meta.openGraph as Record).siteName).toBeUndefined() + }) + + test('the meta reads the current site name on every access (openGraph survives a shallow copy)', () => { + const { meta } = buildAdminMeta({ agency: DEFAULT_AGENCY, defaultLocale: 'en' }) + const sanitized = { titleSuffix: '- Payload', ...meta } // what Payload's sanitize does + adminMetaStore().site = 'Acme' + expect({ ...(sanitized.openGraph as object) }).toMatchObject({ siteName: 'Acme' }) + expect({ ...meta }.titleSuffix).toBe('— Acme | Panel') + adminMetaStore().site = 'Acme 2' + expect((sanitized.openGraph as Record).description).toContain('Acme 2') + }) + + test('sync never throws', async () => { + const { resolved } = buildAdminMeta({ agency: DEFAULT_AGENCY }) + const warn = vi.fn() + const payload = { config: { admin: {} }, findGlobal: vi.fn(async () => { throw new Error('db down') }), logger: { warn } } as unknown as Payload + await expect(syncAdminMeta(payload, resolved)).resolves.toBeUndefined() + expect(warn).toHaveBeenCalled() + }) +}) + +describe('plugin wiring', () => { + test('on by default: meta, endpoints, Site settings hook; agency in the credit', async () => { + const config = await ipalKit({ i18n, twoFactor: false, whiteLabel: true } as never)(base()) + expect(config.admin?.meta?.robots).toEqual({ follow: false, index: false }) + const paths = (config.endpoints ?? []).map((e) => e.path) + expect(paths).toEqual(expect.arrayContaining(['/ipal/admin-og', '/ipal/admin-icon'])) + const settings = config.globals!.find((g) => g.slug === 'site-settings')! + expect(settings.hooks?.afterChange?.length).toBeGreaterThan(0) + const credit = config.admin!.components!.afterLogin!.find((c) => typeof c === 'object' && c.path.endsWith('#IntecionCredit')) as { serverProps: Record } + expect(credit.serverProps).toMatchObject({ agency: 'Intecion.com', url: 'https://intecion.com', variant: 'login' }) + }) + + test('adminMeta: false and agency: false switch the pieces off', async () => { + const config = await ipalKit({ adminMeta: false, agency: false, i18n, twoFactor: false, whiteLabel: true } as never)(base()) + expect(config.admin?.meta?.robots).toBeUndefined() + expect((config.endpoints ?? []).some((e) => e.path === '/ipal/admin-og')).toBe(false) + expect(config.admin?.components?.afterLogin ?? []).toEqual([]) + }) + + test('a custom agency reaches the credit; whiteLabel.credit text still wins', async () => { + const config = await ipalKit({ + agency: { name: 'Studio X', url: 'https://studio.example' }, + i18n, + twoFactor: false, + whiteLabel: { credit: { text: 'Made by X' } }, + } as never)(base()) + const credit = config.admin!.components!.afterNavLinks!.find((c) => typeof c === 'object' && c.path.endsWith('#IntecionCredit')) as { serverProps: Record } + expect(credit.serverProps).toMatchObject({ agency: 'Studio X', text: 'Made by X', url: 'https://studio.example' }) + }) +}) + +describe('preview image endpoints', () => { + const req = (settings: Record) => + ({ payload: { config: { localization: false }, findGlobal: vi.fn(async () => settings) }, url: 'http://localhost:3000/api/ipal/admin-og' }) as unknown as PayloadRequest + const [og, icon] = buildAdminImageEndpoints(buildAdminMeta({ agency: DEFAULT_AGENCY }).resolved) as [Endpoint, Endpoint] + + test('renders a PNG from the site name when there is no logo', async () => { + const res = (await og.handler(req({ siteName: 'Acme' }))) + expect(res.headers.get('content-type')).toBe('image/png') + expect((await res.arrayBuffer()).byteLength).toBeGreaterThan(1000) + }, 30_000) + + test('draws the logo from the upload (fetched once, inlined)', async () => { + // 1×1 transparent PNG + const png = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=', 'base64') + const fetchMock = vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(png, { headers: { 'content-type': 'image/png' } })) + try { + const res = (await og.handler(req({ logo: { url: '/api/media/file/logo.png' }, siteName: 'Acme' }))) + expect(res.headers.get('content-type')).toBe('image/png') + expect(fetchMock).toHaveBeenCalledWith('http://localhost:3000/api/media/file/logo.png') + } finally { + fetchMock.mockRestore() + } + }, 30_000) + + test('icon redirects to the site favicon, else draws initials', async () => { + const redirect = (await icon.handler(req({ favicon: { url: '/api/media/file/icon.png' }, siteName: 'Acme' }))) + expect(redirect.status).toBe(302) + expect(redirect.headers.get('location')).toBe('http://localhost:3000/api/media/file/icon.png') + const drawn = (await icon.handler(req({ siteName: 'Acme Studio' }))) + expect(drawn.headers.get('content-type')).toBe('image/png') + }, 30_000) +})