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
9 changes: 9 additions & 0 deletions .changeset/v1-image-url-transformations.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
"@cloudflare/vite-plugin": minor
---

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

Enable `images.url_transformations` in the Wrangler configuration to transform images locally, including files served by Vite from `public/` and through a parent server in middleware mode. Local transforms use the low-fidelity Sharp mock: resize, rotate, format conversion and a small set of options. Requests return 404 when transformations are disabled and 403 for disallowed origins, instead of reaching the Worker.

Same-host image sources are checked against `allowed_origins` using the hostname of the first configured route. Projects without a route continue to allow local sources.
Comment thread
NuroDev marked this conversation as resolved.
Resolved
Original file line number Diff line number Diff line change
@@ -1,7 +1,28 @@
/// <reference lib="dom" />

import { test } from "vitest";
import { page } from "../../__test-utils__";
import { page, viteTestUrl } from "../../__test-utils__";

test("returns the correct home page", async ({ expect }) => {
const content = await page.textContent("h1");
expect(content).toBe("Vite + TypeScript");
});

test("transforms images via /cdn-cgi/image/", async ({ expect }) => {
const response = await fetch(
`${viteTestUrl}/cdn-cgi/image/width=100,format=webp/image.png`
);
expect(response.status).toBe(200);
expect(response.headers.get("content-type")).toBe("image/webp");
expect(response.headers.get("cf-resized")).toBe("internal=ok/m");
const bytes = Array.from(new Uint8Array(await response.arrayBuffer()));
const width = await page.evaluate(async (imageBytes) => {
const image = await createImageBitmap(
new Blob([new Uint8Array(imageBytes)])
);
const imageWidth = image.width;
image.close();
return imageWidth;
}, bytes);
expect(width).toBe(100);
});
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"name": "static",
"compatibility_date": "2024-12-30",
"assets": {},
"images": { "url_transformations": { "enabled": true } },
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,208 @@
import assert from "node:assert";
import { once } from "node:events";
import { readFileSync } from "node:fs";
import { realpath } from "node:fs/promises";
import { createServer as createHttpServer, get } from "node:http";
import { createServer as createNetServer } from "node:net";
import { buffer } from "node:stream/consumers";
import { cloudflare } from "@cloudflare/vite-plugin";
import { runInTempDir, seed } from "@cloudflare/workers-utils/test-helpers";
import { createServer } from "vite";
import { afterEach, beforeEach, describe, test, vi } from "vitest";
import type { RawConfig } from "@cloudflare/workers-utils/config";
import type { IncomingMessage } from "node:http";

const image = readFileSync(
new URL("../../playground/static/public/image.png", import.meta.url)
);

const images = {
url_transformations: {
enabled: true,
allowed_origins: ["app.example.com/allowed"],
},
};

describe.each(["worker", "assets-only"] as const)(
"%s image URL transformations",
(type) => {
runInTempDir();
afterEach(() => vi.unstubAllEnvs());
beforeEach(async () => {
// Vite cannot load the Worker entry from Windows 8.3 short temp paths.
if (process.platform === "win32") {
const root = await realpath(process.cwd());
process.chdir(root);
vi.stubEnv("PWD", root);
}
});

async function createDevServer(
routeConfig: Pick<RawConfig, "env" | "route" | "routes"> = {},
middlewareMode = false
) {
await seed({
"wrangler.json": JSON.stringify({
name: "image-url-transformations",
...(type === "worker" && { main: "worker.js" }),
compatibility_date: "2025-05-01",
assets: {},
images,
...routeConfig,
}),
"worker.js": `export default {
fetch() { return new Response("Worker fallback", { status: 418 }); }
};`,
"index.html": "<h1>Image URL transformations</h1>",
"public/allowed/image.png": image,
"public/blocked/image.png": image,
});
// Miniflare needs the public URL's port before it starts in assets-only mode.
const portServer = createNetServer().listen(0, "127.0.0.1");
await once(portServer, "listening");
const address = portServer.address();
assert(address && typeof address === "object");
const closed = once(portServer, "close");
portServer.close();
await closed;
return createServer({
root: process.cwd(),
configFile: false,
logLevel: "silent",
server: {
host: "127.0.0.1",
port: address.port,
strictPort: true,
middlewareMode,
},
plugins: [
cloudflare({
inspectorPort: false,
persistState: false,
remoteBindings: false,
}),
],
});
}

test.for([
{
name: "a route string",
routeConfig: { route: "app.example.com/*" },
},
{
name: "the first route object",
routeConfig: {
routes: [
{ pattern: "app.example.com/*", zone_name: "example.com" },
{ pattern: "other.example.com/*", zone_name: "example.com" },
],
},
},
{
name: "an environment's routes over an inherited route",
routeConfig: {
route: "other.example.com/*",
env: { staging: { images, routes: ["app.example.com/*"] } },
},
cloudflareEnv: "staging",
},
])(
"checks local sources against allowed origins using $name",
async ({ cloudflareEnv, routeConfig }, { expect, onTestFinished }) => {
if (cloudflareEnv) {
vi.stubEnv("CLOUDFLARE_ENV", cloudflareEnv);
}
const server = await createDevServer(routeConfig);
onTestFinished(() => server.close());
await server.listen();
const url = server.resolvedUrls?.local[0];
assert(url);

const allowed = await fetch(
new URL("/cdn-cgi/image/width=50/allowed/image.png", url)
);
const allowedBody = await allowed.arrayBuffer();
expect(allowed.status, new TextDecoder().decode(allowedBody)).toBe(200);
expect(allowed.headers.get("cf-resized")).toBe("internal=ok/m");

const blocked = await fetch(
new URL("/cdn-cgi/image/width=50/blocked/image.png", url)
);
const body = await blocked.text();
expect(blocked.status).toBe(403);
expect(body).toContain("ERROR 9401");
}
);

test("allows local sources when no route is configured", async ({
expect,
onTestFinished,
}) => {
const server = await createDevServer();
onTestFinished(() => server.close());
await server.listen();
const url = server.resolvedUrls?.local[0];
assert(url);

const response = await fetch(
new URL("/cdn-cgi/image/width=50/blocked/image.png", url)
);
const body = await response.arrayBuffer();
expect(response.status, new TextDecoder().decode(body)).toBe(200);
expect(response.headers.get("cf-resized")).toBe("internal=ok/m");
});

test("fetches middleware image sources from the parent listener regardless of request headers", async ({
expect,
onTestFinished,
}) => {
const vite = await createDevServer({ route: "app.example.com/*" }, true);
onTestFinished(() => vite.close());
let wrongServerRequests = 0;
const wrongServer = createHttpServer((_req, res) => {
wrongServerRequests++;
res.writeHead(418).end("Wrong image source server");
}).listen(vite.config.server.port, "127.0.0.1");
onTestFinished(
() => new Promise<void>((resolve) => wrongServer.close(() => resolve()))
);
await once(wrongServer, "listening");
const parent = createHttpServer(vite.middlewares).listen(0, "127.0.0.1");
onTestFinished(
() => new Promise<void>((resolve) => parent.close(() => resolve()))
);
await once(parent, "listening");
const address = parent.address();
assert(address && typeof address === "object");
expect(address.port).not.toBe(vite.config.server.port);
const url = `http://127.0.0.1:${address.port}`;
const source = await fetch(`${url}/allowed/image.png`);
expect(source.status).toBe(200);
expect(Buffer.from(await source.arrayBuffer())).toEqual(image);

for (const headers of [
{},
{
Host: `localhost:${vite.config.server.port}`,
"X-Forwarded-Host": `localhost:${vite.config.server.port}`,
"X-Forwarded-Proto": "https",
},
]) {
const response = await new Promise<IncomingMessage>(
(resolve, reject) => {
get(
`${url}/cdn-cgi/image/width=50/allowed/image.png`,
{ headers },
resolve
).on("error", reject);
}
);
const body = await buffer(response);
expect(response.statusCode, body.toString()).toBe(200);
expect(response.headers["cf-resized"]).toBe("internal=ok/m");
}
expect(wrongServerRequests).toBe(0);
});
}
);
21 changes: 21 additions & 0 deletions packages/vite-plugin-cloudflare/src/miniflare-options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
import { maybeStartOrUpdateRemoteProxySession } from "@cloudflare/remote-bindings";
import {
getBrowserRenderingHeadfulFromEnv,
getHostnameFromRoute,
getLocalExplorerEnabledFromEnv,
getLocalObservabilityEnabledFromEnv,
} from "@cloudflare/workers-utils";
Expand Down Expand Up @@ -159,9 +160,27 @@ export async function getDevMiniflareOptions(
resolvedViteConfig
);

const entryConfig =
resolvedPluginConfig.type === "assets-only"
? resolvedPluginConfig.config
: entryWorkerConfig;
const imageUrlTransformations = entryConfig?.images?.url_transformations;
// Match Wrangler: `routes` wins when defined, even if a top-level `route` is inherited.
const firstRoute =
entryConfig?.routes === undefined
? entryConfig?.route
: entryConfig.routes[0];
Comment thread
NuroDev marked this conversation as resolved.
Resolved

const assetWorkers: Array<V4WorkerOptions> = [
{
name: ROUTER_WORKER_NAME,
// Requests are routed here, so Miniflare reads the image configuration here.
routeHostname:
firstRoute === undefined ? undefined : getHostnameFromRoute(firstRoute),
imageUrlTransformations: imageUrlTransformations && {
enabled: imageUrlTransformations.enabled,
allowedOrigins: imageUrlTransformations.allowed_origins,
},
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Resolved
access: entryWorkerConfig?.access?.dev,
unsafeRegisterWorker: false,
compatibilityDate: INTERNAL_WORKERS_COMPATIBILITY_DATE,
Expand Down Expand Up @@ -584,6 +603,8 @@ export async function getDevMiniflareOptions(
const v4MiniflareOptions: V4MiniflareOptions = {
log: logger,
publicUrl,
// Vite serves public/ files that Miniflare cannot see.
unsafeImageUrlTransformationsFetchViaPublicUrl: true,
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Resolved
unsafeProxySharedSecret: PROXY_SHARED_SECRET,
logRequests: false,
inspectorPort:
Expand Down
46 changes: 34 additions & 12 deletions packages/vite-plugin-cloudflare/src/plugins/dev.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ import {
} from "../utils";
import { handleWebSocket } from "../websockets";
import type { StaticRouting } from "@cloudflare/workers-shared/utils/types";
import type { Request as MiniflareRequest } from "miniflare";
import type { IncomingMessage } from "node:http";

/**
* Plugin to provide core development functionality
Expand Down Expand Up @@ -80,6 +82,30 @@ export const devPlugin = createPlugin("dev", (ctx) => {
});
}

async function dispatchFetch(
request: MiniflareRequest,
req: IncomingMessage
) {
const miniflare = ctx.miniflare;
const { localAddress, localPort } = req.socket;
if (
viteDevServer.config.server.middlewareMode &&
localAddress &&
localPort
) {
Comment thread
NuroDev marked this conversation as resolved.
Resolved
// The parent owns the listener in middleware mode. Use its socket,
// not request headers, to fetch Vite-served image sources locally.
// Wait for initialization so it cannot overwrite the parent's URL.
await miniflare.ready;
miniflare.publicUrl = buildPublicUrl({
hostname: localAddress,
port: localPort,
secure: "encrypted" in req.socket && !!req.socket.encrypted,
});
Comment thread
NuroDev marked this conversation as resolved.
Resolved
Comment thread
NuroDev marked this conversation as resolved.
Resolved
Comment thread
NuroDev marked this conversation as resolved.
Resolved
}
return miniflare.dispatchFetch(request, { redirect: "manual" });
}

if (ctx.resolvedPluginConfig.type === "workers") {
debuglog("Initializing the Vite module runners");
await initRunners(
Expand Down Expand Up @@ -179,13 +205,13 @@ export const devPlugin = createPlugin("dev", (ctx) => {
const includeRulesMatcher = generateStaticRoutingRuleMatcher(
staticRouting.user_worker
);
const userWorkerHandler = createRequestHandler(async (request) => {
request.headers.set(CoreHeaders.ROUTE_OVERRIDE, entryWorkerName);
const userWorkerHandler = createRequestHandler(
async (request, req) => {
request.headers.set(CoreHeaders.ROUTE_OVERRIDE, entryWorkerName);

return ctx.miniflare.dispatchFetch(request, {
redirect: "manual",
});
});
return dispatchFetch(request, req);
}
);

viteDevServer.middlewares.use(
function cloudflarePreMiddleware(req, res, next) {
Expand Down Expand Up @@ -285,18 +311,14 @@ export const devPlugin = createPlugin("dev", (ctx) => {
ASSET_WORKER_NAME
);

return ctx.miniflare.dispatchFetch(request, {
redirect: "manual",
});
return dispatchFetch(request, req);
} else {
request.headers.set(
CoreHeaders.ROUTE_OVERRIDE,
ROUTER_WORKER_NAME
);

return ctx.miniflare.dispatchFetch(request, {
redirect: "manual",
});
return dispatchFetch(request, req);
}
})
);
Expand Down
Loading