Merge claude/login-page-whitelabel-616f3d: the panel's sign-in look (whiteLabel.signIn), the client's logo, hardened brand image fetch

Conflicts kept both sides: the 2FA texts (twoFactorBusy from A, twoFactorCodeDigit here), the reference index rows,
and the e2e:built line (closed doors from C and the sign-in look here). routes.snapshot.json judges the new public
GET /api/ipal/admin-language.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-26 22:04:30 +01:00
co-authored by Claude Opus 5.5
126 changed files with 2283 additions and 46 deletions
+7 -2
View File
@@ -137,7 +137,7 @@ describe('plugin wiring', () => {
describe('preview image endpoints', () => {
const req = (settings: Record<string, unknown>) =>
({ payload: { config: { localization: false }, findGlobal: vi.fn(async () => settings) }, url: 'http://localhost:3000/api/ipal/admin-og' }) as unknown as PayloadRequest
({ 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 () => {
@@ -153,14 +153,19 @@ describe('preview image endpoints', () => {
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')
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' })))
+159
View File
@@ -0,0 +1,159 @@
import type { Endpoint, PayloadRequest } from 'payload'
import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'
import { afterAll, afterEach, beforeAll, describe, expect, test, vi } from 'vitest'
import { buildAdminImageEndpoints } from '../src/modules/branding/adminImages.js'
import { buildAdminMeta, DEFAULT_AGENCY } from '../src/modules/branding/adminMeta.js'
import { fetchPublicImage, PUBLIC_IMAGE_MAX_BYTES, PUBLIC_IMAGE_TIMEOUT_MS } from '../src/modules/branding/publicImage.js'
/**
* The server-side fetch of a brand image (the public endpoints `/api/ipal/admin-og` and `/api/ipal/admin-icon`,
* the logo and icon on the 2FA screens) against REAL local servers: the site's own, one standing for an
* internal address, and one standing for a host an attacker names in the request.
* The fetch may reach the site's configured origin only, once, without following a redirect, for a bounded
* time and a bounded number of bytes.
*/
// 1×1 transparent PNG
const PNG = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=', 'base64')
type Started = { hits: string[]; origin: string; server: Server }
const start = (handler: (req: IncomingMessage, res: ServerResponse) => void): Promise<Started> =>
new Promise((resolve) => {
const hits: string[] = []
const server = createServer((req, res) => {
hits.push(req.url ?? '')
handler(req, res)
})
server.listen(0, '127.0.0.1', () => {
const address = server.address() as { port: number }
resolve({ hits, origin: `http://127.0.0.1:${address.port}`, server })
})
})
let site: Started
let internal: Started
let attacker: Started
/** Bytes the endless answer has written, and whether its connection was closed by the reader. */
const endless = { closed: false, sent: 0 }
beforeAll(async () => {
const png = (_req: IncomingMessage, res: ServerResponse) => res.writeHead(200, { 'content-type': 'image/png' }).end(PNG)
internal = await start(png) // stands for 169.254.169.254 or any host only the server can reach
attacker = await start(png)
site = await start((req, res) => {
if (req.url === '/api/media/file/logo.png') {return png(req, res)}
if (req.url === '/to-internal') {return res.writeHead(302, { location: `${internal.origin}/latest/meta-data/` }).end()}
if (req.url === '/to-metadata') {return res.writeHead(302, { location: 'http://169.254.169.254/latest/meta-data/' }).end()}
if (req.url === '/endless') {
res.writeHead(200, { 'content-type': 'image/png' }) // no content-length: only reading can find the size
const chunk = Buffer.alloc(64 * 1024, 1)
const timer = setInterval(() => {
endless.sent += chunk.length
res.write(chunk)
}, 2)
res.on('close', () => {
endless.closed = true
clearInterval(timer)
})
return
}
if (req.url === '/hang') {return} // never answers
res.writeHead(404).end()
})
})
afterAll(async () => {
for (const s of [site, internal, attacker]) {
s.server.closeAllConnections()
await new Promise((resolve) => s.server.close(resolve))
}
})
afterEach(() => {
vi.unstubAllEnvs()
for (const s of [site, internal, attacker]) {s.hits.length = 0}
})
describe('fetchPublicImage against a real server', () => {
test('the picture is fetched', async () => {
const image = await fetchPublicImage('/api/media/file/logo.png', site.origin)
expect(image?.type).toBe('image/png')
expect(image?.bytes.equals(PNG)).toBe(true)
})
test('a 302 to an internal host is not followed: no image, and the internal host is never asked', async () => {
expect(await fetchPublicImage('/to-internal', site.origin)).toBeNull()
expect(await fetchPublicImage('/to-metadata', site.origin)).toBeNull() // 169.254.169.254: answered at once, no connection attempt
expect(site.hits).toEqual(['/to-internal', '/to-metadata'])
expect(internal.hits).toEqual([])
})
test('an endless body stops at the cap: no image, the connection is dropped, little more than the cap was read', async () => {
expect(await fetchPublicImage('/endless', site.origin)).toBeNull()
await vi.waitFor(() => expect(endless.closed).toBe(true), { timeout: 3000 })
expect(endless.sent).toBeGreaterThan(PUBLIC_IMAGE_MAX_BYTES)
expect(endless.sent).toBeLessThan(PUBLIC_IMAGE_MAX_BYTES * 8) // some more is in flight when reading stops
})
test('a server that never answers is given up on within the timeout', async () => {
expect(PUBLIC_IMAGE_TIMEOUT_MS).toBe(5000)
const started = Date.now()
expect(await fetchPublicImage('/hang', site.origin, { timeoutMs: 400 })).toBeNull()
expect(Date.now() - started).toBeLessThan(2000)
})
})
describe('the public preview-image and icon endpoints', () => {
const [og, icon] = buildAdminImageEndpoints(buildAdminMeta({ agency: DEFAULT_AGENCY }).resolved) as [Endpoint, Endpoint]
/** A request as an attacker sends it: its own host in the URL and in the forwarding headers. */
const hostile = (settings: Record<string, unknown>, serverURL: string | undefined, path: string) =>
({
headers: new Headers({ host: new URL(attacker.origin).host, 'x-forwarded-host': new URL(attacker.origin).host, 'x-forwarded-proto': 'http' }),
payload: { config: { localization: false, ...(serverURL ? { serverURL } : {}) }, findGlobal: () => Promise.resolve(settings) },
url: `${attacker.origin}${path}`,
}) as unknown as PayloadRequest
const logo = { logo: { url: '/api/media/file/logo.png' }, siteName: 'Acme' }
const favicon = { favicon: { url: '/api/media/file/logo.png' }, siteName: 'Acme' }
test('the normal logo still renders: one request, to the site\'s configured origin', async () => {
const res = await og.handler(hostile(logo, site.origin, '/api/ipal/admin-og'))
expect(res.headers.get('content-type')).toBe('image/png')
expect((await res.arrayBuffer()).byteLength).toBeGreaterThan(1000)
expect(site.hits).toEqual(['/api/media/file/logo.png'])
expect(attacker.hits).toEqual([])
}, 30_000)
test('a hostile Host / X-Forwarded-Host makes no fetch to that host — also when the site has no configured origin', async () => {
vi.stubEnv('NEXT_PUBLIC_SERVER_URL', '')
const preview = await og.handler(hostile(logo, undefined, '/api/ipal/admin-og'))
expect(preview.headers.get('content-type')).toBe('image/png') // the site's name is drawn instead
const tab = await icon.handler(hostile(favicon, undefined, '/api/ipal/admin-icon'))
expect(tab.status).toBe(302)
expect(tab.headers.get('location')).toBe('/api/media/file/logo.png') // as stored: the browser resolves it, not the request's host
expect(attacker.hits).toEqual([])
expect(site.hits).toEqual([])
const served = await icon.handler(hostile(favicon, site.origin, '/api/ipal/admin-icon'))
expect(served.status).toBe(200)
expect(served.headers.get('content-type')).toBe('image/png')
expect(site.hits).toEqual(['/api/media/file/logo.png'])
expect(attacker.hits).toEqual([])
}, 30_000)
test('a logo address that redirects to an internal host: not followed, the name is drawn, the icon redirects the browser', async () => {
const preview = await og.handler(hostile({ logo: { url: '/to-internal' }, siteName: 'Acme' }, site.origin, '/api/ipal/admin-og'))
expect(preview.headers.get('content-type')).toBe('image/png')
const tab = await icon.handler(hostile({ favicon: { url: '/to-internal' }, siteName: 'Acme' }, site.origin, '/api/ipal/admin-icon'))
expect(tab.status).toBe(302)
expect(tab.headers.get('location')).toBe(`${site.origin}/to-internal`)
expect(internal.hits).toEqual([])
expect(attacker.hits).toEqual([])
}, 30_000)
test('an endless logo does not hold the endpoint: the name is drawn', async () => {
const res = await og.handler(hostile({ logo: { url: '/endless' }, siteName: 'Acme' }, site.origin, '/api/ipal/admin-og'))
expect(res.headers.get('content-type')).toBe('image/png')
}, 30_000)
})
+2 -2
View File
@@ -58,7 +58,7 @@ describe('the brand image for a session the browser cannot load it in', () => {
vi.stubGlobal('fetch', fetchMock)
const icon = buildAdminImageEndpoints({ agency: false, language: 'en' } as never).find((e) => e.path.endsWith('admin-icon'))!
const req = {
payload: { config: {}, findGlobal: async () => ({ favicon: { url: '/api/media/file/icon.png' }, siteName: 'Example' }) },
payload: { config: { serverURL: 'https://example.com' }, findGlobal: async () => ({ favicon: { url: '/api/media/file/icon.png' }, siteName: 'Example' }) },
url: 'https://example.com/api/ipal/admin-icon',
user: { _strategy: 'local-jwt', collection: 'users', hasTotp: true },
}
@@ -79,7 +79,7 @@ describe('the tab icon endpoint and an SVG', () => {
const SVG = '<svg xmlns="http://www.w3.org/2000/svg"><script>document.title="XSS"</script></svg>'
const icon = (fields: Record<string, unknown> = {}) => buildAdminImageEndpoints({ agency: false, language: 'en' } as never, fields as never).find((e) => e.path.endsWith('admin-icon'))!
const req = {
payload: { config: {}, findGlobal: async () => ({ favicon: { url: '/api/media/file/icon.svg' }, siteName: 'Example' }) },
payload: { config: { serverURL: 'https://example.com' }, findGlobal: async () => ({ favicon: { url: '/api/media/file/icon.svg' }, siteName: 'Example' }) },
url: 'https://example.com/api/ipal/admin-icon',
user: null,
}
+428
View File
@@ -0,0 +1,428 @@
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<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 PNG = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 0])
/** The logo's file as the site would answer an anonymous request for it. */
const serve = (body: null | Uint8Array, init: ResponseInit = {}) =>
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<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, checkLogo: false, languages: false, logoPlate: true, svgLogo: true },
}),
).toEqual({
allScreens: true,
props: { accent: '#0B6E4F', checkLogo: false, imageField: 'brandLogo', inlineImages: false, languages: false, logoPlate: true, nameField: 'brandName', settingsSlug: 'settings', svgLogo: true },
})
})
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: a bitmap by its type, an http(s) or site-relative address, never enlarged; SVG only when asked', () => {
const png = (extra: Record<string, unknown>) => ({ 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' })
for (const mimeType of ['image/jpeg', 'image/png', 'image/webp', 'image/avif', 'image/gif', 'IMAGE/PNG']) {expect(signInLogo({ mimeType, url: '/l' })).toEqual({ src: '/l' })}
for (const mimeType of ['application/pdf', 'text/html', 'image/x-icon', 'image/tiff', 'video/mp4', undefined, 7]) {expect(signInLogo({ mimeType, url: '/l' })).toBeNull()}
for (const url of ['javascript:alert(1)', 'data:text/html,<script>1</script>', '//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)).toBeNull()
expect(signInLogo(svg, { svgLogo: true })).toEqual({ src: svg.url })
expect(signInLogo(png({ url: '/api/media/file/renamed.SVG?v=2' }))).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<string, unknown>) => ({ 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, broken, foreign or too large file gives the name', async () => {
const settings = { logo: { height: 160, mimeType: 'image/png', url: '/api/media/file/logo.png', width: 560 }, siteName: 'Acme' }
const brand = () => {
forgetCheckedLogos()
return loadSignInBrand({ look: {}, payload: fakePayload(settings) })
}
serve(PNG)
expect((await brand()).logo?.src).toBe(settings.logo.url)
vi.restoreAllMocks()
serve(null, { status: 404 })
expect(await brand()).toEqual({ name: 'Acme', logo: null })
vi.restoreAllMocks()
serve(new TextEncoder().encode('<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>')) // says image/png, is not
expect((await brand()).logo).toBeNull()
vi.restoreAllMocks()
serve(new TextEncoder().encode('<html>'), { headers: { 'content-type': 'text/html' } })
expect((await brand()).logo).toBeNull()
vi.restoreAllMocks()
serve(PNG, { headers: { 'content-length': String(600 * 1024), 'content-type': 'image/png' } })
expect((await brand()).logo).toBeNull()
vi.restoreAllMocks()
// 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
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(String(redirected.mock.calls[0][0])).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')
vi.restoreAllMocks()
// nothing answers (the site cannot reach its own address): the upload document is believed
vi.spyOn(globalThis, 'fetch').mockRejectedValue(new Error('ECONNREFUSED'))
expect((await brand()).logo?.src).toBe(settings.logo.url)
vi.restoreAllMocks()
// one look per address in ten minutes, and none with checkLogo: false
const fetched = serve(PNG)
forgetCheckedLogos()
await loadSignInBrand({ look: {}, payload: fakePayload(settings) })
await loadSignInBrand({ look: {}, payload: fakePayload(settings) })
expect(fetched).toHaveBeenCalledTimes(1)
forgetCheckedLogos()
await loadSignInBrand({ look: { checkLogo: false }, payload: fakePayload(settings) })
expect(fetched).toHaveBeenCalledTimes(1)
expect(await checkLogoFile('ftp://site.test/logo.png', null)).toBe('bad')
expect(await checkLogoFile('/relative.png', null)).toBe('unknown')
})
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('&lt;script&gt;alert(1)&lt;/script&gt;')
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, 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('<img alt="Acme" decoding="async" height="69" src="/api/media/file/logo.png" width="240"/>')
expect(html).toContain('<a class="iapl-signin__brand" href="/">')
expect(html).not.toContain('iapl-signin__brand--plate')
expect(html).not.toContain('<nav')
expect(await panel({ look: { logoPlate: true }, payload })).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: { mimeType: 'image/png', url: 'https://site.test/api/media/file/logo.png' }, siteName: 'Acme' }
const guarded = () => fakePayload(settings, { custom: { ipal: { twoFactor: { collection: 'users', requireSetup: true } } } })
const pending = { id: 1, _strategy: 'local-jwt', collection: 'users', hasTotp: true }
const brandFor = (look: Record<string, unknown>, user?: Record<string, unknown>) => {
forgetCheckedLogos()
return loadSignInBrand({ look, payload: guarded(), user })
}
serve(PNG)
expect((await brandFor({}, pending)).logo?.src).toBe(`data:image/png;base64,${Buffer.from(PNG).toString('base64')}`)
expect((await brandFor({}, { ...pending, _strategy: 'totp' })).logo?.src).toBe(settings.logo.url)
expect((await brandFor({})).logo?.src).toBe(settings.logo.url)
// never fetched for it (inlineImages: false), not checked (checkLogo: false), or nothing answers: the name
expect((await brandFor({ inlineImages: false }, pending)).logo).toBeNull()
vi.restoreAllMocks()
vi.spyOn(globalThis, 'fetch').mockRejectedValue(new Error('ECONNREFUSED'))
expect((await brandFor({}, pending)).logo).toBeNull()
expect((await brandFor({ checkLogo: false }, pending)).logo).toBeNull()
})
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('with the sign-in look the brand fields are admin-only; "editor" or no look leaves them as they were', async () => {
const fieldsJson = async (options: Record<string, unknown>) => JSON.stringify((await build(options)).globals!.find((g) => g.slug === 'site-settings')!.fields)
const plain = await fieldsJson({})
expect(await fieldsJson({ whiteLabel: { brandAccess: 'editor' } })).toBe(plain)
expect(await fieldsJson({ whiteLabel: { signIn: false } })).toBe(plain)
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)
}
// no field is added or removed: nothing for a database to migrate
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: true }, { 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()
})
})