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
@@ -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.
|
||||
|
||||
Reference in New Issue
Block a user