Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions .changeset/cdn-cgi-image-local-transforms.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
---
"miniflare": minor
"wrangler": minor
"@cloudflare/vite-plugin": minor
"@cloudflare/workers-utils": minor
---

Add local development support for `/cdn-cgi/image/` URL transformations

When `images.url_transformations` (or `images.urlTransformations` in `cloudflare.config.ts`) is enabled, Miniflare now handles `/cdn-cgi/image/<options>/<source>` requests locally before they reach your Worker. Requests return a 404 when URL transformations aren't enabled for the Worker, and a 403 when the source image isn't allowed by `allowed_origins`. Transforms use the same low-fidelity Sharp-backed mock as `cf.image` fetches, so only resize, rotate, format conversion and a small set of options are applied.
Comment thread
mglewis marked this conversation as resolved.
Resolved

This is a change in behaviour: previously `/cdn-cgi/image/` requests were passed through to the Worker during local development.

Requests made through `SELF` in `@cloudflare/vitest-plugin` bypass Miniflare's routing and are not intercepted.
8 changes: 8 additions & 0 deletions .changeset/images-allowed-origins-docs.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
"@cloudflare/config": patch
"@cloudflare/workers-utils": patch
---

Clarify the `images.url_transformations.allowed_origins` documentation

When `allowed_origins` is set, only the listed origins are allowed. The Worker's own zone isn't included unless it's listed.
9 changes: 5 additions & 4 deletions packages/config/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -614,10 +614,11 @@ export interface WorkerConfig {
*/
enabled: boolean;
/**
* Hostnames that images may be fetched from, in addition to the
* Worker's own zone, without a protocol (e.g. `"images.example.com"`
* or `"*.example.com"`). Use `["*"]` to allow any origin. At most 10
* entries.
* Origins that images may be fetched from, e.g. `"images.example.com"`,
* `"*.example.com"` or `"images.example.com/uploads/"`, without the protocol.
* When set, only these origins are allowed; the Worker's own zone isn't implied.
* Use `["*"]` to allow any origin, which is less secure as anyone can then
* use this Worker to transform images from any site. At most 10 entries.
*/
allowedOrigins?: string[];
};
Expand Down
39 changes: 39 additions & 0 deletions packages/dev-helpers/src/miniflare-options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import assert from "node:assert";
import path from "node:path";
import { createContainerDevPlan } from "@cloudflare/containers-shared";
import {
getHostnameFromRoute,
getWranglerHiddenDirPath,
getZoneFromRoute,
UserError,
Expand Down Expand Up @@ -1261,6 +1262,21 @@ export function getZoneFromConfig(config: Config): string | undefined {
return undefined;
}

/**
* Gets the hostname of a normalized Wrangler config's first route. Miniflare
* checks same-host `/cdn-cgi/image/` sources against `allowed_origins` as if
* they came from it.
*
* @param config The Wrangler config.
* @returns The hostname, if the Worker has a route with one.
*/
export function getRouteHostnameFromConfig(config: Config): string | undefined {
const firstRoute = config.route ?? config.routes?.[0];
return firstRoute === undefined
? undefined
: getHostnameFromRoute(firstRoute);
}

export type SourcelessWorkerOptions = Omit<
V4WorkerOptions,
"script" | "scriptPath" | "modules" | "modulesRoot"
Expand Down Expand Up @@ -1387,7 +1403,11 @@ export function getMiniflareWorkerOptions(
compatibilityFlags: config.compatibility_flags,
modulesRules,
zone: getZoneFromConfig(config),
routeHostname: getRouteHostnameFromConfig(config),
access: config.access?.dev,
imageUrlTransformations: buildImageUrlTransformationsOptions(
config.images?.url_transformations
),
connectHandlers: config.connect.map((handler) => ({
protocol: handler.protocol,
port: handler.port,
Expand Down Expand Up @@ -1482,3 +1502,22 @@ function assignWorkflowEvents(
}
return assignment;
}

/**
* Converts the Wrangler `images.url_transformations` config to Miniflare's
* `imageUrlTransformations` option.
*
* @param urlTransformations The Wrangler `images.url_transformations` config.
* @returns The Miniflare option, or `undefined` if not configured.
*/
export function buildImageUrlTransformationsOptions(
urlTransformations: NonNullable<Config["images"]>["url_transformations"]
): V4WorkerOptions["imageUrlTransformations"] {
if (urlTransformations === undefined) {
return undefined;
}
return {
enabled: urlTransformations.enabled,
allowedOrigins: urlTransformations.allowed_origins,
};
}
15 changes: 15 additions & 0 deletions packages/miniflare/src/config/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -645,6 +645,9 @@ export const DevConfigSchema = z.strictObject({
// Zone to use for the CF-Worker header in outbound fetches. If not
// specified, defaults to `${worker-name}.example.com`
zone: z.string().optional(),
// Hostname of the Worker's first route. Same-host `/cdn-cgi/image/` sources
// are checked against `allowedOrigins` as if they came from it.
routeHostname: z.string().optional(),
});

export type DevConfig = z.input<typeof DevConfigSchema>;
Expand Down Expand Up @@ -727,6 +730,18 @@ export const InstanceOptionsSchema = z.strictObject({
// Logging
logRequests: z.boolean().default(true),
stripDisablePrettyError: z.boolean().default(true),
/**
* Pass `/cdn-cgi/image/` requests through to the routed Worker rather than
* handling them in Miniflare. For instances that only proxy to another
* Miniflare instance or to the edge, which handles them instead.
*/
unsafeImageUrlTransformationsPassthrough: z.boolean().optional(),
/**
* Fetch same-host `/cdn-cgi/image/` source images from `publicUrl` rather
* than routing them within Miniflare. For dev servers, such as Vite, that
* serve files Miniflare can't see.
*/
unsafeImageUrlTransformationsFetchViaPublicUrl: z.boolean().optional(),

// Persistence
/**
Expand Down
8 changes: 8 additions & 0 deletions packages/miniflare/src/config/v4-convert.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,10 @@ function convertSharedOptions(options: ParsedV4MiniflareOptions) {
isolatedResourcePersistencePath: options.isolatedResourcePersistencePath,
resourceTmpPath: options.resourceTmpPath,
stripDisablePrettyError: options.stripDisablePrettyError,
unsafeImageUrlTransformationsPassthrough:
options.unsafeImageUrlTransformationsPassthrough,
unsafeImageUrlTransformationsFetchViaPublicUrl:
options.unsafeImageUrlTransformationsFetchViaPublicUrl,
telemetry: options.telemetry,
publicUrl: options.publicUrl,
containerEngine: options.containerEngine,
Expand Down Expand Up @@ -207,9 +211,13 @@ function convertWorkerOptions(
dev.unsafeEphemeralDurableObjects = worker.unsafeEphemeralDurableObjects;
dev.stripCfConnectingIp = worker.stripCfConnectingIp;
dev.zone = worker.zone;
dev.routeHostname = worker.routeHostname;
if (worker.access !== undefined) {
config.access = { dev: worker.access };
}
if (worker.imageUrlTransformations !== undefined) {
config.images = { urlTransformations: worker.imageUrlTransformations };
}

const options: WorkerOptions = { config };
if (Object.values(legacy).some((value) => value !== undefined)) {
Expand Down
13 changes: 13 additions & 0 deletions packages/miniflare/src/config/v4-schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -402,13 +402,20 @@ const V4WorkerOptionsShapeSchema = z.object({
streamingTails: z.array(V4ServiceDesignatorSchema).optional(),
stripCfConnectingIp: z.boolean().default(true),
zone: z.string().optional(),
routeHostname: z.string().optional(),
/** Cloudflare Access authentication metadata exposed as `ctx.access` */
access: z
.object({
aud: z.string(),
identity: z.record(z.string(), z.unknown()).optional(),
})
.optional(),
imageUrlTransformations: z
.object({
enabled: z.boolean(),
allowedOrigins: z.array(z.string()).optional(),
})
.optional(),
unsafeBindings: z
.array(
z.object({
Expand Down Expand Up @@ -708,6 +715,8 @@ export const V4SharedOptionsSchema = z.object({
/** Project temp directory for plugin files; relative to cwd if not absolute. */
resourceTmpPath: z.string().optional(),
stripDisablePrettyError: z.boolean().default(true),
unsafeImageUrlTransformationsPassthrough: z.boolean().optional(),
unsafeImageUrlTransformationsFetchViaPublicUrl: z.boolean().optional(),
telemetry: z
.object({
enabled: z.boolean().default(false),
Expand Down Expand Up @@ -857,7 +866,9 @@ export type V4WorkerOptionsShape = {
streamingTails?: V4ServiceDesignator[];
stripCfConnectingIp?: boolean;
zone?: string;
routeHostname?: string;
access?: { aud: string; identity?: Record<string, unknown> };
imageUrlTransformations?: { enabled: boolean; allowedOrigins?: string[] };
unsafeBindings?: Array<{
name: string;
type: string;
Expand Down Expand Up @@ -1029,6 +1040,8 @@ export type V4SharedOptions = {
isolatedResourcePersistencePath?: string;
resourceTmpPath?: string;
stripDisablePrettyError?: boolean;
unsafeImageUrlTransformationsPassthrough?: boolean;
unsafeImageUrlTransformationsFetchViaPublicUrl?: boolean;
telemetry?: { enabled?: boolean; deviceId?: string };
publicUrl?: string;
containerEngine?:
Expand Down
70 changes: 65 additions & 5 deletions packages/miniflare/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import {
} from "@cloudflare/workflows-shared/src/introspection";
import { $ as colors$, bold, dim, green, yellow } from "kleur/colors";
import stoppable from "stoppable";
import { getGlobalDispatcher, Pool } from "undici";
import { Agent, getGlobalDispatcher, Pool } from "undici";
import SCRIPT_DEV_REGISTRY_PROXY from "worker:core/dev-registry-proxy";
import SCRIPT_MINIFLARE_SHARED from "worker:shared/index";
import SCRIPT_MINIFLARE_ZOD from "worker:shared/zod";
Expand Down Expand Up @@ -908,6 +908,9 @@ export class Miniflare {
publicUrl?: string;
#socketPorts?: SocketPorts;
#runtimeDispatcher?: Dispatcher;
// Fetches `/cdn-cgi/image/` sources from `publicUrl`, accepting the dev
// server's self-signed certificate
#imageSourceDispatcher?: Dispatcher;
#dispatchConnectTcpSockets = new Set<net.Socket>();
#dispatchConnectDatagramSockets = new Set<dgram.Socket>();
#proxyClient?: ProxyClient;
Expand Down Expand Up @@ -968,6 +971,10 @@ export class Miniflare {
// than on every `setOptions()`.
#warnedArtifactsEventsWithoutLocalNamespace = false;

// Keys of `/core/log` messages sent with `MF-Log-Once` that have already
// been logged, so embedded workers can warn once per instance
#loggedOnce = new Set<string>();

constructor(opts: MiniflareOptions) {
// Split and validate options
const [sharedOpts, workerOpts] = validateOptions(opts);
Expand Down Expand Up @@ -1297,6 +1304,48 @@ export class Miniflare {
}
}

/**
* Fetches a same-host `/cdn-cgi/image/` source image from the public URL.
* The request is made from Node so a dev server's self-signed certificate
* can be accepted; only the public URL is ever fetched.
*
* @param url in format: /core/image-source?pathname&search
*/
async #handleLoopbackImageSourceRequest(
request: Request,
url: URL
): Promise<Response> {
const publicUrl = this.publicUrl ?? this.#runtimeEntryURL?.toString();
if (publicUrl === undefined) {
return new Response("Public URL is not available.", { status: 503 });
}
// Assign the path rather than resolving it against the public URL, so a
// path such as `//example.com/` can't change the host
const target = new URL(publicUrl);
target.pathname = url.searchParams.get("pathname") ?? "/";
target.search = url.searchParams.get("search") ?? "";

const headers = new Headers(request.headers);
headers.delete("host");
this.#imageSourceDispatcher ??= new Agent({
connect: { rejectUnauthorized: false },
});
const res = await fetch(target, {
headers,
redirect: "manual",
dispatcher: this.#imageSourceDispatcher,
});
// `fetch` decodes the body, so its encoding and length no longer apply
const resHeaders = new Headers(res.headers);
resHeaders.delete("content-encoding");
resHeaders.delete("content-length");
return new Response(res.body, {
status: res.status,
statusText: res.statusText,
headers: resHeaders,
});
}

/**
* Writes a request body to a temp file and responds with its on-disk path.
*
Expand Down Expand Up @@ -1658,11 +1707,17 @@ export class Miniflare {
`Expected ${SharedHeaders.LOG_LEVEL} header to be log level, got ${level}`
);
const logLevel = level as LogLevel;
let message = await request.text();
if (!colors$.enabled) {
message = stripAnsi(message);
const onceKey = request.headers.get(SharedHeaders.LOG_ONCE);
if (onceKey === null || !this.#loggedOnce.has(onceKey)) {
if (onceKey !== null) {
this.#loggedOnce.add(onceKey);
}
let message = await request.text();
if (!colors$.enabled) {
message = stripAnsi(message);
}
this.#log.logWithLevel(logLevel, message);
}
this.#log.logWithLevel(logLevel, message);
response = new Response(null, { status: 204 });
} else if (url.pathname === "/core/remote-bindings-access-warning") {
// Reported by the remote-bindings proxy CLIENT worker when it sees
Expand Down Expand Up @@ -1817,6 +1872,8 @@ export class Miniflare {
this.#devRegistry.instanceId,
},
});
} else if (url.pathname === "/core/image-source") {
response = await this.#handleLoopbackImageSourceRequest(request, url);
} else if (url.pathname === "/core/public-url") {
// Returns the public URL for this Miniflare instance. If a publicUrl
// has been set (e.g. the Vite dev server URL), use that; otherwise
Expand Down Expand Up @@ -4028,6 +4085,9 @@ export class Miniflare {
try {
await this.#devRegistryDispatcher?.close();
} catch {}
try {
await this.#imageSourceDispatcher?.close();
} catch {}

await this.#stopLoopbackServer();
// Close the WebSocket server so any connected clients are disconnected
Expand Down
38 changes: 38 additions & 0 deletions packages/miniflare/src/plugins/core/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ import {
} from "../r2";
import {
buildRemoteProxyProps,
getRouteHostname,
parseRoutes,
ProxyNodeBinding,
remoteProxyClientWorker,
Expand Down Expand Up @@ -767,6 +768,13 @@ export interface GlobalServicesOptions {
/** All worker options for building per-worker resource bindings */
allWorkerOpts?: ParsedWorkerOptions[];
}
function getFirstRouteHostname(
routes: string[] | undefined
): string | undefined {
const route = routes?.[0];
return route === undefined ? undefined : getRouteHostname(route);
}

export function getGlobalServices({
sharedOptions,
loopbackSecret,
Expand Down Expand Up @@ -821,6 +829,18 @@ export function getGlobalServices({
name: CoreBindings.STRIP_DISABLE_PRETTY_ERROR,
json: JSON.stringify(sharedOptions.stripDisablePrettyError),
},
{
name: CoreBindings.IMAGE_URL_TRANSFORMATIONS_PASSTHROUGH,
json: JSON.stringify(
!!sharedOptions.unsafeImageUrlTransformationsPassthrough
),
},
{
name: CoreBindings.IMAGE_URL_TRANSFORMATIONS_FETCH_VIA_PUBLIC_URL,
json: JSON.stringify(
!!sharedOptions.unsafeImageUrlTransformationsFetchViaPublicUrl
),
},
// Add `proxyBindings` here, they'll be added to the `ProxyServer` `env`
...proxyBindings,
// Add cache service binding for purgeCache() API
Expand Down Expand Up @@ -926,6 +946,24 @@ export function getGlobalServices({
});
}
}
// Per-worker `/cdn-cgi/image/` config, keyed by worker name so the entry
// worker can pick the correct one after routing.
for (const workerOpt of allWorkerOpts ?? []) {
const urlTransformations = workerOpt.config.images?.urlTransformations;
if (urlTransformations !== undefined) {
serviceEntryBindings.push({
name:
CoreBindings.JSON_IMAGE_URL_TRANSFORMATIONS_PREFIX +
workerOpt.config.name,
json: JSON.stringify({
...urlTransformations,
routeHostname:
workerOpt.dev?.routeHostname ??
getFirstRouteHostname(allWorkerRoutes.get(workerOpt.config.name)),
}),
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Resolved
});
}
}
// Pass the first worker's raw name so the entry worker can look up its
// access blob when no route matches (the fallback is always the first worker).
serviceEntryBindings.push({
Expand Down
Loading
Loading