Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .changeset/preview-media-urls.md
Original file line number Diff line number Diff line change
@@ -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/<slug>.<ext>?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.
2 changes: 1 addition & 1 deletion docs/guides/cloudflare-hardening.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<site>/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

Expand Down
1 change: 1 addition & 0 deletions docs/guides/self-host.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<site>/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. |
Expand Down
5 changes: 5 additions & 0 deletions packages/api/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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";
Expand Down Expand Up @@ -104,6 +106,8 @@ const SITE_AREAS: readonly (readonly [string, Hono<Env>])[] = [
["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],
];
Expand Down Expand Up @@ -349,6 +353,7 @@ function setContext(c: Context<Env>, 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. */
Expand Down
13 changes: 13 additions & 0 deletions packages/api/src/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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;
};
};
1 change: 1 addition & 0 deletions packages/api/src/playground.ts
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,7 @@ export const PLAYGROUND_ALLOW: ReadonlySet<string> = 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`,
]);
Expand Down
130 changes: 130 additions & 0 deletions packages/api/src/preview-media.ts
Original file line number Diff line number Diff line change
@@ -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<CryptoKey | undefined>;
readonly query: string | undefined;
}

const signers = new WeakMap<ApiDeps, PreviewMediaSigner>();

/**
* 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<string>;
readonly prefixes: Set<string>;
}

/** The `asset:<id>` 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/<prefix>/…` 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:<id>` references (markdown, directives,
* surfaces) and site-relative `/media/<prefix>/…` 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<Env>,
siteId: string,
...values: unknown[]
): Promise<Pick<MediaContext, "assets" | "previewAssetUrl">> {
const store = c.get("store");
const refs = mediaRefsIn(...values);
const assets = new Map<string, Asset>(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<string, string>();
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) };
}
10 changes: 7 additions & 3 deletions packages/api/src/preview.ts
Original file line number Diff line number Diff line change
@@ -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",
});
Expand Down
41 changes: 40 additions & 1 deletion packages/api/src/routes/asset-content-headers.ts
Original file line number Diff line number Diff line change
@@ -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/<file>` 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
Expand Down Expand Up @@ -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<string, string> {
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<Env>,
asset: Asset,
headers: Record<string, string>,
): Promise<Response | 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 = 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<ArrayBuffer>, 200, headers);
}
16 changes: 4 additions & 12 deletions packages/api/src/routes/assets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down Expand Up @@ -638,17 +638,9 @@ export const assets: Hono<Env> = new Hono<Env>()
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<ArrayBuffer>, 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");
Expand Down
Loading