Skip to content

Design: resize remote photos before they reach the canvas - #9855

Open
shomix wants to merge 17 commits into
mainfrom
shomix-p-design-resize-photos
Open

shomix wants to merge 17 commits into
mainfrom
shomix-p-design-resize-photos

Conversation

@shomix

@shomix shomix commented Nov 25, 2026

Copy link
Copy Markdown
Contributor

Designs with big camera photos shown as small thumbnails stutter when you pan, because Chrome decodes every full-size image while the canvas moves. Canvas frames now load remote images through a new endpoint that resizes them to at most 2048 px, and the original URLs are put back before anything is saved or exported.

Panning on design 9DaCvN3lsBHVCC3ygOVnK, production builds, 6 runs each:

                             main          this branch
p95 frame                    102-110 ms    9-10 ms
frames over 50 ms per run    4-8           0

What changes

1. Canvas images go through a resize proxy.
Remote <img> src/srcset and <picture> sources in canvas frames, interact previews and thumbnails point at /api/canvas-image instead of the original. A small script in the frame handles images added later, and falls back to the original URL if the proxy fails, so the worst case is the same as main. Private and local hosts are left alone.

<img src="https://images.example.test/photo.jpg">
-> in the frame
<img src="/api/canvas-image?src=https%3A%2F%2Fimages.example.test%2Fphoto.jpg&w=2048&u=…&exp=…&t=…">

One cost: on a cold cache the endpoint has to download the full original first, so screens with heavy photos finish loading a few seconds later. First paint is the same.

2. The /api/canvas-image endpoint.
Fetches through ssrfSafeFetch (private addresses get 403), resizes with sharp, and caps input at 40 MB / 100 MP. Images that are already small pass through untouched. Successful resizes are cached for a day, shared across Netlify edges (durable); failures aren't cached. Adds sharp to the Design template.

3. The endpoint requires a signed token.
Canvas frames can't send cookies, so the route is public, and without a check it would be an open image proxy. The editor now calls a get-canvas-image-token action once per load (signed-in users only) and appends the token to every proxy URL. The endpoint checks it before fetching anything and returns an uncached 403 otherwise. The token expires at UTC midnight and identifies the user by a hash, never the email. The CDN caches on src and w only (Netlify-Vary: query=src|w), so cached images are shared across users and tokens.

No token (signed out, shared link viewer, secret not set) means no rewrite: images load from their original URLs like on main.

Deploy: set DESIGN_CANVAS_IMAGE_SECRET (32+ chars, e.g. openssl rand -hex 32) on beta and production. Without it the proxy is off on hosted deploys. Local dev uses a random key per process.

4. Proxy URLs never get saved.
Saving, bridge messages, snapshot export and clipboard all turn proxy URLs (token included) back into the originals. PNG export uses the full-size original, not the 2048 px copy.

<img src="/api/canvas-image?src=…photo.jpg&w=2048&u=…&exp=…&t=…">
-> saved as
<img src="https://images.example.test/photo.jpg">

5. Typed "too large" error in core.
readBoundedResponseBytes throws an exported RemoteArtifactTooLargeError so the endpoint can return 413 without matching the message. Changeset included.

@shomix shomix changed the title Shomix p design resize photos Design: resize remote photos before they reach the canvas Nov 25, 2026

@steve8708 steve8708 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved under Steve’s standing instruction for verified BuilderIO members. This approval records that instruction and carries no independent review or merge-readiness assessment.

@steve8708 steve8708 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved under Steve’s standing instruction for verified BuilderIO members. This approval records that instruction and carries no independent review or merge-readiness assessment.

Milos Petrovic added 2 commits November 26, 2026 11:06

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Unresolved image-proxy defects can corrupt exported HTML, leak signed tokens into clipboard data, leave previews using stale credentials, alter background rendering, and cache failure responses.

5 open issues
1 file not reviewed
  • pnpm-lock.yaml: Generated file
What changed in this PR

This PR reduces Design canvas panning overhead by serving smaller remote images while preserving original URLs for saved content and exports.

Changes:

  • Adds a signed-token image proxy with bounded downloads, resizing, and CDN caching.
  • Integrates image rewriting and restoration across canvas frames, previews, clipboard handling, and exports.
  • Adds regression coverage and exports a typed oversized-response error from core.
File Description
templates/​design/​shared/​visual-layers.ts Extracts reusable head-start markup injection.
templates/​design/​shared/​export-image-source.ts Restores original image sources for export.
templates/​design/​shared/​export-image-source.spec.ts Tests export source restoration.
templates/​design/​shared/​canvas-image-url.ts Adds URL rewriting, restoration, and frame bootstrap.
templates/​design/​shared/​canvas-image-url.spec.ts Tests URL transformations and message restoration.
templates/​design/​shared/​canvas-image-frame-bootstrap.spec.ts Tests dynamic image rewriting and fallback.
templates/​design/​server/​routes/​api/​canvas-image.get.ts Implements authenticated image fetching and resizing.
templates/​design/​server/​routes/​api/​canvas-image.get.spec.ts Tests proxy validation, resizing, caching, and errors.
templates/​design/​server/​plugins/​auth.ts Allows cookie-free access to the token-checked route.
templates/​design/​server/​plugins/​auth.spec.ts Tests the public-route configuration.
templates/​design/​server/​lib/​canvas-image-token.ts Implements token signing, expiry, and verification.
templates/​design/​server/​lib/​canvas-image-token.spec.ts Tests token validity and expiry.
templates/​design/​README.md Documents proxy secret configuration.
templates/​design/​package.json Adds sharp.
templates/​design/​e2e/​interact-injection.spec.ts Checks image bootstrap injection in Interact previews.
templates/​design/​changelog/​2026-11-24-large-photos-no-longer-make-the-canvas-stutter-while-panning.md Records the panning improvement.
templates/​design/​app/​pages/​DesignEditor.tsx Connects image-token readiness to the editor.
templates/​design/​app/​pages/​design-editor/​source-publication.ts Restores original URLs before source publication.
templates/​design/​app/​pages/​design-editor/​source-publication.test.ts Tests restoration and canonical-source caching.
templates/​design/​app/​pages/​design-editor/​png-export-render.ts Restores sources in cloned export documents.
templates/​design/​app/​pages/​design-editor/​host-computed-preview.spec.ts Updates preview rewrite expectations.
templates/​design/​app/​pages/​design-editor/​design-editor-view.tsx Gates initial rendering on image readiness.
templates/​design/​app/​components/​design/​MultiScreenCanvas.tsx Integrates proxy sources and message restoration.
templates/​design/​app/​components/​design/​DesignThumbnail.tsx Applies image sizing to thumbnail previews.
templates/​design/​app/​components/​design/​DesignCanvas.tsx Integrates rewriting, bootstrap injection, and restoration.
templates/​design/​app/​components/​design/​design-canvas/​native-public-asset-preview.ts Excludes proxy URLs from public-asset handling.
templates/​design/​app/​components/​design/​design-canvas/​interact-document.ts Adds proxy support to Interact documents.
templates/​design/​app/​components/​design/​design-canvas/​canvas-image-sources.ts Manages client tokens, retries, and refreshes.
templates/​design/​app/​components/​design/​design-canvas/​canvas-image-sources.spec.ts Tests token readiness and lifecycle behavior.
templates/​design/​app/​components/​design/​bridge/​editor-chrome.bridge.ts Restores URLs before snapshot resource processing.
templates/​design/​app/​components/​design/​bridge/​bridge.guard.spec.ts Allows the shared URL helper import.
templates/​design/​actions/​get-canvas-image-token.ts Adds signed-in token issuance.
templates/​design/​.generated/​bridge/​editor-chrome.generated.ts Regenerates bridge restoration and export logic.
pnpm-lock.yaml Locks dependency updates.
packages/​core/​src/​ingestion/​media.ts Adds a typed oversized-response error.
packages/​core/​src/​ingestion/​index.ts Exports the new error type.
.changeset/​remote-artifact-too-large-error.md Records the core patch release change.

⠀
🟢 Review complete.

Review effort: Balanced

Milos Petrovic added 2 commits November 26, 2026 14:24

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Active issues include an HTML round-trip that enables event-handler injection, cross-realm image exports retaining resized proxy URLs, and image rewriting that changes intrinsic layout.

2 open issues
2 previously missed issues

In code that hasn't changed since last review

Medium severity Preserve intrinsic dimensions when rewriting remote images

templates/​design/​shared/​canvas-image-url.ts:128

Every remote <img> is rewritten, including images whose layout uses their intrinsic dimensions. An image with no authored width, height or CSS sizing changes from 4096×2048 to 2048×1024, shrinking the element and moving surrounding content; restoring the original for export then produces a different layout. Preserve the original intrinsic geometry or leave intrinsically sized images untouched, including in the bootstrap's dynamic rewrite at lines 467–469.

Medium severity Detect cross-realm root elements when preparing image exports

templates/​design/​shared/​export-image-source.ts:59

The host PNG-export path passes images cloned from a canvas iframe, so root instanceof Element is false for those cross-realm clones. Because querySelectorAll() excludes the root, a standalone <img> retains its proxy URLs and export preparation decodes the resized asset instead of the original. Use a realm-independent element check and regenerate templates/design/.generated/bridge/editor-chrome.generated.ts.

4 resolved since last review
1 file not reviewed
  • pnpm-lock.yaml: Generated file

Review effort: Balanced

@steve8708 steve8708 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved under Steve’s standing instruction for verified BuilderIO members. This approval records that instruction and carries no independent review or merge-readiness assessment.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Active issues include critical corruption of foreign protocol-relative URLs, altered image geometry, invalid CSS URL restoration, and an oversized-response rejection path that leaves the upstream body open.

No open issues 🎉

4 previously missed issues

In code that hasn't changed since last review

High severity Check protocol-relative image URLs against the resolved origin

templates/​design/​shared/​canvas-image-url.ts:159

The matcher treats a foreign protocol-relative authority as part of a relative proxy path: //other.example.com/api/canvas-image?src=https%3A%2F%2Fimages.example.com%2Fphoto.jpg&w=2048 becomes /https://images.example.com/photo.jpg. Canonical source preparation therefore corrupts this authored URL on opening or saving, even though it was never rewritten. Recognize protocol-relative authorities and check their resolved origin before restoring them.

Medium severity Cancel oversized response bodies before returning 413

templates/​design/​server/​routes/​api/​canvas-image.get.ts:98

When Content-Length exceeds 40 MB, readBoundedResponseBytes throws before reading or cancelling the response body (packages/core/src/ingestion/media.ts:259–261). Returning 413 here therefore leaves the upstream response open until the fetch timeout instead of releasing it immediately. Cancel the body on this rejection path, as the earlier content-type and upstream-status rejection paths already do.

Medium severity Preserve intrinsic sizing when rewriting remote images

templates/​design/​shared/​canvas-image-url.ts:128

Every remote <img> is rewritten even when its layout depends on intrinsic dimensions: an unsized 4096×2048 image becomes 2048×1024 on the canvas, while exports restore the larger layout. Unchanged srcset density descriptors and object-fit: none can also change sizing or cropping. Preserve the original display geometry or skip images whose rendering depends on intrinsic dimensions, in both the markup rewrite and frame bootstrap.

Medium severity Escape restored CSS URLs in computed background values

templates/​design/​shared/​canvas-image-url.ts:204

For an authored background such as url('https://images.example.com/a"b.jpg'), restoring the double-quoted computed proxy value produces invalid CSS: url("https://images.example.com/a"b.jpg"). Portable-style snapshots and bridge messages carry that broken value, so copying or moving the layer can lose its background. Restore CSS URLs with CSS-string escaping separately from bare URLs and serialized HTML.

2 resolved since last review
1 file not reviewed
  • pnpm-lock.yaml: Generated file

Review effort: Balanced

@steve8708 steve8708 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved under Steve’s standing instruction for verified BuilderIO members. This approval records that instruction and carries no independent review or merge-readiness assessment.

@steve8708 steve8708 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved under Steve’s standing instruction for verified BuilderIO members. This approval records that instruction and carries no independent review or merge-readiness assessment.

@enzoames

Copy link
Copy Markdown
Contributor

Read through this with an eye on what ends up in design_files.content, since Design checkpoints now hash each screen's saved HTML (#9731). The restore holds on every path I traced. There's one place where nothing on the server catches a mistake. The risk is low today and I'm not asking to block on it, but the fix is small.

What I checked (head 11915b0):

  • Every editor write runs prepareCanonicalSourceContent before writing, which calls restoreCanvasImageUrls: apply-file-content-update.ts, apply-local-content-update.ts, both writeCollabText calls in commit-visual-styles.ts, undo/redo, and the editor's prepared file list.
  • writeInlineSourceFile and writeInlineSourceFilesBatch run restoreSignedCanvasImageUrls, so update-file (including queued browser saves replayed from IndexedDB) and the agent source-edit actions are covered.
  • Cross-screen drag (MultiScreenCanvas.tsx, the captureCrossScreenSourceHtmlSnapshot(sourcePreviewIframe.contentDocument, ...) call) reads the live iframe DOM without restoring. The result goes through applyFileContentUpdate, so the restore at that boundary catches it.
  • I round-tripped 14 markup cases through withCanvasImageSizing and then restoreCanvasImageUrls, restoreSignedCanvasImageUrls, and a jsdom parse/serialize. All of them came back identical: plain URLs, &amp; queries, srcset, inline background-image, <style> blocks, spaces, unicode, parentheses, +, fragments, protocol-relative. The one exception is cosmetic: a raw & in the original (?w=800&q=80) comes back as &amp; from the markup restore. That's the same URL to the browser, and DOM serialization already does this on main, so I'm not asking for a change.

The gap: collaborative text has no server-side restore.

Live edits are written into the screen's Y.Text (writeCollabText). The collab layer saves that text to _collab_docs.text_snapshot, and it eventually lands in design_files.content. As far as I can tell, that path never goes through writeInlineSourceFile, so restoreSignedCanvasImageUrls doesn't run on it. I didn't trace the exact function that copies collab text back into design_files. Please confirm.

Why the risk is low: only a handful of call sites write Y.Text directly, they all canonicalize first, and new editor commands normally go through applyFileContentUpdate / applyLocalContentUpdate, which already restore. A leak needs a new direct writeCollabText call fed with markup read from the live canvas.

Why it's still worth closing: nothing enforces the convention, and since this PR any markup serialized from the live canvas contains proxy URLs. Before this PR that markup was safe to write back, so existing patterns don't account for it. If a future command does write it to Y.Text without prepareCanonicalSourceContent, it fails silently:

  1. Proxy URLs carrying u, exp and t are stored in _collab_docs.text_snapshot, then in design_files.content.
  2. The token is persisted, then copied into version history, exports and anything that reads source.
  3. The token expires at UTC midnight. The saved HTML then points at a proxy URL that 403s, and outside the canvas (exports, shared links, other apps) nothing falls back to the original.
  4. Design checkpoints read _collab_docs.text_snapshot directly for unsaved collaborative edits, and store screens by content hash. A leaked token makes an unchanged screen hash differently every day, so each checkpoint stores a fresh copy of it.

Suggested fix, smallest first:

  1. Run the restore inside writeCollabText itself (app/pages/design-editor/collab-sync.ts), so no caller can skip it. It's a no-op on clean text (it returns early when /api/canvas-image isn't in the string).
  2. Or, stronger: run restoreSignedCanvasImageUrls on the server where collab text is accepted or copied into design_files, the same way writeInlineSourceFile already does. That also covers clients other than the editor.
  3. Add a test either way: write collab text containing a signed proxy URL, let it persist, then assert design_files.content holds the original URL and contains no t=.

Fine as a quick follow-up if you'd rather ship this first. Nothing leaks with today's code.

@shomix

shomix commented Nov 30, 2026

Copy link
Copy Markdown
Contributor Author

#9731

thanks for the review, and good catch! Fixed using your first suggestion

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants