diff --git a/.changeset/preview-media-urls.md b/.changeset/preview-media-urls.md new file mode 100644 index 00000000..3c150797 --- /dev/null +++ b/.changeset/preview-media-urls.md @@ -0,0 +1,8 @@ +--- +"@cloudhal/core-ts": patch +"@cloudhal/astro-renderer": patch +"@cloudhal/api": patch +"@cloudhal/cloudflare": patch +--- + +Studio previews show their images again when Studio and the site are on different hosts (#383). Preview HTML pointed blob images at the site's `/media/…` path, which only the site's host serves; Studio answered it with its own HTML. Previews now name a short-lived signed URL that Studio serves itself, `GET /api/sites/:siteId/preview-media/:assetId/.?v=…&exp=…&sig=…`: HMAC-SHA256 over the site, asset, SHA-256 prefix and expiry, with a key derived (HKDF) from `CLOUDHAL_PREVIEW_SECRET` or else `BETTER_AUTH_SECRET`. The signature is the credential, because the sandboxed preview sends no session cookie and has an opaque origin (the route answers `Cross-Origin-Resource-Policy: cross-origin`). Expiries are bucketed to 6 hours, so re-renders keep the same URL and the browser cache hits. Covers, section images, `asset:` references, Markdown `/media/…` images and drafts' never-published uploads are all rewritten; external images keep their URL. A taken-down file answers 410. The playground routes these URLs to their session without the cookie. diff --git a/docs/guides/cloudflare-hardening.md b/docs/guides/cloudflare-hardening.md index 3b1ba7ab..fac1ba83 100644 --- a/docs/guides/cloudflare-hardening.md +++ b/docs/guides/cloudflare-hardening.md @@ -13,7 +13,7 @@ on your own account. The sources were checked on 2026-10-13 in `cloudflare/cloud - **Site Worker:** a strict `Content-Security-Policy` on HTML pages (`SITE_CSP`: no inline or third-party scripts, no plugins, no foreign framing), `nosniff` and a referrer policy. - **Content:** `html` bodies are sanitized when rendered (RFC-0012): parsed like a browser, kept to an allowlist (no scripts, styles, frames, forms, SVG or event handlers), and links and media checked like markdown's. This applies to pages, previews, feeds and static builds, whoever wrote the body. Markdown has always been rendered as data. - **Static builds** (`cloudhal build`) get the same policy and headers through `dist/_headers`. Hosts that read `_headers` apply it: Cloudflare Workers static assets, Cloudflare Pages and Netlify. On any other host, set these headers in its own configuration. `cloudhal dev` sends no CSP, because Vite's live reload needs inline code. -- **Logs:** both Workers send their logs to [Workers Logs](https://developers.cloudflare.com/workers/observability/logs/workers-logs/) with **query strings redacted** (`observability.redact_query_string`). Preview links carry their signed token in the query string, and logs are readable by every account member with Workers access. +- **Logs:** both Workers send their logs to [Workers Logs](https://developers.cloudflare.com/workers/observability/logs/workers-logs/) with **query strings redacted** (`observability.redact_query_string`). Preview links carry their signed token in the query string, and so do the image URLs of Studio's previews (`/api/sites//preview-media/…?sig=…`, signed with `CLOUDHAL_PREVIEW_SECRET` or, without it, a key derived from `BETTER_AUTH_SECRET`; valid at most a day). Logs are readable by every account member with Workers access. ## Logs sampling and traces diff --git a/docs/guides/self-host.md b/docs/guides/self-host.md index 0259bad0..821955a7 100644 --- a/docs/guides/self-host.md +++ b/docs/guides/self-host.md @@ -108,6 +108,7 @@ location / { | `CLOUDHAL_BASE_URL`, `CLOUDHAL_BEHIND_PROXY` | As above. | | `CLOUDHAL_SITE_NAME` | The name of the site the first start creates. | | `CLOUDHAL_AUTOMATIONS` | `off` turns scheduled automations off. | +| `CLOUDHAL_PREVIEW_SECRET` | Also signs the image URLs of Studio's previews (`/api/sites//preview-media/…`, valid 6 to 12 hours), which Studio serves itself because the site's `/media/…` lives on another host. Unset, a key derived from `BETTER_AUTH_SECRET` signs them. Rotating either only makes open previews reload their images. | | `CLOUDHAL_UPLOAD_SECRET` | Optional, at least 32 characters (`_FILE` works too): signs agents' upload links ([agent uploads](agent-uploads.md)). Unset, the preview secret signs them. | | `CLOUDHAL_AGENT_UPLOADS`, `CLOUDHAL_AGENT_UPLOAD_BYTES` | `off` turns agents' upload links off; a cap per file in bytes (default 25 MB, at most 100 MB). | | `CLOUDHAL_SMTP_URL` | The SMTP server for invites and password resets ([mail](#mail)): `smtp://user:password@host:587` (STARTTLS) or `smtps://…:465`. `_FILE` works too. Unset, mail is off. | diff --git a/packages/api/src/app.ts b/packages/api/src/app.ts index e23f8184..6a5e5ee3 100644 --- a/packages/api/src/app.ts +++ b/packages/api/src/app.ts @@ -15,6 +15,7 @@ import { errorHandler } from "./errors.ts"; import { mountMcp } from "./mcp-mount.ts"; import { fencedOauthPath, mountClientRegistration, mountOauthServer } from "./oauth-server.ts"; import { PLAYGROUND_PRINCIPAL, playgroundGuard } from "./playground.ts"; +import { previewMediaSigner } from "./preview-media.ts"; import { activity, deploymentActivity } from "./routes/activity.ts"; import { mountAdmin } from "./routes/admin-mount.ts"; import { agentKeys } from "./routes/agent-keys.ts"; @@ -47,6 +48,7 @@ import { notificationRoutes } from "./routes/notifications.ts"; import { pages } from "./routes/pages.ts"; import { passwordResetRoutes } from "./routes/password-reset.ts"; import { previewLinks } from "./routes/preview-links.ts"; +import { previewMedia } from "./routes/preview-media.ts"; import { projects } from "./routes/projects.ts"; import { proposals } from "./routes/proposals.ts"; import { redirects } from "./routes/redirects.ts"; @@ -104,6 +106,8 @@ const SITE_AREAS: readonly (readonly [string, Hono])[] = [ ["assets/agent-uploads", agentUploads], ["assets", assets], ["media", siteMedia], + // #383: signed media URLs of Studio's previews (the signature is the credential). + ["preview-media", previewMedia], // #150: the self-hosted static site's rebuild on publish (`enabled: false` elsewhere). ["site-build", siteBuild], ]; @@ -349,6 +353,7 @@ function setContext(c: Context, deps: ApiDeps, shared: SharedContext): void c.set("siteBuild", deps.siteBuild); // #165: where rate limits read the client's address (`ApiDeps.clientAddressHeader`). c.set("clientAddressHeader", deps.clientAddressHeader); + c.set("previewMedia", previewMediaSigner(deps)); } /** Who is calling: the playground's one principal (RFC-0036 §5), else the deployment's resolver. */ diff --git a/packages/api/src/context.ts b/packages/api/src/context.ts index 4a42f9c2..801d18f3 100644 --- a/packages/api/src/context.ts +++ b/packages/api/src/context.ts @@ -20,6 +20,7 @@ import type { BuildHub } from "./build.ts"; import type { MailSender } from "./mail.ts"; import type { McpOauthOptions } from "./mcp-oauth.ts"; import type { PlaygroundOptions } from "./playground.ts"; +import type { PreviewMediaSigner } from "./preview-media.ts"; import type { AiDeps } from "./routes/ai.ts"; import type { SiteBuildService } from "./routes/site-build.ts"; import type { UploadSecret } from "./uploads.ts"; @@ -71,6 +72,16 @@ export interface ApiDeps { * links ahead of the preview secret and the MCP state key, so it rotates on its own. */ readonly uploadSecret?: string | Uint8Array | undefined; + /** + * #383: signed media URLs in Studio's previews (`/api/sites/:id/preview-media/…`). `secret` (any + * length; the key is derived from it with HKDF) defaults to `preview.secret`; without either, + * a random key of this process (local tools). The admin Worker passes `CLOUDHAL_PREVIEW_SECRET` + * or else `BETTER_AUTH_SECRET`. `query` is appended to every URL (the playground's session). + */ + readonly previewMedia?: { + readonly secret?: string | Uint8Array | undefined; + readonly query?: string | undefined; + }; /** * Mounts `/api/admin/*` (site bundle export/import for `cloudhal push`/`pull`) behind this * deployment token. Needs the raw storage the store was built on. @@ -206,5 +217,7 @@ export type Env = { siteBuild: SiteBuildService | undefined; /** `ApiDeps.clientAddressHeader`: where the client's address is read for rate limits. */ clientAddressHeader: string | undefined; + /** #383: how previews sign media URLs (`preview-media.ts`). */ + previewMedia: PreviewMediaSigner; }; }; diff --git a/packages/api/src/playground.ts b/packages/api/src/playground.ts index d1965f45..054fc1a1 100644 --- a/packages/api/src/playground.ts +++ b/packages/api/src/playground.ts @@ -214,6 +214,7 @@ export const PLAYGROUND_ALLOW: ReadonlySet = new Set([ `GET ${S}/assets`, `GET ${S}/assets/:assetId`, `GET ${S}/assets/:assetId/content`, + `GET ${S}/preview-media/:assetId/:file`, `POST ${S}/migrations/tags-to-terms`, `POST ${S}/migrations/tags-to-terms/revert`, ]); diff --git a/packages/api/src/preview-media.ts b/packages/api/src/preview-media.ts new file mode 100644 index 00000000..6f77d992 --- /dev/null +++ b/packages/api/src/preview-media.ts @@ -0,0 +1,130 @@ +/** + * #383: the media a Studio preview shows, with signed URLs Studio itself serves. Previews are + * shown on Studio's origin (a served, sandboxed document or an iframe's `srcdoc`), where the + * site's `/media/…` paths do not exist, and the sandbox's opaque origin sends no session cookie + * and matches no `CORP: same-origin`. So every blob asset a preview refers to gets a short-lived + * URL whose signature is the credential (`routes/preview-media.ts` serves it). + */ +import type { MediaContext } from "@cloudhal/astro-renderer/media"; +import type { Asset } from "@cloudhal/core-contracts"; +import { previewMediaKey, previewMediaUrl } from "@cloudhal/core-ts"; +import { mediaPrefix } from "@cloudhal/core-ts/media"; +import type { Context } from "hono"; +import type { ApiDeps, Env } from "./context.ts"; + +/** How this API signs preview media URLs: the derived key (undefined: none) and a query suffix. */ +export interface PreviewMediaSigner { + readonly key: Promise; + readonly query: string | undefined; +} + +const signers = new WeakMap(); + +/** + * The signer of an API: from `previewMedia.secret`, else the preview secret, else a random key of + * this process (one process: local `cloudhal studio`, tests). Built once per `createApi`. + */ +export function previewMediaSigner(deps: ApiDeps): PreviewMediaSigner { + let signer = signers.get(deps); + if (!signer) { + const secret = + deps.previewMedia?.secret ?? + deps.preview?.secret ?? + crypto.getRandomValues(new Uint8Array(32)); + signer = { key: previewMediaKey(secret), query: deps.previewMedia?.query }; + signers.set(deps, signer); + } + return signer; +} + +/** At most this many references are looked up per preview. */ +const MAX_IDS = 500; +const MAX_PREFIXES = 100; +const MAX_DEPTH = 64; +const ASSET_ID = /^asset_[A-Za-z0-9]{6,32}$/; +const ID_CHAR = /[A-Za-z0-9_]/; +const HEX = /^[0-9a-f]{16}$/; + +interface MediaRefs { + readonly ids: Set; + readonly prefixes: Set; +} + +/** The `asset:` references in a text (linear: `indexOf`, then a bounded read). */ +function scanAssetRefs(text: string, refs: MediaRefs): void { + let at = text.indexOf("asset:asset_"); + while (at !== -1 && refs.ids.size < MAX_IDS) { + let end = at + 6; + while (end < text.length && end - at < 46 && ID_CHAR.test(text[end] as string)) end++; + const id = text.slice(at + 6, end); + if (ASSET_ID.test(id)) refs.ids.add(id); + at = text.indexOf("asset:asset_", end); + } +} + +/** The 16-hex prefixes of `/media//…` paths in a text. */ +function scanMediaPaths(text: string, refs: MediaRefs): void { + let at = text.indexOf("/media/"); + while (at !== -1 && refs.prefixes.size < MAX_PREFIXES) { + const prefix = text.slice(at + 7, at + 23); + if (text[at + 23] === "/" && HEX.test(prefix)) refs.prefixes.add(prefix); + at = text.indexOf("/media/", at + 7); + } +} + +function walk(value: unknown, refs: MediaRefs, depth: number): void { + if (depth > MAX_DEPTH) return; + if (typeof value === "string") { + if (value.length <= 38 && ASSET_ID.test(value)) { + if (refs.ids.size < MAX_IDS) refs.ids.add(value); + return; + } + scanAssetRefs(value, refs); + scanMediaPaths(value, refs); + } else if (Array.isArray(value)) { + for (const v of value) walk(v, refs, depth + 1); + } else if (value && typeof value === "object") { + for (const v of Object.values(value)) walk(v, refs, depth + 1); + } +} + +/** + * Every asset a node may show: image `assetId`s, `asset:` references (markdown, directives, + * surfaces) and site-relative `/media//…` paths (markdown bodies, legacy `src`), found + * anywhere in its JSON. Over-collecting costs a lookup, never a wrong image. + */ +export function mediaRefsIn(...values: unknown[]): { ids: string[]; prefixes: string[] } { + const refs: MediaRefs = { ids: new Set(), prefixes: new Set() }; + walk(values, refs, 0); + return { ids: [...refs.ids], prefixes: [...refs.prefixes] }; +} + +/** + * The media part of a preview's render context: the referenced assets of `siteId` and, when the + * API can sign, `previewAssetUrl` naming each blob asset's signed URL (relative, so it resolves + * against Studio's origin in a served preview and in a `srcdoc` alike). + */ +export async function previewMediaFor( + c: Context, + siteId: string, + ...values: unknown[] +): Promise> { + const store = c.get("store"); + const refs = mediaRefsIn(...values); + const assets = new Map(await store.getAssets(siteId, refs.ids)); + const known = new Set([...assets.values()].map((a) => mediaPrefix(a.sha256))); + const byPrefix = await Promise.all( + refs.prefixes.filter((p) => !known.has(p)).map((p) => store.getAssetByPrefix(siteId, p)), + ); + for (const a of byPrefix) if (a) assets.set(a.id, a); + const signer = c.get("previewMedia"); + const key = await signer.key; + if (!key) return { assets }; + const now = c.get("now")().getTime(); + const suffix = signer.query ? `&${signer.query}` : ""; + const urls = new Map(); + for (const a of assets.values()) + if (a.storage.kind === "blob" && a.siteId === siteId) + urls.set(a.id, `${await previewMediaUrl(key, a, now)}${suffix}`); + return { assets, previewAssetUrl: (a) => urls.get(a.id) }; +} diff --git a/packages/api/src/preview.ts b/packages/api/src/preview.ts index 3404b8b1..ab568ebb 100644 --- a/packages/api/src/preview.ts +++ b/packages/api/src/preview.ts @@ -1,15 +1,19 @@ +import { PREVIEW_IMG_SRC } from "@cloudhal/astro-renderer/preview"; import type { Context } from "hono"; /** * Serves a rendered preview document. Previews include drafts, so they are private (no caching) - * and sandboxed: no scripts, no framing by other origins, nothing leaves the page. + * and sandboxed: no scripts, no framing by other origins, nothing leaves the page. Images may also + * come from this server's own origin when it is plain http (#383: signed `preview-media` URLs on + * a local or LAN Studio; the sandbox's opaque origin matches no 'self'). */ export function previewResponse(c: Context, html: string): Response { + const own = new URL(c.req.url); + const imgSrc = own.protocol === "http:" ? `${PREVIEW_IMG_SRC} ${own.origin}` : PREVIEW_IMG_SRC; return c.body(html, 200, { "content-type": "text/html; charset=utf-8", "cache-control": "private, no-store", - "content-security-policy": - "default-src 'none'; img-src https: data:; style-src 'unsafe-inline'; frame-ancestors 'self'; base-uri 'none'; form-action 'none'; sandbox", + "content-security-policy": `default-src 'none'; img-src ${imgSrc}; style-src 'unsafe-inline'; frame-ancestors 'self'; base-uri 'none'; form-action 'none'; sandbox`, "referrer-policy": "no-referrer", "x-content-type-options": "nosniff", }); diff --git a/packages/api/src/routes/asset-content-headers.ts b/packages/api/src/routes/asset-content-headers.ts index 69578c75..2af6c4db 100644 --- a/packages/api/src/routes/asset-content-headers.ts +++ b/packages/api/src/routes/asset-content-headers.ts @@ -1,8 +1,11 @@ /** - * Headers of Studio's private copy of an asset's bytes (`GET …/assets/:id/content`). + * Studio's copies of an asset's bytes: the private `GET …/assets/:id/content` and the signed + * `GET …/preview-media/:id/` of previews (#383). Their headers, and the bytes themselves. */ import type { Asset } from "@cloudhal/core-contracts"; import { MEDIA_TYPES, mediaExtension, servedContentType } from "@cloudhal/core-ts/media"; +import type { Context } from "hono"; +import type { Env } from "../context.ts"; /** * Response headers for Studio's private previews (never shared caches, never executed). A URL @@ -31,3 +34,39 @@ export function contentHeaders(asset: Asset, version: string | undefined): Recor etag: `"${asset.sha256}"`, }; } + +/** + * #383: headers of a signed preview media URL. The served preview is sandboxed (an opaque origin), + * so `same-origin` could never match: `cross-origin` lets it load, and the signature, not the + * origin, is what guards the bytes. The browser keeps them while the URL is valid (at most a + * day); never a shared cache. + */ +export function previewMediaHeaders(asset: Asset, maxAgeSeconds: number): Record { + const age = Math.max(0, Math.min(Math.floor(maxAgeSeconds), 86_400)); + return { + ...contentHeaders(asset, undefined), + "cache-control": `private, max-age=${age}`, + "cross-origin-resource-policy": "cross-origin", + "referrer-policy": "no-referrer", + "x-robots-tag": "noindex", + }; +} + +/** The stored bytes of a blob asset with `headers` (304 on a matching ETag), or undefined. */ +export async function assetBytesResponse( + c: Context, + asset: Asset, + headers: Record, +): Promise { + if (c.req.header("if-none-match") === headers.etag) return c.body(null, 304, headers); + const key = `media/${asset.siteId}/${asset.sha256}`; + const blobs = c.get("store").blobs; + if (blobs.getStream) { + const s = await blobs.getStream(key); + if (!s) return undefined; + return c.body(s.body, 200, { ...headers, "content-length": String(s.size) }); + } + const bytes = await blobs.get(key); + if (!bytes) return undefined; + return c.body(bytes as Uint8Array, 200, headers); +} diff --git a/packages/api/src/routes/assets.ts b/packages/api/src/routes/assets.ts index aa983d98..8d246426 100644 --- a/packages/api/src/routes/assets.ts +++ b/packages/api/src/routes/assets.ts @@ -32,7 +32,7 @@ import { actorOf, requireSite } from "../governance.ts"; import { personOf } from "../own.ts"; import { param } from "../params.ts"; import { signUploadTicket, verifyUploadTicket } from "../uploads.ts"; -import { contentHeaders } from "./asset-content-headers.ts"; +import { assetBytesResponse, contentHeaders } from "./asset-content-headers.ts"; /** RFC-0004 §5.1: per request, per actor and per ticket. */ export const UPLOAD_LIMITS = { @@ -638,17 +638,9 @@ export const assets: Hono = new Hono() if (state?.state === "purged") throw apiError(410, "purged", "this file was taken down; its bytes are gone"); const headers = contentHeaders(asset, c.req.query("v") || undefined); - if (c.req.header("if-none-match") === headers.etag) return c.body(null, 304, headers); - const key = `media/${asset.siteId}/${asset.sha256}`; - const blobs = store.blobs; - if (blobs.getStream) { - const s = await blobs.getStream(key); - if (!s) throw notFound("the file's bytes are not stored"); - return c.body(s.body, 200, { ...headers, "content-length": String(s.size) }); - } - const bytes = await blobs.get(key); - if (!bytes) throw notFound("the file's bytes are not stored"); - return c.body(bytes as Uint8Array, 200, headers); + const res = await assetBytesResponse(c, asset, headers); + if (!res) throw notFound("the file's bytes are not stored"); + return res; }) .put("/:assetId", async (c) => { const store = c.get("store"); diff --git a/packages/api/src/routes/entries.ts b/packages/api/src/routes/entries.ts index 97d43710..9dd995a9 100644 --- a/packages/api/src/routes/entries.ts +++ b/packages/api/src/routes/entries.ts @@ -14,6 +14,7 @@ import { API_ACTOR, writerOf } from "../governance.ts"; import { editsLiveCorrections, entryLimit, personOf } from "../own.ts"; import { param } from "../params.ts"; import { type DraftPreview, previewResponse } from "../preview.ts"; +import { previewMediaFor } from "../preview-media.ts"; import { previewStructuredData } from "../structured-data.ts"; import { entryReferences } from "./entry-references.ts"; @@ -102,7 +103,8 @@ export const entries: Hono = new Hono() const b = (await c.req.json().catch(() => ({}))) as { markdown?: unknown }; if (typeof b.markdown !== "string" || b.markdown.length > 64_000) throw badRequest("markdown must be text of at most 64 000 characters"); - return c.json(renderFragmentPreview(site, b.markdown, { blocks: store.blocks })); + const media = await previewMediaFor(c, site.id, b.markdown); + return c.json(renderFragmentPreview(site, b.markdown, { blocks: store.blocks, ...media })); }) .get("/:entryId/preview", async (c) => { const store = c.get("store"); @@ -110,7 +112,11 @@ export const entries: Hono = new Hono() if (!site) throw notFound("site not found"); const entry = await store.getContentEntry(param(c, "entryId")); if (!entry || entry.siteId !== site.id) throw notFound("entry not found"); - return previewResponse(c, renderEntryPreview(site, entry, { blocks: store.blocks }).html); + const media = await previewMediaFor(c, site.id, entry); + return previewResponse( + c, + renderEntryPreview(site, entry, { blocks: store.blocks, ...media }).html, + ); }) // The editor's unsaved title, summary, body and cover (RFC-0014 phase 1c): writes nothing. .post("/:entryId/preview", async (c) => { @@ -120,8 +126,9 @@ export const entries: Hono = new Hono() const entry = await store.getContentEntry(param(c, "entryId")); if (!entry || entry.siteId !== site.id) throw notFound("entry not found"); const draft = entryDraft(entry, await c.req.json().catch(() => ({}))); + const media = await previewMediaFor(c, site.id, draft); return c.json({ - html: renderEntryPreview(site, draft, { blocks: store.blocks }).html, + html: renderEntryPreview(site, draft, { blocks: store.blocks, ...media }).html, } satisfies DraftPreview); }) // RFC-0042 §7: the JSON-LD the entry's page emits under its collection's preset (read-only). diff --git a/packages/api/src/routes/pages.ts b/packages/api/src/routes/pages.ts index 1319c9bd..a2a49387 100644 --- a/packages/api/src/routes/pages.ts +++ b/packages/api/src/routes/pages.ts @@ -11,6 +11,7 @@ import { badRequest, notFound } from "../errors.ts"; import { writerOf } from "../governance.ts"; import { param } from "../params.ts"; import { type DraftPreview, previewResponse } from "../preview.ts"; +import { previewMediaFor } from "../preview-media.ts"; async function requireSite(c: Context) { const site = await c.get("store").getSite(param(c, "siteId")); @@ -34,7 +35,8 @@ async function pagePreview(c: Context, site: Site, page: Page): Promise [col, await store.listContentEntries(site.id, col)]), ), ); - return renderPagePreview(site, page, entries, { blocks: store.blocks }).html; + const media = await previewMediaFor(c, site.id, page); + return renderPagePreview(site, page, entries, { blocks: store.blocks, ...media }).html; } /** Who did it, as a viewer may see it: never an email or a key. */ diff --git a/packages/api/src/routes/preview-media.ts b/packages/api/src/routes/preview-media.ts new file mode 100644 index 00000000..f03619f9 --- /dev/null +++ b/packages/api/src/routes/preview-media.ts @@ -0,0 +1,41 @@ +/** + * #383: `GET /api/sites/:siteId/preview-media/:assetId/.?v=&exp=&sig=…`, + * the bytes of a blob asset for Studio's previews. No session: the served preview is sandboxed + * (an opaque origin), so its image requests carry no `SameSite=Lax` cookie. The signature minted + * by `previewMediaFor` is the credential (`public` in `ROUTE_SCOPES`). Every refusal is a bare + * 403 or 404 (410 once the file was taken down), never a reason. + */ +import { verifyPreviewMedia } from "@cloudhal/core-ts"; +import { mediaPrefix } from "@cloudhal/core-ts/media"; +import { type Context, Hono } from "hono"; +import type { Env } from "../context.ts"; +import { param } from "../params.ts"; +import { assetBytesResponse, previewMediaHeaders } from "./asset-content-headers.ts"; + +const refuse = (c: Context, status: 403 | 404 | 410) => + c.body(null, status, { "cache-control": "no-store", "referrer-policy": "no-referrer" }); + +export const previewMedia: Hono = new Hono().get("/:assetId/:file", async (c) => { + const siteId = param(c, "siteId"); + const assetId = param(c, "assetId"); + const v = c.req.query("v") ?? ""; + const expText = c.req.query("exp") ?? ""; + const key = await c.get("previewMedia").key; + if (!key || !/^\d{1,12}$/.test(expText)) return refuse(c, 403); + const now = c.get("now")().getTime(); + const claims = { site: siteId, assetId, v, exp: Number(expText) }; + if ((await verifyPreviewMedia(key, claims, c.req.query("sig"), now)) !== "ok") + return refuse(c, 403); + const store = c.get("store"); + const asset = await store.getAsset(assetId); + if ( + !asset || + asset.siteId !== siteId || + asset.storage.kind !== "blob" || + mediaPrefix(asset.sha256) !== v + ) + return refuse(c, 404); + if ((await store.blobState(siteId, asset.sha256))?.state === "purged") return refuse(c, 410); + const headers = previewMediaHeaders(asset, claims.exp - Math.floor(now / 1000)); + return (await assetBytesResponse(c, asset, headers)) ?? refuse(c, 404); +}); diff --git a/packages/api/src/routes/terms.ts b/packages/api/src/routes/terms.ts index be20a397..e8a40fbd 100644 --- a/packages/api/src/routes/terms.ts +++ b/packages/api/src/routes/terms.ts @@ -8,6 +8,7 @@ import { badRequest, missingScope, notFound } from "../errors.ts"; import { type PreviewOp, previewGovernance, requireSite, snapshotAfter } from "../governance.ts"; import { param } from "../params.ts"; import { previewResponse } from "../preview.ts"; +import { previewMediaFor } from "../preview-media.ts"; type TermInput = Omit; @@ -184,6 +185,7 @@ async function archivePreview(c: Context, term: Term) { terms: vocabulary.map((t) => (t.id === term.id ? term : t)), termId: term.id, entries, + media: await previewMediaFor(c, site.id, term), }); } diff --git a/packages/api/src/scopes.ts b/packages/api/src/scopes.ts index 7dbc4fc2..6a11e023 100644 --- a/packages/api/src/scopes.ts +++ b/packages/api/src/scopes.ts @@ -283,6 +283,9 @@ export const ROUTE_SCOPES: readonly (readonly [Method, string, RouteRequirement] ["PUT", `${A}/agent-uploads/:uploadId`, "upload-link"], ["GET", `${A}/:assetId`, "site:read"], ["GET", `${A}/:assetId/content`, "site:read"], + // #383: a preview's signed media URL. The URL is the credential (sandboxed previews send no + // session cookie); the handler checks the signature, its expiry and the asset's site. + ["GET", `${S}/preview-media/:assetId/:file`, "public"], ["PUT", `${A}/:assetId`, "asset:upload"], ["POST", `${A}/:assetId/retire`, "asset:manage"], ["POST", `${A}/:assetId/restore`, "asset:manage"], diff --git a/packages/api/src/testing-preview-media.ts b/packages/api/src/testing-preview-media.ts new file mode 100644 index 00000000..eab6a326 --- /dev/null +++ b/packages/api/src/testing-preview-media.ts @@ -0,0 +1,218 @@ +/** + * Shared API suite for #383 (signed media URLs in Studio's previews) — runs against any + * SiteGraphStore backend (better-sqlite3 and Miniflare D1 in `test/preview-media-api.test.ts`): + * previews name `/api/sites/…/preview-media/…` URLs instead of the site's `/media/…`, and those + * URLs serve the bytes without a session, to anyone holding a valid signature, until they expire. + */ +import type { Asset, ContentEntry } from "@cloudhal/core-contracts"; +import { + previewMediaKey, + previewMediaUrl, + type SiteGraphStore, + seedStarterSite, +} from "@cloudhal/core-ts"; +import { mediaPath } from "@cloudhal/core-ts/media"; +import { makeJpeg } from "@cloudhal/core-ts/media/fixtures"; +import { sha256OfBytes } from "@cloudhal/storage"; +import { afterAll, beforeEach, describe, expect, it } from "vitest"; +import { createApi } from "./app.ts"; +import type { UploadTicketResult } from "./routes/assets.ts"; + +export interface PreviewMediaApiBackend { + create(): Promise<{ store: SiteGraphStore }>; + dispose?(): Promise; +} + +const SECRET = "preview-media-suite-secret-0123456789abcdef"; +const person = { kind: "human" as const, id: "user_apitest00001", name: "Tester" }; + +/** The signed preview media URLs in an HTML document, unescaped. */ +const signedUrls = (html: string) => + [...html.matchAll(/"(\/api\/sites\/[^"]+\/preview-media\/[^"]+)"/g)].map((m) => + (m[1] as string).replaceAll("&", "&"), + ); + +export function describePreviewMediaApi(label: string, backend: PreviewMediaApiBackend): void { + describe(`API preview media (#383): ${label}`, () => { + let store: SiteGraphStore; + let siteId: string; + let nowMs: number; + let app: ReturnType; + const build = (extra: Partial[0]> = {}) => + createApi({ + store, + now: () => new Date(nowMs), + resolveActor: async (c) => (c.req.header("x-test-user") ? person : undefined), + ...extra, + }); + const call = (path: string, init: { method?: string; body?: unknown; anon?: boolean } = {}) => + Promise.resolve( + app.request(path, { + method: init.method ?? "GET", + headers: { + "content-type": "application/json", + ...(init.anon ? {} : { "x-test-user": "1" }), + }, + ...(init.body !== undefined ? { body: JSON.stringify(init.body) } : {}), + }), + ); + const upload = async (site: string, bytes: Uint8Array, filename: string): Promise => { + const t = await call(`/api/sites/${site}/assets/uploads`, { + method: "POST", + body: { files: [{ bytes: bytes.byteLength, filename, mediaType: "image/jpeg", alt: "A" }] }, + }); + const file = ((await t.json()) as { files: UploadTicketResult[] }).files[0] as Extract< + UploadTicketResult, + { uploadId: string } + >; + const put = await app.request(file.url, { + method: "PUT", + headers: { + "x-test-user": "1", + "content-type": "image/jpeg", + "content-length": String(bytes.byteLength), + }, + body: bytes as Uint8Array, + }); + expect(put.status).toBe(201); + return ((await put.json()) as { asset: Asset }).asset; + }; + const bytes = makeJpeg({ width: 640, height: 480 }); + let asset: Asset; + let entry: ContentEntry; + + beforeEach(async () => { + store = (await backend.create()).store; + nowMs = Date.parse("2026-12-02T10:00:00.000Z"); + siteId = (await seedStarterSite(store, { name: "Preview Media", slug: "preview-media" })).id; + app = build({ preview: { secret: SECRET } }); + // Uploaded, never published: only Studio has it. + asset = await upload(siteId, bytes, "Clavius cover.jpg"); + const first = (await store.listContentEntries(siteId))[0] as ContentEntry; + entry = await store.updateContentEntry({ + ...first, + coverImage: { assetId: asset.id, alt: "" } as never, + body: { format: "markdown", value: `Intro\n\n![Inline](${mediaPath(asset)})\n` }, + }); + }); + + afterAll(async () => { + await backend.dispose?.(); + }); + + it("previews name signed Studio URLs, never the site's /media/ path", async () => { + const res = await call(`/api/sites/${siteId}/entries/${entry.id}/preview`); + expect(res.status).toBe(200); + const html = await res.text(); + const urls = signedUrls(html); + expect(urls.length).toBe(2); + expect(new Set(urls).size).toBe(1); + expect(urls[0]).toMatch( + new RegExp( + `^/api/sites/${siteId}/preview-media/${asset.id}/clavius-cover\\.jpg\\?v=[0-9a-f]{16}&exp=\\d+&sig=[\\w-]+$`, + ), + ); + expect(html).not.toMatch(/src="\/media\//); + // A local http Studio: its own origin may serve the images. + expect(res.headers.get("content-security-policy")).toContain("http://localhost"); + + const draft = await call(`/api/sites/${siteId}/entries/${entry.id}/preview`, { + method: "POST", + body: { title: "Draft title" }, + }); + expect(signedUrls(((await draft.json()) as { html: string }).html)).toEqual(urls); + const fragment = await call(`/api/sites/${siteId}/entries/preview-fragment`, { + method: "POST", + body: { markdown: `![x](asset:${asset.id})` }, + }); + expect(signedUrls(((await fragment.json()) as { html: string }).html)).toEqual([urls[0]]); + }); + + it("page previews sign section images too", async () => { + const [home] = await store.listPages(siteId); + const page = home as NonNullable; + await store.updatePage({ + ...page, + sections: [ + ...page.sections, + { id: "sec_previewimg1", kind: "image", image: { assetId: asset.id, alt: "" } as never }, + ], + }); + const html = await (await call(`/api/sites/${siteId}/pages/${page.id}/preview`)).text(); + expect(signedUrls(html)).toHaveLength(1); + expect(html).not.toMatch(/src="\/media\//); + }); + + it("serves the bytes without a session, for any origin, cached privately until expiry", async () => { + const html = await (await call(`/api/sites/${siteId}/entries/${entry.id}/preview`)).text(); + const url = signedUrls(html)[0] as string; + const res = await call(url, { anon: true }); + expect(res.status).toBe(200); + const got = new Uint8Array(await res.arrayBuffer()); + expect(await sha256OfBytes(got)).toBe(asset.sha256); + expect(res.headers.get("content-type")).toBe("image/jpeg"); + expect(res.headers.get("cross-origin-resource-policy")).toBe("cross-origin"); + expect(res.headers.get("x-content-type-options")).toBe("nosniff"); + expect(res.headers.get("referrer-policy")).toBe("no-referrer"); + expect(res.headers.get("x-robots-tag")).toBe("noindex"); + const age = Number(/max-age=(\d+)/.exec(res.headers.get("cache-control") ?? "")?.[1]); + expect(res.headers.get("cache-control")).toMatch(/^private, max-age=/); + expect(age).toBeGreaterThanOrEqual(6 * 3600); + expect(age).toBeLessThanOrEqual(12 * 3600); + // Another instance with the same secret signs the same URL (bucketed expiry). + app = build({ preview: { secret: SECRET } }); + const again = await (await call(`/api/sites/${siteId}/entries/${entry.id}/preview`)).text(); + expect(signedUrls(again)[0]).toBe(url); + }); + + it("refuses bad signatures and expired URLs with a bare 403", async () => { + const html = await (await call(`/api/sites/${siteId}/entries/${entry.id}/preview`)).text(); + const url = signedUrls(html)[0] as string; + const tampered = url.replace( + /sig=([\w-])/, + (_m, c: string) => `sig=${c === "A" ? "B" : "A"}`, + ); + const bad = await call(tampered, { anon: true }); + expect(bad.status).toBe(403); + expect(await bad.text()).toBe(""); + expect((await call(url.replace(/&sig=.*$/, ""), { anon: true })).status).toBe(403); + expect((await call(url.replace(/exp=\d+/, "exp=9999999999"), { anon: true })).status).toBe( + 403, + ); + nowMs += 13 * 3600 * 1000; + expect((await call(url, { anon: true })).status).toBe(403); + // Another deployment's key never verifies. + app = build({ preview: { secret: `${SECRET}-other` } }); + nowMs -= 13 * 3600 * 1000; + expect((await call(url, { anon: true })).status).toBe(403); + }); + + it("answers 404 for another site's asset, 410 once the file was taken down", async () => { + const other = (await seedStarterSite(store, { name: "Other", slug: "other-site" })).id; + const theirs = await upload(other, makeJpeg({ width: 320, height: 240 }), "Theirs.jpg"); + const key = await previewMediaKey(SECRET); + // Signed for this site's path, naming the other site's asset. + const cross = await previewMediaUrl(key as CryptoKey, { ...theirs, siteId }, nowMs); + const res = await call(cross, { anon: true }); + expect(res.status).toBe(404); + expect(await res.text()).toBe(""); + + const html = await (await call(`/api/sites/${siteId}/entries/${entry.id}/preview`)).text(); + const url = signedUrls(html)[0] as string; + const purge = await call(`/api/sites/${siteId}/assets/${asset.id}/purge`, { + method: "POST", + body: { reason: "Copyright notice", legal: true }, + }); + expect(purge.status).toBe(200); + expect((await call(url, { anon: true })).status).toBe(410); + }); + + it("signs with a process key when no secret is configured (local Studio)", async () => { + app = build(); + const html = await (await call(`/api/sites/${siteId}/entries/${entry.id}/preview`)).text(); + const url = signedUrls(html)[0] as string; + expect((await call(url, { anon: true })).status).toBe(200); + expect(html).not.toMatch(/src="\/media\//); + }); + }); +} diff --git a/packages/api/test/preview-media-api.test.ts b/packages/api/test/preview-media-api.test.ts new file mode 100644 index 00000000..b154ab07 --- /dev/null +++ b/packages/api/test/preview-media-api.test.ts @@ -0,0 +1,30 @@ +import { SiteGraphStore } from "@cloudhal/core-ts"; +import { MemoryBlobStore } from "@cloudhal/storage"; +import { D1Driver } from "@cloudhal/storage/d1"; +import { BetterSqlite3Driver } from "@cloudhal/storage/sqlite"; +import { createMiniflareD1, createTableReset } from "@cloudhal/storage/testing"; +import { describePreviewMediaApi } from "../src/testing-preview-media.ts"; + +describePreviewMediaApi("better-sqlite3", { + async create() { + const sql = await BetterSqlite3Driver.open(":memory:"); + const store = new SiteGraphStore({ sql, blobs: new MemoryBlobStore() }); + await store.init(); + return { store }; + }, +}); + +let d1: Awaited> | undefined; +const reset = createTableReset(); +describePreviewMediaApi("Cloudflare D1 (Miniflare)", { + async create() { + d1 ??= await createMiniflareD1(); + const sql = new D1Driver(d1.db); + const store = new SiteGraphStore({ sql, blobs: new MemoryBlobStore() }); + await reset(sql, () => store.init()); + return { store }; + }, + async dispose() { + await d1?.dispose(); + }, +}); diff --git a/packages/astro-renderer/src/fields.ts b/packages/astro-renderer/src/fields.ts index 477fdab9..46bcf3ee 100644 --- a/packages/astro-renderer/src/fields.ts +++ b/packages/astro-renderer/src/fields.ts @@ -36,6 +36,7 @@ import { type PlaceholderBudget, REFERENCE_BUDGET, } from "./media.ts"; +import { previewOptions } from "./preview-media.ts"; import { conversionsFor } from "./reference-conversions.ts"; import { type ReferencedEntry, referenceCards } from "./references.ts"; import { safeHref } from "./safe-urls.ts"; @@ -151,7 +152,7 @@ function picture( defaultLocale: o.defaultLocale, transform: ctx.transform ?? "none", sizes: o.sizes, - ...(ctx.preview ? { preview: true } : {}), + ...previewOptions(ctx), ...(ctx.budget ? { budget: ctx.budget } : {}), }); return { ...image, assetId: asset.id }; diff --git a/packages/astro-renderer/src/markdown.ts b/packages/astro-renderer/src/markdown.ts index 36f65c7a..09e94d90 100644 --- a/packages/astro-renderer/src/markdown.ts +++ b/packages/astro-renderer/src/markdown.ts @@ -2,7 +2,7 @@ import type { Asset, ContentEntry } from "@cloudhal/core-contracts"; import { type BlockRegistry, createBlockRegistry } from "@cloudhal/core-ts/blocks"; import { type DirectiveToken, directiveExtension } from "@cloudhal/core-ts/body-blocks"; import { checkDirective, directiveProps } from "@cloudhal/core-ts/directives"; -import { ASSET_HREF, assetUrl, mediaPath } from "@cloudhal/core-ts/media"; +import { ASSET_HREF, mediaPath } from "@cloudhal/core-ts/media"; import { trimChar } from "@cloudhal/core-ts/names"; import { parseSurfaceFence } from "@cloudhal/core-ts/surfaces"; import { Marked } from "marked"; @@ -16,6 +16,7 @@ import { isAttachment, type MediaContext, } from "./media.ts"; +import { previewMediaSrc, previewOptions, shownAssetUrl } from "./preview-media.ts"; import { safeHref, safeSrc } from "./safe-urls.ts"; import { sanitizeHtml } from "./sanitize.ts"; import { renderSurface, surfaceProblems } from "./surfaces.ts"; @@ -84,7 +85,7 @@ function localeOf(): { locale: string; defaultLocale: string } { /** A download link: the URL comes from validated parts only, the label is the markdown's (§7.6). */ function assetLink(asset: Asset, labelHtml: string, title?: string | null): string { - const href = assetUrl(asset); + const href = shownAssetUrl(asset, current); const download = isAttachment(asset) ? " download" : ""; const link = `${labelHtml}`; return asset.kind === "document" || asset.kind === "data" || asset.kind === "other" @@ -108,14 +109,14 @@ function assetEmbed(asset: Asset, text: string, title?: string | null): string { transform: current?.transform ?? "none", ...(current?.budget ? { budget: current.budget } : {}), sizes: "(min-width: 48rem) 48rem, 100vw", - ...(current?.preview ? { preview: true } : {}), + ...previewOptions(current), }, ), titleAttr, ); case "video": case "audio": { - const src = escapeHtml(assetUrl(asset)); + const src = escapeHtml(shownAssetUrl(asset, current)); const fallback = assetLink(asset, escapeHtml(alt || asset.slug)); return `<${asset.kind} controls preload="metadata" src="${src}"${alt ? ` aria-label="${escapeHtml(alt)}"` : ""}${titleAttr}>${fallback}`; } @@ -280,7 +281,7 @@ md.use({ } const safe = safeHref(href); if (!safe) return label; - return `${label}`; + return `${label}`; }, image({ href, title, text }) { if (inlineOnly) return escapeHtml(text); @@ -290,7 +291,7 @@ md.use({ } const safe = safeSrc(href); if (!safe) return escapeHtml(text); - return `${escapeHtml(text)}`; + return `${escapeHtml(text)}`; }, }, }); @@ -452,13 +453,14 @@ function coverFigure(image: ContentEntry["coverImage"], ctx?: MediaContext): str ...(ctx?.budget ? { budget: ctx.budget } : {}), sizes: "(min-width: 48rem) 48rem, 100vw", priority: true, - ...(ctx?.preview ? { preview: true } : {}), + ...previewOptions(ctx), }); const caption = assetCaption(asset, locale, defaultLocale); return `
${imgHtml(attrs)}${caption ? `
${escapeHtml(caption)}
` : ""}
`; } - const src = safeSrc(image.src); - if (!src) return ""; + const safe = safeSrc(image.src); + if (!safe) return ""; + const src = previewMediaSrc(safe, ctx); const size = image.width && image.height ? ` width="${image.width}" height="${image.height}"` : ""; return `
${escapeHtml(image.alt)}
`; diff --git a/packages/astro-renderer/src/media.ts b/packages/astro-renderer/src/media.ts index b940eb16..4b80c9c8 100644 --- a/packages/astro-renderer/src/media.ts +++ b/packages/astro-renderer/src/media.ts @@ -13,7 +13,8 @@ import type { Asset, ImageRef } from "@cloudhal/core-contracts"; import type { PermalinkSite } from "@cloudhal/core-ts"; import type { BlockRegistry } from "@cloudhal/core-ts/blocks"; import type { IconSet } from "@cloudhal/core-ts/icons"; -import { assetUrl, formatBytes, MEDIA_TYPES, mediaPath } from "@cloudhal/core-ts/media"; +import { formatBytes, MEDIA_TYPES, mediaPath } from "@cloudhal/core-ts/media"; +import { shownAssetUrl } from "./preview-media.ts"; const escapeHtml = (s: string) => s.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); @@ -26,6 +27,12 @@ export const WIDTH_LADDER: readonly number[] = [320, 640, 960, 1280, 1600, 1920, /** Assets by id (what a page needs to resolve `assetId` and `asset:`). */ export type AssetIndex = ReadonlyMap; +/** + * #383: where a preview shows a blob asset from (Studio's signed `preview-media` URL), or + * undefined to keep its `/media/…` path. Previews are shown on Studio's origin, not the site's. + */ +export type PreviewAssetUrl = (asset: Asset) => string | undefined; + export interface MediaContext { readonly assets?: AssetIndex | undefined; readonly locale?: string | undefined; @@ -48,6 +55,8 @@ export interface MediaContext { readonly budget?: PlaceholderBudget | undefined; /** RFC-0038: the site's collection permalinks, for links to entries (`entryPath`). */ readonly permalinks?: PermalinkSite | undefined; + /** #383: in previews, the URL a blob asset is shown from (see `shownAssetUrl`). */ + readonly previewAssetUrl?: PreviewAssetUrl | undefined; } export interface ImageAttributeOptions { @@ -59,6 +68,8 @@ export interface ImageAttributeOptions { quality?: number; priority?: boolean; preview?: boolean; + /** #383: with `preview`, the URL a blob asset is shown from. */ + previewAssetUrl?: PreviewAssetUrl; /** RFC-0028 §4: the page's placeholder bytes left; spent as LQIPs are drawn (colour only after). */ budget?: PlaceholderBudget; /** RFC-0028 §3: how the image meets its frame (the theme sets `object-fit` to match). */ @@ -211,7 +222,7 @@ export function imageAttributes( const width = asset.image?.width ?? ref?.width ?? 0; const height = asset.image?.height ?? ref?.height ?? 0; const base: ImageAttributes = { - src: assetUrl(asset), + src: shownAssetUrl(asset, o), width, height, alt: assetAlt(asset, ref?.alt, o.locale, o.defaultLocale), diff --git a/packages/astro-renderer/src/preview-media.ts b/packages/astro-renderer/src/preview-media.ts new file mode 100644 index 00000000..7b61016e --- /dev/null +++ b/packages/astro-renderer/src/preview-media.ts @@ -0,0 +1,60 @@ +/** + * #383: the one place a preview's media URLs are rewritten. Previews are shown on Studio's origin + * (a served, sandboxed document or an iframe's `srcdoc`), where the site's `/media/…` paths do not + * exist; the caller (the admin API) passes `previewAssetUrl`, which names a signed URL Studio + * serves. Published pages never set it. External (https) assets keep their own URL. + */ +import type { Asset } from "@cloudhal/core-contracts"; +import { assetUrl, MEDIA_ROUTE, mediaPrefix } from "@cloudhal/core-ts/media"; +import type { AssetIndex, MediaContext, PreviewAssetUrl } from "./media.ts"; + +interface PreviewUrlOptions { + readonly preview?: boolean | undefined; + readonly previewAssetUrl?: PreviewAssetUrl | undefined; +} + +/** Where an asset is shown from: in a preview with the hook, a blob's signed URL; else `assetUrl`. */ +export function shownAssetUrl(asset: Asset, o: PreviewUrlOptions | undefined): string { + if (o?.preview && o.previewAssetUrl && asset.storage.kind === "blob") + return o.previewAssetUrl(asset) ?? assetUrl(asset); + return assetUrl(asset); +} + +/** The preview fields of `imageAttributes` options for a render context (none on the site). */ +export function previewOptions( + ctx: PreviewUrlOptions | undefined, +): { preview: true; previewAssetUrl?: PreviewAssetUrl } | Record { + if (!ctx?.preview) return {}; + return ctx.previewAssetUrl + ? { preview: true, previewAssetUrl: ctx.previewAssetUrl } + : { preview: true }; +} + +/** Blob assets by their 16-hex media prefix, built once per index. */ +const byPrefix = new WeakMap>(); + +function assetAtPrefix(assets: AssetIndex, prefix: string): Asset | undefined { + let map = byPrefix.get(assets); + if (!map) { + map = new Map(); + for (const a of assets.values()) + if (a.storage.kind === "blob") map.set(mediaPrefix(a.sha256), a); + byPrefix.set(assets, map); + } + return map.get(prefix); +} + +/** + * A site-relative `/media/<16 hex>/.` written as a plain URL (a markdown image, a + * legacy `image.src` without `assetId`) resolved to its asset by the prefix, then shown like an + * asset. Anything else, or a path whose asset the render does not know, is returned unchanged. + */ +export function previewMediaSrc(src: string, ctx: MediaContext | undefined): string { + if (!ctx?.preview || !ctx.previewAssetUrl || !ctx.assets) return src; + // Bounded before the (anchored) route pattern runs: a media path is short. + if (src.length > 160 || !src.startsWith("/media/")) return src; + const m = MEDIA_ROUTE.exec(src); + if (!m || m[4] !== undefined) return src; + const asset = assetAtPrefix(ctx.assets, m[1] as string); + return asset ? shownAssetUrl(asset, ctx) : src; +} diff --git a/packages/astro-renderer/src/preview.ts b/packages/astro-renderer/src/preview.ts index c10e5dd3..f1ad053b 100644 --- a/packages/astro-renderer/src/preview.ts +++ b/packages/astro-renderer/src/preview.ts @@ -23,6 +23,7 @@ import { evaluateEntryQuery, listsByField, sectionQuery } from "./entry-query.ts import { formatGateTime, gateNotice } from "./gates.ts"; import { renderBody, renderEntryArticle, renderMarkdown, safeHref, safeSrc } from "./markdown.ts"; import { assetCaption, imageAttributes, imgHtml, type MediaContext } from "./media.ts"; +import { previewMediaSrc, previewOptions } from "./preview-media.ts"; import { archiveHead, siteOrigin } from "./seo.ts"; import { pickEntries, renderSurface, surfaceSources } from "./surfaces.ts"; import { @@ -58,11 +59,12 @@ function sectionImage(image: ImageRef, media: MediaContext | undefined): string transform: "none", sizes: "(min-width: 48rem) 48rem, 100vw", preview: true, + ...previewOptions(media), }), ); } const src = safeSrc(image.src); - return src ? `${esc(image.alt)}` : ""; + return src ? `${esc(image.alt)}` : ""; } /** The collections a page's sections list: content lists and surfaces' entry sources. */ @@ -349,6 +351,8 @@ export interface ArchivePreviewInput { readonly termId: string; /** The site's entries (any status): the archive lists the published ones in the default locale. */ readonly entries: readonly ContentEntry[]; + /** #383: the assets the term shows and how a preview names them (`MediaContext`). */ + readonly media?: MediaContext | undefined; /** Entries per page (the blog starter's `ARCHIVE_PAGE_SIZE`). */ readonly perPage?: number; } @@ -489,7 +493,9 @@ export function renderArchivePreview( const label = term.labels[locale]; const kind = taxonomy.labels[locale]?.singular ?? Object.values(taxonomy.labels)[0]?.singular ?? ""; - const imageSrc = term.image ? safeSrc(term.image.src) : undefined; + const media = previewMedia(site, input.media); + const safeImage = term.image ? safeSrc(term.image.src) : undefined; + const imageSrc = safeImage ? previewMediaSrc(safeImage, media) : undefined; const crumbs = [ { name: words.home, href: "/" as string | undefined }, ...view.trail.map((t) => ({ name: t.name, href: t.href })), @@ -531,7 +537,7 @@ export function renderArchivePreview( term.image && imageSrc ? `${esc(term.image.alt)}` : "" - }${label?.description ? `
${renderMarkdown(label.description)}
` : ""}${list}${pagination}`; + }${label?.description ? `
${renderMarkdown(label.description, media)}
` : ""}${list}${pagination}`; return { title: head.title, path: root, @@ -627,10 +633,12 @@ const PREVIEW_CSS = /** * The same policy `previewResponse` (packages/api) sends as a header, repeated in the document so - * it also holds where the document is shown without that response (an iframe's `srcdoc`). + * it also holds where the document is shown without that response (an iframe's `srcdoc`). Images: + * any https host, data URLs, and Studio's own signed `preview-media` URLs (#383), which are + * http on a local `cloudhal studio`; a sandboxed `srcdoc` has no origin of its own to call 'self'. */ -const PREVIEW_CSP = - "default-src 'none'; img-src https: data:; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'"; +export const PREVIEW_IMG_SRC = "'self' https: data: http://localhost:* http://127.0.0.1:*"; +const PREVIEW_CSP = `default-src 'none'; img-src ${PREVIEW_IMG_SRC}; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'`; function document( site: Site, diff --git a/packages/astro-renderer/src/surfaces/primitives/carousel.ts b/packages/astro-renderer/src/surfaces/primitives/carousel.ts index 99bf8136..c3dc4da5 100644 --- a/packages/astro-renderer/src/surfaces/primitives/carousel.ts +++ b/packages/astro-renderer/src/surfaces/primitives/carousel.ts @@ -5,6 +5,7 @@ */ import { escapeHtml } from "../../markdown.ts"; import { imageAttributes, imgHtml, type MediaContext } from "../../media.ts"; +import { previewOptions } from "../../preview-media.ts"; import { attr, CHILDREN, iconOf, type PrimitiveRenderer, SPACE, str } from "../markup.ts"; import type { SurfaceNode } from "../tree.ts"; @@ -31,7 +32,7 @@ function thumbHtml(slide: SurfaceNode | undefined, i: number, media?: MediaConte transform: media?.transform ?? "none", ...(media?.budget ? { budget: media.budget } : {}), sizes: "5rem", - ...(media?.preview ? { preview: true } : {}), + ...previewOptions(media), }, ), ).replace(/ alt="[^"]*"/, ' alt=""'); diff --git a/packages/astro-renderer/src/surfaces/primitives/content.ts b/packages/astro-renderer/src/surfaces/primitives/content.ts index 77e59e62..1d96941c 100644 --- a/packages/astro-renderer/src/surfaces/primitives/content.ts +++ b/packages/astro-renderer/src/surfaces/primitives/content.ts @@ -4,6 +4,7 @@ */ import { escapeHtml, renderMarkdown, safeHref } from "../../markdown.ts"; import { IMAGE_FITS, type ImageFit, imageAttributes, imgHtml } from "../../media.ts"; +import { previewOptions } from "../../preview-media.ts"; import { ALIGN, attr, @@ -61,7 +62,7 @@ export const imageHtml: PrimitiveRenderer = (node, { media }) => { transform: media?.transform ?? "none", ...(media?.budget ? { budget: media.budget } : {}), sizes: "(min-width: 64rem) 64rem, 100vw", - ...(media?.preview ? { preview: true } : {}), + ...previewOptions(media), ...(node.priority ? { priority: true } : {}), ...(fit ? { fit } : {}), }, diff --git a/packages/astro-renderer/src/surfaces/primitives/overlays.ts b/packages/astro-renderer/src/surfaces/primitives/overlays.ts index a7b4b5d0..9bf60d53 100644 --- a/packages/astro-renderer/src/surfaces/primitives/overlays.ts +++ b/packages/astro-renderer/src/surfaces/primitives/overlays.ts @@ -4,6 +4,7 @@ */ import { escapeHtml } from "../../markdown.ts"; import { imageAttributes, imgHtml, type MediaContext } from "../../media.ts"; +import { previewOptions } from "../../preview-media.ts"; import { attr, CHILDREN, closeButton, iconOf, type PrimitiveRenderer, str } from "../markup.ts"; /** @@ -19,7 +20,7 @@ function lightboxHtml(id: string, p: Record, media?: MediaConte defaultLocale, transform: media?.transform ?? "none", ...(media?.budget ? { budget: media.budget } : {}), - ...(media?.preview ? { preview: true } : {}), + ...previewOptions(media), } as const; const items = (Array.isArray(p.items) ? p.items : []).slice(0, 24).flatMap((raw) => { const it = (raw ?? {}) as Record; diff --git a/packages/astro-renderer/test/preview-media.test.ts b/packages/astro-renderer/test/preview-media.test.ts new file mode 100644 index 00000000..04b176ca --- /dev/null +++ b/packages/astro-renderer/test/preview-media.test.ts @@ -0,0 +1,130 @@ +/** + * #383: in previews, blob assets are shown from the URL `previewAssetUrl` names (Studio's signed + * route), whether a node refers to them by `assetId`, `asset:` or a plain `/media/…` path. + */ +import type { Asset, ContentEntry, Site } from "@cloudhal/core-contracts"; +import { describe, expect, it } from "vitest"; +import type { MediaContext } from "../src/media.ts"; +import { renderEntryPreview, renderSectionHtml } from "../src/preview.ts"; +import { previewMediaSrc } from "../src/preview-media.ts"; + +const SHA = "62c9a4572c47edbd".padEnd(64, "0"); +const blob = { + id: "asset_cover00001", + siteId: "site_preview01", + kind: "image", + mediaType: "image/webp", + slug: "clavius-live-cover", + sha256: SHA, + bytes: 17_000, + storage: { kind: "blob" }, + image: { width: 1200, height: 630 }, + status: "active", +} as unknown as Asset; +const external = { + ...blob, + id: "asset_external01", + sha256: "ab".repeat(32), + storage: { kind: "external", url: "https://cdn.example.com/x.webp" }, +} as unknown as Asset; +const assets = new Map([ + [blob.id, blob], + [external.id, external], +]); +const signed = (a: Asset) => `/api/sites/${a.siteId}/preview-media/${a.id}/file.webp?sig=x`; +const site = { + id: "site_preview01", + name: "Preview", + defaultLocale: "en", + locales: ["en"], + domains: [], +} as unknown as Site; +const MEDIA = "/media/62c9a4572c47edbd/clavius-live-cover.webp"; + +function entry(patch: Partial): ContentEntry { + return { + id: "entry_preview01", + siteId: site.id, + collection: "posts", + title: "Clavius is live", + slug: "clavius-is-live", + locale: "en", + status: "draft", + body: { format: "markdown", value: "" }, + createdAt: "2026-12-01T00:00:00.000Z", + updatedAt: "2026-12-01T00:00:00.000Z", + ...patch, + } as ContentEntry; +} + +const srcs = (html: string) => [...html.matchAll(/ m[1]); + +describe("preview media URLs (#383)", () => { + const media: MediaContext = { assets, previewAssetUrl: signed }; + + it("shows a cover with an assetId from the signed URL", () => { + const html = renderEntryPreview( + site, + entry({ coverImage: { assetId: blob.id, src: MEDIA, alt: "Cover" } }), + media, + ).html; + expect(srcs(html)).toEqual([signed(blob).replaceAll("&", "&")]); + expect(html).not.toContain('src="/media/'); + }); + + it("resolves plain /media/ paths in markdown and asset: references", () => { + const value = `![inline](${MEDIA})\n\n![ref](asset:${blob.id})\n\n[file](${MEDIA})`; + const html = renderEntryPreview( + site, + entry({ body: { format: "markdown", value } }), + media, + ).html; + expect(srcs(html)).toEqual([signed(blob), signed(blob)]); + expect(html).toContain(`href="${signed(blob)}"`); + expect(html).not.toContain("/media/62c9"); + }); + + it("rewrites section images, by assetId or by a legacy /media/ src", () => { + const ctx: MediaContext = { ...media, preview: true }; + const byId = renderSectionHtml( + { id: "sec_x000000001", kind: "image", image: { assetId: blob.id, src: MEDIA, alt: "" } }, + {}, + ctx, + ); + const bySrc = renderSectionHtml( + { id: "sec_x000000002", kind: "image", image: { src: MEDIA, alt: "" } }, + {}, + ctx, + ); + expect(srcs(byId)).toEqual([signed(blob)]); + expect(srcs(bySrc)).toEqual([signed(blob)]); + }); + + it("leaves external assets, unknown paths and the published site alone", () => { + const html = renderEntryPreview( + site, + entry({ + coverImage: { assetId: external.id, src: "https://cdn.example.com/x.webp", alt: "" }, + }), + media, + ).html; + expect(srcs(html)).toEqual(["https://cdn.example.com/x.webp"]); + const unknown = "/media/0000000000000000/other.png"; + expect(previewMediaSrc(unknown, { ...media, preview: true })).toBe(unknown); + expect(previewMediaSrc(`${MEDIA}.sha256`, { ...media, preview: true })).toBe(`${MEDIA}.sha256`); + // Not a preview: the site's own path. + expect(previewMediaSrc(MEDIA, media)).toBe(MEDIA); + // A preview without the hook (no signing key): unchanged. + const plain = renderEntryPreview( + site, + entry({ coverImage: { assetId: blob.id, src: MEDIA, alt: "" } }), + { assets }, + ).html; + expect(srcs(plain)).toEqual([MEDIA]); + }); + + it("lets images load from a local http Studio", () => { + const html = renderEntryPreview(site, entry({}), media).html; + expect(html).toContain("img-src 'self' https: data: http://localhost:* http://127.0.0.1:*"); + }); +}); diff --git a/packages/cloudflare/src/admin-worker.ts b/packages/cloudflare/src/admin-worker.ts index 5fc1210f..a3fa202e 100644 --- a/packages/cloudflare/src/admin-worker.ts +++ b/packages/cloudflare/src/admin-worker.ts @@ -326,6 +326,17 @@ function withStudioHeaders(res: Response): Response { const WORKER_PATHS = /^\/(api\/|mcp(\/|$)|\.well-known\/)/; +/** + * RFC-0048's upload secret, and the secret #383's signed preview media URLs derive their key from: + * the preview secret when there is one, else the auth secret (every deployment has it). + */ +function signingSecrets(env: AdminEnv) { + return { + uploadSecret: env.CLOUDHAL_UPLOAD_SECRET, + previewMedia: { secret: env.CLOUDHAL_PREVIEW_SECRET || env.BETTER_AUTH_SECRET }, + }; +} + function required(env: AdminEnv, key: keyof AdminEnv): string { const value = env[key]; if (typeof value !== "string" || value.length < 32) @@ -526,7 +537,7 @@ export function createAdminWorker(options: AdminWorkerOptions = {}) { ...(env.CLOUDHAL_PREVIEW_SECRET ? { preview: { secret: env.CLOUDHAL_PREVIEW_SECRET } } : {}), - uploadSecret: env.CLOUDHAL_UPLOAD_SECRET, + ...signingSecrets(env), ...(env.CLOUDHAL_DEPLOY_TOKEN ? { admin: { deployToken: env.CLOUDHAL_DEPLOY_TOKEN, storage: { sql, blobs } } } : {}), diff --git a/packages/cloudflare/src/playground-session.ts b/packages/cloudflare/src/playground-session.ts index f5cf1a2b..22604bbe 100644 --- a/packages/cloudflare/src/playground-session.ts +++ b/packages/cloudflare/src/playground-session.ts @@ -62,6 +62,20 @@ export async function verifySession(value: string, secret: string): Promise.`), so the Worker can + * route them to the session without its cookie: a sandboxed preview sends none. Its own MAC key + * (the secret with a purpose suffix), so it never passes as the cookie, and the Worker accepts it + * on `preview-media` GETs only. + */ +export function signPreviewSession(id: string, secret: string): Promise { + return signSession(id, `${secret}\npreview-media`); +} + +export function verifyPreviewSession(value: string, secret: string): Promise { + return verifySession(value, `${secret}\npreview-media`); +} + /** The session cookie's value in a request, if any. */ export function readSessionCookie(request: Request): string | undefined { const header = request.headers.get("cookie") ?? ""; diff --git a/packages/cloudflare/src/playground-site.ts b/packages/cloudflare/src/playground-site.ts index 8fc6ae88..b47d9abf 100644 --- a/packages/cloudflare/src/playground-site.ts +++ b/packages/cloudflare/src/playground-site.ts @@ -25,7 +25,7 @@ import { SITE_PREFIX, } from "./playground-options.ts"; import { privateSiteResponse } from "./playground-render.ts"; -import { sessionTime } from "./playground-session.ts"; +import { sessionTime, signPreviewSession } from "./playground-session.ts"; const MINUTE = 60_000; const json = (status: number, body: unknown) => @@ -78,7 +78,7 @@ export function playgroundSiteClass(options: PlaygroundOptions): PlaygroundSiteC await this.#wipe(); return json(410, { error: "playground_expired" }); } - const session = await this.#open(); + const session = await this.#open(id); this.#expiresAt = Math.min( now + limits.idleMinutes * MINUTE, created + limits.maxMinutes * MINUTE, @@ -116,7 +116,7 @@ export function playgroundSiteClass(options: PlaygroundOptions): PlaygroundSiteC } /** The session's store, API and site; migrated and seeded on first use. */ - async #open(): Promise { + async #open(id: string): Promise { if (this.#session) return this.#session; await this.state.blockConcurrencyWhile(async () => { if (this.#session) return; @@ -147,6 +147,7 @@ export function playgroundSiteClass(options: PlaygroundOptions): PlaygroundSiteC } const api = createApi({ store, + ...(await previewMediaOf(id, this.env.PLAYGROUND_SECRET)), defer: (task) => this.state.waitUntil(task.catch(() => {})), playground: { info: () => ({ @@ -164,6 +165,20 @@ export function playgroundSiteClass(options: PlaygroundOptions): PlaygroundSiteC }; } +/** + * #383: a session's signed preview media URLs. The key comes from the playground secret and the + * session, so it outlives an evicted object; `ps` lets the Worker route a URL without the cookie. + */ +async function previewMediaOf(id: string, secret: string | undefined) { + if (!secret) return {}; + return { + previewMedia: { + secret: `${secret}\npreview-media\n${id}`, + query: `ps=${await signPreviewSession(id, secret)}`, + }, + }; +} + /** RFC-0036 §7: a full database or too many nodes refuse writes with 507. */ async function fullResponse( request: Request, diff --git a/packages/cloudflare/src/playground.ts b/packages/cloudflare/src/playground.ts index 3ee2f68d..7f9fa9d6 100644 --- a/packages/cloudflare/src/playground.ts +++ b/packages/cloudflare/src/playground.ts @@ -27,6 +27,7 @@ import { sessionCookie, sessionTime, signSession, + verifyPreviewSession, verifySession, } from "./playground-session.ts"; import { type PlaygroundSiteClass, playgroundSiteClass } from "./playground-site.ts"; @@ -43,6 +44,9 @@ const json = (status: number, body: unknown, headers: Record = { headers: { "content-type": "application/json", "cache-control": "no-store", ...headers }, }); +/** #383: a preview's signed media URL (`/api/sites//preview-media/…`). */ +const PREVIEW_MEDIA_PATH = /^\/api\/sites\/[^/]{1,64}\/preview-media\//; + /** Paths that belong to a session's Durable Object. */ function isSessionPath(path: string): boolean { return ( @@ -75,7 +79,24 @@ export function createPlaygroundWorker(options: PlaygroundOptions): PlaygroundWo async function sessionOf(request: Request, env: PlaygroundEnv): Promise { const value = readSessionCookie(request); if (!value || !env.PLAYGROUND_SECRET) return undefined; - const id = await verifySession(value, env.PLAYGROUND_SECRET); + return unexpired(await verifySession(value, env.PLAYGROUND_SECRET)); + } + + /** #383: a preview media GET's session, from its `ps` token (sandboxed previews send no cookie). */ + async function previewMediaSessionOf(request: Request, env: PlaygroundEnv, url: URL) { + if (request.method !== "GET" && request.method !== "HEAD") return undefined; + if (url.pathname.length > 512 || !PREVIEW_MEDIA_PATH.test(url.pathname)) return undefined; + const value = url.searchParams.get("ps"); + if (!value || value.length > 128 || !env.PLAYGROUND_SECRET) return undefined; + return unexpired(await verifyPreviewSession(value, env.PLAYGROUND_SECRET)); + } + + /** The cookie's session, else (#383) a preview media URL's. */ + async function requestSession(request: Request, env: PlaygroundEnv, url: URL) { + return (await sessionOf(request, env)) ?? (await previewMediaSessionOf(request, env, url)); + } + + function unexpired(id: string | undefined): string | undefined { const created = id ? sessionTime(id) : undefined; if (!id || created === undefined) return undefined; const now = Date.now(); @@ -148,7 +169,7 @@ export function createPlaygroundWorker(options: PlaygroundOptions): PlaygroundWo return enabled ? createSession(request, env) : landing(request, env, 503); if (isSessionPath(path)) { if (!enabled) return json(503, { error: "playground_closed" }); - const id = await sessionOf(request, env); + const id = await requestSession(request, env, url); if (!id) return path.startsWith("/api/") || path === "/mcp" || path === RESET_PATH ? json(410, { error: "playground_expired", message: "This session has ended." }) diff --git a/packages/cloudflare/test/playground.test.ts b/packages/cloudflare/test/playground.test.ts index 81f28577..99e78c72 100644 --- a/packages/cloudflare/test/playground.test.ts +++ b/packages/cloudflare/test/playground.test.ts @@ -9,7 +9,12 @@ import { signSession, verifySession, } from "../src/playground.ts"; -import { readSessionCookie, SESSION_COOKIE } from "../src/playground-session.ts"; +import { + readSessionCookie, + SESSION_COOKIE, + signPreviewSession, + verifyPreviewSession, +} from "../src/playground-session.ts"; const SECRET = "playground-unit-secret-0123456789abcdef"; @@ -135,6 +140,25 @@ describe("the playground Worker without workerd", () => { expect((await call(`/s/${newSessionId(Date.now())}/`)).status).toBe(404); }); + it("routes a preview's media URL by its ps token, never as a session cookie (#383)", async () => { + const id = newSessionId(Date.now()); + const ps = await signPreviewSession(id, SECRET); + const media = `/api/sites/site_x/preview-media/asset_x000001/a.jpg?v=0123456789abcdef&exp=1&sig=x`; + const get = (path: string, init: RequestInit = {}) => + worker.fetch(new Request(`https://try.test${path}`, init), env()); + expect(await (await get(`${media}&ps=${ps}`)).text()).toBe("from the session"); + expect(await verifyPreviewSession(ps, SECRET)).toBe(id); + // Only on preview media GETs; not as a cookie; not with a cookie's MAC. + expect((await get(`/api/me?ps=${ps}`)).status).toBe(410); + expect((await get(`${media}&ps=${ps}`, { method: "POST" })).status).toBe(410); + expect((await get("/api/me", { headers: { cookie: `${SESSION_COOKIE}=${ps}` } })).status).toBe( + 410, + ); + expect((await get(`${media}&ps=${await signSession(id, SECRET)}`)).status).toBe(410); + const old = await signPreviewSession(newSessionId(Date.now() - 121 * 60_000), SECRET); + expect((await get(`${media}&ps=${old}`)).status).toBe(410); + }); + it("serves only the landing page behind the kill switch", async () => { const off = env({ PLAYGROUND_ENABLED: "false" }); const cookie = await cookieFor(newSessionId(Date.now())); diff --git a/packages/core-ts/src/index.ts b/packages/core-ts/src/index.ts index 004147d6..92b92106 100644 --- a/packages/core-ts/src/index.ts +++ b/packages/core-ts/src/index.ts @@ -76,6 +76,7 @@ export { export * from "./menu.ts"; export * from "./names.ts"; export * from "./permalinks.ts"; +export * from "./preview-media.ts"; export * from "./preview-token.ts"; export * from "./proposals.ts"; export { diff --git a/packages/core-ts/src/preview-media.ts b/packages/core-ts/src/preview-media.ts new file mode 100644 index 00000000..44736af9 --- /dev/null +++ b/packages/core-ts/src/preview-media.ts @@ -0,0 +1,157 @@ +/** + * Signed preview media URLs (#383). Studio's previews are shown from Studio's origin, where the + * site's `/media/…` paths do not exist, and the served preview is sandboxed (an opaque origin), so + * neither the session cookie nor `CORP: same-origin` can authorize an image from it. Instead each + * blob asset a preview shows gets a short-lived URL whose signature is the credential: + * + * `/api/sites//preview-media//.?v=&exp=&sig=` + * + * HMAC-SHA256 over `site|asset|sha16|exp`, with a key derived by HKDF-SHA256 from a deployment + * secret (the preview secret, else the auth secret). The expiry is bucketed (`previewMediaExpiry`) + * so re-renders give identical URLs and the browser cache hits. WebCrypto only (Node 24, Workers). + */ +import { mediaExtension, mediaPrefix } from "./media/types.ts"; + +export interface PreviewMediaClaims { + readonly site: string; + readonly assetId: string; + /** The first 16 hex digits of the asset's SHA-256 (its media prefix). */ + readonly v: string; + /** Expiry, unix seconds. */ + readonly exp: number; +} + +/** Expiries step in 6-hour buckets. */ +export const PREVIEW_MEDIA_BUCKET_SECONDS = 6 * 3600; +/** A URL is refused when its expiry is further ahead than this (a day). */ +export const PREVIEW_MEDIA_MAX_AHEAD_SECONDS = 24 * 3600; +/** HKDF `info`: the key is for this purpose only. */ +const INFO = "cloudhal preview-media v1"; + +export type PreviewMediaCheck = "ok" | "malformed" | "expired" | "too-far" | "signature"; + +const enc = new TextEncoder(); + +function b64url(bytes: Uint8Array): string { + let s = ""; + for (const b of bytes) s += String.fromCharCode(b); + return btoa(s).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", ""); +} + +function fromB64url(text: string): Uint8Array | undefined { + if (text.length === 0 || text.length > 128 || !/^[A-Za-z0-9_-]+$/.test(text)) return undefined; + const pad = text.length % 4 === 0 ? "" : "=".repeat(4 - (text.length % 4)); + try { + const bin = atob(text.replaceAll("-", "+").replaceAll("_", "/") + pad); + return Uint8Array.from(bin, (c) => c.charCodeAt(0)); + } catch { + return undefined; + } +} + +/** + * The signing key derived from a deployment secret, or undefined when there is none (an empty + * secret) or WebCrypto refuses it. Never throws: without a key, previews keep their URLs. + */ +export async function previewMediaKey( + secret: string | Uint8Array | undefined, +): Promise { + const raw = typeof secret === "string" ? enc.encode(secret) : secret; + if (!raw || raw.byteLength === 0) return undefined; + try { + const base = await crypto.subtle.importKey("raw", new Uint8Array(raw), "HKDF", false, [ + "deriveKey", + ]); + return await crypto.subtle.deriveKey( + { name: "HKDF", hash: "SHA-256", salt: enc.encode("cloudhal"), info: enc.encode(INFO) }, + base, + { name: "HMAC", hash: "SHA-256", length: 256 }, + false, + ["sign", "verify"], + ); + } catch { + return undefined; + } +} + +/** + * The expiry of a URL minted at `nowMs`: the end of the current 6-hour bucket plus one bucket, so + * every render in a bucket names the same URL and it stays valid 6 to 12 hours. + */ +export function previewMediaExpiry(nowMs: number = Date.now()): number { + const now = Math.floor(nowMs / 1000); + const bucket = PREVIEW_MEDIA_BUCKET_SECONDS; + return Math.ceil(now / bucket) * bucket + bucket; +} + +function wellFormed(c: PreviewMediaClaims): boolean { + return ( + !c.site.includes("|") && + !c.assetId.includes("|") && + /^[0-9a-f]{16}$/.test(c.v) && + Number.isSafeInteger(c.exp) && + c.exp > 0 + ); +} + +const payload = (c: PreviewMediaClaims) => enc.encode(`${c.site}|${c.assetId}|${c.v}|${c.exp}`); + +/** The base64url signature of `claims`. */ +export async function signPreviewMedia( + key: CryptoKey, + claims: PreviewMediaClaims, +): Promise { + if (!wellFormed(claims)) throw new RangeError("malformed preview media claims"); + return b64url(new Uint8Array(await crypto.subtle.sign("HMAC", key, payload(claims)))); +} + +/** + * Checks a URL's signature (WebCrypto's verify compares in constant time) and expiry: in the + * future and at most a day ahead. Never throws. + */ +export async function verifyPreviewMedia( + key: CryptoKey, + claims: PreviewMediaClaims, + sig: string | undefined, + nowMs: number = Date.now(), +): Promise { + const mac = sig ? fromB64url(sig) : undefined; + if (!mac || !wellFormed(claims)) return "malformed"; + let ok = false; + try { + ok = await crypto.subtle.verify("HMAC", key, mac, payload(claims)); + } catch { + return "malformed"; + } + if (!ok) return "signature"; + const now = Math.floor(nowMs / 1000); + if (claims.exp <= now) return "expired"; + if (claims.exp - now > PREVIEW_MEDIA_MAX_AHEAD_SECONDS) return "too-far"; + return "ok"; +} + +/** The asset fields a signed URL names. */ +export type PreviewMediaAsset = { + readonly id: string; + readonly siteId: string; + readonly sha256: string; + readonly slug: string; + readonly mediaType: string; +}; + +/** The signed, root-relative URL of a blob asset for previews (served on Studio's origin). */ +export async function previewMediaUrl( + key: CryptoKey, + asset: PreviewMediaAsset, + nowMs: number = Date.now(), +): Promise { + const claims = { + site: asset.siteId, + assetId: asset.id, + v: mediaPrefix(asset.sha256), + exp: previewMediaExpiry(nowMs), + }; + const sig = await signPreviewMedia(key, claims); + const file = `${asset.slug}.${mediaExtension(asset.mediaType)}`; + return `/api/sites/${encodeURIComponent(asset.siteId)}/preview-media/${encodeURIComponent(asset.id)}/${file}?v=${claims.v}&exp=${claims.exp}&sig=${sig}`; +} diff --git a/packages/core-ts/test/preview-media.test.ts b/packages/core-ts/test/preview-media.test.ts new file mode 100644 index 00000000..10998d5a --- /dev/null +++ b/packages/core-ts/test/preview-media.test.ts @@ -0,0 +1,98 @@ +import { describe, expect, it } from "vitest"; +import { + PREVIEW_MEDIA_BUCKET_SECONDS, + previewMediaExpiry, + previewMediaKey, + previewMediaUrl, + signPreviewMedia, + verifyPreviewMedia, +} from "../src/preview-media.ts"; + +const SECRET = "preview-media-secret-of-at-least-32-bytes"; +const NOW = Date.UTC(2026, 11, 2, 10, 17, 0); +const claims = { site: "site_abc123", assetId: "asset_xyz789", v: "0123456789abcdef", exp: 0 }; + +async function keyOf(secret = SECRET) { + const key = await previewMediaKey(secret); + if (!key) throw new Error("no key"); + return key; +} + +describe("preview media signatures (#383)", () => { + it("round-trips", async () => { + const key = await keyOf(); + const c = { ...claims, exp: previewMediaExpiry(NOW) }; + const sig = await signPreviewMedia(key, c); + expect(sig).toMatch(/^[A-Za-z0-9_-]{43}$/); + expect(await verifyPreviewMedia(key, c, sig, NOW)).toBe("ok"); + }); + + it("refuses tampered claims, signatures and other keys", async () => { + const key = await keyOf(); + const c = { ...claims, exp: previewMediaExpiry(NOW) }; + const sig = await signPreviewMedia(key, c); + expect(await verifyPreviewMedia(key, { ...c, site: "site_other1" }, sig, NOW)).toBe( + "signature", + ); + expect(await verifyPreviewMedia(key, { ...c, assetId: "asset_other1" }, sig, NOW)).toBe( + "signature", + ); + expect(await verifyPreviewMedia(key, { ...c, v: "fedcba9876543210" }, sig, NOW)).toBe( + "signature", + ); + expect(await verifyPreviewMedia(key, { ...c, exp: c.exp + 1 }, sig, NOW)).toBe("signature"); + const flipped = `${sig[0] === "A" ? "B" : "A"}${sig.slice(1)}`; + expect(await verifyPreviewMedia(key, c, flipped, NOW)).toBe("signature"); + expect(await verifyPreviewMedia(await keyOf(`${SECRET}-2`), c, sig, NOW)).toBe("signature"); + expect(await verifyPreviewMedia(key, c, undefined, NOW)).toBe("malformed"); + expect(await verifyPreviewMedia(key, c, "not base64!", NOW)).toBe("malformed"); + expect(await verifyPreviewMedia(key, { ...c, v: "XYZ" }, sig, NOW)).toBe("malformed"); + }); + + it("refuses expired URLs and expiries more than a day ahead", async () => { + const key = await keyOf(); + const past = { ...claims, exp: Math.floor(NOW / 1000) - 1 }; + expect(await verifyPreviewMedia(key, past, await signPreviewMedia(key, past), NOW)).toBe( + "expired", + ); + const far = { ...claims, exp: Math.floor(NOW / 1000) + 25 * 3600 }; + expect(await verifyPreviewMedia(key, far, await signPreviewMedia(key, far), NOW)).toBe( + "too-far", + ); + const c = { ...claims, exp: previewMediaExpiry(NOW) }; + const sig = await signPreviewMedia(key, c); + expect(await verifyPreviewMedia(key, c, sig, c.exp * 1000)).toBe("expired"); + }); + + it("buckets the expiry: one URL per 6 hours, valid 6 to 12 hours", async () => { + const bucket = PREVIEW_MEDIA_BUCKET_SECONDS * 1000; + const start = Math.ceil(NOW / bucket) * bucket - bucket + 1000; + const a = previewMediaExpiry(start); + expect(previewMediaExpiry(start + bucket - 2000)).toBe(a); + expect(previewMediaExpiry(start + bucket)).toBe(a + PREVIEW_MEDIA_BUCKET_SECONDS); + for (const t of [start, start + bucket / 2, start + bucket - 2000]) { + const ahead = previewMediaExpiry(t) - t / 1000; + expect(ahead).toBeGreaterThanOrEqual(PREVIEW_MEDIA_BUCKET_SECONDS); + expect(ahead).toBeLessThanOrEqual(2 * PREVIEW_MEDIA_BUCKET_SECONDS); + } + const key = await keyOf(); + const asset = { + id: "asset_xyz789", + siteId: "site_abc123", + sha256: "0123456789abcdef".repeat(4), + slug: "cover", + mediaType: "image/webp", + }; + const url = await previewMediaUrl(key, asset, start); + expect(await previewMediaUrl(key, asset, start + bucket - 2000)).toBe(url); + expect(url).toMatch( + /^\/api\/sites\/site_abc123\/preview-media\/asset_xyz789\/cover\.webp\?v=0123456789abcdef&exp=\d+&sig=[\w-]+$/, + ); + }); + + it("has no key without a secret", async () => { + expect(await previewMediaKey(undefined)).toBeUndefined(); + expect(await previewMediaKey("")).toBeUndefined(); + expect(await previewMediaKey(new Uint8Array(32))).toBeDefined(); + }); +}); diff --git a/scripts/size-baseline.json b/scripts/size-baseline.json index e332ff77..9a9104c7 100644 --- a/scripts/size-baseline.json +++ b/scripts/size-baseline.json @@ -10,7 +10,7 @@ "apps/studio/src/routes/SchedulesPage.tsx": 1296, "apps/studio/src/routes/SiteSettingsPage.tsx": 859, "packages/api/src/build-turn.ts": 885, - "packages/api/src/routes/assets.ts": 833, + "packages/api/src/routes/assets.ts": 825, "packages/api/src/routes/comments.ts": 874, "packages/api/src/routes/schedules.ts": 992, "packages/api/src/testing-roles.ts": 1936,