Repository navigation
fix(media): optimize stored media without a build-time site URL - #4701
Conversation
Adds a host-agnostic remote pattern for EmDash media when EmDash's image endpoint is active, so Image and Gallery request resized renditions on sites without siteUrl. The endpoints read these URLs from local storage by pathname and refuse to delegate internal-media hrefs that point at another host. Components only optimize this site's media, and prerendered pages without a configured origin keep plain images. On Node without sharp, the endpoint serves the original file. Closes emdash-cms#3507
🦋 Changeset detectedLatest commit: 4e5993b The changes in this PR will be included in the next version bump. This PR includes changesets to release 12 packages
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
There was a problem hiding this comment.
The approach fits EmDash's storage-backed image pipeline and addresses the Cloudflare problem in #3507, where media was not optimized because no build-time origin was known. The reviewers disagree on the host-agnostic remote pattern. The Claude reviewer traced the endpoint and component guards and found nothing blocking. The GPT reviewer found that the request-origin exception in the delegation guard can authorize a server-side fetch to an attacker-chosen host on Node, and that finding is kept as needs_fixing. Other points: the configured siteUrl is missing from the anonymous middleware path, the missing-sharp fallback emits an ETag its own revalidation path never matches, and the configuration docs overstate which transform failures fall back to the original file. One smaller suggestion covers repeated error logging when sharp is missing.
Reviewed by anthropic/claude-opus-5-5 and openai/gpt-6.1-sol.
| if (!href) return true; | ||
| const target = parseUrl(href, origin); | ||
| if (!target) return false; | ||
| if (target.origin === origin) return true; |
There was a problem hiding this comment.
[needs fixing] Do not treat the request origin as a trusted fetch allowlist. Both callers derive origin from ctx.request.url, whose host can be supplied by the client on a directly reachable Node deployment. For example, a request with Host: 127.0.0.1:9000 and href=http://127.0.0.1:9000/_emdash/api/media/file/nested/photo.jpg passes this early return. The nested key fails matchInternalMediaKey, so the Node wrapper delegates to Astro. The newly added host-agnostic remote pattern then authorizes the fetch to that internal address. Previously, production builds without a build-time origin did not authorize it.
Reject internal-media URLs that cannot be served from storage rather than allowing them through based on request-origin equality, or use an independently trusted configured origin. Add a regression covering a spoofed request host and an unsafe or nested key, not just an href whose host differs from the request.
Note: the Claude reviewer traced the canDelegateImageHref guard and judged it sufficient. That trace did not cover this spoofed-host case with a nested key.
| isPrerendered: boolean; | ||
| locals: { emdash?: { config?: SiteUrlConfig } }; | ||
| }): string | undefined { | ||
| const configured = getConfiguredOrigin(astro.locals.emdash?.config); |
There was a problem hiding this comment.
[needs fixing] The configured siteUrl is absent on the anonymous middleware path. astro/middleware.ts constructs anonymous locals.emdash with storage and page helpers but without config (around lines 920–930), then returns through runAnon. Consequently, with emdash({ siteUrl: "https://example.com" }) and no environment override, this lookup sees no configured origin. On a prerendered page it returns undefined, and all three components leave internal media unoptimized despite the documented support for a build-time siteUrl. On on-demand pages it also rejects absolute public media URLs when the request origin differs from the configured public origin.
Make the configured origin available on the anonymous/prerender path, or resolve it from the serialized configuration. Exercise that real middleware shape in a regression test. The new unit test supplies locals.emdash.config manually and misses this case.
| console.error("[emdash] sharp is not installed, serving the original image:", error); | ||
| return new Response(ctx.request.method === "HEAD" ? null : inputBuffer, { | ||
| status: 200, | ||
| headers: originalMediaHeaders(source.contentType, source.size, source.lastModified), |
There was a problem hiding this comment.
[needs fixing] Keep the fallback ETag consistent with the conditional-request check. This response emits the original-file ETag without a transform suffix, but the next request to the same /_image?...&w=150&f=webp URL compares If-None-Match against an ETag containing getTransformFingerprint(...) at lines 129–131. The fallback's own validator therefore never matches. Every revalidation downloads and buffers the complete original, retries the failing transform, and sends another full 200 response. Because the response uses max-age=0, must-revalidate, this repeatedly transfers the full-size files on the missing-sharp deployments this branch supports.
Use matching validators for the fallback and its conditional check, and add a second-request regression that replays the returned ETag and expects 304.
| **Optional.** Controls whether EmDash integrates stored media with Astro's image optimization. The default is `true`. | ||
|
|
||
| When enabled, EmDash wraps Astro's image endpoint so `<Image>` and `getImage()` can read source bytes directly from the configured storage adapter. This also works when the original media URL is behind Cloudflare Access. Requests to the wrapped endpoint skip EmDash's runtime startup, so on them `locals.emdash` holds only `storage`, plus `db` for a signed-in user. `locals.user` is set as on other public routes. Set `images: false` when another image service handles the media or when every image should render without EmDash's endpoint wrapper. | ||
| When enabled, EmDash wraps Astro's image endpoint so `<Image>` and `getImage()` can read source bytes directly from the configured storage adapter. On pages rendered on demand, locally stored media is optimized without `siteUrl` or a build-time `EMDASH_SITE_URL`. Prerendered pages still need one of them when `astro build` runs. This also works when the original media URL is behind Cloudflare Access. If the image service can't transform an image (for example, when `sharp` isn't installed on Node), the endpoint serves the original file. Requests to the wrapped endpoint skip EmDash's runtime startup, so on them `locals.emdash` holds only `storage`, plus `db` for a signed-in user. `locals.user` is set as on other public routes. Set `images: false` when another image service handles the media or when every image should render without EmDash's endpoint wrapper. |
There was a problem hiding this comment.
[needs fixing] The new sentence "If the image service can't transform an image … the endpoint serves the original file" promises fallback for transform failures generally. The Node implementation only catches an error named MissingSharp. Other transform errors return 500, as the newly added unsupported-image test explicitly verifies. The Cloudflare endpoint also returns 500 when the Images transform throws. Narrow the claim to missing sharp on Node and the specific Cloudflare fallback conditions rather than implying unsupported or corrupt images are served unchanged.
@emdash-cms/admin
@emdash-cms/auth
@emdash-cms/auth-atproto
@emdash-cms/blocks
@emdash-cms/cloudflare
@emdash-cms/contentful-to-portable-text
emdash
create-emdash
@emdash-cms/gutenberg-to-portable-text
@emdash-cms/plugin-cli
@emdash-cms/plugin-test
@emdash-cms/plugin-types
@emdash-cms/registry-client
@emdash-cms/registry-lexicons
@emdash-cms/registry-loader
@emdash-cms/registry-moderation
@emdash-cms/registry-verification
upgrade-emdash
@emdash-cms/sandbox-workerd
@emdash-cms/x402
@emdash-cms/plugin-ai-moderation
@emdash-cms/plugin-ai-search
@emdash-cms/plugin-atproto
@emdash-cms/plugin-audit-log
@emdash-cms/plugin-color
@emdash-cms/plugin-embeds
@emdash-cms/plugin-field-kit
@emdash-cms/plugin-forms
@emdash-cms/plugin-webhook-notifier
commit: |
…eUrl, revalidate missing-sharp fallback Internal media URLs that can't be read from storage now return 404 instead of reaching the stock endpoint, which trusted the request's client-supplied host. mediaOrigin falls back to the build-time siteUrl on anonymous requests, whose locals carry no config. Without sharp the endpoint skips the transform after the first failure, logs once, and answers conditional requests for the served original with 304.
There was a problem hiding this comment.
The approach fits EmDash's storage-backed image pipeline and addresses the build-time origin gap behind #3507. The host-agnostic remote pattern is registered only when EmDash's own image endpoint is installed, and the safety checks sit at the endpoint and in the components. Both reviewers approved and found nothing blocking at this head. Both judged all five earlier findings addressed. Internal-media URLs the endpoints can't serve from storage are rejected, including spoofed-host and nested-key cases. The configured siteUrl resolves on the anonymous path. The missing-sharp fallback uses matching validators and a once-per-process log. The docs narrow the fallback claim to missing sharp on Node. One behavior change is noted but needs no fix: on sites that set siteUrl, media with unsafe transform keys now renders as a plain <img> instead of being optimized through the stock endpoint. One reviewer could not confirm that Astro's sharp service names its error MissingSharp. The review was static and no tests or builds were run.
Reviewed by anthropic/claude-opus-5-5 and openai/gpt-6.1-sol.
danielmlr
left a comment
There was a problem hiding this comment.
Found 2 things, worth checking:
-
I think the Cloudflare endpoint should fall back to the original file when the Images binding fails. Once a site on the free Images plan runs out of transformations for the month, new widths answer 500, and visitors get broken images instead of the full-size file. Maybe the catch could download the file again and hand it to
serveOriginal, like the missing-sharp fallback on Node? -
The any-host media pattern also lets Astro follow a redirect to any host's media path, internal ones included. It needs an open redirect on an allowed host, so it's narrow. A placeholder host for EmDash media (like
emdash-media.invalid) would close it, but that's fine as a follow-up. Until then, maybe thecanDelegateImageHrefcomment could mention that redirects aren't covered?
Once a plan's monthly transformations run out, the Images binding errors and visitors got a 500. The endpoint now re-reads the file and serves the original with its own validator, so the transform resumes once the binding recovers. Also notes in canDelegateImageHref that redirects are not covered.
There was a problem hiding this comment.
The approach still fits EmDash’s storage-backed image pipeline. The new Cloudflare fallback sensibly preserves image delivery when transformations fail, uses distinct validators, and allows optimization to resume when the binding recovers.
I reviewed the follow-up’s endpoint changes, stream cleanup, conditional responses, regression tests, and changeset. The earlier findings remain addressed. I found one documentation inconsistency introduced by the expanded fallback; no new code defect was confirmed. Review was static; no tests or builds were run.
Follow-up review by openai/gpt-6.1-sol, scoped to the changes since the last review.
| "@emdash-cms/cloudflare": patch | ||
| --- | ||
|
|
||
| Fixes media stored in R2 or local storage being served as full-size originals in production when `siteUrl` isn't set in `astro.config.mjs` and `EMDASH_SITE_URL` isn't set at build time, as in the Cloudflare templates. On pages rendered on demand, the `Image` and `Gallery` components from `emdash/ui` now get resized WebP renditions and a responsive `srcset` without extra configuration, through the Cloudflare Images binding with the Cloudflare adapter's default image service, or through sharp on Node. Prerendered pages still need `siteUrl` or `EMDASH_SITE_URL` when `astro build` runs. These images are served as the original file instead of failing when the Cloudflare Images binding returns an error, for example after the plan's monthly transformations run out, or on Node without `sharp` installed. |
There was a problem hiding this comment.
[needs fixing] Update the canonical Cloudflare deployment documentation alongside this fallback claim. docs/src/content/docs/deployment/cloudflare.mdx:248 still says that after the monthly transformation limit, new transformations return 9422 and “the image request fails.” For internal media, the new catch branch now serves the original successfully instead. Distinguish internal media’s original-file fallback from bucket/public-URL media delegated to the adapter, where requests can still fail. Otherwise readers diagnosing quota exhaustion receive contradictory guidance from the release notes and deployment guide.
danielmlr
left a comment
There was a problem hiding this comment.
The Cloudflare deployment guide still says that once the free Images transformations run out, "the image request fails". With your fallback, media on the internal route gets the full-size original instead, as the changeset says. Maybe that sentence in deployment/cloudflare.mdx could say so and keep the failure only for media from a bucket URL, like the caution aside above it does for a missing binding?
|
This PR is waiting on its author because it has merge conflicts with |
…e-optimization # Conflicts: # packages/cloudflare/src/image-endpoint.ts # packages/core/src/astro/image-endpoint.ts # packages/core/src/components/Gallery.astro # packages/core/tests/unit/astro/image-endpoint.test.ts
…ate revalidation The fallbacks now opt out of any matching route-cache rule and omit Last-Modified, so a date-only revalidation can't keep the original once transforms work again. The Cloudflare failed-transform test fixture returns a fresh stream per download, and the cross-site render test checks the rendered image.
…ver fallback 304s Opts the missing-sharp 304 out of route caching as well, only calls cache.set(false) when a cache is enabled, and mentions SITE_URL next to EMDASH_SITE_URL in the docs and changeset.
|
Thanks for the review, @danielmlr! I've updated I also merged |
There was a problem hiding this comment.
The approach fits EmDash's storage-backed image pipeline. Internal media can now be optimized without a build-time site URL, and both endpoints refuse to delegate internal-media hrefs that storage can't serve. Both reviewers approved. They found all prior findings addressed: the request-origin SSRF concern, the anonymous/prerender siteUrl lookup, fallback ETag consistency, the missing-sharp log flood, and the two documentation claims. Anthropic raised one non-blocking suggestion: the Cloudflare fallback logs a full error on every request while the transformation quota is exhausted. The review was static and no tests or builds were run.
Reviewed by anthropic/claude-opus-5-5 and openai/gpt-6.1-sol. The change since the last review (1133 lines) was too large for a scoped follow-up, so this is a full review.
| } catch (error) { | ||
| // The Images binding fails once a plan's monthly transformations run | ||
| // out; the full-size original keeps the image visible. | ||
| console.error("[emdash] image transform failed, serving the original:", error); |
There was a problem hiding this comment.
[suggestion] During quota exhaustion, which is the main case this branch handles, every new /_image request reaches this line and writes a full error log. A Worker has no cross-request memory, so the Node fix (a process-wide flag) doesn't carry over as-is. A busy site past its monthly limit would still write one stack trace per image request for the rest of the month. Consider logging only the error message, or logging once per isolate with a module-level flag.
What does this PR do?
Sites without
siteUrlinastro.config.mjs(and withoutEMDASH_SITE_URLat build time), which includes the Cloudflare templates, served media from R2 or local storage as full-size originals.image.remotePatternsonly allowed EmDash media for a build-time origin, so Astro never sent these images through/_image.This PR adds a pattern for the EmDash media path whenever EmDash's own image endpoint is active. That endpoint already reads media from storage by its path, so the host doesn't matter. To keep the open pattern safe:
hrefare checked, which also covers forms likehttp:host/path.Image,GalleryandEmDashImageonly optimize this site's media. Media URLs from another EmDash site render unoptimized as before.astro builddoesn't try to fetch media from a server that isn't running.sharp, the endpoint serves the original file instead of a 500. Other transform errors still fail.Measured on
templates/blog-cloudflare(production build,wrangler devwith the Images binding, nositeUrl), 19 images across 4 pages:srcsetsrcsetentriesCloses #3507
Type of change
Your connection to this change
Checklist
pnpm typecheckpassespnpm lintpassespnpm testpasses (or targeted tests for my change)pnpm formathas been runmessages.pochanges except in translation PRs — a workflow extracts catalogs on merge tomain.AI assistance disclosure
Screenshots / test output
Not applicable (no UI change). Tests: core 10771 passed, core render tests 229 passed, cloudflare 577 passed.