2FA screens: the brand image loads for a session that still owes its code; browser spec checks it

The tab icon endpoint answers with the image itself instead of a redirect
to the media file, and the logo components hand a session that owes its
2FA code (or has not set 2FA up) the picture fetched without credentials,
as an anonymous visitor gets it. Who can read media is unchanged; when the
file is not public or is larger than 512 KB the site name is used.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-24 18:46:32 +01:00
co-authored by Claude Fable 5.2
parent 2aaaaa115a
commit 5d44ac3135
10 changed files with 152 additions and 3 deletions
+3
View File
@@ -31,6 +31,9 @@ once there are more than 20.
- Options: `twoFactor.requireSetup: false | { windowHours, exempt }`, `twoFactor.resetAccess`. Exports:
`twoFactorSetupState`, `twoFactorSetupDeadline`; admin components `TwoFactorStatusField`, `TwoFactorResetButton`,
`TwoFactorAlert`.
- The panel's tab icon and logo load on the verify and setup screens: `GET /api/ipal/admin-icon` answers with the
image itself (no redirect to the media file), and the logo components give a session that still owes its code
the picture as an anonymous visitor would get it. No change to who can read `media`.
- ipal-doctor: the `2fa` rule says how many accounts without 2FA are blocked (`usersSetupClosed` in the deep
status), warns when `requireSetup` is switched off and notes a missing setup window.
@@ -39,7 +39,7 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT
| `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` |
| `buildAdminImageEndpoints(resolved, { settingsSlug?, nameField?, logoField?, iconField? })` | `@intecion/ipal-kit` | `GET /api/ipal/admin-og` (1200×630 PNG via `next/og`) and `GET /api/ipal/admin-icon` (the favicon itself, or initials) — already added by `adminMeta` |
| `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`
+7
View File
@@ -490,6 +490,13 @@ twoFactor: {
`twoFactorSetupRequired`, `twoFactorSetupClosed`, `twoFactorStatus*`, `twoFactorReopen`, `twoFactorReset*`,
`twoFactorAlert*`.
**The brand on the setup and verify screens.** A session that still owes its code is refused `media` like every
other collection, so the browser could not load the panel's logo or tab icon from it. The plugin therefore hands
such a session the picture itself — fetched on the server without any credentials, exactly as an anonymous visitor
gets it (`AdminLogo` / `AdminIcon` as a `data:` address; `GET /api/ipal/admin-icon` always answers with the image
instead of a redirect). Nothing is opened by this: when `media` is not publicly readable, or the file is larger
than 512 KB, the site name (or the browser's own attempt) is used instead.
**What it does not do.** Inside the window, someone who knows the password of an account that has not set TOTP up
can still set it up with their own authenticator. The real owner then cannot ("already set") and has to ask an
administrator — the takeover is visible, and the window keeps it to the first days. So still: **create the
+1 -1
View File
@@ -84,7 +84,7 @@ image. The plugin now fills the panel's `<head>` from Site settings, **with or w
| `og:site_name` | the site name | your `admin.meta.openGraph.siteName` wins |
| description | "Administration panel of <site>. 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 |
| icon | `GET /api/ipal/admin-icon` — answers with the site's favicon itself (fetched as an anonymous visitor would get it; a redirect only when that is not possible), 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
@@ -39,7 +39,7 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT
| `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` |
| `buildAdminImageEndpoints(resolved, { settingsSlug?, nameField?, logoField?, iconField? })` | `@intecion/ipal-kit` | `GET /api/ipal/admin-og` (1200×630 PNG via `next/og`) and `GET /api/ipal/admin-icon` (the favicon itself, or initials) — already added by `adminMeta` |
| `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`
+6
View File
@@ -77,12 +77,18 @@ test('a new editor: setup screen with the deadline, nothing else, in after the c
editorId = String((await created.json()).doc.id)
await api.dispose()
// the brand images must load on the setup screen too (the session is refused `media` itself)
const refusedImages: string[] = []
page.on('response', (r) => {
if (r.status() === 403 && /\/api\/(media\/|ipal\/admin-icon)/.test(r.url())) {refusedImages.push(r.url())}
})
await signIn(page, EDITOR)
await page.waitForURL(/setup-totp/)
await expect(page.locator('#ipal-two-factor-notice')).toContainText(/Ustaw weryfikację dwuetapową do|Set up two-step verification by/)
for (const path of ['/api/pages', '/api/form-submissions', '/api/globals/site-settings', `/api/users/${editorId}`]) {
expect((await page.request.get(path, { headers: { origin: baseURL! } })).status(), path).toBe(403)
}
expect(refusedImages).toEqual([])
// going elsewhere in the panel leads back to setup
await page.goto('/admin/collections/pages')
await page.waitForURL(/setup-totp/)
+11
View File
@@ -2,6 +2,8 @@ import type { Payload } from 'payload'
import { ipalT } from '../admin-i18n/t.js'
import { settingsTexts } from '../admin-i18n/texts/settings.js'
import { secondFactorPassed } from '../security/totp/secondFactor.js'
import { publicImageDataUri, siteOrigin } from './publicImage.js'
/**
* White-label admin branding: the Payload admin panel's logo (login + nav) and
@@ -33,6 +35,8 @@ type BrandingProps = {
payload?: Payload
/** SiteSettings global slug. Default 'site-settings'. */
settingsSlug?: string
/** Injected by Payload into admin server components — the account looking at the panel. */
user?: null | Record<string, unknown>
}
type MediaLike = { url?: null | string } | null | undefined
@@ -70,6 +74,13 @@ async function loadBranding(
const image = settings[imageField] as MediaLike
const url =
image && typeof image === 'object' && typeof image.url === 'string' ? image.url : null
// A session that still owes its 2FA code (or has not set 2FA up) is refused `media` like every
// other collection, so the browser would show a broken image on the verify / setup screens.
// Give it the picture itself, fetched as an anonymous visitor would get it; when that fails
// (media is not public), the site name is shown instead.
if (url && props.user && !secondFactorPassed({ payload, user: props.user })) {
return { name, url: await publicImageDataUri(url, siteOrigin(payload.config.serverURL)) }
}
return { name, url }
} catch (error) {
console.warn('[ipal] admin branding: falling back to Payload default:', error)
+8
View File
@@ -3,6 +3,7 @@ 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'
import { fetchPublicImage } from './publicImage.js'
/**
* The panel's link-preview image (1200×630) and icon, drawn from SiteSettings:
@@ -105,6 +106,13 @@ export function buildAdminImageEndpoints(resolved: ResolvedAdminMeta, fields: Fi
handler: async (req) => {
const brand = await loadBranding(req, f)
if (brand.icon) {
// The picture itself, fetched the way an anonymous visitor gets it — not a redirect to the
// media file: a panel session that still owes its 2FA code is refused that file (it is
// refused every collection), and a cached redirect would send it there anyway. The answer
// is the same for everyone, so it can be cached like the redirect was.
const image = await fetchPublicImage(absolute(brand.icon, req), null)
if (image) {return new Response(new Uint8Array(image.bytes), { headers: { 'Cache-Control': CACHE, 'Content-Type': image.type } })}
// Not fetchable from here (too large, or media is not public): let the browser try.
return new Response(null, { headers: { 'Cache-Control': CACHE, Location: absolute(brand.icon, req) }, status: 302 })
}
const ImageResponse = await imageResponse()
+40
View File
@@ -0,0 +1,40 @@
/**
* An image of the site's brand fetched the way an anonymous visitor would get
* it: no cookies, no credentials. For the moments when the browser itself
* cannot load it — a panel session that still owes its 2FA code (or has not
* set 2FA up) is refused every collection, `media` included, although the
* same file is public. Serving the bytes from here opens nothing: only what
* answers an anonymous request comes back, and only an image of a sane size.
*/
const MAX_BYTES = 512 * 1024
export async function fetchPublicImage(url: null | string | undefined, base: null | string | undefined): Promise<{ bytes: Buffer; type: string } | null> {
if (!url) {return null}
let target: URL
try {
target = new URL(url, base || undefined)
} catch {
return null // a relative address and no site origin to resolve it against
}
if (target.protocol !== 'http:' && target.protocol !== 'https:') {return null}
try {
const res = await fetch(target, { credentials: 'omit', redirect: 'follow', signal: AbortSignal.timeout(5000) })
if (!res.ok) {return null}
const type = (res.headers.get('content-type') ?? '').split(';')[0].trim()
if (!type.startsWith('image/')) {return null}
const bytes = Buffer.from(await res.arrayBuffer())
if (!bytes.length || bytes.length > MAX_BYTES) {return null}
return { type, bytes }
} catch {
return null
}
}
/** The same as a `data:` address for an `<img>`. */
export async function publicImageDataUri(url: null | string | undefined, base: null | string | undefined): Promise<null | string> {
const image = await fetchPublicImage(url, base)
return image ? `data:${image.type};base64,${image.bytes.toString('base64')}` : null
}
/** The site's own origin as the config or the environment states it, for resolving `/api/media/file/…`. */
export const siteOrigin = (serverURL: null | string | undefined): null | string => serverURL || process.env.NEXT_PUBLIC_SERVER_URL || null
+74
View File
@@ -0,0 +1,74 @@
import { afterEach, describe, expect, test, vi } from 'vitest'
import { AdminLogo } from '../src/modules/branding/adminGraphics.js'
import { buildAdminImageEndpoints } from '../src/modules/branding/adminImages.js'
import { fetchPublicImage, publicImageDataUri } from '../src/modules/branding/publicImage.js'
const png = Buffer.from('89504e470d0a1a0a', 'hex')
const respond = (body: BodyInit | null, init: ResponseInit) => vi.fn(async () => new Response(body, init))
afterEach(() => {
vi.unstubAllGlobals()
})
describe('the brand image for a session the browser cannot load it in', () => {
test('fetched without credentials; only an image of a sane size comes back', async () => {
const fetchMock = respond(png, { headers: { 'content-type': 'image/png' }, status: 200 })
vi.stubGlobal('fetch', fetchMock)
const image = await fetchPublicImage('/api/media/file/logo.png', 'https://example.com')
expect(image?.type).toBe('image/png')
const [url, init] = fetchMock.mock.calls[0] as unknown as [URL, RequestInit]
expect(String(url)).toBe('https://example.com/api/media/file/logo.png')
expect(init.credentials).toBe('omit')
expect(init.headers).toBeUndefined() // no cookie, no authorization
expect(await publicImageDataUri('/api/media/file/logo.png', 'https://example.com')).toMatch(/^data:image\/png;base64,/)
})
test.each([
['media is not public (403)', respond('no', { status: 403 })],
['not an image', respond('<html>', { headers: { 'content-type': 'text/html' }, status: 200 })],
['too large', respond(Buffer.alloc(600 * 1024), { headers: { 'content-type': 'image/png' }, status: 200 })],
])('%s → nothing', async (_, fetchMock) => {
vi.stubGlobal('fetch', fetchMock)
expect(await fetchPublicImage('/x.png', 'https://example.com')).toBeNull()
})
test('no origin for a relative address, or another scheme → nothing, and no request', async () => {
const fetchMock = respond(png, { headers: { 'content-type': 'image/png' }, status: 200 })
vi.stubGlobal('fetch', fetchMock)
expect(await fetchPublicImage('/x.png', null)).toBeNull()
expect(await fetchPublicImage('file:///etc/passwd', null)).toBeNull()
expect(fetchMock).not.toHaveBeenCalled()
})
test('the panel logo: a data address for a session that owes its code, the plain address otherwise', async () => {
vi.stubGlobal('fetch', respond(png, { headers: { 'content-type': 'image/png' }, status: 200 }))
const payload = {
config: { custom: { ipal: { twoFactor: { collection: 'users' } } }, serverURL: 'https://example.com' },
findGlobal: async () => ({ logo: { url: '/api/media/file/logo.png' }, siteName: 'Example' }),
}
const src = async (user: unknown) => ((await AdminLogo({ payload: payload as never, user: user as never })) as { props: { src?: string } }).props.src
expect(await src({ _strategy: 'local-jwt', collection: 'users', hasTotp: true })).toMatch(/^data:image\/png;base64,/)
expect(await src({ _strategy: 'totp', collection: 'users', hasTotp: true })).toBe('/api/media/file/logo.png')
expect(await src(null)).toBe('/api/media/file/logo.png') // the login screen: an anonymous visitor loads it as before
})
test('the tab icon endpoint serves the picture itself, so no session is sent to a file it is refused', async () => {
const fetchMock = respond(png, { headers: { 'content-type': 'image/png' }, status: 200 })
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' }) },
url: 'https://example.com/api/ipal/admin-icon',
user: { _strategy: 'local-jwt', collection: 'users', hasTotp: true },
}
const res = await icon.handler(req as never)
expect(res.status).toBe(200)
expect(res.headers.get('content-type')).toBe('image/png')
expect(res.headers.get('location')).toBeNull()
expect(String((fetchMock.mock.calls[0] as unknown as [URL])[0])).toBe('https://example.com/api/media/file/icon.png')
// not fetchable → the redirect, as before
vi.stubGlobal('fetch', respond('no', { status: 403 }))
expect((await icon.handler(req as never)).status).toBe(302)
})
})