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 { afterEach, describe, expect, test, vi } from 'vitest' import { adminTexts } from '../src/modules/admin-i18n/index.js' import { AdminLogo } from '../src/modules/branding/adminGraphics.js' import { checkLogoFile, fitLogo, forgetCheckedLogos, 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 = {}, extra: Partial = {}) => 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)[key.replace('ipal:', '')] ?? key /** The panel's own markup, without the stylesheet in front of it. */ const panel = async (props: Parameters[0]) => { const html = renderToStaticMarkup(await SignInPanel(props)) return html.slice(html.indexOf(' vi.spyOn(globalThis, 'fetch').mockImplementation(() => Promise.resolve(new Response(body as never, { headers: { 'content-type': 'image/png' }, ...init }))) afterEach(() => { vi.restoreAllMocks() forgetCheckedLogos() }) const fakePayload = (settings: Record, extra: Record = {}) => ({ 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, checkLogo: false, languages: false, logoPlate: true, svgLogo: false }, }), ).toEqual({ allScreens: true, props: { accent: '#0B6E4F', checkLogo: false, imageField: 'brandLogo', inlineImages: false, languages: false, logoPlate: true, 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 }; 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: any picture the upload holds, at an http(s) or site-relative address, never enlarged; SVG out only when asked', () => { const png = (extra: Record) => ({ mimeType: 'image/png', ...extra }) expect(signInLogo(png({ 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, mimeType: 'image/webp', url: 'https://cdn.test/logo.webp', width: 60 })).toEqual({ height: 20, src: 'https://cdn.test/logo.webp', width: 60 }) expect(signInLogo(png({ url: '/logo.png' }))).toEqual({ src: '/logo.png' }) // no list of types: what a browser shows as a picture is the browser's business; no stated type counts as before for (const mimeType of ['image/jpeg', 'image/png', 'image/webp', 'image/avif', 'image/gif', 'IMAGE/PNG', 'image/x-icon', 'image/bmp', 'image/tiff', undefined, null, '']) { expect(signInLogo({ mimeType, url: '/l' }), String(mimeType)).toEqual({ src: '/l' }) } for (const mimeType of ['application/pdf', 'text/html', 'video/mp4']) {expect(signInLogo({ mimeType, url: '/l' })).toBeNull()} for (const url of ['javascript:alert(1)', 'data:text/html,', '//evil.test/x.png', 'file:///etc/passwd', '', ' ']) { expect(signInLogo(png({ 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(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('the served file: the smallest generated size at least twice the shown width, same proportions, an allowed type', () => { const logoDoc = (sizes: Record) => ({ height: 400, mimeType: 'image/png', sizes, url: '/full.png', width: 1600 }) const size = (width: number, height: number, url: string, mimeType = 'image/webp') => ({ height, mimeType, url, width }) // shown 240 wide: 480 or more expect(signInLogo(logoDoc({ card: size(768, 192, '/768.webp'), hero: size(1200, 300, '/1200.webp'), thumb: size(300, 75, '/300.webp') }))?.src).toBe('/768.webp') expect(signInLogo(logoDoc({ square: size(600, 600, '/crop.webp'), thumb: size(300, 75, '/300.webp') }))?.src).toBe('/full.png') expect(signInLogo(logoDoc({ bad: size(600, 150, 'javascript:1'), empty: null, svg: size(600, 150, '/x.svg', 'image/svg+xml') }))?.src).toBe('/full.png') expect(signInLogo(logoDoc({}))).toEqual({ height: 60, src: '/full.png', width: 240 }) }) test('the file is looked at before it is printed: a deleted file, or one that is no picture, gives the name', async () => { const settings = { logo: { height: 160, mimeType: 'image/png', url: '/api/media/file/logo.png', width: 560 }, siteName: 'Acme' } const brand = (look: Record = {}) => { forgetCheckedLogos() return loadSignInBrand({ look, payload: fakePayload(settings) }) } const answer = async (body: null | Uint8Array, init: ResponseInit, look?: Record) => { vi.restoreAllMocks() serve(body, init) return (await brand(look)).logo } const html = new TextEncoder().encode('') const svg = new TextEncoder().encode('') expect((await answer(PNG, {}))?.src).toBe(settings.logo.url) // certainly not a picture at that address: the name expect(await answer(null, { status: 404 })).toBeNull() expect(await answer(null, { status: 410 })).toBeNull() expect(await answer(html, { headers: { 'content-type': 'text/html' } })).toBeNull() expect(await answer(new Uint8Array(0), {})).toBeNull() // an SVG, also one the server calls a PNG: a picture in (it cannot run script there) — unless refused expect((await answer(svg, { headers: { 'content-type': 'image/svg+xml' } }))?.src).toBe(settings.logo.url) expect((await answer(svg, {}))?.src).toBe(settings.logo.url) expect(await answer(svg, { headers: { 'content-type': 'image/svg+xml' } }, { svgLogo: false })).toBeNull() expect(await answer(svg, {}, { svgLogo: false })).toBeNull() // a redirect is never followed by the server (it could point at an internal address): one request, to the // logo's own address, asked not to follow; the upload document is believed and nothing is inlined from it vi.restoreAllMocks() const redirected = serve(null, { headers: { location: 'http://169.254.169.254/latest/meta-data/' }, status: 302 }) expect((await brand()).logo?.src).toBe(settings.logo.url) expect(redirected).toHaveBeenCalledTimes(1) expect((redirected.mock.calls[0][0] as URL).href).toBe('https://site.test/api/media/file/logo.png') expect((redirected.mock.calls[0][1] as RequestInit).redirect).toBe('manual') expect(await checkLogoFile('https://site.test/l.png', null)).toBe('unknown') // one look per address in ten minutes, and none with checkLogo: false vi.restoreAllMocks() const fetched = serve(PNG) forgetCheckedLogos() await loadSignInBrand({ look: {}, payload: fakePayload(settings) }) await loadSignInBrand({ look: {}, payload: fakePayload(settings) }) expect(fetched).toHaveBeenCalledTimes(1) await brand({ checkLogo: false }) expect(fetched).toHaveBeenCalledTimes(1) expect(await checkLogoFile('ftp://site.test/logo.png', null)).toBe('bad') expect(await checkLogoFile('/relative.png', null)).toBe('unknown') }) // The owner's rule (2026-11-26): the logo is handled as IAPL's white label handled it on the login screen in // 1.17.0 — `AdminLogo` printed `` for whatever Site settings → Logo held. Nothing that showed there may // be missing on the new screens. test('a logo visible on the 1.17.0 login screen is visible after the upgrade', async () => { const big = new Uint8Array(700 * 1024).fill(1) big.set(PNG) const svgBody = new TextEncoder().encode('') const ok = (body: Uint8Array, type: string) => () => Promise.resolve(new Response(body as never, { headers: { 'content-type': type } })) const cases: [string, Record, () => Promise][] = [ ['an SVG logo', { mimeType: 'image/svg+xml', url: '/api/media/file/logo.svg' }, ok(svgBody, 'image/svg+xml')], ['a PNG logo', { height: 80, mimeType: 'image/png', url: '/api/media/file/logo.png', width: 300 }, ok(PNG, 'image/png')], ['a WebP logo on a CDN', { mimeType: 'image/webp', url: 'https://cdn.site.test/logo.webp' }, ok(new TextEncoder().encode('RIFF....WEBPVP8 '), 'image/webp')], ['an ICO or BMP logo', { mimeType: 'image/bmp', url: '/api/media/file/logo.bmp' }, ok(new TextEncoder().encode('BM......'), 'image/bmp')], ['an upload document without a type', { url: '/api/media/file/logo.png' }, ok(PNG, 'image/png')], ['a logo larger than 512 KB', { mimeType: 'image/png', url: '/api/media/file/big.png' }, ok(big, 'image/png')], ['a logo larger than 512 KB, length stated', { mimeType: 'image/png', url: '/api/media/file/big.png' }, () => Promise.resolve(new Response(PNG as never, { headers: { 'content-length': String(700 * 1024), 'content-type': 'image/png' } }))], ['a logo whose address redirects (a CDN)', { mimeType: 'image/png', url: '/api/media/file/logo.png' }, () => Promise.resolve(new Response(null, { headers: { location: 'https://cdn.site.test/logo.png' }, status: 302 }))], ['a site that cannot reach its own address', { mimeType: 'image/png', url: '/api/media/file/logo.png' }, () => Promise.reject(new Error('ECONNREFUSED'))], ['a firewall that refuses the server, not browsers', { mimeType: 'image/png', url: '/api/media/file/logo.png' }, () => Promise.resolve(new Response('denied', { status: 403 }))], ['a media server answering 500 to the server', { mimeType: 'image/png', url: '/api/media/file/logo.png' }, () => Promise.resolve(new Response('', { status: 503 }))], ['a media server that states no type', { mimeType: 'image/png', url: '/api/media/file/logo.png' }, () => Promise.resolve(new Response(PNG as never))], ] for (const [name, logo, respond] of cases) { vi.restoreAllMocks() forgetCheckedLogos() vi.spyOn(globalThis, 'fetch').mockImplementation(respond) const payload = fakePayload({ logo, siteName: 'Acme' }) // 1.17.0: the plain logo component (no `signIn`) — unchanged code path const before = (await AdminLogo({ payload })) as { props: { src?: string }; type: unknown } expect(before.type, name).toBe('img') expect(before.props.src, name).toBe(logo.url) // after: the same address, in an on the panel expect((await loadSignInBrand({ look: {}, payload })).logo?.src, name).toBe(logo.url) expect(await panel({ look: {}, payload }), name).toContain(`src="${String(logo.url)}"`) } }) test('markup in the name is text; the only links are the site, and the language endpoint', async () => { const payload = fakePayload({ siteName: ' reset https://evil.test' }) const html = await panel({ i18n: { language: 'en', t: t as never }, look: {}, payload }) expect(html).not.toContain(' 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('English') }) test('a logo: an with the name as its text and its size, straight on the panel; a plate when asked', async () => { serve(PNG) 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('Acme') expect(html).toContain('