Skip to content

fix: signed media URLs in Studio previews (#383) - #384

Merged
Madraka merged 1 commit into
mainfrom
fix/preview-media-383
Dec 1, 2026
Merged

Madraka merged 1 commit into
mainfrom
fix/preview-media-383

Conversation

@Madraka

@Madraka Madraka commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

Fixes #383

Problem

Preview HTML pointed blob images at the site-relative /media/<sha16>/<slug>.<ext>. Only the site's host serves that path; on Studio's host (studio.cloudhal.com, and a local cloudhal studio) the SPA fallback answered with HTML. So previews showed no cover, body or section images whenever Studio and the site have different hosts.

Why not Studio's private /assets/:id/content route

  • The served preview (GET …/preview) has sandbox in its CSP, and the editor's srcdoc frame uses sandbox="". Both give the document an opaque origin.
  • Image requests from an opaque origin count as cross-site, so the SameSite=Lax session cookie is not sent and the private route answers 401.
  • That route sends Cross-Origin-Resource-Policy: same-origin, which can never match an opaque origin either.

Design: the signature is the credential

Other products either make asset URLs public (Sanity) or sign them for a short time (Storyblok, Contentful embargoed assets, Cloudflare Images). This PR takes the second approach, served from Studio's own origin.

  • Signing (@cloudhal/core-ts, preview-media.ts, WebCrypto only):
    • HMAC-SHA256 over site|assetId|sha16|exp, encoded as base64url.
    • The key is derived with HKDF-SHA256 (info: "cloudhal preview-media v1") from CLOUDHAL_PREVIEW_SECRET, or else BETTER_AUTH_SECRET.
    • Without a configured secret (local cloudhal studio, tests) it uses a random key for the process.
    • Expiry is bucketed: exp = ceil(now/6h)*6h + 6h. Re-renders give identical URLs, so the browser cache hits. A URL is valid for 6 to 12 hours.
  • Route GET /api/sites/:siteId/preview-media/:assetId/<slug>.<ext>?v=&exp=&sig=:
    • Declared public in ROUTE_SCOPES, so no session is needed.
    • Checks: signature (WebCrypto verify, constant time); exp in the future and at most 24 h ahead; the asset belongs to the site; v equals its sha prefix; blob storage only.
    • Answers: 410 after a takedown; a bare 403 or 404 with no body for every other failure.
    • Streams through the same code as /content (assetBytesResponse, which also shrinks assets.ts).
    • Headers: CORP: cross-origin, cache-control: private, max-age=<remaining, ≤ 1 day>, referrer-policy: no-referrer, x-robots-tag: noindex, nosniff, plus the existing SVG sandbox CSP and disposition rules. Nothing goes in a shared cache.
  • Renderer (@cloudhal/astro-renderer):
    • Adds a MediaContext.previewAssetUrl hook, applied in one place, src/preview-media.ts:
      • shownAssetUrl covers asset images, links, video and audio, covers and section images.
      • previewMediaSrc covers plain /media/… paths (Markdown images and links, legacy src, term images). It resolves them to their asset with the existing MEDIA_ROUTE parser, after a length check.
    • External https assets and published pages are unchanged.
  • Call sites:
    • previewMediaFor collects assetIds, asset:<id> references (Markdown, directives, surfaces) and /media/<prefix>/ paths from a node's JSON. It uses linear scans with indexOf, then loads the assets and presigns their URLs.
    • It is wired into the entry GET and POST previews, preview-fragment, page previews (which also feed the Build view's srcdoc) and term-archive previews.
    • URLs are relative, so they resolve against Studio's origin both in a served preview and in srcdoc.
  • CSP: the preview's img-src gains 'self' http://localhost:* http://127.0.0.1:*. The served preview also gets the request's own origin when that origin is http, so a local Studio loads the images. https: already covers deployments.
  • Playground: keys are per session, derived from PLAYGROUND_SECRET and the session id, so they survive an evicted Durable Object.
    • The Worker routes /api/sites/*/preview-media/* GETs that carry no cookie by a ps=<ulid>.<mac> token, which has its own MAC key. It is accepted on that path only and never works as the cookie.

Deviations and notes for review

  • The brief said to use the preview secret directly. Both secrets go through HKDF instead, so the media key is separate from the one that signs preview tokens. Operationally nothing changes: CLOUDHAL_PREVIEW_SECRET still signs preview media.
  • ApiDeps.previewMedia { secret?, query? } is new. The admin Worker passes CLOUDHAL_PREVIEW_SECRET || BETTER_AUTH_SECRET, so the auth secret itself never enters ApiDeps.
  • Not changed:
    • previewDoc, used for Build chat's look() for the vision model and for MCP preview_page. It renders for an agent or a headless browser, not for Studio, and prefers the signed site URL.
    • build-eval.ts, which renders without assets.
    • The menus preview, which draws no images.
  • A srcdoc preview on a plain-http host other than localhost (for example http://nas:4321) still blocks these images through the document's meta CSP. The served preview allows them through the header. Deployments are https.

Tests (run locally, single files)

  • core-ts/test/preview-media.test.ts: round trip; tampered site, asset, sha, exp or signature; another key; expired; more than a day ahead; bucket stability; no secret.
  • api/test/preview-media-api.test.ts, on sqlite and Miniflare D1 (12/12):
    • The GET, POST-draft and fragment previews of an entry with a never-published blob cover and a Markdown /media/… image name only signed URLs and no bare /media/ src. The page preview signs section images.
    • The URL fetched with no session returns the exact bytes with CORP: cross-origin and a private max-age of 6 to 12 h. A second instance with the same secret signs the same URL.
    • A bad signature, a missing signature, a forged exp, an expired URL or another key gives a bare 403. Another site's asset gives a bare 404. A taken-down file gives 410. The process-key fallback works.
  • astro-renderer/test/preview-media.test.ts: a cover by assetId, Markdown /media/ plus an asset: image and link, section images by id and by legacy src; external, unknown and .sha256 paths are untouched; no hook or no preview means no change; the CSP is checked.
  • cloudflare/test/playground.test.ts: ps routing works on preview-media GETs only, refuses POST, refuses use as a cookie or with the cookie's MAC, and refuses expired sessions.
  • Re-run and green: route-scopes, api/playground, assets-api (sqlite), and the renderer's media, preview, carousel, fields and surfaces tests. Typecheck is clean in core-ts, astro-renderer, api and cloudflare. size:check is OK (baseline tightened: assets.ts 833 → 825).

🤖 Generated with Claude Code

Studio previews pointed blob images at the site's `/media/<sha16>/<slug>.<ext>`,
which only the site's host serves; on Studio's host the SPA answered with HTML,
so previews showed no images whenever Studio and the site have different hosts.

Previews now name a short-lived signed URL Studio serves itself:
`GET /api/sites/:siteId/preview-media/:assetId/<slug>.<ext>?v=&exp=&sig=`.
The signature is the credential: the served preview is sandboxed (opaque
origin), so the Lax session cookie is not sent and `CORP: same-origin` cannot
match, which rules out the private `/assets/:id/content` route.

- core-ts: `preview-media.ts`, HMAC-SHA256 over `site|asset|sha16|exp` with a
  key derived by HKDF from the preview secret or else the auth secret;
  6-hour bucketed expiry so re-renders keep the same URL.
- api: the public `preview-media` route (constant-time verify, exp in the
  future and at most a day ahead, asset of the site, sha prefix, blob only,
  410 after a takedown, bare 403/404 otherwise; CORP cross-origin, private
  max-age up to the expiry, no-referrer, noindex); `previewMediaFor` loads the
  assets a node refers to and presigns them for entry, draft, fragment, page
  (Build view) and term-archive previews; the preview CSP also allows a local
  http Studio's own origin.
- astro-renderer: `MediaContext.previewAssetUrl`, applied in one place
  (`preview-media.ts`) for asset images, links, players, covers, section
  images and plain `/media/` paths in Markdown and legacy `src`.
- cloudflare: the admin Worker passes CLOUDHAL_PREVIEW_SECRET or
  BETTER_AUTH_SECRET; the playground signs per session and its Worker routes
  these URLs by a `ps` token, since the sandboxed preview sends no cookie.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Madraka <8898640+Madraka@users.noreply.github.com>
@Madraka
Madraka merged commit a82e2af into main Dec 1, 2026
9 checks passed
@Madraka
Madraka deleted the fix/preview-media-383 branch December 1, 2026 22:24
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.

Studio previews show no images when Studio and the site are on different hosts

1 participant