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]>
This commit is contained in:
co-authored by
Claude Fable 5.2
parent
562bf5388d
commit
aef1efac73
@@ -624,7 +624,7 @@ Server only (`pnpm payload run`); never import it from client code, the Payload
|
||||
| `buildTwoFactorResetEndpoint(collection, { access? })`, `TWO_FACTOR_RESET_PATH` | `@intecion/ipal-kit` | `POST /api/ipal/two-factor/reset` `{ userId }`: clears the account's TOTP secret and sessions and starts a new window. Default: a staff admin whose session entered its own TOTP code; `access` replaces that (only `true` allows; a session that owes its code is always refused). `iapl` registers it only with `twoFactor.guard` on. |
|
||||
| `countAccountsWithoutTotp(payload, collection, setupWindowMs?)` | `@intecion/ipal-kit` | `{ without, blocked }` — accounts of the 2FA collection without TOTP, and how many are past their window. |
|
||||
| `resolveRequireSetup(option)`, `strictExempt(fn)`, `SETUP_FROM_FIELD`, `DEFAULT_SETUP_WINDOW_HOURS` | `@intecion/ipal-kit` | `twoFactor.requireSetup` → `{ requireSetup, setupWindowMs, exempt? }` as the guard reads it (throws on a `windowHours` that is not a number ≥ 0 or `false`, and on an `async` `exempt`); the wrapper that makes an `exempt` function answer `true` only for exactly `true`; the field name `'totpSetupFrom'`; `72`. |
|
||||
| `fetchPublicImage(url, base)`, `publicImageDataUri(url, base)`, `rasterImageType(bytes)`, `siteOrigin(serverURL)`, `PUBLIC_IMAGE_MAX_BYTES` | `@intecion/ipal-kit` | An image fetched the way an anonymous visitor gets it (no cookies; http(s) only; `image/*`; at most 512 KB, reading stops at the limit) as `{ bytes, type }` or a `data:` address, else `null`. Used for the logo and icon on the 2FA screens. `rasterImageType(bytes)` → the media type of a bitmap by its first bytes (PNG, JPEG, GIF, WebP, ICO, AVIF) or `null` — never trust a claimed type before answering a file's bytes from the site's origin; an SVG gives `null`. |
|
||||
| `fetchPublicImage(url, base, { timeoutMs? }?)`, `publicImageDataUri(url, base)`, `rasterImageType(bytes)`, `siteOrigin(serverURL)`, `PUBLIC_IMAGE_MAX_BYTES`, `PUBLIC_IMAGE_TIMEOUT_MS` | `@intecion/ipal-kit` | An image fetched the way an anonymous visitor gets it, as `{ bytes, type }` or a `data:` address, else `null`: no cookies; http(s) only; `image/*`; ONE address — a redirect is never followed (a 3xx is "no image"); the whole exchange within `PUBLIC_IMAGE_TIMEOUT_MS` (5000); at most `PUBLIC_IMAGE_MAX_BYTES` (512 KB), reading stops at the limit whatever `content-length` says. `base` is the site's configured origin (`siteOrigin(config.serverURL)` = `serverURL`, else `NEXT_PUBLIC_SERVER_URL`) — never build it from a request's `Host` / `X-Forwarded-Host`. Used for the logo and icon on the 2FA screens and by `/api/ipal/admin-og` and `/api/ipal/admin-icon`. `rasterImageType`: the bitmap type by the first bytes (PNG, JPEG, GIF, WebP, ICO, AVIF), `null` for anything else, SVG included. |
|
||||
| `resolveSignInLook(whiteLabel)` | `@intecion/ipal-kit` | `whiteLabel` option → `null` (white-label or `signIn` off) or `{ allScreens, props }` (`ResolvedSignInLook`; `props` = `SignInLookProps`, the plain values the components get: `accent`, `checkLogo`, `imageField`, `inlineImages`, `languages`, `logoPlate`, `nameField`, `settingsSlug`, `svgLogo`). Option type: `SignInLookOptions`. |
|
||||
| `loadSignInBrand({ payload, look, locale?, user? })`, `signInName(value, locale?)`, `signInLogo(media, { svgLogo? })`, `checkLogoFile(url, base, allowSvg?)`, `fitLogo(width, height, box?)`, `isSvgUpload(media)`, `SIGN_IN_LOGO_TYPES` | `@intecion/ipal-kit` | What the sign-in panel shows: `{ name, logo }` (`SignInBrand`, `SignInLogo = { src, width?, height? }`) read from Site settings, never throwing; the name as one line of plain text (control characters out, cut at `SIGN_IN_NAME_MAX` = 80); the logo of an upload document — only JPEG / PNG / WebP / AVIF / GIF (`SIGN_IN_LOGO_TYPES`; SVG with `svgLogo: true`), only an `http(s)` or site-relative address, fitted into `SIGN_IN_LOGO_BOX` (240 × 72) without enlarging, served from the smallest generated size ≥ 2× the shown width with the same proportions; the look at the file itself (`LogoCheck`: `{ bytes, type }`, `'bad'` = the server answered and it is no such picture or over 512 KB, `'unknown'` = nothing answered). A session that owes its 2FA code gets the checked picture inlined or no logo. |
|
||||
| `signInCss({ accent? })`, `isHexColour(value)`, `SIGN_IN_STYLE_ID` | `@intecion/ipal-kit` | The stylesheet of the sign-in look as a string (no `url()`, no font, no other host; every rule needs `.iapl-signin` on the page), the hex check `accent` must pass, and the `href` of its `<style>` (`'iapl-sign-in'`). |
|
||||
|
||||
@@ -648,7 +648,7 @@ PROGRAMISTA §6, items 73–75; email.md; AGENT.md §7.2) — nothing to run; re
|
||||
**Send test e-mail** names the transport you expect; a form submission arrives. **The service is live at
|
||||
`https://webservices.intecion.net/mail`; while the service runs with enrolment "pending" (from its launch until Intecion switches to open enrolment), every new site waits for approval — keep SMTP until it is approved, or `relay: false`.**
|
||||
|
||||
**→ 1.18.0, the sign-in look (CHANGELOG 1.18.0; white-label.md → "The sign-in screens") — nothing is required:**
|
||||
**→ 1.17.1, the sign-in look (CHANGELOG 1.17.1; white-label.md → "The sign-in screens") — nothing is required:**
|
||||
1. **Sites with `whiteLabel`:** after the update the login screen and the 2FA screens (code, setup) have the new
|
||||
look — a dark panel with the client's logo or the site's name beside the form. No edit, no
|
||||
`generate:importmap`, no migration: the look comes through `AdminLogo` and `SafeTotpView`, which the site's
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# Changelog draft — the sign-in look (for the next minor, written as 1.18.0)
|
||||
# Changelog draft — the sign-in look (for 1.17.1)
|
||||
|
||||
To be placed in `docs/CHANGELOG.md` by the release; the version number is the integration session's call.
|
||||
|
||||
@@ -16,6 +16,18 @@ Three things to look at on such a site, each with a one-line way back:
|
||||
- **Editors can no longer change the site's name, logo and icon** in Site settings (admins can): these are what the
|
||||
public sign-in page shows. `whiteLabel: { brandAccess: 'editor' }` gives them back.
|
||||
|
||||
## Security
|
||||
|
||||
- **The public preview-image endpoint could be made to fetch from a host named in the request.**
|
||||
`GET /api/ipal/admin-og` resolved a site-relative logo address against the request's own host and fetched it with
|
||||
redirects followed, no timeout and no size limit; `GET /api/ipal/admin-icon` resolved the same way. Both now
|
||||
resolve against the site's configured origin only (`serverURL`, else `NEXT_PUBLIC_SERVER_URL`), ask one address,
|
||||
never follow a redirect, give up after 5 s and stop reading at 512 KB. `fetchPublicImage` (exported) behaves so
|
||||
for every caller and takes `{ timeoutMs }`; new export `PUBLIC_IMAGE_TIMEOUT_MS`. **For a project:** nothing to do
|
||||
when `serverURL` is set (the starter sets it). A site without `serverURL` and without `NEXT_PUBLIC_SERVER_URL`
|
||||
loses the logo in its panel link preview (the site name is drawn) and the icon endpoint redirects to the media
|
||||
file — set `serverURL`. A logo or icon whose address answers with a redirect is no longer fetched by the server.
|
||||
|
||||
## Added
|
||||
|
||||
- **Sign-in look (`whiteLabel.signIn`, on with `whiteLabel`).** A dark panel with the label "Administration panel",
|
||||
|
||||
@@ -100,6 +100,12 @@ image. The plugin now fills the panel's `<head>` from Site settings, **with or w
|
||||
(`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.
|
||||
- **How the server fetches the logo and icon (1.17.1):** a site-relative upload address is resolved against the
|
||||
site's **configured** origin — `serverURL`, else `NEXT_PUBLIC_SERVER_URL` — never against the request's `Host`
|
||||
or `X-Forwarded-Host` (the endpoints are public; a request names its own host). No configured origin: a
|
||||
relative address is not fetched (the site name / the redirect to the media file is used). One address is
|
||||
asked, **a redirect is never followed**, the whole exchange has 5 s, and reading stops at 512 KB whatever
|
||||
the server says about the length. Set `serverURL` (every IAPL site does) for the logo to appear.
|
||||
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).
|
||||
|
||||
@@ -624,7 +624,7 @@ Server only (`pnpm payload run`); never import it from client code, the Payload
|
||||
| `buildTwoFactorResetEndpoint(collection, { access? })`, `TWO_FACTOR_RESET_PATH` | `@intecion/ipal-kit` | `POST /api/ipal/two-factor/reset` `{ userId }`: clears the account's TOTP secret and sessions and starts a new window. Default: a staff admin whose session entered its own TOTP code; `access` replaces that (only `true` allows; a session that owes its code is always refused). `iapl` registers it only with `twoFactor.guard` on. |
|
||||
| `countAccountsWithoutTotp(payload, collection, setupWindowMs?)` | `@intecion/ipal-kit` | `{ without, blocked }` — accounts of the 2FA collection without TOTP, and how many are past their window. |
|
||||
| `resolveRequireSetup(option)`, `strictExempt(fn)`, `SETUP_FROM_FIELD`, `DEFAULT_SETUP_WINDOW_HOURS` | `@intecion/ipal-kit` | `twoFactor.requireSetup` → `{ requireSetup, setupWindowMs, exempt? }` as the guard reads it (throws on a `windowHours` that is not a number ≥ 0 or `false`, and on an `async` `exempt`); the wrapper that makes an `exempt` function answer `true` only for exactly `true`; the field name `'totpSetupFrom'`; `72`. |
|
||||
| `fetchPublicImage(url, base)`, `publicImageDataUri(url, base)`, `rasterImageType(bytes)`, `siteOrigin(serverURL)`, `PUBLIC_IMAGE_MAX_BYTES` | `@intecion/ipal-kit` | An image fetched the way an anonymous visitor gets it (no cookies; http(s) only; `image/*`; at most 512 KB, reading stops at the limit) as `{ bytes, type }` or a `data:` address, else `null`. Used for the logo and icon on the 2FA screens. `rasterImageType(bytes)` → the media type of a bitmap by its first bytes (PNG, JPEG, GIF, WebP, ICO, AVIF) or `null` — never trust a claimed type before answering a file's bytes from the site's origin; an SVG gives `null`. |
|
||||
| `fetchPublicImage(url, base, { timeoutMs? }?)`, `publicImageDataUri(url, base)`, `rasterImageType(bytes)`, `siteOrigin(serverURL)`, `PUBLIC_IMAGE_MAX_BYTES`, `PUBLIC_IMAGE_TIMEOUT_MS` | `@intecion/ipal-kit` | An image fetched the way an anonymous visitor gets it, as `{ bytes, type }` or a `data:` address, else `null`: no cookies; http(s) only; `image/*`; ONE address — a redirect is never followed (a 3xx is "no image"); the whole exchange within `PUBLIC_IMAGE_TIMEOUT_MS` (5000); at most `PUBLIC_IMAGE_MAX_BYTES` (512 KB), reading stops at the limit whatever `content-length` says. `base` is the site's configured origin (`siteOrigin(config.serverURL)` = `serverURL`, else `NEXT_PUBLIC_SERVER_URL`) — never build it from a request's `Host` / `X-Forwarded-Host`. Used for the logo and icon on the 2FA screens and by `/api/ipal/admin-og` and `/api/ipal/admin-icon`. `rasterImageType`: the bitmap type by the first bytes (PNG, JPEG, GIF, WebP, ICO, AVIF), `null` for anything else, SVG included. |
|
||||
| `resolveSignInLook(whiteLabel)` | `@intecion/ipal-kit` | `whiteLabel` option → `null` (white-label or `signIn` off) or `{ allScreens, props }` (`ResolvedSignInLook`; `props` = `SignInLookProps`, the plain values the components get: `accent`, `checkLogo`, `imageField`, `inlineImages`, `languages`, `logoPlate`, `nameField`, `settingsSlug`, `svgLogo`). Option type: `SignInLookOptions`. |
|
||||
| `loadSignInBrand({ payload, look, locale?, user? })`, `signInName(value, locale?)`, `signInLogo(media, { svgLogo? })`, `checkLogoFile(url, base, allowSvg?)`, `fitLogo(width, height, box?)`, `isSvgUpload(media)`, `SIGN_IN_LOGO_TYPES` | `@intecion/ipal-kit` | What the sign-in panel shows: `{ name, logo }` (`SignInBrand`, `SignInLogo = { src, width?, height? }`) read from Site settings, never throwing; the name as one line of plain text (control characters out, cut at `SIGN_IN_NAME_MAX` = 80); the logo of an upload document — only JPEG / PNG / WebP / AVIF / GIF (`SIGN_IN_LOGO_TYPES`; SVG with `svgLogo: true`), only an `http(s)` or site-relative address, fitted into `SIGN_IN_LOGO_BOX` (240 × 72) without enlarging, served from the smallest generated size ≥ 2× the shown width with the same proportions; the look at the file itself (`LogoCheck`: `{ bytes, type }`, `'bad'` = the server answered and it is no such picture or over 512 KB, `'unknown'` = nothing answered). A session that owes its 2FA code gets the checked picture inlined or no logo. |
|
||||
| `signInCss({ accent? })`, `isHexColour(value)`, `SIGN_IN_STYLE_ID` | `@intecion/ipal-kit` | The stylesheet of the sign-in look as a string (no `url()`, no font, no other host; every rule needs `.iapl-signin` on the page), the hex check `accent` must pass, and the `href` of its `<style>` (`'iapl-sign-in'`). |
|
||||
|
||||
@@ -648,7 +648,7 @@ PROGRAMISTA §6, items 73–75; email.md; AGENT.md §7.2) — nothing to run; re
|
||||
**Send test e-mail** names the transport you expect; a form submission arrives. **The service is live at
|
||||
`https://webservices.intecion.net/mail`; while the service runs with enrolment "pending" (from its launch until Intecion switches to open enrolment), every new site waits for approval — keep SMTP until it is approved, or `relay: false`.**
|
||||
|
||||
**→ 1.18.0, the sign-in look (CHANGELOG 1.18.0; white-label.md → "The sign-in screens") — nothing is required:**
|
||||
**→ 1.17.1, the sign-in look (CHANGELOG 1.17.1; white-label.md → "The sign-in screens") — nothing is required:**
|
||||
1. **Sites with `whiteLabel`:** after the update the login screen and the 2FA screens (code, setup) have the new
|
||||
look — a dark panel with the client's logo or the site's name beside the form. No edit, no
|
||||
`generate:importmap`, no migration: the look comes through `AdminLogo` and `SafeTotpView`, which the site's
|
||||
|
||||
+1
-1
@@ -69,7 +69,7 @@ export type { SectionHeaderFieldOptions, SectionSettingsFieldOptions } from './m
|
||||
export { buildAdminImageEndpoints } from './modules/branding/adminImages.js'
|
||||
export { ADMIN_META_TEXTS, adminMetaForSite, buildAdminMeta, DEFAULT_AGENCY, syncAdminMeta } from './modules/branding/adminMeta.js'
|
||||
export type { AdminMetaOptions, AgencyOption, ResolvedAdminMeta } from './modules/branding/adminMeta.js'
|
||||
export { fetchPublicImage, PUBLIC_IMAGE_MAX_BYTES, publicImageDataUri, rasterImageType, siteOrigin } from './modules/branding/publicImage.js'
|
||||
export { fetchPublicImage, PUBLIC_IMAGE_MAX_BYTES, PUBLIC_IMAGE_TIMEOUT_MS, publicImageDataUri, rasterImageType, siteOrigin } from './modules/branding/publicImage.js'
|
||||
export {
|
||||
ADMIN_LANGUAGE_PATH,
|
||||
adminPathFromReferer,
|
||||
|
||||
@@ -4,7 +4,7 @@ import type { AgencyOption, ResolvedAdminMeta } from './adminMeta.js'
|
||||
|
||||
import { UPLOAD_SECURITY_HEADERS } from '../security/buildSecurityHeaders.js'
|
||||
import { ADMIN_ICON_PATH, ADMIN_META_TEXTS, ADMIN_OG_PATH } from './adminMeta.js'
|
||||
import { fetchPublicImage, rasterImageType } from './publicImage.js'
|
||||
import { fetchPublicImage, rasterImageType, siteOrigin } from './publicImage.js'
|
||||
|
||||
/**
|
||||
* The panel's link-preview image (1200×630) and icon, drawn from SiteSettings:
|
||||
@@ -33,24 +33,40 @@ async function loadBranding(req: PayloadRequest, f: Required<Omit<Fields, 'serve
|
||||
}
|
||||
}
|
||||
|
||||
/** 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 site's own origin for resolving a site-relative upload address: what the CONFIG says (`serverURL`, else
|
||||
* `NEXT_PUBLIC_SERVER_URL`), never the request. These endpoints are public, and a request names its own host
|
||||
* (`Host`, `X-Forwarded-Host`): resolving against it would let anyone point the server's fetch at a host of
|
||||
* their choice. No configured origin: a relative address is not fetched at all.
|
||||
*/
|
||||
const origin = (req: PayloadRequest): null | string => siteOrigin(req.payload.config?.serverURL)
|
||||
|
||||
/** 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<null | string> {
|
||||
if (!url) {return null}
|
||||
/** The upload's address as the browser is sent to it: absolute when the site's origin is known, else as stored. */
|
||||
function publicAddress(url: string, req: PayloadRequest): string {
|
||||
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')}`
|
||||
return new URL(url, origin(req) || undefined).toString()
|
||||
} catch {
|
||||
return null
|
||||
return url
|
||||
}
|
||||
}
|
||||
|
||||
/** What the preview image's renderer can draw, by the file's first bytes. */
|
||||
const DRAWABLE = ['image/png', 'image/jpeg', 'image/gif']
|
||||
|
||||
/**
|
||||
* The image as a data URI, so the renderer needs no network access of its own. Fetched like every public
|
||||
* brand image (publicImage.ts: one address, no redirect, a timeout, at most 512 KB read). PNG, JPEG and GIF
|
||||
* by their bytes; an SVG by its declared type, as before (drawn by the renderer on the server, not by a
|
||||
* browser); WebP / AVIF cannot be drawn: the site name is shown instead.
|
||||
*/
|
||||
async function inline(url: null | string, req: PayloadRequest): Promise<null | string> {
|
||||
const image = await fetchPublicImage(url, origin(req))
|
||||
if (!image) {return null}
|
||||
const raster = rasterImageType(image.bytes)
|
||||
const type = raster && DRAWABLE.includes(raster) ? raster : !raster && image.type === 'image/svg+xml' ? image.type : null
|
||||
return type ? `data:${type};base64,${image.bytes.toString('base64')}` : 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
|
||||
@@ -111,7 +127,7 @@ export function buildAdminImageEndpoints(resolved: ResolvedAdminMeta, fields: Fi
|
||||
// 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 = fields.serveIcon === false ? null : await fetchPublicImage(absolute(brand.icon, req), null)
|
||||
const image = fields.serveIcon === false ? null : await fetchPublicImage(brand.icon, origin(req))
|
||||
// Only a bitmap is answered from here, recognised by its first bytes — never an SVG, which
|
||||
// is a document that can run script in the site's origin. The headers below are the upload
|
||||
// routes' (sandbox, no sniffing), but a Next project's site-wide CSP rule overrides a
|
||||
@@ -124,7 +140,7 @@ export function buildAdminImageEndpoints(resolved: ResolvedAdminMeta, fields: Fi
|
||||
}
|
||||
// An SVG favicon, or not fetchable from here (too large, media is not public): the browser
|
||||
// goes to the media file itself, where the upload route's own headers apply.
|
||||
return new Response(null, { headers: { 'Cache-Control': CACHE, Location: absolute(brand.icon, req) }, status: 302 })
|
||||
return new Response(null, { headers: { 'Cache-Control': CACHE, Location: publicAddress(brand.icon, req) }, status: 302 })
|
||||
}
|
||||
const ImageResponse = await imageResponse()
|
||||
return new ImageResponse(
|
||||
|
||||
@@ -5,11 +5,24 @@
|
||||
* 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.
|
||||
*
|
||||
* The server asks ONE address and nothing else: a redirect is never followed
|
||||
* (an answer "go to http://169.254.169.254/…" or to any internal host makes
|
||||
* the server fetch nothing there — it counts as "no image"), the whole
|
||||
* exchange has `PUBLIC_IMAGE_TIMEOUT_MS`, and reading stops at
|
||||
* `PUBLIC_IMAGE_MAX_BYTES` whatever the server says about the length.
|
||||
*/
|
||||
export const PUBLIC_IMAGE_MAX_BYTES = 512 * 1024
|
||||
const MAX_BYTES = PUBLIC_IMAGE_MAX_BYTES
|
||||
/** Headers and body together: a server that never answers, or never ends, is given up on. */
|
||||
export const PUBLIC_IMAGE_TIMEOUT_MS = 5000
|
||||
|
||||
export async function fetchPublicImage(url: null | string | undefined, base: null | string | undefined): Promise<{ bytes: Buffer; type: string } | null> {
|
||||
export async function fetchPublicImage(
|
||||
url: null | string | undefined,
|
||||
base: null | string | undefined,
|
||||
/** `timeoutMs`: another limit for the whole exchange (default `PUBLIC_IMAGE_TIMEOUT_MS`). */
|
||||
options: { timeoutMs?: number } = {},
|
||||
): Promise<{ bytes: Buffer; type: string } | null> {
|
||||
if (!url) {return null}
|
||||
let target: URL
|
||||
try {
|
||||
@@ -19,8 +32,12 @@ export async function fetchPublicImage(url: null | string | undefined, base: nul
|
||||
}
|
||||
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 res = await fetch(target, { credentials: 'omit', redirect: 'manual', signal: AbortSignal.timeout(options.timeoutMs ?? PUBLIC_IMAGE_TIMEOUT_MS) })
|
||||
// `!res.ok` covers a redirect too (3xx, or the opaque answer `redirect: 'manual'` gives): never followed.
|
||||
if (!res.ok || res.type === 'opaqueredirect') {
|
||||
await res.body?.cancel().catch(() => undefined)
|
||||
return null
|
||||
}
|
||||
const type = (res.headers.get('content-type') ?? '').split(';')[0].trim()
|
||||
if (!type.startsWith('image/')) {return null}
|
||||
// Too large is known before reading when the server says so; otherwise stop reading at the limit.
|
||||
|
||||
+1
-1
@@ -449,7 +449,7 @@ export type IaplOptions = {
|
||||
* Who may change the brand the sign-in screens show (the name, logo and
|
||||
* icon fields of Site settings). Default with the sign-in look: `'admin'`
|
||||
* (field-level access, admins only; no schema change). `'editor'`: whoever
|
||||
* may edit Site settings, as before 1.18. With `signIn: false` the default
|
||||
* may edit Site settings, as before 1.17.1. With `signIn: false` the default
|
||||
* is `'editor'`.
|
||||
*/
|
||||
brandAccess?: 'admin' | 'editor'
|
||||
|
||||
@@ -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' })))
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
@@ -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,
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user