Skip to content

Enforce remotePatterns when fetching external images #727

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jun 14, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
5 changes: 5 additions & 0 deletions .changeset/plain-beds-win.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@opennextjs/cloudflare": minor
---

Enforce remotePatterns when fetching external images
2 changes: 2 additions & 0 deletions packages/cloudflare/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@
"@tsconfig/strictest": "catalog:",
"@types/mock-fs": "catalog:",
"@types/node": "catalog:",
"@types/picomatch": "^4.0.0",
"diff": "^8.0.2",
"esbuild": "catalog:",
"eslint": "catalog:",
Expand All @@ -73,6 +74,7 @@
"globals": "catalog:",
"mock-fs": "catalog:",
"next": "catalog:",
"picomatch": "^4.0.2",
"rimraf": "catalog:",
"typescript": "catalog:",
"typescript-eslint": "catalog:",
Expand Down
24 changes: 24 additions & 0 deletions packages/cloudflare/src/cli/build/open-next/compile-init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { fileURLToPath } from "node:url";
import { loadConfig } from "@opennextjs/aws/adapters/config/util.js";
import type { BuildOptions } from "@opennextjs/aws/build/helper.js";
import { build } from "esbuild";
import pm from "picomatch";

/**
* Compiles the initialization code for the workerd runtime
Expand All @@ -16,6 +17,27 @@ export async function compileInit(options: BuildOptions) {
const nextConfig = loadConfig(path.join(options.appBuildOutputPath, ".next"));
const basePath = nextConfig.basePath ?? "";

// https://github.com/vercel/next.js/blob/d76f0b13/packages/next/src/build/index.ts#L573
const nextRemotePatterns = nextConfig.images?.remotePatterns ?? [];

const remotePatterns = nextRemotePatterns.map((p) => ({
protocol: p.protocol,
hostname: p.hostname ? pm.makeRe(p.hostname).source : undefined,
port: p.port,
pathname: pm.makeRe(p.pathname ?? "**", { dot: true }).source,
// search is canary only as of June 2025
search: (p as any).search,
}));

// Local patterns are only in canary as of June 2025
const nextLocalPatterns = (nextConfig.images as any)?.localPatterns ?? [];

// https://github.com/vercel/next.js/blob/d76f0b13/packages/next/src/build/index.ts#L573
const localPatterns = nextLocalPatterns.map((p: any) => ({
pathname: pm.makeRe(p.pathname ?? "**", { dot: true }).source,
search: p.search,
}));

await build({
entryPoints: [initPath],
outdir: path.join(options.outputDir, "cloudflare"),
Expand All @@ -27,6 +49,8 @@ export async function compileInit(options: BuildOptions) {
define: {
__BUILD_TIMESTAMP_MS__: JSON.stringify(Date.now()),
__NEXT_BASE_PATH__: JSON.stringify(basePath),
__IMAGES_REMOTE_PATTERNS__: JSON.stringify(remotePatterns),
__IMAGES_LOCAL_PATTERNS__: JSON.stringify(localPatterns),
},
});
}
92 changes: 92 additions & 0 deletions packages/cloudflare/src/cli/templates/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,11 +140,103 @@ function populateProcessEnv(url: URL, env: CloudflareEnv) {
process.env.__NEXT_PRIVATE_ORIGIN = url.origin;
}

export type RemotePattern = {
protocol?: "http" | "https";
hostname: string;
port?: string;
pathname: string;
search?: string;
};

const imgRemotePatterns = JSON.parse(__IMAGES_REMOTE_PATTERNS__);

export function fetchImage(fetcher: Fetcher | undefined, url: string) {
// https://github.com/vercel/next.js/blob/d76f0b1/packages/next/src/server/image-optimizer.ts#L208
if (!url || url.length > 3072 || url.startsWith("//")) {
return new Response("Not Found", { status: 404 });
}

// Local
if (url.startsWith("/")) {
if (/\/_next\/image($|\/)/.test(decodeURIComponent(parseUrl(url)?.pathname ?? ""))) {
return new Response("Not Found", { status: 404 });
}

return fetcher?.fetch(`http://assets.local${url}`);
}

// Remote
let hrefParsed: URL;
try {
hrefParsed = new URL(url);
} catch {
return new Response("Not Found", { status: 404 });
}

if (!["http:", "https:"].includes(hrefParsed.protocol)) {
return new Response("Not Found", { status: 404 });
}

if (!imgRemotePatterns.some((p: RemotePattern) => matchRemotePattern(p, hrefParsed))) {
return new Response("Not Found", { status: 404 });
}

fetch(url, { cf: { cacheEverything: true } });
}

export function matchRemotePattern(pattern: RemotePattern, url: URL): boolean {
// https://github.com/vercel/next.js/blob/d76f0b1/packages/next/src/shared/lib/match-remote-pattern.ts
if (pattern.protocol !== undefined) {
if (pattern.protocol.replace(/:$/, "") !== url.protocol.replace(/:$/, "")) {
return false;
}
}
if (pattern.port !== undefined) {
if (pattern.port !== url.port) {
return false;
}
}

if (pattern.hostname === undefined) {
throw new Error(`Pattern should define hostname but found\n${JSON.stringify(pattern)}`);
} else {
if (new RegExp(pattern.hostname).test(url.hostname)) {
return false;
}
}

if (pattern.search !== undefined) {
if (pattern.search !== url.search) {
return false;
}
}

// Should be the same as writeImagesManifest()
if (new RegExp(pattern.pathname).test(url.pathname)) {
return false;
}

return true;
}

function parseUrl(url: string): URL | undefined {
let parsed: URL | undefined = undefined;
try {
parsed = new URL(url, "http://n");
} catch {
// empty
}
return parsed;
}

/* eslint-disable no-var */
declare global {
// Build timestamp
var __BUILD_TIMESTAMP_MS__: number;
// Next basePath
var __NEXT_BASE_PATH__: string;
// Images patterns
var __IMAGES_REMOTE_PATTERNS__: string;
var __IMAGES_LOCAL_PATTERNS__: string;
}
/* eslint-enable no-var */
6 changes: 2 additions & 4 deletions packages/cloudflare/src/cli/templates/worker.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
//@ts-expect-error: Will be resolved by wrangler build
import { runWithCloudflareRequestContext } from "./cloudflare/init.js";
import { fetchImage, runWithCloudflareRequestContext } from "./cloudflare/init.js";
// @ts-expect-error: Will be resolved by wrangler build
import { handler as middlewareHandler } from "./middleware/handler.mjs";

Expand Down Expand Up @@ -31,9 +31,7 @@ export default {
// Fallback for the Next default image loader.
if (url.pathname === `${globalThis.__NEXT_BASE_PATH__}/_next/image`) {
const imageUrl = url.searchParams.get("url") ?? "";
return imageUrl.startsWith("/")
? env.ASSETS?.fetch(`http://assets.local${imageUrl}`)
: fetch(imageUrl, { cf: { cacheEverything: true } });
return fetchImage(env.ASSETS, imageUrl);
}

// - `Request`s are handled by the Next server
Expand Down
Loading
Loading