Files
ipal-kit/test/adminMeta.test.ts
Radosław SmolińskiandClaude Fable 5.2 aef1efac73 Public brand image fetch: the site's configured origin only, no redirect followed, a time and a byte limit
/api/ipal/admin-og resolved a relative logo address against the request's own host and fetched it with
Node's defaults (redirects followed, no timeout, no size cap); /api/ipal/admin-icon resolved the same way.
Both now resolve against serverURL / NEXT_PUBLIC_SERVER_URL (never the request) and fetch through
fetchPublicImage, which asks one address with redirect: 'manual' (a 3xx is no image), within
PUBLIC_IMAGE_TIMEOUT_MS, reading at most 512 KB. The renderer still draws PNG, JPEG, GIF (by their bytes)
and SVG (by its type, as before). Tests against local servers: hostile Host / X-Forwarded-Host, a 302 to an
internal host, an endless body, a hanging server, the normal logo. Docs say 1.17.1 instead of 1.18.0.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-26 22:03:52 +01:00

175 lines
9.8 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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 { iapl } from '../src/plugin.js'
const i18n = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }, { code: 'en', label: 'English' }] }
const base = (meta?: Record<string, unknown>): 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<string, unknown>).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<string, unknown>).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()
})
test('sync without a Payload instance resolves (no logger to call)', async () => {
const { resolved } = buildAdminMeta({ agency: DEFAULT_AGENCY })
await expect(syncAdminMeta(undefined as unknown as Payload, resolved)).resolves.toBeUndefined()
})
})
describe('plugin wiring', () => {
test('on by default: meta, endpoints, Site settings hook; agency in the credit', async () => {
const config = await iapl({ 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<string, unknown> }
expect(credit.serverProps).toMatchObject({ agency: 'Intecion.com', url: 'https://intecion.com', variant: 'login' })
})
test('every plugin global afterChange hook resolves with req: {} (no Payload instance)', async () => {
const config = await iapl({ cookieScanner: { crawl: true }, i18n, twoFactor: false, whiteLabel: true } as never)(base())
const calls = (config.globals ?? []).flatMap((g) =>
(g.hooks?.afterChange ?? []).map((h) => h({ context: {}, doc: {}, global: g, previousDoc: {}, req: {} } as never)),
)
expect(calls.length).toBeGreaterThan(0)
await expect(Promise.all(calls)).resolves.toBeDefined()
})
test('adminMeta: false and agency: false switch the pieces off', async () => {
const config = await iapl({ 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 iapl({
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<string, unknown> }
expect(credit.serverProps).toMatchObject({ agency: 'Studio X', text: 'Made by X', url: 'https://studio.example' })
})
})
describe('preview image endpoints', () => {
const req = (settings: Record<string, unknown>) =>
({ payload: { config: { localization: false, serverURL: 'http://localhost:3000' }, 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).toHaveBeenCalledTimes(1)
expect(String(fetchMock.mock.calls[0][0])).toBe('http://localhost:3000/api/media/file/logo.png')
expect((fetchMock.mock.calls[0][1] as RequestInit).redirect).toBe('manual')
} finally {
fetchMock.mockRestore()
}
}, 30_000)
test('icon redirects to the site favicon, else draws initials', async () => {
// the favicon cannot be fetched here (nothing is asked of a real server in this test): the redirect
const fetchMock = vi.spyOn(globalThis, 'fetch').mockRejectedValue(new Error('ECONNREFUSED'))
const redirect = (await icon.handler(req({ favicon: { url: '/api/media/file/icon.png' }, siteName: 'Acme' })))
fetchMock.mockRestore()
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)
})