From 8eb69db55c6c24a2ffe9b3219432e53752a8e0f0 Mon Sep 17 00:00:00 2001 From: Blake Bauman Date: Sat, 7 Nov 2026 16:12:20 -0700 Subject: [PATCH 1/8] Get preview ready to be framed by the admin for live preview MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Fragment token handoff: /__preview?entry=#token= answers a tiny no-store, noindex page whose (nonced) script drops the fragment from history and trades the token for the cookie with a same-origin POST /__preview (Origin checked, JSON only, 4 KB cap). ?token= still works; cw_session carries through to the draft URL. - Preview cookie is SameSite=None; Secure; Partitioned (CHIPS), still HttpOnly and Path=/__preview, so it is sent inside the admin's frame and kept in the admin's partition. - /__preview responses send frame-ancestors (derived from cdn./api., or the new optional CONTENTWORKER_ADMIN; https only, never a wildcard; 'none' when unknown) and Referrer-Policy: no-referrer. withNonce now keeps a response's own directives. Public pages keep frame-ancestors 'self'. - Preview-only markup: data-cw-slot on
for a blocks field, data-cw-block="<_key>" on block sections, data-cw-ref (the SDK's content-ref format, reimplemented in src/content-ref.ts) on the page's title and body. A test holds every public render free of them. - POST /__preview/render re-renders blocks (or all of
) from unsaved draft fields with the page's own renderers, for the entry in the preview cookie only, token rechecked per call, same-origin JSON, 2 MB cap, no-store, noindex. - scripts/live-preview.js: a stub that will call startLivePreview from @contentworker/sdk/live-preview once it is published; loaded only under /__preview for the draft with cw_session. Budgeted at 4 KB. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 4 +- README.md | 32 +- docs/budget.md | 1 + packages/frontend/CHANGELOG.md | 12 + packages/frontend/budgets.json | 5 + .../frontend/public/scripts/live-preview.js | 110 +++++++ packages/frontend/src/config.ts | 49 ++++ packages/frontend/src/content-ref.ts | 50 ++++ packages/frontend/src/headers.ts | 32 +- packages/frontend/src/nonce.ts | 30 +- packages/frontend/src/preview-render.ts | 187 ++++++++++++ packages/frontend/src/preview.ts | 257 +++++++++++++--- packages/frontend/src/render/document.ts | 147 ++++++++-- packages/frontend/src/render/page.ts | 11 +- packages/frontend/src/types.ts | 39 ++- packages/frontend/src/worker.ts | 19 +- packages/frontend/test/config.test.ts | 57 ++++ packages/frontend/test/content-ref.test.ts | 32 ++ packages/frontend/test/preview-marks.test.ts | 83 ++++++ packages/frontend/test/preview-render.test.ts | 117 ++++++++ packages/frontend/test/preview.test.ts | 276 ++++++++++++++---- packages/frontend/test/support/preview.ts | 80 +++++ 22 files changed, 1484 insertions(+), 146 deletions(-) create mode 100644 packages/frontend/public/scripts/live-preview.js create mode 100644 packages/frontend/src/content-ref.ts create mode 100644 packages/frontend/src/preview-render.ts create mode 100644 packages/frontend/test/content-ref.test.ts create mode 100644 packages/frontend/test/preview-marks.test.ts create mode 100644 packages/frontend/test/preview-render.test.ts create mode 100644 packages/frontend/test/support/preview.ts diff --git a/AGENTS.md b/AGENTS.md index 7807804..bc2eeff 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -49,7 +49,9 @@ Performance is the top priority: every other requirement yields to it. export is an uncached gateway that must stay cheap (no I/O on the hot path). Anything a page renders from must be in its `Cache-Tag` (`tagsFor`), or a publish won't purge it. Nothing personalised or per-request goes in cached HTML: no nonces, cookies or user data. Drafts live - only under `/__preview`. + only under `/__preview`, and so do the editing marks (`data-cw-slot`, `data-cw-block`, + `data-cw-ref`) and `scripts/live-preview.js`: a public render never changes for live preview + (`test/preview-marks.test.ts`). - **The HTML is finished at first byte.** Sections, wrappers, buttons, image attributes and the LCP choice are decided in the Worker. Block JS may add behaviour, elements and attributes; it diff --git a/README.md b/README.md index 0f9b278..ca205ed 100644 --- a/README.md +++ b/README.md @@ -134,9 +134,35 @@ content and cached at the edge. ## Preview drafts Set the entry preview link in ContentWorker to -`https:///__preview?entry={id}&token={token}`. Drafts render under `/__preview/…`, -never cached and never indexed. If your Preview API isn't at `api.`, set -`CONTENTWORKER_PREVIEW` to its origin. +`https:///__preview?entry={id}#token={token}`. The token rides in the fragment, so it +never reaches a server log or a `Referer`: the site answers a tiny page that reads it, removes it +from the address bar and history, and trades it (a same-origin POST) for an HttpOnly cookie +scoped to `/__preview`. The older `?entry={id}&token={token}` form still works. Drafts render +under `/__preview/…`, never cached and never indexed. If your Preview API isn't at +`api.`, set `CONTENTWORKER_PREVIEW` to its origin. + +### Live preview in the admin + +The ContentWorker admin frames `/__preview` pages and re-renders each unsaved edit in them. +Preview responses may be framed by the admin's origin only (`Content-Security-Policy: +frame-ancestors `) and send no `Referer`; public pages still refuse every frame but their +own. The admin's origin comes from your backend setting: `cdn.` (or a +`CONTENTWORKER_PREVIEW` of `api.`) means the admin is `https://`. Otherwise, or +over a service binding with a bare namespace, set it: + +```jsonc +"vars": { "CONTENTWORKER_ADMIN": "https://" } +``` + +It must be an exact https origin (http only on localhost); without one, preview pages can't be +framed at all. The preview cookie is `SameSite=None; Secure; Partitioned`, so it works inside the +admin's frame and lives only in the admin's partition there. + +Under `/__preview`, the draft's markup also says what is editable: `data-cw-slot` on the element +holding a blocks field's blocks, `data-cw-block="<_key>"` on each block, and `data-cw-ref` on the +page's own fields. Public pages carry none of it. With `cw_session` on the URL (the admin adds +it), the page loads `scripts/live-preview.js`, which re-renders edited blocks through +`POST /__preview/render`. ## Develop diff --git a/docs/budget.md b/docs/budget.md index aca8998..350627b 100644 --- a/docs/budget.md +++ b/docs/budget.md @@ -9,6 +9,7 @@ budgets keep it there as a site adds blocks. `budgets.json` is enforced by `npm | Eager JS (`lib.js`, `site.js`, `shared.js`) | 10 KB | Modules never block, but they compete with the LCP image. | | Lazy CSS (`lazy.css`, `fonts.css`) | 8 KB | Loaded after the first section. | | Delayed JS | 20 KB | Runs 3 s after `load`; still counts toward TBT on slow phones. | +| Preview JS (`live-preview.js`) | 4 KB | Loads only under `/__preview` with `cw_session`, never on a public page. | | Each block | 3 KB CSS, 4 KB JS | Blocks add up; a block over this needs a recorded reason. | | HTML document | first 14 KB holds head + first section | One round trip to first paint. | | Requests before LCP | ≤ 5 | Document, eager.css, site.js (+ lib.js preloaded), LCP image, first-section block CSS. | diff --git a/packages/frontend/CHANGELOG.md b/packages/frontend/CHANGELOG.md index 90bcfa0..67479bf 100644 --- a/packages/frontend/CHANGELOG.md +++ b/packages/frontend/CHANGELOG.md @@ -11,6 +11,18 @@ tokens or options are **minor**; fixes that keep output stable are **patch**. Bump `version` in `package.json`, add its section here, merge, then push the tag `frontend@v`: `release.yml` checks and publishes it to npm with provenance. +## Unreleased + +- Preview links can carry the token in the fragment (`/__preview?entry={id}#token={token}`), so it + never reaches a log or a `Referer`; `?token=` still works. +- Preview pages are ready to be framed by the ContentWorker admin: `frame-ancestors` names the + admin origin only (derived from `CONTENTWORKER`, or the new optional `CONTENTWORKER_ADMIN`), + `Referrer-Policy: no-referrer`, and the preview cookie is `SameSite=None; Secure; Partitioned`. +- Under `/__preview` only, drafts carry `data-cw-slot`, `data-cw-block` and `data-cw-ref`; + `POST /__preview/render` re-renders blocks from unsaved fields; `scripts/live-preview.js` (a stub + until `@contentworker/sdk/live-preview` is published) loads when the URL has `cw_session`. + Public pages are unchanged. + ## 0.3.0 - Navigation menus: the header renders ContentWorker's `main` menu and the footer its `footer` diff --git a/packages/frontend/budgets.json b/packages/frontend/budgets.json index f0a1531..b5df9b2 100644 --- a/packages/frontend/budgets.json +++ b/packages/frontend/budgets.json @@ -16,6 +16,11 @@ "files": ["styles/lazy.css", "styles/fonts.css"], "max": 8192 }, + { + "name": "preview JS (only /__preview, live)", + "files": ["scripts/live-preview.js"], + "max": 4096 + }, { "name": "delayed JS", "files": ["scripts/delayed.js", "scripts/consent.js", "scripts/consented.js"], diff --git a/packages/frontend/public/scripts/live-preview.js b/packages/frontend/public/scripts/live-preview.js new file mode 100644 index 0000000..7f82f7a --- /dev/null +++ b/packages/frontend/public/scripts/live-preview.js @@ -0,0 +1,110 @@ +/** + * Live preview, the page side. Loaded only under /__preview, for the draft, when the admin frames + * the page with `cw_session` on its URL (src/render/document.ts); public pages never load it. + * + * The admin holds the unsaved fields and sends edits by postMessage; `startLivePreview` from + * `@contentworker/sdk/live-preview` applies them and calls `onChange`, which asks the Worker to + * re-render with the edited fields (POST /__preview/render) and swaps the result in by + * `data-cw-block`. The Worker renders with the same block renderers and escaping as any page. + * + * STUB: the SDK isn't published yet, so `startLivePreview` below is null and nothing starts. Once + * it is, serve its browser build next to this file (no bundler: the served file is the source) + * and replace the stub with: + * + * import { startLivePreview } from './vendor/live-preview.js'; + */ +import { loadCSS, loadSection, loadSections } from './lib.js'; + +/** + * @typedef {Record>} LiveFields + * @typedef {{ op: string, key?: string, field: string }} LivePatchOp + * @typedef {{ entryId: string, contentType: string, locale: string, version: number, + * seq: number, ops: readonly LivePatchOp[] }} LivePreviewUpdate + * @typedef {{ adminOrigin: string, + * onChange: (fields: LiveFields, update: LivePreviewUpdate) => void | Promise }} LivePreviewOptions + * @typedef {{ readonly active: boolean, refresh(): void, destroy(): void }} LivePreview + */ + +/** STUB until the SDK is published (see above). @type {((options: LivePreviewOptions) => LivePreview) | null} */ +const startLivePreview = null; + +/** The one Trusted Types policy preview pages allow besides the loader's (src/headers.ts). */ +const htmlPolicy = /** @type {Window & { trustedTypes?: { createPolicy(name: string, + * rules: { createHTML(html: string): string }): { createHTML(html: string): string } } }} */ ( + window +).trustedTypes?.createPolicy('cw-preview', { + // Markup from this origin's own render endpoint, escaped there like every page; nothing else. + createHTML: (html) => html, +}); + +/** @param {string} html */ +function fragment(html) { + const template = document.createElement('template'); + template.innerHTML = /** @type {string} */ (htmlPolicy ? htmlPolicy.createHTML(html) : html); + return template.content; +} + +/** + * Block keys a patch touched, or null when it moved, added or removed blocks, or changed another + * field: then the whole of
is re-rendered. + * @param {readonly LivePatchOp[]} ops + */ +function touchedKeys(ops) { + if (!ops.length) return null; + const keys = new Set(); + for (const op of ops) { + if (op.op !== 'update' || !op.key || op.field !== 'sections') return null; + keys.add(op.key); + } + return [...keys]; +} + +/** + * Re-renders the edited fields through the Worker and puts the result on the page. + * @param {LiveFields} fields + * @param {LivePreviewUpdate} update + */ +export async function render(fields, update) { + const keys = touchedKeys(update.ops); + const res = await fetch('/__preview/render', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + credentials: 'same-origin', + // Preview pages send no Referer, which would blank Origin; the Worker checks Origin. + referrerPolicy: 'same-origin', + body: JSON.stringify({ + entryId: update.entryId, + locale: update.locale, + fields, + ...(keys ? { keys } : {}), + }), + }); + if (!res.ok) throw new Error(`render failed (${res.status})`); + /** @type {{ css: string[], main?: string, blocks?: { key: string, html: string }[], missing?: string[] }} */ + const out = await res.json(); + await Promise.all(out.css.map((href) => loadCSS(href))); + const main = document.querySelector('main'); + if (!main) return; + // A block the page doesn't show yet: re-render
whole instead. + if (out.missing?.length) return render(fields, { ...update, ops: [] }); + if (out.main !== undefined) { + main.replaceChildren(fragment(out.main)); + await loadSections(main); + return; + } + for (const { key, html } of out.blocks ?? []) { + const el = main.querySelector(`[data-cw-block="${CSS.escape(key)}"]`); + const next = fragment(html).firstElementChild; + if (!el || !(next instanceof HTMLElement)) continue; + el.replaceWith(next); + await loadSection(next); + } +} + +const adminOrigin = document.querySelector('meta[name="cw-admin-origin"]')?.getAttribute('content'); +if (adminOrigin && startLivePreview) { + /** @type {(options: LivePreviewOptions) => LivePreview} */ (startLivePreview)({ + adminOrigin, + onChange: render, + }); +} diff --git a/packages/frontend/src/config.ts b/packages/frontend/src/config.ts index bd86afb..9624336 100644 --- a/packages/frontend/src/config.ts +++ b/packages/frontend/src/config.ts @@ -11,6 +11,12 @@ * Preview reads drafts from the Preview API (the CMS's api host, not its delivery host). Over * HTTP it is derived: cdn. → api.. Set CONTENTWORKER_PREVIEW to its origin to * override that, or to enable preview when the backend is a bare namespace over a binding. + * + * Live preview frames /__preview pages in the ContentWorker admin, so those pages name the one + * origin allowed to frame them (CSP frame-ancestors). The admin is the deployment's own domain: + * cdn. → https://, or api. from CONTENTWORKER_PREVIEW. Set + * CONTENTWORKER_ADMIN to its origin to override that, or over a binding with no URL to derive + * from. Without one, preview pages can't be framed at all. */ export class ConfigError extends Error {} @@ -27,6 +33,8 @@ export interface Backend { base: string; /** The Preview API base for drafts, or null when preview isn't configured. */ preview: string | null; + /** The admin's origin, the only one allowed to frame /__preview pages; null when unknown. */ + admin: string | null; fetch: typeof fetch; space: string; environment: string; @@ -78,9 +86,11 @@ export function backend(env: Partial): Backend { : null; if (!preview && origin && /^https?:\/\/cdn\./.test(origin)) preview = origin.replace('//cdn.', '//api.'); + const admin = adminOrigin(env.CONTENTWORKER_ADMIN, origin, preview); const key: string = env.CONTENTWORKER_KEY; const config: Backend = { preview: preview ? `${preview}/preview/${space}/${environment}` : null, + admin, transport: binding ? 'binding' : 'http', base: `${binding ? BINDING_ORIGIN : origin}/delivery/${space}/${environment}`, fetch: binding ? (u, i) => binding.fetch(u, i) : (u, i) => fetch(u, i), @@ -92,3 +102,42 @@ export function backend(env: Partial): Backend { memo.set(env, config); return config; } + +/** + * The admin origin: CONTENTWORKER_ADMIN, else the domain behind cdn. (the Delivery URL) + * or api. (the Preview API). Only an exact https origin is accepted (http only on + * localhost, as the live preview SDK requires); never a wildcard. + */ +function adminOrigin( + explicit: string | undefined, + delivery: string | null, + preview: string | null, +): string | null { + if (explicit?.trim()) { + const value = explicit.trim().replace(/\/$/, ''); + const origin = previewOrigin(value); + if (!origin || origin !== value || value.includes('*')) + throw new ConfigError( + `CONTENTWORKER_ADMIN must be an exact https origin like https://admin.example.com (http only on localhost), got "${explicit}".`, + ); + return origin; + } + if (delivery && /^https?:\/\/cdn\./.test(delivery)) + return previewOrigin(delivery.replace('//cdn.', '//')); + if (preview && /^https?:\/\/api\./.test(preview)) + return previewOrigin(preview.replace('//api.', '//')); + return null; +} + +/** The origin of an https URL (or http on localhost), or null. */ +function previewOrigin(value: string): string | null { + let url: URL; + try { + url = new URL(value); + } catch { + return null; + } + const local = /^(localhost|127\.0\.0\.1|\[::1\])$/.test(url.hostname); + if (url.protocol !== 'https:' && !(url.protocol === 'http:' && local)) return null; + return url.origin; +} diff --git a/packages/frontend/src/content-ref.ts b/packages/frontend/src/content-ref.ts new file mode 100644 index 0000000..43fa2cf --- /dev/null +++ b/packages/frontend/src/content-ref.ts @@ -0,0 +1,50 @@ +/** + * Content refs: the identity of one editable value on a rendered page, stamped as `data-cw-ref` + * on preview renders so the admin can map a click back to the field it came from. + * + * The same format as `formatContentRef` in `@contentworker/sdk`: six parts (space, environment, + * entry id, content type, field apiId, locale), each URI-encoded and joined with `|`. Encoding each + * part means a part containing `|` can't forge a boundary and shift the parts after it. Kept here + * rather than imported so the Worker doesn't pull the SDK's client into its bundle; the tests hold + * it to the SDK's examples. + */ + +export interface ContentRef { + readonly space: string; + readonly environment: string; + readonly entryId: string; + readonly contentType: string; + /** apiId of the field, e.g. `title`. */ + readonly field: string; + readonly locale: string; +} + +export const CONTENT_REF_ATTRIBUTE = 'data-cw-ref'; +const SEPARATOR = '|'; + +export function formatContentRef(ref: ContentRef): string { + return [ref.space, ref.environment, ref.entryId, ref.contentType, ref.field, ref.locale] + .map(encodeURIComponent) + .join(SEPARATOR); +} + +/** Parses a serialized ref, or returns undefined if it is not one. */ +export function parseContentRef(value: string | null | undefined): ContentRef | undefined { + if (!value) return undefined; + let parts: string[]; + try { + parts = value.split(SEPARATOR).map(decodeURIComponent); + } catch { + return undefined; + } + if (parts.length !== 6 || parts.some((p) => p === '')) return undefined; + const [space, environment, entryId, contentType, field, locale] = parts as [ + string, + string, + string, + string, + string, + string, + ]; + return { space, environment, entryId, contentType, field, locale }; +} diff --git a/packages/frontend/src/headers.ts b/packages/frontend/src/headers.ts index edd09ad..a04824c 100644 --- a/packages/frontend/src/headers.ts +++ b/packages/frontend/src/headers.ts @@ -17,6 +17,31 @@ export const CSP_DIRECTIVES = [ /** The policy cached pages carry; the gateway upgrades it with a nonce (src/nonce.ts). */ export const CSP = CSP_DIRECTIVES.join('; '); +/** + * The policy /__preview responses carry instead. Public pages may only be framed by the site + * itself; preview pages only by the ContentWorker admin (live preview), never by the site or + * anyone else, and by nobody when the admin origin isn't known. Trusted Types also allows + * `cw-preview`, the policy the live preview script swaps re-rendered blocks in through. + */ +export function previewCsp(admin: string | null): string { + return CSP_DIRECTIVES.map((d) => + d.startsWith('frame-ancestors ') + ? `frame-ancestors ${admin ?? "'none'"}` + : d.startsWith('trusted-types ') + ? `${d} cw-preview` + : d, + ).join('; '); +} + +/** Headers every /__preview response adds: its own CSP, no Referer, never indexed. */ +export function previewHeaders(admin: string | null): Record { + return { + 'content-security-policy': previewCsp(admin), + 'referrer-policy': 'no-referrer', + 'x-robots-tag': 'noindex', + }; +} + const SECURITY = { 'content-security-policy': CSP, 'strict-transport-security': 'max-age=31536000; includeSubDomains', @@ -28,8 +53,6 @@ const SECURITY = { /** * Headers for an HTML page. - * @param {{ kind: 'page' | 'not-found' | 'preview', tags?: string[], etag?: string, - * codeBase: string, preconnect?: string[] }} opts */ export interface HtmlHeaderOptions { kind: 'page' | 'not-found' | 'preview'; @@ -37,6 +60,8 @@ export interface HtmlHeaderOptions { etag?: string | null; codeBase: string; preconnect?: string[]; + /** The admin origin allowed to frame a preview page (kind 'preview' only). */ + admin?: string | null; } export function htmlHeaders({ @@ -45,11 +70,12 @@ export function htmlHeaders({ etag, codeBase, preconnect = [], + admin = null, }: HtmlHeaderOptions): Headers { const h = new Headers({ 'content-type': 'text/html; charset=utf-8', ...SECURITY }); if (kind === 'preview') { h.set('cache-control', NO_STORE); - h.set('x-robots-tag', 'noindex'); + for (const [k, v] of Object.entries(previewHeaders(admin))) h.set(k, v); } else { h.set('cache-control', BROWSER_HTML); // Edge-only TTL: Workers Caching reads it, browsers never see it. diff --git a/packages/frontend/src/nonce.ts b/packages/frontend/src/nonce.ts index b49f534..2490d6d 100644 --- a/packages/frontend/src/nonce.ts +++ b/packages/frontend/src/nonce.ts @@ -8,18 +8,33 @@ * byte is unchanged. Outside workerd (node tests) there is no HTMLRewriter and responses pass * through with the `'self'` policy. */ -import { CSP_DIRECTIVES } from './headers.ts'; +import { CSP, CSP_DIRECTIVES } from './headers.ts'; export function newNonce(): string { const bytes = crypto.getRandomValues(new Uint8Array(16)); return btoa(String.fromCharCode(...bytes)); } -/** The page CSP with a nonce: strict-dynamic for CSP3 browsers, 'self' for older ones. */ -export function nonceCsp(nonce: string): string { - return [`script-src 'nonce-${nonce}' 'strict-dynamic' 'self'`, ...CSP_DIRECTIVES.slice(1)].join( - '; ', +/** + * A response's CSP with a nonce: strict-dynamic for CSP3 browsers, 'self' for older ones. Every + * page directive stays; one the response sets itself replaces the page's (a preview page's + * frame-ancestors and Trusted Types), and `script-src` always becomes the nonce. + */ +export function nonceCsp(nonce: string, policy: string = CSP): string { + const own = new Map( + policy + .split(';') + .map((d) => d.trim()) + .filter(Boolean) + .map((d) => [d.split(/\s+/)[0] ?? d, d] as const), ); + const names = new Set([...CSP_DIRECTIVES.map((d) => d.split(' ')[0] ?? d), ...own.keys()]); + names.delete('script-src'); + const page = new Map(CSP_DIRECTIVES.map((d) => [d.split(' ')[0] ?? d, d] as const)); + return [ + `script-src 'nonce-${nonce}' 'strict-dynamic' 'self'`, + ...[...names].map((n) => own.get(n) ?? page.get(n) ?? n), + ].join('; '); } const weak = (etag: string | null) => (etag && !etag.startsWith('W/') ? `W/${etag}` : etag); @@ -46,7 +61,10 @@ export function withNonce(res: Response): Response { } const nonce = newNonce(); const headers = new Headers(res.headers); - headers.set('content-security-policy', nonceCsp(nonce)); + headers.set( + 'content-security-policy', + nonceCsp(nonce, headers.get('content-security-policy') ?? CSP), + ); // The bytes now differ per visitor; the content doesn't: a weak validator says exactly that. const etag = weak(headers.get('etag')); if (etag) headers.set('etag', etag); diff --git a/packages/frontend/src/preview-render.ts b/packages/frontend/src/preview-render.ts new file mode 100644 index 0000000..271b86b --- /dev/null +++ b/packages/frontend/src/preview-render.ts @@ -0,0 +1,187 @@ +import type { Backend } from './config.ts'; +import { previewHeaders, textHeaders } from './headers.ts'; +import { fetchDraft, jsonBody, readCookie } from './preview.ts'; +import { createRenderCtx } from './render/block-ctx.ts'; +import { type MainPart, mainParts, marksFor } from './render/document.ts'; +import { pathFor } from './routes.ts'; +import type { Entry } from './types.ts'; + +/** + * POST /__preview/render: the live preview script's re-render. Takes the draft fields the editor + * holds (not saved yet) and answers the HTML of the blocks they produce, rendered by the same + * block renderers and escaping as any page: + * + * { "entryId": "…", "fields": { … }, "locale"?: "en-US", "keys"?: ["<_key>", …] } + * + * `fields` are Delivery-shaped (one locale, `{ id, linkType }` links), or locale-keyed as the + * Management API and the live preview protocol hold them when `locale` names the one to render. + * A field left out, or missing in that locale, keeps the draft's value. A link the draft already + * embeds (an image, a linked entry) is resolved from the draft; any other stays a stub, which + * renders as nothing, as on a page. + * + * Answers `{ blocks: [{ key, html }], missing: [keys], css: [hrefs] }` for `keys`, or + * `{ main, css }` (all of
) without. `css` is every block stylesheet the HTML needs. + * + * Only for the grant in this browser's preview cookie, and only for that entry: the token is + * checked against the Preview API on every call, as a preview page load does. Same-origin POSTs + * only (the script runs in the framed preview page), JSON only, at most MAX_RENDER_BYTES, never + * cached and never indexed. + */ +export const MAX_RENDER_BYTES = 2 * 1024 * 1024; +const MAX_KEYS = 500; +const MAX_KEY_LENGTH = 256; +const MAX_DEPTH = 64; +const MAX_NODES = 200_000; +/** Names that reach an object's prototype when assigned; dropped from supplied fields. */ +const FORBIDDEN = new Set(['__proto__', 'constructor', 'prototype']); + +export interface RenderDeps { + request: Request; + url: URL; + cw: Backend; + site: { origin: string; codeBase: string }; +} + +const json = (cw: Backend, body: unknown, status = 200): Response => + new Response(JSON.stringify(body), { + status, + headers: { + ...textHeaders(previewHeaders(cw.admin)), + 'content-type': 'application/json; charset=utf-8', + }, + }); + +export async function renderPreviewBlocks({ + request, + url, + cw, + site, +}: RenderDeps): Promise { + const read = await jsonBody(request, url, cw, MAX_RENDER_BYTES); + if ('refused' in read) return read.refused; + const { entryId, fields, locale, keys } = read.body; + if (typeof entryId !== 'string' || !isRecord(fields)) + return json(cw, { error: 'Send entryId and fields.' }, 400); + if (locale !== undefined && (typeof locale !== 'string' || !locale || FORBIDDEN.has(locale))) + return json(cw, { error: 'locale must be a locale code.' }, 400); + if ( + keys !== undefined && + !( + Array.isArray(keys) && + keys.length <= MAX_KEYS && + keys.every((k) => typeof k === 'string' && k && k.length <= MAX_KEY_LENGTH) + ) + ) + return json(cw, { error: `keys must be at most ${MAX_KEYS} block keys.` }, 400); + + const granted = readCookie(request); + if (!granted || granted.entryId !== entryId) + return json(cw, { error: 'No preview grant for this entry.' }, 403); + const draft = await fetchDraft(cw, granted.entryId, granted.token); + if (!draft) return json(cw, { error: 'This preview has expired.' }, 403); + + let entry: Entry; + try { + entry = overlay(draft, fields, locale); + } catch (error) { + if (error instanceof TooLarge) return json(cw, { error: error.message }, 413); + throw error; + } + const path = pathFor(draft) ?? '/'; + const ctx = createRenderCtx({ path, origin: site.origin }); + const marks = marksFor({ + entry, + path, + scope: { space: cw.space, environment: cw.environment, locale: cw.locale }, + }); + let parts: MainPart[]; + try { + parts = [...mainParts({ entry, ctx, codeBase: site.codeBase, linked: new Set(), marks })]; + } catch (error) { + // A half-edited field a renderer can't take: the page keeps what it shows. + console.error(JSON.stringify({ msg: 'preview render failed', error: String(error) })); + return json(cw, { error: 'These fields could not be rendered.' }, 422); + } + + if (!Array.isArray(keys)) { + return json(cw, { + main: parts.map((p) => p.html).join(''), + css: [...new Set(parts.flatMap((p) => p.needs))], + }); + } + const byKey = new Map(parts.filter((p) => p.key).map((p) => [p.key as string, p])); + const wanted = [...new Set(keys as string[])]; + const found = wanted.flatMap((key) => { + const part = byKey.get(key); + return part ? [{ key, part }] : []; + }); + return json(cw, { + blocks: found.map(({ key, part }) => ({ key, html: part.section })), + missing: wanted.filter((k) => !byKey.has(k)), + css: [...new Set(found.flatMap(({ part }) => part.needs))], + }); +} + +class TooLarge extends Error {} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +/** + * The draft with the supplied fields over it, links resolved from what the draft embeds. Copies + * every supplied value (nothing the caller sent is rendered by reference), drops prototype names, + * and refuses values nested deeper than MAX_DEPTH or larger than MAX_NODES. + */ +export function overlay( + draft: Entry, + fields: Record, + locale?: string | undefined, +): Entry { + const index = new Map(); + collect(draft.fields, index, 0); + let nodes = 0; + const copy = (value: unknown, depth: number): unknown => { + nodes += 1; + if (nodes > MAX_NODES) throw new TooLarge('fields are too large to render'); + if (depth > MAX_DEPTH) throw new TooLarge('fields are nested too deeply to render'); + if (Array.isArray(value)) return value.map((v) => copy(v, depth + 1)); + if (!isRecord(value)) return value; + if (isStub(value)) return index.get(value.id) ?? { id: value.id, linkType: value.linkType }; + const out: Record = {}; + for (const [k, v] of Object.entries(value)) if (!FORBIDDEN.has(k)) out[k] = copy(v, depth + 1); + return out; + }; + const next: Record = { ...draft.fields }; + for (const [name, value] of Object.entries(fields)) { + if (FORBIDDEN.has(name)) continue; + if (locale === undefined) { + next[name] = copy(value, 0); + } else if (isRecord(value) && Object.hasOwn(value, locale)) { + next[name] = copy(value[locale], 0); + } + } + return { ...draft, fields: next }; +} + +function isStub(value: Record): value is { id: string; linkType: string } { + return ( + typeof value.id === 'string' && + (value.linkType === 'Entry' || value.linkType === 'Asset') && + !('fields' in value) && + !('url' in value) + ); +} + +/** Every entry and asset the draft embeds, by id. */ +function collect(value: unknown, index: Map, depth: number): void { + if (depth > 12) return; + if (Array.isArray(value)) { + for (const v of value) collect(v, index, depth + 1); + return; + } + if (!isRecord(value)) return; + if (typeof value.id === 'string' && (isRecord(value.fields) || typeof value.url === 'string')) + index.set(value.id, value); + for (const v of Object.values(value)) collect(v, index, depth + 1); +} diff --git a/packages/frontend/src/preview.ts b/packages/frontend/src/preview.ts index d3092fd..f9e5c5e 100644 --- a/packages/frontend/src/preview.ts +++ b/packages/frontend/src/preview.ts @@ -1,23 +1,41 @@ import type { Backend } from './config.ts'; -import { textHeaders } from './headers.ts'; +import { previewHeaders, textHeaders } from './headers.ts'; +import { renderPreviewBlocks } from './preview-render.ts'; import { normalize, pathFor } from './routes.ts'; -import type { Entry } from './types.ts'; +import type { Entry, PreviewState } from './types.ts'; /** * Draft preview, never cached. ContentWorker mints a preview link per entry (a `pw_…` token, - * valid for that one entry). Point the link at: + * valid for that one entry). Point the link at either form: * - * https:///__preview?entry=&token= + * https:///__preview?entry=#token= (recommended) + * https:///__preview?entry=&token= (still accepted) * - * That checks the token against the Preview API, keeps it in an HttpOnly cookie scoped to - * /__preview, and redirects to /__preview/. Pages under /__preview render the - * draft for its own path and published content everywhere else, with `private, no-store` and - * noindex. The /__preview prefix is also what keeps drafts out of the edge cache: it is a - * different cache key, and it is answered by the uncached gateway. + * A token in the fragment never reaches a server log or a Referer. The fragment never reaches + * this Worker either, so that form answers a tiny page whose script reads it, drops it from + * history and POSTs it back here (same origin only). Both forms check the token against the + * Preview API, keep it in an HttpOnly cookie scoped to /__preview, and send the browser to + * /__preview/. Pages under /__preview render the draft for its own path and + * published content everywhere else, with `private, no-store` and noindex. The /__preview + * prefix is also what keeps drafts out of the edge cache: it is a different cache key, and it is + * answered by the uncached gateway. + * + * The admin frames these pages for live preview, so the cookie is `SameSite=None; Partitioned` + * (sent inside the admin's iframe, and kept in the admin's partition only) and every response + * names the admin as the only origin that may frame it. With `cw_session` on the URL the page + * also loads the live preview script, which re-renders blocks through POST /__preview/render. */ export const PREFIX = '/__preview'; +export const RENDER_PATH = `${PREFIX}/render`; const COOKIE = 'cw_preview'; const MAX_AGE = 60 * 60; +/** Entry ids are UUIDs (and test ids): no `~`, which separates the cookie's two parts. */ +const ENTRY_ID = /^[A-Za-z0-9_-]{1,128}$/; +const TOKEN = /^[\w.-]{1,512}$/; +/** A live preview session id, as `@contentworker/sdk/live-preview` checks it. */ +const SESSION = /^[A-Za-z0-9_-]{8,128}$/; +export const SESSION_PARAM = 'cw_session'; +const MAX_HANDOFF_BYTES = 4 * 1024; /** Reads one draft entry with its preview token (no API key needed: the token is the grant). */ export async function fetchDraft( @@ -34,56 +52,198 @@ export async function fetchDraft( return (await res.json()) as Entry; } -function readCookie(request: Request): { entryId: string; token: string } | null { +export function readCookie(request: Request): { entryId: string; token: string } | null { const raw = request.headers.get('cookie') ?? ''; const match = raw.split(/;\s*/).find((c) => c.startsWith(`${COOKIE}=`)); if (!match) return null; - const [entryId, token] = decodeURIComponent(match.slice(COOKIE.length + 1)).split('~'); + let value: string; + try { + value = decodeURIComponent(match.slice(COOKIE.length + 1)); + } catch { + return null; + } + const [entryId, token] = value.split('~'); return entryId && token ? { entryId, token } : null; } -const cookie = (value: string, maxAge: number): string => - `${COOKIE}=${value}; Path=${PREFIX}; HttpOnly; Secure; SameSite=Lax; Max-Age=${maxAge}`; - /** - * @param {{ request: Request, url: URL, cw: any, render: (opts: { path: string, preview: any }) => Promise }} deps + * The grant cookie. `SameSite=None` so it is sent inside the admin's cross-site iframe; + * `Partitioned` (CHIPS) so a framed copy lives only in the admin's partition and no other site + * that frames this one can use it; HttpOnly, Secure and the /__preview path as before. Clearing + * repeats the same attributes, or the browser would treat it as a different cookie. */ +const cookie = (value: string, maxAge: number): string => + `${COOKIE}=${value}; Path=${PREFIX}; HttpOnly; Secure; SameSite=None; Partitioned; Max-Age=${maxAge}`; + export interface PreviewDeps { request: Request; url: URL; cw: Backend; - render: (opts: { - path: string; - preview: { entry: Entry | null; path: string }; - }) => Promise; + /** The site's origin and versioned code base, for the re-render endpoint. */ + site: { origin: string; codeBase: string }; + render: (opts: { path: string; preview: PreviewState }) => Promise; +} + +/** A plain-text answer with the preview headers (framing, Referer, noindex). */ +function text(cw: Backend, body: string, status: number, extra: Record = {}) { + return new Response(body, { + status, + headers: textHeaders({ ...previewHeaders(cw.admin), ...extra }), + }); +} + +/** Where a valid grant lands: the draft's path, carrying the live preview session through. */ +function landing(draft: Entry, session: string | null): string { + const path = pathFor(draft) ?? '/'; + const to = `${PREFIX}${path === '/' ? '/' : path}`; + return session ? `${to}?${new URLSearchParams({ [SESSION_PARAM]: session })}` : to; +} + +const sessionOf = (value: unknown): string | null => + typeof value === 'string' && SESSION.test(value) ? value : null; + +/** + * A POST from this site's own pages: `Origin` must be exactly this origin (and Sec-Fetch-Site, when + * sent, `same-origin`). Pages under /__preview send no Referer, which also blanks `Origin` on a + * POST, so their scripts ask for `referrerPolicy: 'same-origin'` on these requests. + */ +export function fromOwnPages(request: Request, url: URL): boolean { + const site = request.headers.get('sec-fetch-site'); + if (site && site !== 'same-origin') return false; + return request.headers.get('origin') === url.origin; +} + +/** The body as text, or null when it is larger than `max` bytes (read no further than that). */ +export async function readCapped(request: Request, max: number): Promise { + const declared = Number(request.headers.get('content-length') ?? 0); + if (declared > max) return null; + if (!request.body) return ''; + const reader = request.body.getReader(); + const chunks: Uint8Array[] = []; + let size = 0; + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + size += value.byteLength; + if (size > max) { + await reader.cancel(); + return null; + } + chunks.push(value); + } + const bytes = new Uint8Array(size); + let at = 0; + for (const c of chunks) { + bytes.set(c, at); + at += c.byteLength; + } + return new TextDecoder().decode(bytes); +} + +/** The JSON body of a same-origin POST, or the Response refusing it. */ +export async function jsonBody( + request: Request, + url: URL, + cw: Backend, + max: number, +): Promise<{ body: Record } | { refused: Response }> { + if (!fromOwnPages(request, url)) + return { refused: text(cw, 'Cross-origin request refused.', 403) }; + if (!(request.headers.get('content-type') ?? '').toLowerCase().startsWith('application/json')) + return { refused: text(cw, 'Send application/json.', 415) }; + const raw = await readCapped(request, max); + if (raw === null) return { refused: text(cw, 'Request body too large.', 413) }; + try { + const body: unknown = JSON.parse(raw); + if (body && typeof body === 'object' && !Array.isArray(body)) + return { body: body as Record }; + } catch { + // fall through + } + return { refused: text(cw, 'Send a JSON object.', 400) }; } -export async function handlePreview({ request, url, cw, render }: PreviewDeps): Promise { +/** Checks a token and answers with the grant cookie, either as a redirect or as JSON. */ +async function grant( + cw: Backend, + entryId: unknown, + token: unknown, + session: string | null, + as: 'redirect' | 'json', +): Promise { + if ( + typeof entryId !== 'string' || + typeof token !== 'string' || + !ENTRY_ID.test(entryId) || + !TOKEN.test(token) + ) + return text(cw, 'Missing entry or token.', 400); + const draft = await fetchDraft(cw, entryId, token); + if (!draft) return text(cw, 'This preview link is invalid or has expired.', 403); + const location = landing(draft, session); + const setCookie = cookie(`${encodeURIComponent(entryId)}~${token}`, MAX_AGE); + if (as === 'redirect') + return new Response(null, { + status: 303, + headers: textHeaders({ ...previewHeaders(cw.admin), location, 'set-cookie': setCookie }), + }); + return new Response(JSON.stringify({ location }), { + headers: { + ...textHeaders(previewHeaders(cw.admin)), + 'content-type': 'application/json; charset=utf-8', + 'set-cookie': setCookie, + }, + }); +} + +/** + * The fragment handoff, run by the page below. It reads `#token=` and drops the fragment from + * history before anything else, so the token is gone from the address bar, history and any + * later Referer, then trades it for the cookie and replaces itself with the draft. Reads the + * entry and session from its own URL: nothing from the request is printed into the page. + */ +export const HANDOFF_SCRIPT = `(()=>{const q=new URLSearchParams(location.search),h=new URLSearchParams(location.hash.slice(1)),t=h.get('token'),s=document.getElementById('cw-status'),say=(m)=>{if(s)s.textContent=m};history.replaceState(null,'',location.pathname+location.search);if(!t){say('This preview link has no token.');return}fetch('${PREFIX}',{method:'POST',headers:{'content-type':'application/json'},credentials:'same-origin',referrerPolicy:'same-origin',body:JSON.stringify({entry:q.get('entry'),token:t,session:q.get('${SESSION_PARAM}')})}).then((r)=>r.ok?r.json():Promise.reject(r.status)).then((d)=>{if(typeof d.location!=='string'||!d.location.startsWith('${PREFIX}/'))throw 0;location.replace(d.location)}).catch((e)=>say(e===403?'This preview link is invalid or has expired.':'The preview could not start. Try the link again.'))})()`; + +const HANDOFF_PAGE = `Opening preview

Opening the preview…

`; + +function handoffPage(cw: Backend): Response { + // The gateway's withNonce stamps this response's nonce on the script and into its CSP. + return new Response(HANDOFF_PAGE, { + headers: { + 'content-type': 'text/html; charset=utf-8', + 'cache-control': 'private, no-store', + 'x-content-type-options': 'nosniff', + ...previewHeaders(cw.admin), + }, + }); +} + +export async function handlePreview(deps: PreviewDeps): Promise { + const { request, url, cw, render, site } = deps; if (!cw.preview) return new Response('Preview is not configured (set CONTENTWORKER_PREVIEW).', { status: 404, - headers: textHeaders(), + headers: textHeaders(previewHeaders(cw.admin)), }); + if (request.method === 'POST') { + if (url.pathname === PREFIX) { + const read = await jsonBody(request, url, cw, MAX_HANDOFF_BYTES); + if ('refused' in read) return read.refused; + const { entry, token, session } = read.body; + return grant(cw, entry, token, sessionOf(session), 'json'); + } + if (url.pathname === RENDER_PATH) return renderPreviewBlocks({ request, url, cw, site }); + return text(cw, 'Method not allowed', 405, { allow: 'GET, HEAD' }); + } + if (url.pathname === PREFIX) { const entryId = url.searchParams.get('entry'); const token = url.searchParams.get('token'); - if (!entryId || !token || !/^[\w.-]+$/.test(token)) - return new Response('Missing entry or token.', { status: 400, headers: textHeaders() }); - const draft = await fetchDraft(cw, entryId, token); - if (!draft) - return new Response('This preview link is invalid or has expired.', { - status: 403, - headers: textHeaders(), - }); - const path = pathFor(draft) ?? '/'; - return new Response(null, { - status: 303, - headers: textHeaders({ - location: `${PREFIX}${path === '/' ? '/' : path}`, - 'set-cookie': cookie(`${encodeURIComponent(entryId)}~${token}`, MAX_AGE), - }), - }); + const session = sessionOf(url.searchParams.get(SESSION_PARAM)); + if (token !== null) return grant(cw, entryId, token, session, 'redirect'); + if (!entryId || !ENTRY_ID.test(entryId)) return text(cw, 'Missing entry or token.', 400); + return handoffPage(cw); } if (url.pathname === `${PREFIX}/exit`) { @@ -91,17 +251,30 @@ export async function handlePreview({ request, url, cw, render }: PreviewDeps): const safe = to.startsWith('/') && !to.startsWith('//') ? to : '/'; return new Response(null, { status: 303, - headers: textHeaders({ location: safe, 'set-cookie': cookie('', 0) }), + headers: textHeaders({ + ...previewHeaders(cw.admin), + location: safe, + 'set-cookie': cookie('', 0), + }), }); } const sitePath = url.pathname.slice(PREFIX.length) || '/'; const { path } = normalize(new URL(sitePath, url.origin)); - const grant = readCookie(request); + const granted = readCookie(request); let entry: Entry | null = null; - if (grant) { - const draft = await fetchDraft(cw, grant.entryId, grant.token); + if (granted) { + const draft = await fetchDraft(cw, granted.entryId, granted.token); if (draft && pathFor(draft) === path) entry = draft; } - return render({ path, preview: { entry, path } }); + const session = sessionOf(url.searchParams.get(SESSION_PARAM)); + return render({ + path, + preview: { + entry, + path, + scope: { space: cw.space, environment: cw.environment, locale: cw.locale }, + live: entry && session && cw.admin ? { admin: cw.admin } : null, + }, + }); } diff --git a/packages/frontend/src/render/document.ts b/packages/frontend/src/render/document.ts index b4be3d2..fbfca4f 100644 --- a/packages/frontend/src/render/document.ts +++ b/packages/frontend/src/render/document.ts @@ -1,6 +1,15 @@ import { toClassName } from '../../public/scripts/shared.js'; +import { type ContentRef, formatContentRef } from '../content-ref.ts'; import { attrs, html, type Safe } from '../html.ts'; -import { type Entry, type Menus, type RenderCtx, sectionsIn } from '../types.ts'; +import { + blockKey, + type Entry, + isBlocksField, + type Menus, + type PreviewState, + type RenderCtx, + sectionsIn, +} from '../types.ts'; import { createRenderCtx } from './block-ctx.ts'; import { BLOCKS, @@ -32,7 +41,7 @@ export interface DocumentInput { codeBase: string; lang: string; notFound: boolean; - preview?: { entry: Entry | null; path: string } | undefined; + preview?: PreviewState | undefined; } export async function* renderDocument(input: DocumentInput): AsyncGenerator { @@ -47,6 +56,7 @@ export async function* renderDocument(input: DocumentInput): AsyncGenerator`; yield renderHead({ @@ -56,56 +66,132 @@ export async function* renderDocument(input: DocumentInput): AsyncGenerator` + .value; + } yield ''; if (preview) { yield html`
Previewing a draft. Exit preview
` .value; } - yield html`
${blockShell(CHROME.header, CHROME.header.default(settings, ctx))}
` + const slot = marks && isBlocksField(entry?.fields?.sections) ? 'sections' : null; + yield html`
${blockShell(CHROME.header, CHROME.header.default(settings, ctx))}
` + .value; + + const linked = new Set(blockCss(firstMods, codeBase)); + for (const part of mainParts({ entry, sections, ctx, codeBase, linked, marks })) yield part.html; + if (notFound) yield notFoundSection().value; + + const footerCss = blockCss([CHROME.footer], codeBase).filter((href) => !linked.has(href)); + yield html`
${footerCss.map((href) => html``)}
${blockShell(CHROME.footer, CHROME.footer.default(settings, ctx))}
` .value; +} + +/** Makes the `data-cw-ref` value for one of the draft's fields, or null outside a draft preview. */ +export type Marks = ((field: string) => string) | null; + +export function marksFor(preview: PreviewState | undefined): Marks { + const entry = preview?.entry; + const scope = preview?.scope; + if (!entry || !scope || !entry.id) return null; + return (field) => { + const ref: ContentRef = { + space: scope.space, + environment: scope.environment, + entryId: entry.id, + contentType: entry.contentType, + field, + locale: scope.locale, + }; + return formatContentRef(ref); + }; +} + +/** One piece of
: the page title, or a section (with the block CSS it newly needs). */ +export interface MainPart { + /** The section's blocks-field `_key`, when it has one. */ + key?: string | undefined; + /** Block CSS hrefs this part linked first (its `html` starts with their links). */ + css: string[]; + /** Every block CSS href the part needs, linked earlier or not. */ + needs: string[]; + /** The part's own element, without the stylesheet links in front of it. */ + section: string; + html: string; +} +/** + * Everything
holds before the not-found notice, in order. Page renders and the preview + * re-render endpoint both come through here, so a re-rendered block is the block the page shows. + */ +export function* mainParts({ + entry, + sections = sectionsOf(entry), + ctx, + codeBase, + linked, + marks = null, +}: { + entry: Entry | null; + sections?: Entry[]; + ctx: RenderCtx; + codeBase: string; + linked: Set; + marks?: Marks; +}): Generator { if (entry?.contentType === 'listing') { - yield html`

${entry.fields.title}

` - .value; + const section = + html`

${entry.fields.title}

` + .value; + yield { css: [], needs: [], section, html: section }; ctx.headingLevel = 2; } else if (entry && sections[0] && !titledBy(sections[0])) { // Every page has exactly one h1, before any block heading (heading order is an a11y audit). - yield html`

${entry.fields.seo?.h1 || entry.fields.title}

` - .value; + const ref = marks ? marks(entry.fields.seo?.h1 ? 'seo' : 'title') : null; + const section = + html`
${entry.fields.seo?.h1 || entry.fields.title}
` + .value; + yield { css: [], needs: [], section, html: section }; ctx.headingLevel = 2; } - const linked = new Set(blockCss(firstMods, codeBase)); for (const [i, section] of sections.entries()) { - const mods = modulesOf(section); - const css = blockCss(mods, codeBase).filter((href) => !linked.has(href)); + const needs = blockCss(modulesOf(section), codeBase); + const css = needs.filter((href) => !linked.has(href)); for (const href of css) linked.add(href); ctx.inFirstSection = i === 0; - yield html`${css.map((href) => html``)}${renderSection(section, i, ctx)}` - .value; + const own = renderSection(section, i, ctx, marks); + yield { + key: blockKey(section), + css, + needs, + section: own.value, + html: html`${css.map((href) => html``)}${own}`.value, + }; } - if (notFound) yield notFoundSection().value; - - const footerCss = blockCss([CHROME.footer], codeBase).filter((href) => !linked.has(href)); - yield html`
${footerCss.map((href) => html``)}
${blockShell(CHROME.footer, CHROME.footer.default(settings, ctx))}
` - .value; } /** A page's sections (linked entries or blocks-field elements), or one from its `body`. */ -function sectionsOf(entry: Entry | null): Entry[] { +export function sectionsOf(entry: Entry | null): Entry[] { if (!entry?.fields) return []; const f = entry.fields; if (Array.isArray(f.sections)) return sectionsIn(f.sections); - if (f.body) - return [ - { - id: `${entry.id}:body`, - contentType: DEFAULT_CONTENT, - fields: { body: f.body, heading: f.title }, - }, - ]; + if (f.body) { + const body: Entry = { + id: `${entry.id}:body`, + contentType: DEFAULT_CONTENT, + fields: { body: f.body, heading: f.title }, + }; + PAGE_BODY.add(body); + return [body]; + } return []; } +/** The sections sectionsOf made from a page's own body and title (their refs are the page's). */ +const PAGE_BODY = new WeakSet(); + const modulesOf = (section: Entry) => modulesIn(section); /** Whether a first section renders the h1 itself: a hero, or default content carrying a heading. */ @@ -113,18 +199,20 @@ const titledBy = (section: Entry): boolean => (section.contentType === DEFAULT_CONTENT && Boolean(section.fields.heading)) || Boolean(BLOCKS.get(section.contentType)?.ownsTitle); -function renderSection(section: Entry, index: number, ctx: RenderCtx): Safe { +function renderSection(section: Entry, index: number, ctx: RenderCtx, marks: Marks): Safe { const style = section.fields?.style ? toClassName(section.fields.style) : null; // Every section starts 'initialized'; scripts/lib.js marks it 'loaded' once its block JS ran. const status = 'initialized'; if (section.contentType === DEFAULT_CONTENT) { + // A page's own body and title (sectionsOf) carry the page's refs; a richText block its key. + const own = marks && PAGE_BODY.has(section) ? marks : null; const { heading, body } = section.fields; let title: Safe | string = ''; if (heading && index === 0 && ctx.headingLevel === 1) { - title = html`

${heading}

`; + title = html`${heading}`; ctx.headingLevel = 2; } - return html`
${title}${renderRichText(body, ctx)}
`; + return html`
${title}${renderRichText(body, ctx)}
`; } const mod = BLOCKS.get(section.contentType); if (!mod) return html``; @@ -132,6 +220,7 @@ function renderSection(section: Entry, index: number, ctx: RenderCtx): Safe { return html`
${blockShell(mod, mod.default(section, ctx))}
`; } diff --git a/packages/frontend/src/render/page.ts b/packages/frontend/src/render/page.ts index bbe14c4..b73e4a2 100644 --- a/packages/frontend/src/render/page.ts +++ b/packages/frontend/src/render/page.ts @@ -3,7 +3,7 @@ import type { Delivery } from '../delivery.ts'; import { htmlHeaders } from '../headers.ts'; import type { RouteMatch } from '../routes.ts'; import { match } from '../routes.ts'; -import type { Entry, SiteEnv } from '../types.ts'; +import type { Entry, PreviewState, SiteEnv } from '../types.ts'; import { renderDocument } from './document.ts'; /** Page → section → fragment → its sections → their assets (Delivery allows five). */ @@ -54,9 +54,6 @@ async function listing( /** * Renders one page as a streamed Response. Head and header go out as soon as they're rendered, * then one chunk per section, so first byte doesn't wait for the whole page. - * - * @param {{ env: any, ctx: ExecutionContext, url: URL, path: string, delivery: any, - * request: Request, preview?: { entry: any, path: string } }} input */ export interface PageInput { env: SiteEnv; @@ -65,7 +62,9 @@ export interface PageInput { path: string; delivery: Delivery; request: Request; - preview?: { entry: Entry | null; path: string } | undefined; + preview?: PreviewState | undefined; + /** The admin origin allowed to frame a preview render. */ + admin?: string | null | undefined; } export async function renderPage({ @@ -76,6 +75,7 @@ export async function renderPage({ delivery, request, preview, + admin = null, }: PageInput): Promise { const route = match(path); const [settings, main, footer, published] = await Promise.all([ @@ -114,6 +114,7 @@ export async function renderPage({ etag, codeBase, preconnect: assetOrigins(origin, entry), + admin, }); const status = notFound ? 404 : 200; diff --git a/packages/frontend/src/types.ts b/packages/frontend/src/types.ts index d463e4a..4f19473 100644 --- a/packages/frontend/src/types.ts +++ b/packages/frontend/src/types.ts @@ -144,6 +144,8 @@ export interface SiteEnv { CONTENTWORKER_KEY?: string; CONTENTWORKER_WEBHOOK_SECRET?: string; CONTENTWORKER_PREVIEW?: string; + /** The ContentWorker admin's origin, allowed to frame /__preview for live preview. */ + CONTENTWORKER_ADMIN?: string; CONTENTWORKER_DELIVERY?: { fetch: typeof fetch }; } @@ -173,10 +175,45 @@ export function asSection(value: unknown): Entry | null { if (!value || typeof value !== 'object' || Array.isArray(value)) return null; const { _type, _key, ...fields } = value as Record; if (typeof _type !== 'string') return null; - return { id: typeof _key === 'string' ? _key : '', contentType: _type, fields }; + const section: Entry = { id: typeof _key === 'string' ? _key : '', contentType: _type, fields }; + if (typeof _key === 'string' && _key) KEYS.set(section, _key); + return section; +} + +/** + * Blocks-field elements by their `_key`, kept beside the section rather than on it so nothing a + * public render hashes or prints changes. Only preview renders read it (`data-cw-block`). + */ +const KEYS = new WeakMap(); + +/** The `_key` of a section that came from a blocks field, or undefined for a linked entry. */ +export function blockKey(section: Entry): string | undefined { + return KEYS.get(section); +} + +/** Whether a field value is a blocks field (inline elements, or empty), not a list of links. */ +export function isBlocksField(value: unknown): boolean { + return ( + Array.isArray(value) && + value.every((v) => v && typeof v === 'object' && !isEntry(v) && !('linkType' in v)) + ); } /** Every section of a field value (a list of links or blocks elements), normalised. */ export function sectionsIn(value: unknown): Entry[] { return Array.isArray(value) ? value.map(asSection).filter((s): s is Entry => s !== null) : []; } + +/** What a page rendered under /__preview knows beyond a public render. */ +export interface PreviewState { + /** The draft shown at its own path, or null (published content everywhere else). */ + entry: Entry | null; + path: string; + /** + * The draft's space, environment and locale, for the editing marks (`data-cw-block`, + * `data-cw-slot`, `data-cw-ref`). Absent, a preview renders without them. + */ + scope?: { space: string; environment: string; locale: string } | undefined; + /** Set when the admin frames the page for a live preview session: the origin it listens to. */ + live?: { admin: string } | null | undefined; +} diff --git a/packages/frontend/src/worker.ts b/packages/frontend/src/worker.ts index f890a87..4a66eb8 100644 --- a/packages/frontend/src/worker.ts +++ b/packages/frontend/src/worker.ts @@ -54,21 +54,34 @@ async function route(request: Request, env: SiteEnv, ctx: ExecutionContext): Pro ctx.exports.PurgeQueue.get(ctx.exports.PurgeQueue.idFromName('purge')).add(tags), }); } - if (request.method !== 'GET' && request.method !== 'HEAD') { + const previewing = url.pathname === PREVIEW || url.pathname.startsWith(`${PREVIEW}/`); + // POST /__preview (the fragment handoff) and /__preview/render are the only other methods. + const read = request.method === 'GET' || request.method === 'HEAD'; + if (!read && !(previewing && request.method === 'POST')) { return new Response('Method not allowed', { status: 405, headers: textHeaders({ allow: 'GET, HEAD' }), }); } - if (url.pathname === PREVIEW || url.pathname.startsWith(`${PREVIEW}/`)) { + if (previewing) { const cw = backend(env); await ensureCmsRoutes(createDelivery(cw)); return await handlePreview({ request, url, cw, + site: { origin: env.SITE_ORIGIN || url.origin, codeBase: `/v/${env.BUILD_ID}` }, render: ({ path, preview }) => - renderPage({ env, ctx, url, path, request, preview, delivery: createDelivery(cw) }), + renderPage({ + env, + ctx, + url, + path, + request, + preview, + admin: cw.admin, + delivery: createDelivery(cw), + }), }); } if (!isVersioned(url.pathname)) { diff --git a/packages/frontend/test/config.test.ts b/packages/frontend/test/config.test.ts index c178474..39772dd 100644 --- a/packages/frontend/test/config.test.ts +++ b/packages/frontend/test/config.test.ts @@ -67,3 +67,60 @@ test('misconfiguration says what to fix', () => { ); } }); + +test('admin origin: derived from cdn. or api., or set; https only, never a wildcard', () => { + const k = { CONTENTWORKER_KEY: 'k' }; + assert.equal( + backend({ CONTENTWORKER: 'https://cdn.acme.example/acme/main', ...k }).admin, + 'https://acme.example', + ); + assert.equal( + backend({ + CONTENTWORKER: 'acme/main', + CONTENTWORKER_DELIVERY: binding, + CONTENTWORKER_PREVIEW: 'https://api.acme.example', + ...k, + }).admin, + 'https://acme.example', + ); + assert.equal( + backend({ CONTENTWORKER: 'acme/main', CONTENTWORKER_DELIVERY: binding, ...k }).admin, + null, + ); + assert.equal( + backend({ + CONTENTWORKER: 'https://cdn.acme.example/acme/main', + CONTENTWORKER_ADMIN: 'https://studio.acme.example/', + ...k, + }).admin, + 'https://studio.acme.example', + ); + assert.equal( + backend({ + CONTENTWORKER: 'acme/main', + CONTENTWORKER_DELIVERY: binding, + CONTENTWORKER_ADMIN: 'http://localhost:5173', + ...k, + }).admin, + 'http://localhost:5173', + ); + for (const bad of [ + '*', + 'https://*.acme.example', + 'http://acme.example', + 'https://acme.example/admin', + 'acme.example', + ]) { + assert.throws( + () => + backend({ + CONTENTWORKER: 'acme/main', + CONTENTWORKER_DELIVERY: binding, + CONTENTWORKER_ADMIN: bad, + ...k, + }), + ConfigError, + bad, + ); + } +}); diff --git a/packages/frontend/test/content-ref.test.ts b/packages/frontend/test/content-ref.test.ts new file mode 100644 index 0000000..90c74bf --- /dev/null +++ b/packages/frontend/test/content-ref.test.ts @@ -0,0 +1,32 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { type ContentRef, formatContentRef, parseContentRef } from '../src/content-ref.ts'; + +// The examples of @contentworker/sdk's own content-ref tests: the formats must stay identical. +const ref: ContentRef = { + space: 's1', + environment: 'main', + entryId: 'e1', + contentType: 'article', + field: 'title', + locale: 'en-US', +}; + +test('a ref formats as six URI-encoded parts joined by |, and round-trips', () => { + assert.equal(formatContentRef(ref), 's1|main|e1|article|title|en-US'); + assert.deepEqual(parseContentRef(formatContentRef(ref)), ref); +}); + +test('a part containing the separator cannot shift the parts after it', () => { + const odd = { ...ref, field: 'we|ird' }; + assert.equal(formatContentRef(odd), 's1|main|e1|article|we%7Cird|en-US'); + assert.deepEqual(parseContentRef(formatContentRef(odd)), odd); +}); + +test('anything that is not a ref parses to undefined', () => { + assert.equal(parseContentRef(''), undefined); + assert.equal(parseContentRef(null), undefined); + assert.equal(parseContentRef('s1|main|e1'), undefined); + assert.equal(parseContentRef('s1|main|e1|article||en-US'), undefined); + assert.equal(parseContentRef('s1|main|e1|article|%E0%A4%A|en-US'), undefined); +}); diff --git a/packages/frontend/test/preview-marks.test.ts b/packages/frontend/test/preview-marks.test.ts new file mode 100644 index 0000000..27d2509 --- /dev/null +++ b/packages/frontend/test/preview-marks.test.ts @@ -0,0 +1,83 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { formatContentRef } from '../src/content-ref.ts'; +import { call, GRANT } from './support/preview.ts'; + +const ref = (entryId: string, contentType: string, field: string) => + formatContentRef({ + space: 'site', + environment: 'main', + entryId, + contentType, + field, + locale: 'en-US', + }); + +test('a preview of a blocks-field page marks its slot, its blocks and its title', async () => { + const { body } = await call('/__preview/inline', { cookie: GRANT }); + assert.match(body, /
/); + assert.match( + body, + /
/, + ); + assert.match( + body, + /
/, + ); + // An unknown variant renders nothing, so there is nothing to mark. + assert.doesNotMatch(body, /k-unknown/); + // The hero owns the h1 here; the page's title has no element of its own to mark. + assert.doesNotMatch(body, /data-cw-ref/); +}); + +test("a preview of a body page marks its title and body with the page entry's refs", async () => { + const { body } = await call('/__preview/about', { cookie: 'cw_preview=p-about~pw_good' }); + assert.ok(body.includes(`data-cw-ref="${ref('p-about', 'page', 'body')}"`)); + assert.ok( + body.includes(`

About (draft)

`), + ); + // A body page has no blocks field. + assert.doesNotMatch(body, /data-cw-slot|data-cw-block/); +}); + +test('published content under /__preview (not the draft) carries no marks', async () => { + const { body } = await call('/__preview/inline', { cookie: 'cw_preview=p-about~pw_good' }); + assert.match(body, /Inline hero/); + assert.doesNotMatch(body, /data-cw-/); +}); + +test('public pages carry none of the preview marks, scripts or meta', async () => { + for (const path of ['/', '/about', '/blocks', '/inline', '/blog', '/missing']) { + const { res, body } = await call(path, { cookie: GRANT }); + const html = body || (await res.text()); + assert.ok(html.length > 0, path); + assert.doesNotMatch(html, /data-cw-|cw-admin-origin|live-preview\.js/, path); + } +}); + +test('live preview loads only under /__preview, for the draft, with cw_session and a known admin', async () => { + const live = await call('/__preview/inline?cw_session=sess_12345678', { cookie: GRANT }); + assert.match( + live.body, + /`)); + // Nothing from the request is printed into the page, and nothing was checked yet. + assert.doesNotMatch(body, /p-about/); + assert.equal(previewCalls.length, 0); + // The page is small: one round trip, well inside any script budget. + assert.ok(Buffer.byteLength(body) < 2048, `handoff page is ${Buffer.byteLength(body)} B`); +}); + +/** Runs the handoff script against a fake window; returns what it did, in order. */ +async function runHandoff(href: string, answer: { status: number; json?: unknown }) { + const url = new URL(href); + const log: unknown[] = []; + const status = { textContent: '' }; + const location = { + search: url.search, + hash: url.hash, + pathname: url.pathname, + replace: (to: string) => log.push(['replace', to]), + }; + const sandbox = { + URLSearchParams, + JSON, + Promise, + location, + document: { getElementById: (id: string) => (id === 'cw-status' ? status : null) }, + history: { + replaceState: (_s: unknown, _t: string, to: string) => { + location.hash = ''; + log.push(['replaceState', to]); + }, + }, + fetch: async (to: string, init: RequestInit) => { + log.push(['fetch', to, { ...init, body: JSON.parse(String(init.body)) }]); + return { + ok: answer.status === 200, + status: answer.status, + json: async () => answer.json, + }; + }, + }; + runInNewContext(HANDOFF_SCRIPT, sandbox); + await new Promise((r) => setTimeout(r, 10)); + return { log, status: status.textContent }; +} + +test('the handoff script drops the fragment first, posts the token, and follows the answer', async () => { + const { log } = await runHandoff( + `${'https://contentworker.site'}/__preview?entry=p-about&cw_session=sess_12345678#token=pw_good`, + { status: 200, json: { location: '/__preview/about?cw_session=sess_12345678' } }, ); + assert.deepEqual(log[0], ['replaceState', '/__preview?entry=p-about&cw_session=sess_12345678']); + const [, to, init] = log[1] as [string, string, RequestInit & { body: unknown }]; + assert.equal(to, '/__preview'); + assert.equal(init.method, 'POST'); + // Preview pages send no Referer, which would blank Origin on the POST; this keeps it. + assert.equal(init.referrerPolicy, 'same-origin'); + assert.equal(init.credentials, 'same-origin'); + assert.deepEqual(init.body, { entry: 'p-about', token: 'pw_good', session: 'sess_12345678' }); + assert.deepEqual(log[2], ['replace', '/__preview/about?cw_session=sess_12345678']); }); -test('an invalid or expired token is refused', async () => { - assert.equal((await get('/__preview?entry=p-about&token=pw_bad')).res.status, 403); - assert.equal((await get('/__preview?entry=p-about')).res.status, 400); +test('the handoff script refuses to go anywhere but /__preview/, and says why it stopped', async () => { + const away = await runHandoff( + 'https://contentworker.site/__preview?entry=p-about#token=pw_good', + { + status: 200, + json: { location: 'https://evil.example/' }, + }, + ); + assert.equal(away.log.length, 2, 'no navigation'); + assert.match(away.status, /could not start/); + const expired = await runHandoff( + 'https://contentworker.site/__preview?entry=p-about#token=pw_bad', + { status: 403 }, + ); + assert.match(expired.status, /invalid or has expired/); + const none = await runHandoff('https://contentworker.site/__preview?entry=p-about', { + status: 200, + }); + assert.deepEqual( + none.log.map((l) => (l as string[])[0]), + ['replaceState'], + ); + assert.match(none.status, /no token/); }); -test('the draft renders under /__preview, uncached and noindex', async () => { - const { res, body } = await get('/__preview/about', { cookie: 'cw_preview=p-about~pw_good' }); +test('POST /__preview trades a token for the cookie and answers where to go', async () => { + const { res, body } = await post('/__preview', { + entry: 'p-about', + token: 'pw_good', + session: 'sess_12345678', + }); + assert.equal(res.status, 200); + assert.deepEqual(JSON.parse(body), { location: '/__preview/about?cw_session=sess_12345678' }); + assert.match(res.headers.get('set-cookie') ?? '', COOKIE); + assert.match(res.headers.get('content-type') ?? '', /^application\/json/); + assertPreviewHeaders(res); + const bad = await post('/__preview', { entry: 'p-about', token: 'pw_bad' }); + assert.equal(bad.res.status, 403); + assert.equal(bad.res.headers.get('set-cookie'), null); +}); + +test('POST /__preview takes same-origin JSON only, and only a little of it', async () => { + const grant = { entry: 'p-about', token: 'pw_good' }; + const status = async (headers: Record, body: unknown = grant) => + (await post('/__preview', body, { headers })).res.status; + assert.equal(await status({ origin: 'https://evil.example' }), 403); + assert.equal(await status({ origin: 'null' }), 403); + assert.equal(await status({ origin: ADMIN }), 403, 'not even the admin'); + assert.equal(await status({ 'sec-fetch-site': 'cross-site' }), 403); + // No Origin at all (a request no browser page made) is refused too. + const bare = await call('/__preview', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify(grant), + }); + assert.equal(bare.res.status, 403); + assert.equal(await status({ 'content-type': 'text/plain' }), 415); + assert.equal(await status({}, { ...grant, pad: 'x'.repeat(5000) }), 413); + assert.equal(await status({}, '[1]'), 400); + assert.equal(await status({}, '{nope'), 400); +}); + +test('the draft renders under /__preview: uncached, noindex, framable by the admin only', async () => { + const { res, body } = await call('/__preview/about', { cookie: 'cw_preview=p-about~pw_good' }); assert.equal(res.status, 200); assert.equal(res.headers.get('cache-control'), 'private, no-store'); assert.equal(res.headers.get('cache-tag'), null); - assert.match(body, /

About \(draft\)<\/h1>

Unpublished words.<\/p>/); + assertPreviewHeaders(res); + assert.match(res.headers.get('content-security-policy') ?? '', /trusted-types loader cw-preview/); + assert.match(body, /]*>About \(draft\)<\/h1>

Unpublished words.<\/p>/); assert.match(body, //); assert.doesNotMatch(body, /rel="canonical"/); assert.match(body, /class="preview-bar".*href="\/__preview\/exit\?to=%2Fabout"/); }); +test('public pages keep refusing every frame but their own, and keep their Referer policy', async () => { + const { res } = await call('/about'); + const csp = res.headers.get('content-security-policy') ?? ''; + assert.match(csp, /frame-ancestors 'self'/); + assert.doesNotMatch(csp, /example|cw-preview/); + assert.equal(res.headers.get('referrer-policy'), 'strict-origin-when-cross-origin'); +}); + +test('with no admin origin to be found, preview pages can be framed by nobody', async () => { + const env = { + CONTENTWORKER: 'site/main', + CONTENTWORKER_PREVIEW: 'https://preview-host.example', + }; + const { res } = await call('/__preview?entry=p-about', { env }); + assert.match(res.headers.get('content-security-policy') ?? '', /frame-ancestors 'none'/); + const named = await call('/__preview?entry=p-about', { + env: { ...env, CONTENTWORKER_ADMIN: 'https://admin.acme.example' }, + }); + assertPreviewHeaders(named.res, 'https://admin.acme.example'); +}); + test('other paths under /__preview show published content; exit clears the cookie', async () => { - const { body } = await get('/__preview/', { cookie: 'cw_preview=p-about~pw_good' }); + const { body } = await call('/__preview/', { cookie: 'cw_preview=p-about~pw_good' }); assert.match(body, /Content, at the edge/); - const exit = await get('/__preview/exit?to=/about'); + const exit = await call('/__preview/exit?to=/about'); assert.equal(exit.res.headers.get('location'), '/about'); - assert.match(exit.res.headers.get('set-cookie') ?? '', /Max-Age=0/); - assert.equal((await get('/__preview/exit?to=//evil.example')).res.headers.get('location'), '/'); + assert.match(exit.res.headers.get('set-cookie') ?? '', /SameSite=None; Partitioned; Max-Age=0$/); + assert.equal((await call('/__preview/exit?to=//evil.example')).res.headers.get('location'), '/'); +}); + +test('POST anywhere else stays refused', async () => { + assert.equal((await post('/about', {})).res.status, 405); + assert.equal((await post('/__preview/about', {})).res.status, 405); +}); + +test('the gateway stamps its nonce on the handoff script and keeps the preview policy', async () => { + class FakeRewriter { + handler?: { element(el: { setAttribute(k: string, v: string): void }): void }; + on(_selector: string, handler: FakeRewriter['handler']) { + this.handler = handler; + return this; + } + transform(res: Response) { + this.handler?.element({ setAttribute: () => {} }); + return new Response(res.body, res); + } + } + const g = globalThis as { HTMLRewriter?: unknown }; + g.HTMLRewriter = FakeRewriter; + try { + const { res } = await call('/__preview?entry=p-about'); + const csp = res.headers.get('content-security-policy') ?? ''; + assert.match(csp, /^script-src 'nonce-[^']+' 'strict-dynamic' 'self'; /); + assert.match(csp, /frame-ancestors https:\/\/example(;|$)/); + assert.match(csp, /require-trusted-types-for 'script'/); + assert.equal(res.headers.get('referrer-policy'), 'no-referrer'); + } finally { + delete g.HTMLRewriter; + } }); diff --git a/packages/frontend/test/support/preview.ts b/packages/frontend/test/support/preview.ts new file mode 100644 index 0000000..aea78f8 --- /dev/null +++ b/packages/frontend/test/support/preview.ts @@ -0,0 +1,80 @@ +import type { Entry } from '../../src/types.ts'; +import worker, { Site } from '../../src/worker.ts'; +import { about, doc, env, fakeDelivery, inlinePage, p, text, world } from '../fixtures.ts'; + +/** The drafts the fake Preview API serves for token pw_good. */ +export const drafts: Record = { + 'p-about': { + ...about, + fields: { ...about.fields, title: 'About (draft)', body: doc(p(text('Unpublished words.'))) }, + }, + 'p-inline': { ...inlinePage, fields: { ...inlinePage.fields, title: 'Inline (draft)' } }, +}; + +export const SITE = 'https://contentworker.site'; +/** The admin the default backend derives: cdn.example → https://example. */ +export const ADMIN = 'https://example'; + +export interface CallOptions { + method?: string; + cookie?: string; + headers?: Record; + body?: string; + env?: Record; +} + +/** + * One request through the gateway, with the Preview API (any host, /preview/…) and Delivery over the + * fake binding. Records every Preview API call. + */ +export async function call(path: string, options: CallOptions = {}) { + const { method = 'GET', cookie, headers = {}, body } = options; + const realFetch = globalThis.fetch; + const previewCalls: URL[] = []; + globalThis.fetch = async (input) => { + const url = new URL(input instanceof Request ? input.url : String(input)); + if (!url.pathname.startsWith('/preview/')) return realFetch(input); + previewCalls.push(url); + const id = /\/entries\/([^/]+)$/.exec(url.pathname)?.[1] ?? ''; + const draft = drafts[decodeURIComponent(id)]; + const ok = draft && url.searchParams.get('preview_token') === 'pw_good'; + return ok ? Response.json(draft) : new Response('no', { status: 403 }); + }; + try { + const delivery = fakeDelivery(); + const e = env({ + CONTENTWORKER: 'https://cdn.example/site/main', + CONTENTWORKER_DELIVERY: delivery, + ...options.env, + }); + const w = await world(Site, e); + const init: RequestInit = { + method, + headers: { ...(cookie ? { cookie } : {}), ...headers }, + ...(body !== undefined ? { body } : {}), + }; + const res = await worker.fetch(new Request(`${SITE}${path}`, init), e, w.ctx); + const out = res.status === 200 ? await res.text() : ''; + await Promise.all(w.ctx.pending); + return { res, body: out, previewCalls }; + } finally { + globalThis.fetch = realFetch; + } +} + +/** A same-origin JSON POST, as the preview page's scripts send it. */ +export function post(path: string, json: unknown, options: CallOptions = {}) { + return call(path, { + method: 'POST', + ...options, + headers: { + origin: SITE, + 'sec-fetch-site': 'same-origin', + 'content-type': 'application/json', + ...options.headers, + }, + body: typeof json === 'string' ? json : JSON.stringify(json), + }); +} + +export const GRANT = 'cw_preview=p-inline~pw_good'; From dee077cd7063c976d1c71379fb32827ff653751b Mon Sep 17 00:00:00 2001 From: Blake Bauman Date: Sat, 7 Nov 2026 16:25:04 -0700 Subject: [PATCH 2/8] Harden live preview after security and code review Security: - /__preview/exit resolves `to` against the site and allows only a same-origin path (no /\host, tab-split or //host targets). - A ?token= link sets the grant only for a navigation (Sec-Fetch-Dest document or iframe, or absent); subresource loads get a 403. - A derived admin origin is logged once; an admin origin equal to the site's own frames nothing. - The cw-preview Trusted Types policy is allowed only on live pages, and its createHTML passes only the markup a render response brought, once. - nonceCsp handles a header joining several policies. Review: - Re-renders: a newer call aborts an older one, an older response is never drawn, and a superseded call settles only after the newest. - The render endpoint answers all of

when a block swap could be wrong: the first section (it decides the h1), a missing key, or a key on two blocks; the client also refuses ambiguous keys. A block that renders to nothing is removed. - A locale other than the site's is refused with 422. - Grants clear the older unpartitioned SameSite=Lax cookie too; with several grants the matching one wins. - A malformed CONTENTWORKER_ADMIN is normalised or logged and disables framing, instead of failing every render. - Whole-
swaps keep stylesheets in , once. - The overlay's link index keeps the shallowest copy. - Live pages drop the preview bar's exit link (public pages can't load in the admin's frame); link handling stays with the SDK's edit mode. - A golden test holds public renders to origin/main's bytes and headers. Co-Authored-By: Claude Opus 5.5 --- README.md | 11 +- packages/frontend/CHANGELOG.md | 3 + .../frontend/public/scripts/live-preview.js | 126 +++++++++++-- packages/frontend/src/config.ts | 52 ++++-- packages/frontend/src/headers.ts | 18 +- packages/frontend/src/nonce.ts | 31 +++- packages/frontend/src/preview-render.ts | 93 ++++++---- packages/frontend/src/preview.ts | 169 +++++++++++++----- packages/frontend/src/render/document.ts | 9 +- packages/frontend/src/render/page.ts | 1 + packages/frontend/src/worker.ts | 4 +- packages/frontend/test/config.test.ts | 29 ++- .../frontend/test/golden/public-renders.json | 121 +++++++++++++ .../frontend/test/live-preview.dom.test.ts | 148 +++++++++++++++ packages/frontend/test/preview-render.test.ts | 90 +++++++++- packages/frontend/test/preview.test.ts | 87 ++++++++- packages/frontend/test/public-golden.test.ts | 26 +++ packages/frontend/test/runtime.test.ts | 16 ++ packages/frontend/test/support/preview.ts | 13 ++ 19 files changed, 892 insertions(+), 155 deletions(-) create mode 100644 packages/frontend/test/golden/public-renders.json create mode 100644 packages/frontend/test/live-preview.dom.test.ts create mode 100644 packages/frontend/test/public-golden.test.ts diff --git a/README.md b/README.md index ca205ed..14b3fe0 100644 --- a/README.md +++ b/README.md @@ -154,15 +154,18 @@ over a service binding with a bare namespace, set it: "vars": { "CONTENTWORKER_ADMIN": "https://" } ``` -It must be an exact https origin (http only on localhost); without one, preview pages can't be -framed at all. The preview cookie is `SameSite=None; Secure; Partitioned`, so it works inside the -admin's frame and lives only in the admin's partition there. +It must be an https origin (http only on localhost). A value that isn't one is logged and +framing stays off, as it does when no admin can be found or the derived one is the site itself; +public pages are never affected. The preview cookie is `SameSite=None; Secure; Partitioned`, so it +works inside the admin's frame and lives only in the admin's partition there. A preview link sets +it only when opened as a page (top level or in a frame), never as an image or other subresource. Under `/__preview`, the draft's markup also says what is editable: `data-cw-slot` on the element holding a blocks field's blocks, `data-cw-block="<_key>"` on each block, and `data-cw-ref` on the page's own fields. Public pages carry none of it. With `cw_session` on the URL (the admin adds it), the page loads `scripts/live-preview.js`, which re-renders edited blocks through -`POST /__preview/render`. +`POST /__preview/render` in the site's locale (`CONTENTWORKER_LOCALE`), and the preview bar drops +its exit link: the admin has its own controls, and public pages can't load inside its frame. ## Develop diff --git a/packages/frontend/CHANGELOG.md b/packages/frontend/CHANGELOG.md index 67479bf..9fe10c4 100644 --- a/packages/frontend/CHANGELOG.md +++ b/packages/frontend/CHANGELOG.md @@ -22,6 +22,9 @@ Bump `version` in `package.json`, add its section here, merge, then push the tag `POST /__preview/render` re-renders blocks from unsaved fields; `scripts/live-preview.js` (a stub until `@contentworker/sdk/live-preview` is published) loads when the URL has `cw_session`. Public pages are unchanged. +- Grants also clear the unpartitioned `SameSite=Lax` cookie earlier releases set; a preview link + sets the cookie only for a navigation; `/__preview/exit?to=` goes only to a path on the site. +- A malformed `CONTENTWORKER_ADMIN` is logged and turns framing off instead of failing renders. ## 0.3.0 diff --git a/packages/frontend/public/scripts/live-preview.js b/packages/frontend/public/scripts/live-preview.js index 7f82f7a..b49a857 100644 --- a/packages/frontend/public/scripts/live-preview.js +++ b/packages/frontend/public/scripts/live-preview.js @@ -13,7 +13,7 @@ * * import { startLivePreview } from './vendor/live-preview.js'; */ -import { loadCSS, loadSection, loadSections } from './lib.js'; +import { loadSection, loadSections } from './lib.js'; /** * @typedef {Record>} LiveFields @@ -28,22 +28,70 @@ import { loadCSS, loadSection, loadSections } from './lib.js'; /** STUB until the SDK is published (see above). @type {((options: LivePreviewOptions) => LivePreview) | null} */ const startLivePreview = null; -/** The one Trusted Types policy preview pages allow besides the loader's (src/headers.ts). */ +/** The next markup `createHTML` may pass: only what render() took from a render response. */ +let allowed = ''; + +/** + * The Trusted Types policy only live preview pages allow besides the loader's (src/headers.ts). + * It passes exactly the string `fragment` is about to parse, once, and refuses anything else, so + * no other script on the page can use it as a way around Trusted Types. + */ const htmlPolicy = /** @type {Window & { trustedTypes?: { createPolicy(name: string, * rules: { createHTML(html: string): string }): { createHTML(html: string): string } } }} */ ( window ).trustedTypes?.createPolicy('cw-preview', { - // Markup from this origin's own render endpoint, escaped there like every page; nothing else. - createHTML: (html) => html, + createHTML: (html) => { + if (!allowed || html !== allowed) throw new TypeError('cw-preview: render responses only'); + allowed = ''; + return html; + }, }); -/** @param {string} html */ +/** + * Parses markup from this origin's render endpoint (escaped there like every page). + * @param {string} html + */ function fragment(html) { const template = document.createElement('template'); + allowed = html; template.innerHTML = /** @type {string} */ (htmlPolicy ? htmlPolicy.createHTML(html) : html); + allowed = ''; return template.content; } +/** + * Links a stylesheet in once (not inside
, which a re-render may replace), and + * resolves when it has loaded or failed. + * @param {string} href + */ +function headStylesheet(href) { + const selector = `link[rel="stylesheet"][href="${CSS.escape(href)}"]`; + if (document.head.querySelector(selector)) return Promise.resolve(); + return /** @type {Promise} */ ( + new Promise((resolve) => { + const link = document.createElement('link'); + link.rel = 'stylesheet'; + link.href = href; + link.onload = () => resolve(); + link.onerror = () => resolve(); + document.head.append(link); + }) + ); +} + +/** + * Drops stylesheet links already has, so a swapped
doesn't repeat them. + * @param {DocumentFragment} frag + */ +function dropLinked(frag) { + for (const link of frag.querySelectorAll('link[rel="stylesheet"]')) { + const href = link.getAttribute('href'); + if (href && document.head.querySelector(`link[rel="stylesheet"][href="${CSS.escape(href)}"]`)) + link.remove(); + } + return frag; +} + /** * Block keys a patch touched, or null when it moved, added or removed blocks, or changed another * field: then the whole of
is re-rendered. @@ -59,12 +107,45 @@ function touchedKeys(ops) { return [...keys]; } +let latest = 0; +/** @type {Promise} */ +let newest = Promise.resolve(); +/** @type {AbortController | undefined} */ +let inflight; + +/** + * Re-renders the edited fields through the Worker and puts the result on the page. A newer call + * aborts an older one, an older response is never drawn over a newer one, and a superseded call + * settles only when the newest has, so the edit is reported on screen only once it is. + * @param {LiveFields} fields + * @param {LivePreviewUpdate} update + * @returns {Promise} + */ +export function render(fields, update) { + const seq = ++latest; + inflight?.abort(); + const controller = new AbortController(); + inflight = controller; + const stale = () => seq !== latest; + const run = draw(fields, update, controller.signal, stale).then( + () => (stale() ? newest : undefined), + (error) => { + if (stale()) return newest; + throw error; + }, + ); + newest = run; + return run; +} + /** - * Re-renders the edited fields through the Worker and puts the result on the page. * @param {LiveFields} fields * @param {LivePreviewUpdate} update + * @param {AbortSignal} signal + * @param {() => boolean} stale + * @returns {Promise} */ -export async function render(fields, update) { +async function draw(fields, update, signal, stale) { const keys = touchedKeys(update.ops); const res = await fetch('/__preview/render', { method: 'POST', @@ -72,6 +153,7 @@ export async function render(fields, update) { credentials: 'same-origin', // Preview pages send no Referer, which would blank Origin; the Worker checks Origin. referrerPolicy: 'same-origin', + signal, body: JSON.stringify({ entryId: update.entryId, locale: update.locale, @@ -80,22 +162,32 @@ export async function render(fields, update) { }), }); if (!res.ok) throw new Error(`render failed (${res.status})`); - /** @type {{ css: string[], main?: string, blocks?: { key: string, html: string }[], missing?: string[] }} */ + /** @type {{ css: string[], main?: string, blocks?: { key: string, html: string }[] }} */ const out = await res.json(); - await Promise.all(out.css.map((href) => loadCSS(href))); + await Promise.all(out.css.map(headStylesheet)); const main = document.querySelector('main'); - if (!main) return; - // A block the page doesn't show yet: re-render
whole instead. - if (out.missing?.length) return render(fields, { ...update, ops: [] }); + if (stale() || !main) return; if (out.main !== undefined) { - main.replaceChildren(fragment(out.main)); + main.replaceChildren(dropLinked(fragment(out.main))); await loadSections(main); return; } - for (const { key, html } of out.blocks ?? []) { - const el = main.querySelector(`[data-cw-block="${CSS.escape(key)}"]`); - const next = fragment(html).firstElementChild; - if (!el || !(next instanceof HTMLElement)) continue; + const blocks = out.blocks ?? []; + // The server swaps the first block with a key; a page showing a key twice gets
whole. + const targets = blocks.map(({ key }) => + main.querySelectorAll(`[data-cw-block="${CSS.escape(key)}"]`), + ); + if (targets.some((found) => found.length !== 1)) + return draw(fields, { ...update, ops: [] }, signal, stale); + for (const [i, { html }] of blocks.entries()) { + const el = targets[i]?.[0]; + if (!el) continue; + // A block that now renders to nothing leaves the page. + const next = html ? dropLinked(fragment(html)).firstElementChild : null; + if (!(next instanceof HTMLElement)) { + el.remove(); + continue; + } el.replaceWith(next); await loadSection(next); } diff --git a/packages/frontend/src/config.ts b/packages/frontend/src/config.ts index 9624336..d2ae762 100644 --- a/packages/frontend/src/config.ts +++ b/packages/frontend/src/config.ts @@ -105,8 +105,10 @@ export function backend(env: Partial): Backend { /** * The admin origin: CONTENTWORKER_ADMIN, else the domain behind cdn. (the Delivery URL) - * or api. (the Preview API). Only an exact https origin is accepted (http only on - * localhost, as the live preview SDK requires); never a wildcard. + * or api. (the Preview API), which is how ContentWorker deployments lay out their hosts. + * Only an https origin is accepted (http only on localhost, as the live preview SDK requires), + * normalised (lowercase host, default port dropped); never a wildcard. A value that still isn't + * one is logged and disables framing, rather than failing every public render. */ function adminOrigin( explicit: string | undefined, @@ -114,19 +116,45 @@ function adminOrigin( preview: string | null, ): string | null { if (explicit?.trim()) { - const value = explicit.trim().replace(/\/$/, ''); - const origin = previewOrigin(value); - if (!origin || origin !== value || value.includes('*')) - throw new ConfigError( - `CONTENTWORKER_ADMIN must be an exact https origin like https://admin.example.com (http only on localhost), got "${explicit}".`, + const origin = exactOrigin(explicit.trim()); + if (!origin) { + notice( + 'error', + `CONTENTWORKER_ADMIN must be an https origin like https://admin.example.com (http only on localhost), got "${explicit}". Preview pages can't be framed until it is.`, ); + } return origin; } - if (delivery && /^https?:\/\/cdn\./.test(delivery)) - return previewOrigin(delivery.replace('//cdn.', '//')); - if (preview && /^https?:\/\/api\./.test(preview)) - return previewOrigin(preview.replace('//api.', '//')); - return null; + const derived = + delivery && /^https?:\/\/cdn\./.test(delivery) + ? previewOrigin(delivery.replace('//cdn.', '//')) + : preview && /^https?:\/\/api\./.test(preview) + ? previewOrigin(preview.replace('//api.', '//')) + : null; + if (derived) + notice( + 'info', + `Preview pages may be framed by ${derived} (derived from the ContentWorker hosts); set CONTENTWORKER_ADMIN to name the admin explicitly.`, + ); + return derived; +} + +const noticed = new Set(); +/** Logs a configuration notice once per isolate, not once per request. */ +function notice(level: 'info' | 'error', msg: string): void { + if (noticed.has(msg)) return; + noticed.add(msg); + console[level](JSON.stringify({ msg })); +} + +/** An origin with nothing after it (a trailing slash is fine), normalised; or null. */ +function exactOrigin(value: string): string | null { + if (value.includes('*')) return null; + const origin = previewOrigin(value); + if (!origin) return null; + const url = new URL(value); + if (url.username || url.password || url.search || url.hash || url.pathname !== '/') return null; + return origin; } /** The origin of an https URL (or http on localhost), or null. */ diff --git a/packages/frontend/src/headers.ts b/packages/frontend/src/headers.ts index a04824c..0e1fbd3 100644 --- a/packages/frontend/src/headers.ts +++ b/packages/frontend/src/headers.ts @@ -20,23 +20,24 @@ export const CSP = CSP_DIRECTIVES.join('; '); /** * The policy /__preview responses carry instead. Public pages may only be framed by the site * itself; preview pages only by the ContentWorker admin (live preview), never by the site or - * anyone else, and by nobody when the admin origin isn't known. Trusted Types also allows - * `cw-preview`, the policy the live preview script swaps re-rendered blocks in through. + * anyone else, and by nobody when the admin origin isn't known. A live preview page (framed with + * `cw_session`) also allows the Trusted Types policy `cw-preview`, which its script swaps + * re-rendered blocks in through; no other page may create it. */ -export function previewCsp(admin: string | null): string { +export function previewCsp(admin: string | null, live = false): string { return CSP_DIRECTIVES.map((d) => d.startsWith('frame-ancestors ') ? `frame-ancestors ${admin ?? "'none'"}` - : d.startsWith('trusted-types ') + : live && d.startsWith('trusted-types ') ? `${d} cw-preview` : d, ).join('; '); } /** Headers every /__preview response adds: its own CSP, no Referer, never indexed. */ -export function previewHeaders(admin: string | null): Record { +export function previewHeaders(admin: string | null, live = false): Record { return { - 'content-security-policy': previewCsp(admin), + 'content-security-policy': previewCsp(admin, live), 'referrer-policy': 'no-referrer', 'x-robots-tag': 'noindex', }; @@ -62,6 +63,8 @@ export interface HtmlHeaderOptions { preconnect?: string[]; /** The admin origin allowed to frame a preview page (kind 'preview' only). */ admin?: string | null; + /** A live preview page (kind 'preview' with `cw_session`). */ + live?: boolean; } export function htmlHeaders({ @@ -71,11 +74,12 @@ export function htmlHeaders({ codeBase, preconnect = [], admin = null, + live = false, }: HtmlHeaderOptions): Headers { const h = new Headers({ 'content-type': 'text/html; charset=utf-8', ...SECURITY }); if (kind === 'preview') { h.set('cache-control', NO_STORE); - for (const [k, v] of Object.entries(previewHeaders(admin))) h.set(k, v); + for (const [k, v] of Object.entries(previewHeaders(admin, live))) h.set(k, v); } else { h.set('cache-control', BROWSER_HTML); // Edge-only TTL: Workers Caching reads it, browsers never see it. diff --git a/packages/frontend/src/nonce.ts b/packages/frontend/src/nonce.ts index 2490d6d..8b28223 100644 --- a/packages/frontend/src/nonce.ts +++ b/packages/frontend/src/nonce.ts @@ -19,22 +19,35 @@ export function newNonce(): string { * A response's CSP with a nonce: strict-dynamic for CSP3 browsers, 'self' for older ones. Every * page directive stays; one the response sets itself replaces the page's (a preview page's * frame-ancestors and Trusted Types), and `script-src` always becomes the nonce. + * + * A header may join several policies with `,` (each is enforced). The first is merged as above; + * each later one keeps its own directives, with its `script-src`, if it has one, given the same + * nonce, so no policy blocks the scripts this response stamped. */ export function nonceCsp(nonce: string, policy: string = CSP): string { - const own = new Map( + const script = `script-src 'nonce-${nonce}' 'strict-dynamic' 'self'`; + const [first = '', ...others] = policy.split(','); + const own = directives(first); + const names = new Set([...CSP_DIRECTIVES.map(nameOf), ...own.keys()]); + names.delete('script-src'); + const page = new Map(CSP_DIRECTIVES.map((d) => [nameOf(d), d] as const)); + const merged = [script, ...[...names].map((n) => own.get(n) ?? page.get(n) ?? n)].join('; '); + const rest = others + .map((p) => [...directives(p)].map(([n, d]) => (n === 'script-src' ? script : d)).join('; ')) + .filter(Boolean); + return [merged, ...rest].join(', '); +} + +const nameOf = (directive: string): string => directive.split(/\s+/)[0] ?? directive; + +function directives(policy: string): Map { + return new Map( policy .split(';') .map((d) => d.trim()) .filter(Boolean) - .map((d) => [d.split(/\s+/)[0] ?? d, d] as const), + .map((d) => [nameOf(d), d] as const), ); - const names = new Set([...CSP_DIRECTIVES.map((d) => d.split(' ')[0] ?? d), ...own.keys()]); - names.delete('script-src'); - const page = new Map(CSP_DIRECTIVES.map((d) => [d.split(' ')[0] ?? d, d] as const)); - return [ - `script-src 'nonce-${nonce}' 'strict-dynamic' 'self'`, - ...[...names].map((n) => own.get(n) ?? page.get(n) ?? n), - ].join('; '); } const weak = (etag: string | null) => (etag && !etag.startsWith('W/') ? `W/${etag}` : etag); diff --git a/packages/frontend/src/preview-render.ts b/packages/frontend/src/preview-render.ts index 271b86b..224e200 100644 --- a/packages/frontend/src/preview-render.ts +++ b/packages/frontend/src/preview-render.ts @@ -19,8 +19,14 @@ import type { Entry } from './types.ts'; * embeds (an image, a linked entry) is resolved from the draft; any other stays a stub, which * renders as nothing, as on a page. * - * Answers `{ blocks: [{ key, html }], missing: [keys], css: [hrefs] }` for `keys`, or - * `{ main, css }` (all of
) without. `css` is every block stylesheet the HTML needs. + * Answers `{ blocks: [{ key, html }], css: [hrefs] }` for `keys`, or `{ main, css }` (all of + *
) without them, and also whenever swapping single blocks could leave the page wrong: a key + * the fields no longer render (removed, or not there yet), a key on more than one block, or the + * first section (it decides the page's h1 and every heading level after it). A block that renders + * to nothing answers `html: ""`. `css` is every block stylesheet the HTML needs. + * + * `locale`, when given, must be the site's own (CONTENTWORKER_LOCALE): the page renders one + * locale, and its refs and links say which. * * Only for the grant in this browser's preview cookie, and only for that entry: the token is * checked against the Preview API on every call, as a preview page load does. Same-origin POSTs @@ -40,13 +46,15 @@ export interface RenderDeps { url: URL; cw: Backend; site: { origin: string; codeBase: string }; + /** The origin allowed to frame preview responses (preview.ts frameAncestor). */ + admin: string | null; } -const json = (cw: Backend, body: unknown, status = 200): Response => +const json = (admin: string | null, body: unknown, status = 200): Response => new Response(JSON.stringify(body), { status, headers: { - ...textHeaders(previewHeaders(cw.admin)), + ...textHeaders(previewHeaders(admin)), 'content-type': 'application/json; charset=utf-8', }, }); @@ -56,14 +64,15 @@ export async function renderPreviewBlocks({ url, cw, site, + admin, }: RenderDeps): Promise { - const read = await jsonBody(request, url, cw, MAX_RENDER_BYTES); + const read = await jsonBody(request, url, admin, MAX_RENDER_BYTES); if ('refused' in read) return read.refused; const { entryId, fields, locale, keys } = read.body; if (typeof entryId !== 'string' || !isRecord(fields)) - return json(cw, { error: 'Send entryId and fields.' }, 400); + return json(admin, { error: 'Send entryId and fields.' }, 400); if (locale !== undefined && (typeof locale !== 'string' || !locale || FORBIDDEN.has(locale))) - return json(cw, { error: 'locale must be a locale code.' }, 400); + return json(admin, { error: 'locale must be a locale code.' }, 400); if ( keys !== undefined && !( @@ -72,19 +81,21 @@ export async function renderPreviewBlocks({ keys.every((k) => typeof k === 'string' && k && k.length <= MAX_KEY_LENGTH) ) ) - return json(cw, { error: `keys must be at most ${MAX_KEYS} block keys.` }, 400); + return json(admin, { error: `keys must be at most ${MAX_KEYS} block keys.` }, 400); + if (locale !== undefined && locale !== cw.locale) + return json(admin, { error: `This site renders ${cw.locale}; send that locale.` }, 422); - const granted = readCookie(request); + const granted = readCookie(request, entryId); if (!granted || granted.entryId !== entryId) - return json(cw, { error: 'No preview grant for this entry.' }, 403); + return json(admin, { error: 'No preview grant for this entry.' }, 403); const draft = await fetchDraft(cw, granted.entryId, granted.token); - if (!draft) return json(cw, { error: 'This preview has expired.' }, 403); + if (!draft) return json(admin, { error: 'This preview has expired.' }, 403); let entry: Entry; try { entry = overlay(draft, fields, locale); } catch (error) { - if (error instanceof TooLarge) return json(cw, { error: error.message }, 413); + if (error instanceof TooLarge) return json(admin, { error: error.message }, 413); throw error; } const path = pathFor(draft) ?? '/'; @@ -100,24 +111,25 @@ export async function renderPreviewBlocks({ } catch (error) { // A half-edited field a renderer can't take: the page keeps what it shows. console.error(JSON.stringify({ msg: 'preview render failed', error: String(error) })); - return json(cw, { error: 'These fields could not be rendered.' }, 422); + return json(admin, { error: 'These fields could not be rendered.' }, 422); } - if (!Array.isArray(keys)) { - return json(cw, { + const whole = () => + json(admin, { main: parts.map((p) => p.html).join(''), css: [...new Set(parts.flatMap((p) => p.needs))], }); - } - const byKey = new Map(parts.filter((p) => p.key).map((p) => [p.key as string, p])); + if (!Array.isArray(keys)) return whole(); const wanted = [...new Set(keys as string[])]; - const found = wanted.flatMap((key) => { - const part = byKey.get(key); - return part ? [{ key, part }] : []; - }); - return json(cw, { + const found: { key: string; part: MainPart }[] = []; + for (const key of wanted) { + const matches = parts.filter((p) => p.key === key); + const part = matches[0]; + if (!part || matches.length > 1 || part.index === 0) return whole(); + found.push({ key, part }); + } + return json(admin, { blocks: found.map(({ key, part }) => ({ key, html: part.section })), - missing: wanted.filter((k) => !byKey.has(k)), css: [...new Set(found.flatMap(({ part }) => part.needs))], }); } @@ -139,7 +151,7 @@ export function overlay( locale?: string | undefined, ): Entry { const index = new Map(); - collect(draft.fields, index, 0); + collect(draft.fields, index); let nodes = 0; const copy = (value: unknown, depth: number): unknown => { nodes += 1; @@ -173,15 +185,28 @@ function isStub(value: Record): value is { id: string; linkType ); } -/** Every entry and asset the draft embeds, by id. */ -function collect(value: unknown, index: Map, depth: number): void { - if (depth > 12) return; - if (Array.isArray(value)) { - for (const v of value) collect(v, index, depth + 1); - return; +/** + * Every entry and asset the draft embeds, by id, breadth first: when one appears more than once, + * the shallowest copy (the one Delivery resolved furthest) wins. + */ +function collect(root: unknown, index: Map): void { + let level: unknown[] = [root]; + for (let depth = 0; depth <= 12 && level.length; depth += 1) { + const next: unknown[] = []; + for (const value of level) { + if (Array.isArray(value)) { + next.push(...value); + continue; + } + if (!isRecord(value)) continue; + if ( + typeof value.id === 'string' && + (isRecord(value.fields) || typeof value.url === 'string') && + !index.has(value.id) + ) + index.set(value.id, value); + next.push(...Object.values(value)); + } + level = next; } - if (!isRecord(value)) return; - if (typeof value.id === 'string' && (isRecord(value.fields) || typeof value.url === 'string')) - index.set(value.id, value); - for (const v of Object.values(value)) collect(v, index, depth + 1); } diff --git a/packages/frontend/src/preview.ts b/packages/frontend/src/preview.ts index f9e5c5e..6c2e840 100644 --- a/packages/frontend/src/preview.ts +++ b/packages/frontend/src/preview.ts @@ -52,18 +52,34 @@ export async function fetchDraft( return (await res.json()) as Entry; } -export function readCookie(request: Request): { entryId: string; token: string } | null { +/** + * Every preview grant the browser sent. There can be two for a while: the partitioned cookie and + * an older unpartitioned (SameSite=Lax) one from before 0.4, which grants also clear. + */ +export function readCookies(request: Request): { entryId: string; token: string }[] { const raw = request.headers.get('cookie') ?? ''; - const match = raw.split(/;\s*/).find((c) => c.startsWith(`${COOKIE}=`)); - if (!match) return null; - let value: string; - try { - value = decodeURIComponent(match.slice(COOKIE.length + 1)); - } catch { - return null; + const out: { entryId: string; token: string }[] = []; + for (const c of raw.split(/;\s*/)) { + if (!c.startsWith(`${COOKIE}=`)) continue; + let value: string; + try { + value = decodeURIComponent(c.slice(COOKIE.length + 1)); + } catch { + continue; + } + const [entryId, token] = value.split('~'); + if (entryId && token && out.length < 4) out.push({ entryId, token }); } - const [entryId, token] = value.split('~'); - return entryId && token ? { entryId, token } : null; + return out; +} + +/** The grant for `entryId` when one was sent, else the first grant. */ +export function readCookie( + request: Request, + entryId?: string, +): { entryId: string; token: string } | null { + const all = readCookies(request); + return all.find((g) => g.entryId === entryId) ?? all[0] ?? null; } /** @@ -75,20 +91,48 @@ export function readCookie(request: Request): { entryId: string; token: string } const cookie = (value: string, maxAge: number): string => `${COOKIE}=${value}; Path=${PREFIX}; HttpOnly; Secure; SameSite=None; Partitioned; Max-Age=${maxAge}`; +/** Clears the unpartitioned SameSite=Lax cookie releases before 0.4 set. Drop it in a later major. */ +const LEGACY_CLEAR = `${COOKIE}=; Path=${PREFIX}; HttpOnly; Secure; SameSite=Lax; Max-Age=0`; + +/** Set-Cookie headers for a grant (or, with '', for clearing it), legacy cookie cleared first. */ +function setCookies(headers: Headers, value: string, maxAge: number): Headers { + headers.append('set-cookie', LEGACY_CLEAR); + headers.append('set-cookie', cookie(value, maxAge)); + return headers; +} + export interface PreviewDeps { request: Request; url: URL; cw: Backend; /** The site's origin and versioned code base, for the re-render endpoint. */ site: { origin: string; codeBase: string }; - render: (opts: { path: string; preview: PreviewState }) => Promise; + render: (opts: { + path: string; + preview: PreviewState; + /** The origin allowed to frame the page (frameAncestor), or null for nobody. */ + admin: string | null; + }) => Promise; +} + +/** + * The origin preview responses let frame them: the admin, unless that would be the site itself + * (a derived guess that landed on the site's own host), when nobody may. + */ +export function frameAncestor(cw: Backend, url: URL, siteOrigin: string): string | null { + return cw.admin && cw.admin !== url.origin && cw.admin !== siteOrigin ? cw.admin : null; } /** A plain-text answer with the preview headers (framing, Referer, noindex). */ -function text(cw: Backend, body: string, status: number, extra: Record = {}) { +function text( + admin: string | null, + body: string, + status: number, + extra: Record = {}, +) { return new Response(body, { status, - headers: textHeaders({ ...previewHeaders(cw.admin), ...extra }), + headers: textHeaders({ ...previewHeaders(admin), ...extra }), }); } @@ -144,15 +188,15 @@ export async function readCapped(request: Request, max: number): Promise } | { refused: Response }> { if (!fromOwnPages(request, url)) - return { refused: text(cw, 'Cross-origin request refused.', 403) }; + return { refused: text(admin, 'Cross-origin request refused.', 403) }; if (!(request.headers.get('content-type') ?? '').toLowerCase().startsWith('application/json')) - return { refused: text(cw, 'Send application/json.', 415) }; + return { refused: text(admin, 'Send application/json.', 415) }; const raw = await readCapped(request, max); - if (raw === null) return { refused: text(cw, 'Request body too large.', 413) }; + if (raw === null) return { refused: text(admin, 'Request body too large.', 413) }; try { const body: unknown = JSON.parse(raw); if (body && typeof body === 'object' && !Array.isArray(body)) @@ -160,12 +204,13 @@ export async function jsonBody( } catch { // fall through } - return { refused: text(cw, 'Send a JSON object.', 400) }; + return { refused: text(admin, 'Send a JSON object.', 400) }; } /** Checks a token and answers with the grant cookie, either as a redirect or as JSON. */ async function grant( cw: Backend, + admin: string | null, entryId: unknown, token: unknown, session: string | null, @@ -177,22 +222,26 @@ async function grant( !ENTRY_ID.test(entryId) || !TOKEN.test(token) ) - return text(cw, 'Missing entry or token.', 400); + return text(admin, 'Missing entry or token.', 400); const draft = await fetchDraft(cw, entryId, token); - if (!draft) return text(cw, 'This preview link is invalid or has expired.', 403); + if (!draft) return text(admin, 'This preview link is invalid or has expired.', 403); const location = landing(draft, session); - const setCookie = cookie(`${encodeURIComponent(entryId)}~${token}`, MAX_AGE); + const value = `${encodeURIComponent(entryId)}~${token}`; if (as === 'redirect') return new Response(null, { status: 303, - headers: textHeaders({ ...previewHeaders(cw.admin), location, 'set-cookie': setCookie }), + headers: setCookies( + new Headers(textHeaders({ ...previewHeaders(admin), location })), + value, + MAX_AGE, + ), }); + const headers = new Headers({ + ...textHeaders(previewHeaders(admin)), + 'content-type': 'application/json; charset=utf-8', + }); return new Response(JSON.stringify({ location }), { - headers: { - ...textHeaders(previewHeaders(cw.admin)), - 'content-type': 'application/json; charset=utf-8', - 'set-cookie': setCookie, - }, + headers: setCookies(headers, value, MAX_AGE), }); } @@ -206,75 +255,99 @@ export const HANDOFF_SCRIPT = `(()=>{const q=new URLSearchParams(location.search const HANDOFF_PAGE = `Opening preview

Opening the preview…

`; -function handoffPage(cw: Backend): Response { +function handoffPage(admin: string | null): Response { // The gateway's withNonce stamps this response's nonce on the script and into its CSP. return new Response(HANDOFF_PAGE, { headers: { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'private, no-store', 'x-content-type-options': 'nosniff', - ...previewHeaders(cw.admin), + ...previewHeaders(admin), }, }); } +/** + * Whether a GET may set the grant cookie: only a navigation (top level or in a frame). A preview + * link loaded as an image, script or fetch could otherwise plant someone else's grant. + */ +function isNavigation(request: Request): boolean { + const dest = request.headers.get('sec-fetch-dest'); + return !dest || dest === 'document' || dest === 'iframe'; +} + +/** `to` as a path on this site (path, query and fragment), or `/` for anything else. */ +export function samePath(to: string, url: URL): string { + let target: URL; + try { + target = new URL(to, url.origin); + } catch { + return '/'; + } + if (target.origin !== url.origin || target.pathname.startsWith('//')) return '/'; + return `${target.pathname}${target.search}${target.hash}`; +} + export async function handlePreview(deps: PreviewDeps): Promise { const { request, url, cw, render, site } = deps; + const admin = frameAncestor(cw, url, site.origin); if (!cw.preview) return new Response('Preview is not configured (set CONTENTWORKER_PREVIEW).', { status: 404, - headers: textHeaders(previewHeaders(cw.admin)), + headers: textHeaders(previewHeaders(admin)), }); if (request.method === 'POST') { if (url.pathname === PREFIX) { - const read = await jsonBody(request, url, cw, MAX_HANDOFF_BYTES); + const read = await jsonBody(request, url, admin, MAX_HANDOFF_BYTES); if ('refused' in read) return read.refused; const { entry, token, session } = read.body; - return grant(cw, entry, token, sessionOf(session), 'json'); + return grant(cw, admin, entry, token, sessionOf(session), 'json'); } - if (url.pathname === RENDER_PATH) return renderPreviewBlocks({ request, url, cw, site }); - return text(cw, 'Method not allowed', 405, { allow: 'GET, HEAD' }); + if (url.pathname === RENDER_PATH) return renderPreviewBlocks({ request, url, cw, site, admin }); + return text(admin, 'Method not allowed', 405, { allow: 'GET, HEAD' }); } if (url.pathname === PREFIX) { const entryId = url.searchParams.get('entry'); const token = url.searchParams.get('token'); const session = sessionOf(url.searchParams.get(SESSION_PARAM)); - if (token !== null) return grant(cw, entryId, token, session, 'redirect'); - if (!entryId || !ENTRY_ID.test(entryId)) return text(cw, 'Missing entry or token.', 400); - return handoffPage(cw); + if (token !== null) { + if (!isNavigation(request)) return text(admin, 'Open preview links as a page.', 403); + return grant(cw, admin, entryId, token, session, 'redirect'); + } + if (!entryId || !ENTRY_ID.test(entryId)) return text(admin, 'Missing entry or token.', 400); + return handoffPage(admin); } if (url.pathname === `${PREFIX}/exit`) { - const to = url.searchParams.get('to') ?? '/'; - const safe = to.startsWith('/') && !to.startsWith('//') ? to : '/'; + const location = samePath(url.searchParams.get('to') ?? '/', url); return new Response(null, { status: 303, - headers: textHeaders({ - ...previewHeaders(cw.admin), - location: safe, - 'set-cookie': cookie('', 0), - }), + headers: setCookies(new Headers(textHeaders({ ...previewHeaders(admin), location })), '', 0), }); } const sitePath = url.pathname.slice(PREFIX.length) || '/'; const { path } = normalize(new URL(sitePath, url.origin)); - const granted = readCookie(request); let entry: Entry | null = null; - if (granted) { + // At most a couple of grants (a legacy cookie beside the current one): the draft for this path. + for (const granted of readCookies(request).slice(0, 2)) { const draft = await fetchDraft(cw, granted.entryId, granted.token); - if (draft && pathFor(draft) === path) entry = draft; + if (draft && pathFor(draft) === path) { + entry = draft; + break; + } } const session = sessionOf(url.searchParams.get(SESSION_PARAM)); return render({ path, + admin, preview: { entry, path, scope: { space: cw.space, environment: cw.environment, locale: cw.locale }, - live: entry && session && cw.admin ? { admin: cw.admin } : null, + live: entry && session && admin ? { admin } : null, }, }); } diff --git a/packages/frontend/src/render/document.ts b/packages/frontend/src/render/document.ts index fbfca4f..11ff370 100644 --- a/packages/frontend/src/render/document.ts +++ b/packages/frontend/src/render/document.ts @@ -72,7 +72,11 @@ export async function* renderDocument(input: DocumentInput): AsyncGenerator'; - if (preview) { + if (preview?.live) { + // Framed by the admin, which has its own controls: an exit link would load a public page, + // and public pages refuse to be framed. + yield html`
Previewing a draft.
`.value; + } else if (preview) { yield html`
Previewing a draft. Exit preview
` .value; } @@ -113,6 +117,8 @@ export function marksFor(preview: PreviewState | undefined): Marks { export interface MainPart { /** The section's blocks-field `_key`, when it has one. */ key?: string | undefined; + /** The section's index in the entry's sections; undefined for the page's own title. */ + index?: number | undefined; /** Block CSS hrefs this part linked first (its `html` starts with their links). */ css: string[]; /** Every block CSS href the part needs, linked earlier or not. */ @@ -164,6 +170,7 @@ export function* mainParts({ const own = renderSection(section, i, ctx, marks); yield { key: blockKey(section), + index: i, css, needs, section: own.value, diff --git a/packages/frontend/src/render/page.ts b/packages/frontend/src/render/page.ts index b73e4a2..a21ea1a 100644 --- a/packages/frontend/src/render/page.ts +++ b/packages/frontend/src/render/page.ts @@ -115,6 +115,7 @@ export async function renderPage({ codeBase, preconnect: assetOrigins(origin, entry), admin, + live: Boolean(preview?.live), }); const status = notFound ? 404 : 200; diff --git a/packages/frontend/src/worker.ts b/packages/frontend/src/worker.ts index 4a66eb8..35a4222 100644 --- a/packages/frontend/src/worker.ts +++ b/packages/frontend/src/worker.ts @@ -71,7 +71,7 @@ async function route(request: Request, env: SiteEnv, ctx: ExecutionContext): Pro url, cw, site: { origin: env.SITE_ORIGIN || url.origin, codeBase: `/v/${env.BUILD_ID}` }, - render: ({ path, preview }) => + render: ({ path, preview, admin }) => renderPage({ env, ctx, @@ -79,7 +79,7 @@ async function route(request: Request, env: SiteEnv, ctx: ExecutionContext): Pro path, request, preview, - admin: cw.admin, + admin, delivery: createDelivery(cw), }), }); diff --git a/packages/frontend/test/config.test.ts b/packages/frontend/test/config.test.ts index 39772dd..7445cc5 100644 --- a/packages/frontend/test/config.test.ts +++ b/packages/frontend/test/config.test.ts @@ -104,22 +104,33 @@ test('admin origin: derived from cdn. or api., or set; https onl }).admin, 'http://localhost:5173', ); + // Normalised, and a value that still isn't an origin disables framing rather than throwing. + assert.equal( + backend({ + CONTENTWORKER: 'acme/main', + CONTENTWORKER_DELIVERY: binding, + CONTENTWORKER_ADMIN: 'https://Studio.ACME.example:443', + ...k, + }).admin, + 'https://studio.acme.example', + ); for (const bad of [ '*', 'https://*.acme.example', 'http://acme.example', 'https://acme.example/admin', + 'https://acme.example?x', + 'https://u:p@acme.example', 'acme.example', ]) { - assert.throws( - () => - backend({ - CONTENTWORKER: 'acme/main', - CONTENTWORKER_DELIVERY: binding, - CONTENTWORKER_ADMIN: bad, - ...k, - }), - ConfigError, + assert.equal( + backend({ + CONTENTWORKER: 'acme/main', + CONTENTWORKER_DELIVERY: binding, + CONTENTWORKER_ADMIN: bad, + ...k, + }).admin, + null, bad, ); } diff --git a/packages/frontend/test/golden/public-renders.json b/packages/frontend/test/golden/public-renders.json new file mode 100644 index 0000000..93f8284 --- /dev/null +++ b/packages/frontend/test/golden/public-renders.json @@ -0,0 +1,121 @@ +{ + "/": { + "status": 200, + "headers": { + "cache-control": "public, max-age=0, must-revalidate", + "cache-tag": "site,e:p-home,e:b-hero,e:a-hero,e:b-text,e:a-two,e:settings,e:p-docs", + "cloudflare-cdn-cache-control": "public, max-age=86400, stale-while-revalidate=86400, stale-if-error=604800", + "content-security-policy": "script-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'self'; require-trusted-types-for 'script'; trusted-types loader", + "content-type": "text/html; charset=utf-8", + "cross-origin-opener-policy": "same-origin", + "etag": "\"0bde92ea99743ea69986b6e2\"", + "link": "; rel=preload; as=style, ; rel=preconnect", + "permissions-policy": "camera=(), microphone=(), geolocation=(), interest-cohort=()", + "referrer-policy": "strict-origin-when-cross-origin", + "speculation-rules": "\"/v/abc123/speculation-rules.json\"", + "strict-transport-security": "max-age=31536000; includeSubDomains", + "vary": "Accept", + "x-content-type-options": "nosniff" + }, + "body": "\n\nHome \u00b7 ContentWorker\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nSkip to content
\"Alt

Content, at the edge

Lead

Read the getting-started guide

Why <fast>

Second image:

\"Alt

Built on Cloudflare.

\u00a9 YEAR ContentWorker

" + }, + "/about": { + "status": 200, + "headers": { + "cache-control": "public, max-age=0, must-revalidate", + "cache-tag": "site,e:p-about,e:settings,e:p-docs", + "cloudflare-cdn-cache-control": "public, max-age=86400, stale-while-revalidate=86400, stale-if-error=604800", + "content-security-policy": "script-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'self'; require-trusted-types-for 'script'; trusted-types loader", + "content-type": "text/html; charset=utf-8", + "cross-origin-opener-policy": "same-origin", + "etag": "\"53ece77d45c411efe5ed16f1\"", + "link": "; rel=preload; as=style", + "permissions-policy": "camera=(), microphone=(), geolocation=(), interest-cohort=()", + "referrer-policy": "strict-origin-when-cross-origin", + "speculation-rules": "\"/v/abc123/speculation-rules.json\"", + "strict-transport-security": "max-age=31536000; includeSubDomains", + "vary": "Accept", + "x-content-type-options": "nosniff" + }, + "body": "\n\nAbout \u00b7 ContentWorker\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nSkip to content

About

About us, in plain words.

Built on Cloudflare.

\u00a9 YEAR ContentWorker

" + }, + "/blocks": { + "status": 200, + "headers": { + "cache-control": "public, max-age=0, must-revalidate", + "cache-tag": "site,e:p-blocks,e:b-cards,e:a-c1,e:p-about,e:b-cols,e:a-col,e:frag-1,e:b-cta,e:b-faq,e:b-media,e:v-1,e:settings,e:p-docs", + "cloudflare-cdn-cache-control": "public, max-age=86400, stale-while-revalidate=86400, stale-if-error=604800", + "content-security-policy": "script-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'self'; require-trusted-types-for 'script'; trusted-types loader", + "content-type": "text/html; charset=utf-8", + "cross-origin-opener-policy": "same-origin", + "etag": "\"5cdca146325d5559723a4cd3\"", + "link": "; rel=preload; as=style, ; rel=preconnect", + "permissions-policy": "camera=(), microphone=(), geolocation=(), interest-cohort=()", + "referrer-policy": "strict-origin-when-cross-origin", + "speculation-rules": "\"/v/abc123/speculation-rules.json\"", + "strict-transport-security": "max-age=31536000; includeSubDomains", + "vary": "Accept", + "x-content-type-options": "nosniff" + }, + "body": "\n\nBlocks \u00b7 ContentWorker\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nSkip to content

Blocks

Cards

  • \"Alt

    One

    First card

  • Two

    Second card

Left

\"Alt

Start now

Get started

Questions

Is it fast?

Yes, it is served from the edge.

Does it need JS?

No.

Built on Cloudflare.

\u00a9 YEAR ContentWorker

" + }, + "/inline": { + "status": 200, + "headers": { + "cache-control": "public, max-age=0, must-revalidate", + "cache-tag": "site,e:p-inline,e:a-inline,e:settings,e:p-docs", + "cloudflare-cdn-cache-control": "public, max-age=86400, stale-while-revalidate=86400, stale-if-error=604800", + "content-security-policy": "script-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'self'; require-trusted-types-for 'script'; trusted-types loader", + "content-type": "text/html; charset=utf-8", + "cross-origin-opener-policy": "same-origin", + "etag": "\"234efa49f8343305432440cd\"", + "link": "; rel=preload; as=style, ; rel=preconnect", + "permissions-policy": "camera=(), microphone=(), geolocation=(), interest-cohort=()", + "referrer-policy": "strict-origin-when-cross-origin", + "speculation-rules": "\"/v/abc123/speculation-rules.json\"", + "strict-transport-security": "max-age=31536000; includeSubDomains", + "vary": "Accept", + "x-content-type-options": "nosniff" + }, + "body": "\n\nInline \u00b7 ContentWorker\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nSkip to content
\"Alt

Inline hero

Asked

Inline?

Yes.

Built on Cloudflare.

\u00a9 YEAR ContentWorker

" + }, + "/blog": { + "status": 200, + "headers": { + "cache-control": "public, max-age=0, must-revalidate", + "cache-tag": "site,e:list:article:1,e:list:article,e:a-1,e:person-1,e:p-about,e:settings,e:p-docs,type:article", + "cloudflare-cdn-cache-control": "public, max-age=86400, stale-while-revalidate=86400, stale-if-error=604800", + "content-security-policy": "script-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'self'; require-trusted-types-for 'script'; trusted-types loader", + "content-type": "text/html; charset=utf-8", + "cross-origin-opener-policy": "same-origin", + "etag": "\"a4be34ac468ec1d8c96659ea\"", + "link": "; rel=preload; as=style", + "permissions-policy": "camera=(), microphone=(), geolocation=(), interest-cohort=()", + "referrer-policy": "strict-origin-when-cross-origin", + "speculation-rules": "\"/v/abc123/speculation-rules.json\"", + "strict-transport-security": "max-age=31536000; includeSubDomains", + "vary": "Accept", + "x-content-type-options": "nosniff" + }, + "body": "\n\nBlog \u00b7 ContentWorker\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nSkip to content

Blog

Built on Cloudflare.

\u00a9 YEAR ContentWorker

" + }, + "/missing": { + "status": 404, + "headers": { + "cache-control": "public, max-age=0, must-revalidate", + "cache-tag": "site,notfound", + "cloudflare-cdn-cache-control": "public, max-age=300", + "content-security-policy": "script-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'self'; require-trusted-types-for 'script'; trusted-types loader", + "content-type": "text/html; charset=utf-8", + "cross-origin-opener-policy": "same-origin", + "link": "; rel=preload; as=style", + "permissions-policy": "camera=(), microphone=(), geolocation=(), interest-cohort=()", + "referrer-policy": "strict-origin-when-cross-origin", + "speculation-rules": "\"/v/abc123/speculation-rules.json\"", + "strict-transport-security": "max-age=31536000; includeSubDomains", + "vary": "Accept", + "x-content-type-options": "nosniff" + }, + "body": "\n\nPage not found \u00b7 ContentWorker\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nSkip to content

Page not found

The page you asked for isn\u2019t here. It may have moved.

Go to the home page

Built on Cloudflare.

\u00a9 YEAR ContentWorker

" + } +} diff --git a/packages/frontend/test/live-preview.dom.test.ts b/packages/frontend/test/live-preview.dom.test.ts new file mode 100644 index 0000000..5af1be8 --- /dev/null +++ b/packages/frontend/test/live-preview.dom.test.ts @@ -0,0 +1,148 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { JSDOM } from 'jsdom'; + +type Rules = { createHTML(html: string): string }; +type Render = (fields: unknown, update: unknown) => Promise; + +const section = (key: string, text: string) => + `

${text}

`; + +/** + * The live preview script in jsdom, with fetch answered by `answer` (in call order) and a + * Trusted Types stand-in that records the policy the script creates. + */ +async function mount( + main: string, + answer: (body: Record, n: number) => Promise, +) { + const dom = new JSDOM( + `
${main}
`, + ); + const { window } = dom; + let rules: Rules | undefined; + Object.assign(window, { + trustedTypes: { + createPolicy: (_name: string, r: Rules) => { + rules = r; + return r; + }, + }, + }); + const requests: Record[] = []; + Object.assign(globalThis, { + window, + document: window.document, + HTMLElement: window.HTMLElement, + CSS: { escape: (s: string) => s }, + fetch: async (_to: string, init: RequestInit) => { + const body = JSON.parse(String(init.body)); + requests.push(body); + const json = await answer(body, requests.length); + return { ok: true, status: 200, json: async () => json }; + }, + }); + const mod = (await import(`../public/scripts/live-preview.js?${Math.random()}`)) as { + render: Render; + }; + return { window, doc: window.document, render: mod.render, requests, rules: () => rules }; +} + +const update = (ops: unknown[] = []) => ({ + entryId: 'p-inline', + contentType: 'page', + locale: 'en-US', + version: 1, + seq: 1, + ops, +}); +const touch = (key: string) => update([{ op: 'update', key, field: 'sections', locale: 'en-US' }]); + +test('an older response never draws over a newer one, and settles only after it', async () => { + let release: () => void = () => {}; + const slow = new Promise((r) => (release = r)); + const { doc, render } = await mount(section('k-a', 'old'), async (_b, n) => { + if (n === 1) await slow; + return { + blocks: [{ key: 'k-a', html: section('k-a', n === 1 ? 'first' : 'second') }], + css: [], + }; + }); + const order: string[] = []; + const first = render({}, touch('k-a')).then(() => order.push('first')); + const second = render({}, touch('k-a')).then(() => order.push('second')); + await second; + release(); + await first; + assert.match(doc.querySelector('main')?.innerHTML ?? '', /second/); + assert.doesNotMatch(doc.querySelector('main')?.innerHTML ?? '', /first/); + assert.deepEqual(order, ['second', 'first']); +}); + +test('swaps one block, removes a block that renders to nothing, and re-renders
for a duplicate key', async () => { + const { doc, render, requests } = await mount( + section('k-a', 'a') + section('k-b', 'b') + section('k-b', 'b again'), + async (body) => + body.keys + ? { + blocks: (body.keys as string[]).map((key) => ({ + key, + html: key === 'k-a' ? section('k-a', 'A!') : '', + })), + css: [], + } + : { main: section('k-a', 'whole'), css: [] }, + ); + await render({}, touch('k-a')); + assert.match(doc.querySelector('[data-cw-block="k-a"]')?.textContent ?? '', /A!/); + await render({}, touch('k-b')); + assert.equal(requests.at(-1)?.keys, undefined, 'k-b is on the page twice: whole
'); + assert.equal( + doc.querySelector('main')?.innerHTML, + section('k-a', 'whole').replace('initialized', 'loaded'), + ); +}); + +test('a block re-rendered to nothing leaves the page', async () => { + const { doc, render } = await mount(section('k-a', 'a') + section('k-b', 'b'), async () => ({ + blocks: [{ key: 'k-b', html: '' }], + css: [], + })); + await render({}, touch('k-b')); + assert.equal(doc.querySelector('[data-cw-block="k-b"]'), null); + assert.ok(doc.querySelector('[data-cw-block="k-a"]')); +}); + +test('a whole-
swap keeps stylesheets in , once', async () => { + const { doc, render, window } = await mount(section('k-a', 'a'), async () => ({ + main: `${section('k-a', 'x')}${section('k-f', 'f')}`, + css: ['/v/b/blocks/hero/hero.css', '/v/b/blocks/faq/faq.css'], + })); + const done = render({}, update()); + // The new stylesheet goes to ; fire its load so the render can go on. + await new Promise((r) => setTimeout(r, 0)); + for (const link of doc.head.querySelectorAll('link')) + link.dispatchEvent(new window.Event('load')); + await done; + assert.deepEqual( + [...doc.head.querySelectorAll('link')].map((l) => l.getAttribute('href')), + ['/v/b/blocks/hero/hero.css', '/v/b/blocks/faq/faq.css'], + ); + assert.equal(doc.querySelector('main')?.querySelectorAll('link').length, 0); +}); + +test('the cw-preview policy passes only the markup a render response brought', async () => { + const { rules, render } = await mount(section('k-a', 'a'), async () => ({ + blocks: [{ key: 'k-a', html: section('k-a', 'ok') }], + css: [], + })); + const policy = rules(); + assert.ok(policy); + assert.throws(() => policy.createHTML(''), /render responses only/); + await render({}, touch('k-a')); + assert.throws( + () => policy.createHTML(section('k-a', 'ok')), + /render responses only/, + 'used once', + ); +}); diff --git a/packages/frontend/test/preview-render.test.ts b/packages/frontend/test/preview-render.test.ts index 142fa87..7169bc9 100644 --- a/packages/frontend/test/preview-render.test.ts +++ b/packages/frontend/test/preview-render.test.ts @@ -10,13 +10,16 @@ const sections = inline.fields.sections as Record[]; const edited = (heading: string) => sections.map((s) => (s._key === 'k-hero' ? { ...s, heading } : s)); +const faqEdited = (heading: string) => + sections.map((s) => (s._key === 'k-faq' ? { ...s, heading } : s)); + test('re-renders the requested blocks from unsaved fields, escaped like any page', async () => { const { res, body, previewCalls } = await post( RENDER, { entryId: 'p-inline', - fields: { sections: edited('Edited "bold"') }, - keys: ['k-hero', 'k-gone'], + fields: { sections: faqEdited('Edited "bold"') }, + keys: ['k-faq'], }, { cookie: GRANT }, ); @@ -26,21 +29,61 @@ test('re-renders the requested blocks from unsaved fields, escaped like any page assert.equal(res.headers.get('x-robots-tag'), 'noindex'); assert.equal(res.headers.get('cache-tag'), null); const out = JSON.parse(body); + assert.equal(out.main, undefined); assert.equal(out.blocks.length, 1); - assert.equal(out.blocks[0].key, 'k-hero'); + assert.equal(out.blocks[0].key, 'k-faq'); const html: string = out.blocks[0].html; assert.match( html, - /^
/, + /^
/, ); assert.match(html, /Edited <b>"bold"<\/b>/); assert.doesNotMatch(html, //); - assert.deepEqual(out.missing, ['k-gone']); - assert.deepEqual(out.css, ['/v/abc123/blocks/hero/hero.css']); + assert.deepEqual(out.css, ['/v/abc123/blocks/faq/faq.css']); // The grant is checked against the Preview API on every call. assert.equal(previewCalls.length, 1); }); +test('answers all of
when a block swap could leave the page wrong', async () => { + const keysFor = async (keys: string[], fields: Record = {}) => + JSON.parse((await post(RENDER, { entryId: 'p-inline', fields, keys }, { cookie: GRANT })).body); + // The first section decides the h1 and the heading levels after it. + assert.match((await keysFor(['k-hero'], { sections: edited('New') })).main, /New/); + // A key the fields no longer render (removed, or not on the page yet). + assert.ok((await keysFor(['k-gone'])).main); + // A key on two blocks: the server can't know which one the page means. + const twice = [...sections, { ...sections[1] }]; + assert.ok((await keysFor(['k-faq'], { sections: twice })).main); + // A block that renders to nothing answers empty markup, so the page removes it. + const gone = sections.map((s) => (s._key === 'k-faq' ? { ...s, _type: 'nope' } : s)); + assert.deepEqual((await keysFor(['k-faq'], { sections: gone })).blocks, [ + { key: 'k-faq', html: '' }, + ]); +}); + +test("the first block's heading changing keeps exactly one h1", async () => { + const rt = drafts['p-rt']; + assert.ok(rt); + const rtSections = rt.fields.sections as Record[]; + const withHeading = (heading: string) => + rtSections.map((s) => (s._key === 'k-rt' ? { ...s, heading } : s)); + const render = async (heading: string) => { + const { body } = await post( + RENDER, + { entryId: 'p-rt', fields: { sections: withHeading(heading) }, keys: ['k-rt'] }, + { cookie: 'cw_preview=p-rt~pw_good' }, + ); + return JSON.parse(body).main as string; + }; + const cleared = await render(''); + assert.equal((cleared.match(/

]*>Rich \(draft\)<\/h1>/); + const added = await render('Fresh heading'); + assert.equal((added.match(/

]*>Fresh heading<\/h1>/); +}); + test("takes locale-keyed fields (the live preview protocol's), resolving links the draft embeds", async () => { const hero = { ...sections[0], @@ -53,15 +96,32 @@ test("takes locale-keyed fields (the live preview protocol's), resolving links t entryId: 'p-inline', locale: 'en-US', fields: { sections: { 'en-US': [hero], 'de-DE': [] }, title: { 'de-DE': 'Nur Deutsch' } }, - keys: ['k-hero'], }, { cookie: GRANT }, ); - const html: string = JSON.parse(body).blocks[0].html; + const html: string = JSON.parse(body).main; assert.match(html, /Localized/); assert.match(html, /]+a-inline/); }); +test("a locale other than the site's is refused", async () => { + const { res } = await post( + RENDER, + { entryId: 'p-inline', locale: 'de-DE', fields: { title: { 'de-DE': 'Nur Deutsch' } } }, + { cookie: GRANT }, + ); + assert.equal(res.status, 422); +}); + +test('with several grants, the one for the requested entry is used', async () => { + const { res } = await post( + RENDER, + { entryId: 'p-inline', fields: {} }, + { cookie: 'cw_preview=p-about~pw_good; cw_preview=p-inline~pw_good' }, + ); + assert.equal(res.status, 200); +}); + test('without keys, answers all of
and every stylesheet it needs', async () => { const { body } = await post(RENDER, { entryId: 'p-inline', fields: {} }, { cookie: GRANT }); const out = JSON.parse(body); @@ -115,3 +175,17 @@ test('supplied fields are copied, prototype names dropped', () => { linkType: 'Asset', }); }); + +test('a link resolves to the shallowest copy the draft embeds', () => { + const full = { id: 'e-x', contentType: 'cta', fields: { heading: 'Full', more: 'yes' } }; + const shallowLater = { + ...inline, + fields: { + // A deeper, less resolved copy comes first in document order. + deep: [{ nested: { again: { id: 'e-x', contentType: 'cta', fields: { heading: 'Deep' } } } }], + link: full, + }, + }; + const entry = overlay(shallowLater, { pick: { id: 'e-x', linkType: 'Entry' } }); + assert.equal(entry.fields.pick, full); +}); diff --git a/packages/frontend/test/preview.test.ts b/packages/frontend/test/preview.test.ts index 039d221..6fd9b64 100644 --- a/packages/frontend/test/preview.test.ts +++ b/packages/frontend/test/preview.test.ts @@ -4,6 +4,15 @@ import { runInNewContext } from 'node:vm'; import { HANDOFF_SCRIPT } from '../src/preview.ts'; import { ADMIN, call, post } from './support/preview.ts'; +const LEGACY_CLEAR = 'cw_preview=; Path=/__preview; HttpOnly; Secure; SameSite=Lax; Max-Age=0'; +/** A grant: the old unpartitioned cookie cleared first, then the partitioned one set. */ +function assertGrantCookies(res: Response) { + const cookies = res.headers.getSetCookie(); + assert.equal(cookies.length, 2); + assert.equal(cookies[0], LEGACY_CLEAR); + assert.match(cookies[1] ?? '', COOKIE); +} + const COOKIE = /^cw_preview=p-about~pw_good; Path=\/__preview; HttpOnly; Secure; SameSite=None; Partitioned; Max-Age=3600$/; @@ -21,7 +30,7 @@ test('a ?token= link sets a partitioned, framable cookie and redirects to the dr const { res } = await call('/__preview?entry=p-about&token=pw_good'); assert.equal(res.status, 303); assert.equal(res.headers.get('location'), '/__preview/about'); - assert.match(res.headers.get('set-cookie') ?? '', COOKIE); + assertGrantCookies(res); assertPreviewHeaders(res); }); @@ -142,7 +151,7 @@ test('POST /__preview trades a token for the cookie and answers where to go', as }); assert.equal(res.status, 200); assert.deepEqual(JSON.parse(body), { location: '/__preview/about?cw_session=sess_12345678' }); - assert.match(res.headers.get('set-cookie') ?? '', COOKIE); + assertGrantCookies(res); assert.match(res.headers.get('content-type') ?? '', /^application\/json/); assertPreviewHeaders(res); const bad = await post('/__preview', { entry: 'p-about', token: 'pw_bad' }); @@ -177,7 +186,8 @@ test('the draft renders under /__preview: uncached, noindex, framable by the adm assert.equal(res.headers.get('cache-control'), 'private, no-store'); assert.equal(res.headers.get('cache-tag'), null); assertPreviewHeaders(res); - assert.match(res.headers.get('content-security-policy') ?? '', /trusted-types loader cw-preview/); + // Only a live page (cw_session) may create the cw-preview Trusted Types policy. + assert.match(res.headers.get('content-security-policy') ?? '', /trusted-types loader(;|$)/); assert.match(body, /]*>About \(draft\)<\/h1>

Unpublished words.<\/p>/); assert.match(body, //); assert.doesNotMatch(body, /rel="canonical"/); @@ -210,7 +220,9 @@ test('other paths under /__preview show published content; exit clears the cooki assert.match(body, /Content, at the edge/); const exit = await call('/__preview/exit?to=/about'); assert.equal(exit.res.headers.get('location'), '/about'); - assert.match(exit.res.headers.get('set-cookie') ?? '', /SameSite=None; Partitioned; Max-Age=0$/); + const cleared = exit.res.headers.getSetCookie(); + assert.equal(cleared[0], LEGACY_CLEAR); + assert.match(cleared[1] ?? '', /^cw_preview=; .*SameSite=None; Partitioned; Max-Age=0$/); assert.equal((await call('/__preview/exit?to=//evil.example')).res.headers.get('location'), '/'); }); @@ -244,3 +256,70 @@ test('the gateway stamps its nonce on the handoff script and keeps the preview p delete g.HTMLRewriter; } }); + +test('exit only ever goes to a path on this site', async () => { + const to = async (q: string) => + (await call(`/__preview/exit?to=${q}`)).res.headers.get('location'); + assert.equal(await to(encodeURIComponent('/about?x=1#top')), '/about?x=1#top'); + assert.equal(await to('/%5Cevil.example'), '/'); + assert.equal(await to('/%09/evil.example'), '/'); + assert.equal(await to('https://evil.example/'), '/'); + assert.equal(await to('javascript:alert(1)'), '/'); + assert.equal(await to('/.//evil.example'), '/'); +}); + +test('a ?token= link sets the cookie only for a navigation, never a subresource', async () => { + const link = '/__preview?entry=p-about&token=pw_good'; + for (const dest of ['image', 'script', 'empty', 'style']) { + const { res, previewCalls } = await call(link, { headers: { 'sec-fetch-dest': dest } }); + assert.equal(res.status, 403, dest); + assert.deepEqual(res.headers.getSetCookie(), [], dest); + assert.equal(previewCalls.length, 0, dest); + } + for (const dest of ['document', 'iframe']) { + const { res } = await call(link, { headers: { 'sec-fetch-dest': dest } }); + assert.equal(res.status, 303, dest); + assertGrantCookies(res); + } +}); + +test('an admin origin that is the site itself frames nothing', async () => { + const self = await call('/__preview?entry=p-about', { + env: { CONTENTWORKER: 'https://cdn.contentworker.site/site/main' }, + }); + assert.match(self.res.headers.get('content-security-policy') ?? '', /frame-ancestors 'none'/); + const named = await call('/__preview?entry=p-about', { + env: { CONTENTWORKER_ADMIN: 'https://contentworker.site' }, + }); + assert.match(named.res.headers.get('content-security-policy') ?? '', /frame-ancestors 'none'/); +}); + +test('a malformed CONTENTWORKER_ADMIN disables framing instead of breaking pages', async () => { + const env = { CONTENTWORKER_ADMIN: 'not an origin' }; + const page = await call('/about', { env }); + assert.equal(page.res.status, 200); + const preview = await call('/__preview?entry=p-about', { env }); + assert.equal(preview.res.status, 200); + assert.match(preview.res.headers.get('content-security-policy') ?? '', /frame-ancestors 'none'/); + const normalised = await call('/__preview?entry=p-about', { + env: { CONTENTWORKER_ADMIN: 'https://Admin.ACME.example:443/' }, + }); + assertPreviewHeaders(normalised.res, 'https://admin.acme.example'); +}); + +test('with an old unpartitioned grant beside the new one, the draft for the path wins', async () => { + const cookie = 'cw_preview=p-inline~pw_good; cw_preview=p-about~pw_good'; + const { body } = await call('/__preview/about', { cookie }); + assert.match(body, /About \(draft\)/); + const inline = await call('/__preview/inline', { cookie }); + assert.match(inline.body, /data-cw-block="k-hero"/); +}); + +test('a live preview page allows the cw-preview policy and drops the exit link', async () => { + const { res, body } = await call('/__preview/inline?cw_session=sess_12345678', { + cookie: 'cw_preview=p-inline~pw_good', + }); + assert.match(res.headers.get('content-security-policy') ?? '', /trusted-types loader cw-preview/); + assert.match(body, /

Previewing a draft.<\/div>/); + assert.doesNotMatch(body, /__preview\/exit/); +}); diff --git a/packages/frontend/test/public-golden.test.ts b/packages/frontend/test/public-golden.test.ts new file mode 100644 index 0000000..f894e8c --- /dev/null +++ b/packages/frontend/test/public-golden.test.ts @@ -0,0 +1,26 @@ +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { test } from 'node:test'; +import { call } from './support/preview.ts'; + +/** + * Public renders, byte for byte, as the runtime served them before live preview (origin/main at + * fed43ef): status, every header and the body. Preview work must never change a public page. + * The footer's year is the only thing normalised. Regenerate this file only for a deliberate + * public change, and say so in the CHANGELOG. + */ +const golden: Record; body: string }> = + JSON.parse(readFileSync(new URL('./golden/public-renders.json', import.meta.url), 'utf8')); + +for (const [path, want] of Object.entries(golden)) { + test(`public ${path} is byte-identical to the golden render`, async () => { + const { res, body: ok } = await call(path, { + cookie: 'cw_preview=p-inline~pw_good', + env: { CONTENTWORKER: 'site/main', CONTENTWORKER_PREVIEW: undefined }, + }); + assert.equal(res.status, want.status); + assert.deepEqual(Object.fromEntries(res.headers), want.headers); + const body = res.status === 200 ? ok : await res.text(); + assert.equal(body.replace(/© \d{4}/g, '© YEAR'), want.body); + }); +} diff --git a/packages/frontend/test/runtime.test.ts b/packages/frontend/test/runtime.test.ts index 947b4ed..31ec371 100644 --- a/packages/frontend/test/runtime.test.ts +++ b/packages/frontend/test/runtime.test.ts @@ -260,3 +260,19 @@ test('CSP nonce: each HTML response gets its own nonce on every script, a weak E delete g.HTMLRewriter; } }); + +test('nonceCsp: a header joining several policies keeps each, every script-src given the nonce', async () => { + const { nonceCsp } = await import('../src/nonce.ts'); + const { CSP } = await import('../src/headers.ts'); + const out = nonceCsp('n0', `${CSP}, script-src 'self'; img-src 'self', frame-ancestors 'none'`); + const policies = out.split(', '); + assert.equal(policies.length, 3); + assert.equal(policies[0], nonceCsp('n0')); + assert.equal(policies[1], "script-src 'nonce-n0' 'strict-dynamic' 'self'; img-src 'self'"); + assert.equal(policies[2], "frame-ancestors 'none'"); + // One policy: the page's directives stay, a response's own replace them. + assert.equal( + nonceCsp('n0', "script-src 'self'; frame-ancestors https://admin.example"), + nonceCsp('n0').replace("frame-ancestors 'self'", 'frame-ancestors https://admin.example'), + ); +}); diff --git a/packages/frontend/test/support/preview.ts b/packages/frontend/test/support/preview.ts index aea78f8..0578a85 100644 --- a/packages/frontend/test/support/preview.ts +++ b/packages/frontend/test/support/preview.ts @@ -9,6 +9,19 @@ export const drafts: Record = { fields: { ...about.fields, title: 'About (draft)', body: doc(p(text('Unpublished words.'))) }, }, 'p-inline': { ...inlinePage, fields: { ...inlinePage.fields, title: 'Inline (draft)' } }, + /** A blocks page whose first block is default content: its heading decides the page's h1. */ + 'p-rt': { + id: 'p-rt', + contentType: 'page', + fields: { + title: 'Rich (draft)', + slug: 'rt', + sections: [ + { _type: 'richText', _key: 'k-rt', heading: 'Rich heading', body: doc(p(text('Body.'))) }, + { _type: 'cta', _key: 'k-cta', heading: 'Act', body: doc(p(text('Now.'))) }, + ], + }, + }, }; export const SITE = 'https://contentworker.site'; From 43dac2b26ffc015babd540d978be3362462be544 Mon Sep 17 00:00:00 2001 From: Blake Bauman Date: Sat, 7 Nov 2026 16:52:14 -0700 Subject: [PATCH 3/8] Keep live preview sessions browsing inside preview On pages rendered for a live preview session (a valid cw_session and a known admin), every link to one of the site's own pages becomes /__preview/?cw_session=, so clicking around in the admin's frame shows drafts where they exist and published content elsewhere, instead of public pages that refuse to be framed. Only to same-origin http(s) routes is rewritten; external, mailto:, tel:, fragment-only and non-page links (files, Markdown twins) are left alone. Done server-side on the runtime's own escaped markup, so no new JS; re-rendered blocks get the same treatment when the live preview script sends its session. A path with no draft keeps the session and the preview bar (without the exit link) and loads no live script. Public renders are unchanged (golden test). Co-Authored-By: Claude Opus 5.5 --- README.md | 7 +- packages/frontend/CHANGELOG.md | 2 + .../frontend/public/scripts/live-preview.js | 1 + packages/frontend/src/preview-links.ts | 59 ++++++++++ packages/frontend/src/preview-render.ts | 19 +++- packages/frontend/src/preview.ts | 1 + packages/frontend/src/render/document.ts | 14 ++- packages/frontend/src/types.ts | 5 + packages/frontend/test/preview-links.test.ts | 104 ++++++++++++++++++ 9 files changed, 206 insertions(+), 6 deletions(-) create mode 100644 packages/frontend/src/preview-links.ts create mode 100644 packages/frontend/test/preview-links.test.ts diff --git a/README.md b/README.md index 14b3fe0..9c3b11c 100644 --- a/README.md +++ b/README.md @@ -164,8 +164,11 @@ Under `/__preview`, the draft's markup also says what is editable: `data-cw-slot holding a blocks field's blocks, `data-cw-block="<_key>"` on each block, and `data-cw-ref` on the page's own fields. Public pages carry none of it. With `cw_session` on the URL (the admin adds it), the page loads `scripts/live-preview.js`, which re-renders edited blocks through -`POST /__preview/render` in the site's locale (`CONTENTWORKER_LOCALE`), and the preview bar drops -its exit link: the admin has its own controls, and public pages can't load inside its frame. +`POST /__preview/render` in the site's locale (`CONTENTWORKER_LOCALE`). Inside a session, links +to the site's own pages become `/__preview/?cw_session=…`, so browsing in the admin's frame +shows drafts where they exist and published content elsewhere; external, `mailto:`, `tel:` and +fragment links are left alone. The preview bar drops its exit link there: the admin has its own +controls, and public pages can't load inside its frame. ## Develop diff --git a/packages/frontend/CHANGELOG.md b/packages/frontend/CHANGELOG.md index 9fe10c4..e1b64c9 100644 --- a/packages/frontend/CHANGELOG.md +++ b/packages/frontend/CHANGELOG.md @@ -25,6 +25,8 @@ Bump `version` in `package.json`, add its section here, merge, then push the tag - Grants also clear the unpartitioned `SameSite=Lax` cookie earlier releases set; a preview link sets the cookie only for a navigation; `/__preview/exit?to=` goes only to a path on the site. - A malformed `CONTENTWORKER_ADMIN` is logged and turns framing off instead of failing renders. +- In a live preview session, links to the site's pages stay under `/__preview` with the session, + in page renders and in re-rendered blocks. ## 0.3.0 diff --git a/packages/frontend/public/scripts/live-preview.js b/packages/frontend/public/scripts/live-preview.js index b49a857..1589473 100644 --- a/packages/frontend/public/scripts/live-preview.js +++ b/packages/frontend/public/scripts/live-preview.js @@ -157,6 +157,7 @@ async function draw(fields, update, signal, stale) { body: JSON.stringify({ entryId: update.entryId, locale: update.locale, + session: new URL(window.location.href).searchParams.get('cw_session'), fields, ...(keys ? { keys } : {}), }), diff --git a/packages/frontend/src/preview-links.ts b/packages/frontend/src/preview-links.ts new file mode 100644 index 0000000..41a610a --- /dev/null +++ b/packages/frontend/src/preview-links.ts @@ -0,0 +1,59 @@ +import { escapeHtml } from './html.ts'; +import { match, normalize } from './routes.ts'; + +/** + * Keeps a live preview session inside preview. In the admin's frame, a link to a public page + * would load a page that refuses to be framed, so on pages rendered for a session every link to + * one of this site's pages becomes `/__preview/?cw_session=`: the draft where the + * link leads to it, published content (with the preview bar) everywhere else. + * + * Runs on the HTML the runtime itself built (every attribute double-quoted and escaped by + * `html`/`attrs`), and only rewrites ``. Links to other origins, fragment-only links, + * mailto:, tel: and anything that isn't one of the site's routes (files, Markdown twins, feeds) + * are left alone, as is anything already under /__preview. Public pages never come through here. + */ +const ANCHOR_HREF = /(]*?\shref=")([^"]*)(")/g; +const PREFIX = '/__preview'; +export const SESSION_PARAM = 'cw_session'; + +const UNESCAPE: Record = { + '&': '&', + '"': '"', + ''': "'", + '<': '<', + '>': '>', +}; + +/** `href` (as written in the page) rewritten into the session, or null to leave it alone. */ +export function previewHref( + href: string, + { origins, session }: { origins: readonly string[]; session: string }, +): string | null { + if (!href || href.startsWith('#')) return null; + const base = origins[0]; + if (!base) return null; + let url: URL; + try { + url = new URL(href, base); + } catch { + return null; + } + if (!['http:', 'https:'].includes(url.protocol) || !origins.includes(url.origin)) return null; + if (url.pathname === PREFIX || url.pathname.startsWith(`${PREFIX}/`)) return null; + const { path } = normalize(url); + if (!match(path)) return null; + const search = new URLSearchParams(url.search); + search.set(SESSION_PARAM, session); + return `${PREFIX}${path === '/' ? '/' : path}?${search}${url.hash}`; +} + +export function stayInPreview( + html: string, + options: { origins: readonly string[]; session: string }, +): string { + return html.replace(ANCHOR_HREF, (whole, open: string, value: string, close: string) => { + const href = value.replace(/&(amp|quot|#39|lt|gt);/g, (e) => UNESCAPE[e] ?? e); + const next = previewHref(href, options); + return next === null ? whole : `${open}${escapeHtml(next)}${close}`; + }); +} diff --git a/packages/frontend/src/preview-render.ts b/packages/frontend/src/preview-render.ts index 224e200..dc0b896 100644 --- a/packages/frontend/src/preview-render.ts +++ b/packages/frontend/src/preview-render.ts @@ -1,6 +1,7 @@ import type { Backend } from './config.ts'; import { previewHeaders, textHeaders } from './headers.ts'; import { fetchDraft, jsonBody, readCookie } from './preview.ts'; +import { stayInPreview } from './preview-links.ts'; import { createRenderCtx } from './render/block-ctx.ts'; import { type MainPart, mainParts, marksFor } from './render/document.ts'; import { pathFor } from './routes.ts'; @@ -25,6 +26,8 @@ import type { Entry } from './types.ts'; * first section (it decides the page's h1 and every heading level after it). A block that renders * to nothing answers `html: ""`. `css` is every block stylesheet the HTML needs. * + * `session`, the page's `cw_session`, keeps links in the HTML inside the live preview session. + * * `locale`, when given, must be the site's own (CONTENTWORKER_LOCALE): the page renders one * locale, and its refs and links say which. * @@ -68,7 +71,7 @@ export async function renderPreviewBlocks({ }: RenderDeps): Promise { const read = await jsonBody(request, url, admin, MAX_RENDER_BYTES); if ('refused' in read) return read.refused; - const { entryId, fields, locale, keys } = read.body; + const { entryId, fields, locale, keys, session } = read.body; if (typeof entryId !== 'string' || !isRecord(fields)) return json(admin, { error: 'Send entryId and fields.' }, 400); if (locale !== undefined && (typeof locale !== 'string' || !locale || FORBIDDEN.has(locale))) @@ -82,6 +85,8 @@ export async function renderPreviewBlocks({ ) ) return json(admin, { error: `keys must be at most ${MAX_KEYS} block keys.` }, 400); + if (session !== undefined && session !== null && !isSession(session)) + return json(admin, { error: "session must be the page's cw_session." }, 400); if (locale !== undefined && locale !== cw.locale) return json(admin, { error: `This site renders ${cw.locale}; send that locale.` }, 422); @@ -114,9 +119,14 @@ export async function renderPreviewBlocks({ return json(admin, { error: 'These fields could not be rendered.' }, 422); } + // The page's links stay in its live preview session, as the page's own render keeps them. + const links = (h: string) => + typeof session === 'string' && admin + ? stayInPreview(h, { origins: [...new Set([site.origin, url.origin])], session }) + : h; const whole = () => json(admin, { - main: parts.map((p) => p.html).join(''), + main: links(parts.map((p) => p.html).join('')), css: [...new Set(parts.flatMap((p) => p.needs))], }); if (!Array.isArray(keys)) return whole(); @@ -129,13 +139,16 @@ export async function renderPreviewBlocks({ found.push({ key, part }); } return json(admin, { - blocks: found.map(({ key, part }) => ({ key, html: part.section })), + blocks: found.map(({ key, part }) => ({ key, html: links(part.section) })), css: [...new Set(found.flatMap(({ part }) => part.needs))], }); } class TooLarge extends Error {} +const isSession = (value: unknown): value is string => + typeof value === 'string' && /^[A-Za-z0-9_-]{8,128}$/.test(value); + function isRecord(value: unknown): value is Record { return typeof value === 'object' && value !== null && !Array.isArray(value); } diff --git a/packages/frontend/src/preview.ts b/packages/frontend/src/preview.ts index 6c2e840..63e3b2e 100644 --- a/packages/frontend/src/preview.ts +++ b/packages/frontend/src/preview.ts @@ -348,6 +348,7 @@ export async function handlePreview(deps: PreviewDeps): Promise { path, scope: { space: cw.space, environment: cw.environment, locale: cw.locale }, live: entry && session && admin ? { admin } : null, + session: session && admin ? session : null, }, }); } diff --git a/packages/frontend/src/render/document.ts b/packages/frontend/src/render/document.ts index 11ff370..f0f761a 100644 --- a/packages/frontend/src/render/document.ts +++ b/packages/frontend/src/render/document.ts @@ -1,6 +1,7 @@ import { toClassName } from '../../public/scripts/shared.js'; import { type ContentRef, formatContentRef } from '../content-ref.ts'; import { attrs, html, type Safe } from '../html.ts'; +import { stayInPreview } from '../preview-links.ts'; import { blockKey, type Entry, @@ -45,6 +46,17 @@ export interface DocumentInput { } export async function* renderDocument(input: DocumentInput): AsyncGenerator { + const session = input.preview?.session; + if (!session) { + yield* renderPage(input); + return; + } + // Framed for a live preview session: links to the site's pages stay in preview. + const origins = [...new Set([input.origin, input.url.origin])]; + for await (const chunk of renderPage(input)) yield stayInPreview(chunk, { origins, session }); +} + +async function* renderPage(input: DocumentInput): AsyncGenerator { const { entry, settings, menus, url, origin, codeBase, lang, notFound, preview } = input; const ctx = createRenderCtx({ path: url.pathname, origin, ...(menus ? { menus } : {}) }); @@ -72,7 +84,7 @@ export async function* renderDocument(input: DocumentInput): AsyncGenerator'; - if (preview?.live) { + if (preview?.session) { // Framed by the admin, which has its own controls: an exit link would load a public page, // and public pages refuse to be framed. yield html`
Previewing a draft.
`.value; diff --git a/packages/frontend/src/types.ts b/packages/frontend/src/types.ts index 4f19473..369b48e 100644 --- a/packages/frontend/src/types.ts +++ b/packages/frontend/src/types.ts @@ -216,4 +216,9 @@ export interface PreviewState { scope?: { space: string; environment: string; locale: string } | undefined; /** Set when the admin frames the page for a live preview session: the origin it listens to. */ live?: { admin: string } | null | undefined; + /** + * The live preview session (`cw_session`) the admin framed the page with, draft shown or not: + * links to the site's pages carry it and stay under /__preview (src/preview-links.ts). + */ + session?: string | null | undefined; } diff --git a/packages/frontend/test/preview-links.test.ts b/packages/frontend/test/preview-links.test.ts new file mode 100644 index 0000000..c14ead3 --- /dev/null +++ b/packages/frontend/test/preview-links.test.ts @@ -0,0 +1,104 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { previewHref, stayInPreview } from '../src/preview-links.ts'; +import { doc, p, text } from './fixtures.ts'; +import { call, GRANT, post } from './support/preview.ts'; + +const SESSION = 'sess_12345678'; +const options = { origins: ['https://contentworker.site'], session: SESSION }; + +test('same-site page links move into preview, carrying the session', () => { + assert.equal(previewHref('/about', options), `/__preview/about?cw_session=${SESSION}`); + assert.equal(previewHref('/', options), `/__preview/?cw_session=${SESSION}`); + assert.equal( + previewHref('https://contentworker.site/blog?page=2#top', options), + `/__preview/blog?page=2&cw_session=${SESSION}#top`, + ); + // A stale session on the link is replaced by the page's own. + assert.equal( + previewHref('/about?cw_session=other_1234', options), + `/__preview/about?cw_session=${SESSION}`, + ); +}); + +test('everything else is left alone', () => { + for (const href of [ + '#main', + 'mailto:hi@example.com', + 'tel:+15550100', + 'https://elsewhere.example/about', + '//elsewhere.example/about', + 'javascript:alert(1)', + '/__preview/exit?to=%2F', + '/about.md', + '/sitemap.xml', + '/v/abc123/styles/eager.css', + '', + ]) + assert.equal(previewHref(href, options), null, href); +}); + +test('only
is rewritten, re-escaped; other tags and attributes keep their bytes', () => { + const html = + 'Axskipout'; + assert.equal( + stayInPreview(html, options), + `Axskipout`, + ); +}); + +test('a live page keeps browsing inside preview', async () => { + const { body } = await call(`/__preview/inline?cw_session=${SESSION}`, { cookie: GRANT }); + assert.match(body, new RegExp(`Docs`)); + assert.match(body, //); + assert.match(body, /href="#main"/); + // Nothing outside preview is linked from the page's own site. + assert.doesNotMatch(body, /]*\shref="\/(?!__preview\/)[^"]*"/); +}); + +test('a path with no draft shows published content, the bar and the session, without the live script', async () => { + const { res, body } = await call(`/__preview/?cw_session=${SESSION}`, { cookie: GRANT }); + assert.equal(res.status, 200); + assert.match(body, /Content, at the edge/); + assert.match(body, /
Previewing a draft.<\/div>/); + assert.match(body, new RegExp(`href="/__preview/docs\\?cw_session=${SESSION}"`)); + assert.doesNotMatch(body, /live-preview\.js|data-cw-/); + assert.doesNotMatch(res.headers.get('content-security-policy') ?? '', /cw-preview/); +}); + +test('without a session, preview links stay as they were', async () => { + const { body } = await call('/__preview/inline', { cookie: GRANT }); + assert.match(body, /Docs<\/a>/); + assert.match(body, /__preview\/exit/); +}); + +test('re-rendered blocks keep their links in the session', async () => { + const { body } = await post( + '/__preview/render', + { + entryId: 'p-inline', + session: SESSION, + fields: { + sections: [ + { + _type: 'richText', + _key: 'k-l', + body: doc( + p({ nodeType: 'hyperlink', data: { uri: '/about' }, content: [text('About')] }), + ), + }, + ], + }, + }, + { cookie: GRANT }, + ); + const main: string = JSON.parse(body).main; + assert.match(main, new RegExp(`About`)); + assert.doesNotMatch(main, /]*\shref="\/(?!__preview\/)[^"]*"/); + const bad = await post( + '/__preview/render', + { entryId: 'p-inline', fields: {}, session: '' }, + { cookie: GRANT }, + ); + assert.equal(bad.res.status, 400); +}); From 55d5c7d96bed044b292da934f88a8cb2b3ad2ff4 Mon Sep 17 00:00:00 2001 From: Blake Bauman Date: Sat, 7 Nov 2026 18:06:37 -0700 Subject: [PATCH 4/8] Realign live preview to the channel spec ContentWorker's docs/specs/live-preview-channel.md (and the SDK's connectPreview) now govern the page side: - No cw_session: the frontend mints its own channel. The handoff and the landing URL carry no session; the live preview script loads on every /__preview page showing the draft (with a known admin), and connectPreview stays a no-op unless framed. - Links to the site's pages stay under /__preview/ on every preview page, with no session parameter. In a frame (Sec-Fetch-Dest: iframe) the preview bar drops its exit link. - Marks follow the spec's content refs with field paths: data-cw-ref on each block (sections[]) and on fields in it (sections[].heading, through the new ctx.ref(field) that block renderers use), data-cw-slot holding the sections ref (the layout extension). data-cw-block is gone. src/content-ref.ts mirrors the SDK's formatFieldPath/parseFieldPath/blockKeyOf/topLevelField, escaping [, ] and % in keys, tested with the SDK's examples. - POST /__preview/render takes one locale's values (onState's) and block refs, which must name this entry's sections[] blocks in the site's space, environment and locale; it answers { ref, key, html }. - The stub calls connectPreview({ adminOrigin, capabilities, onState }) with select, patch.fields, patch.blocks, proposals, scroll and layout; onState renders view.withProposals, re-rendering only the blocks that changed, and marks view.ghosts with data-cw-ghost, styled by the new preview-only styles/preview.css (own 1 KB budget). - frame-ancestors and the refusal of an admin origin equal to the site's stay as built. Public renders are unchanged (golden test). Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 6 +- README.md | 23 +- docs/budget.md | 3 +- packages/frontend/CHANGELOG.md | 27 +- packages/frontend/budgets.json | 7 +- .../public/blocks/cards/cards.render.ts | 2 +- .../frontend/public/blocks/cta/cta.render.ts | 2 +- .../frontend/public/blocks/faq/faq.render.ts | 2 +- .../public/blocks/hero/hero.render.ts | 2 +- .../frontend/public/scripts/live-preview.js | 249 +++++++++++------- packages/frontend/public/styles/preview.css | 29 ++ packages/frontend/src/content-ref.ts | 86 +++++- packages/frontend/src/headers.ts | 8 +- packages/frontend/src/preview-links.ts | 22 +- packages/frontend/src/preview-render.ts | 115 ++++---- packages/frontend/src/preview.ts | 36 +-- packages/frontend/src/render/block-ctx.ts | 4 + packages/frontend/src/render/blocks.ts | 11 +- packages/frontend/src/render/document.ts | 58 ++-- packages/frontend/src/types.ts | 22 +- packages/frontend/test/content-ref.test.ts | 79 +++++- .../frontend/test/live-preview.dom.test.ts | 198 +++++++++----- packages/frontend/test/preview-links.test.ts | 59 ++--- packages/frontend/test/preview-marks.test.ts | 64 +++-- packages/frontend/test/preview-render.test.ts | 92 ++++++- packages/frontend/test/preview.test.ts | 50 ++-- packages/frontend/test/support/preview.ts | 10 + 27 files changed, 838 insertions(+), 428 deletions(-) create mode 100644 packages/frontend/public/styles/preview.css diff --git a/AGENTS.md b/AGENTS.md index bc2eeff..5c9f294 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -49,9 +49,9 @@ Performance is the top priority: every other requirement yields to it. export is an uncached gateway that must stay cheap (no I/O on the hot path). Anything a page renders from must be in its `Cache-Tag` (`tagsFor`), or a publish won't purge it. Nothing personalised or per-request goes in cached HTML: no nonces, cookies or user data. Drafts live - only under `/__preview`, and so do the editing marks (`data-cw-slot`, `data-cw-block`, - `data-cw-ref`) and `scripts/live-preview.js`: a public render never changes for live preview - (`test/preview-marks.test.ts`). + only under `/__preview`, and so do the editing marks (`data-cw-ref`, `data-cw-slot`, through + `ctx.ref`), `scripts/live-preview.js` and `styles/preview.css`: a public render never changes + for live preview (`test/public-golden.test.ts`, `test/preview-marks.test.ts`). - **The HTML is finished at first byte.** Sections, wrappers, buttons, image attributes and the LCP choice are decided in the Worker. Block JS may add behaviour, elements and attributes; it diff --git a/README.md b/README.md index 9c3b11c..ca2499a 100644 --- a/README.md +++ b/README.md @@ -160,15 +160,20 @@ public pages are never affected. The preview cookie is `SameSite=None; Secure; P works inside the admin's frame and lives only in the admin's partition there. A preview link sets it only when opened as a page (top level or in a frame), never as an image or other subresource. -Under `/__preview`, the draft's markup also says what is editable: `data-cw-slot` on the element -holding a blocks field's blocks, `data-cw-block="<_key>"` on each block, and `data-cw-ref` on the -page's own fields. Public pages carry none of it. With `cw_session` on the URL (the admin adds -it), the page loads `scripts/live-preview.js`, which re-renders edited blocks through -`POST /__preview/render` in the site's locale (`CONTENTWORKER_LOCALE`). Inside a session, links -to the site's own pages become `/__preview/?cw_session=…`, so browsing in the admin's frame -shows drafts where they exist and published content elsewhere; external, `mailto:`, `tel:` and -fragment links are left alone. The preview bar drops its exit link there: the admin has its own -controls, and public pages can't load inside its frame. +Under `/__preview`, the draft's markup says what is editable, in the content-ref format of +`@contentworker/sdk`: `data-cw-ref` on the page's own fields (`title`, `body`), on each block +(`sections[]`) and on fields inside it (`sections[].heading`), and `data-cw-slot` (the +`sections` ref) on the element holding the blocks. Public pages carry none of it. A page showing +the draft also loads `scripts/live-preview.js`, which connects only when the admin frames it, +re-renders edited blocks through `POST /__preview/render` in the site's locale +(`CONTENTWORKER_LOCALE`), and shows Coworker's proposed blocks as ghosts (`styles/preview.css`). + +On every `/__preview` page, links to the site's own pages point to `/__preview/`, so browsing +in the admin's frame shows drafts where they exist and published content elsewhere; external, +`mailto:`, `tel:` and fragment links are left alone. Loaded in a frame, the preview bar drops its +exit link: the admin has its own controls, and public pages can't load inside its frame. Your +own block renderers can mark their fields too: `` adds the field's ref +under preview and nothing on public pages. ## Develop diff --git a/docs/budget.md b/docs/budget.md index 350627b..fce0dc6 100644 --- a/docs/budget.md +++ b/docs/budget.md @@ -9,7 +9,8 @@ budgets keep it there as a site adds blocks. `budgets.json` is enforced by `npm | Eager JS (`lib.js`, `site.js`, `shared.js`) | 10 KB | Modules never block, but they compete with the LCP image. | | Lazy CSS (`lazy.css`, `fonts.css`) | 8 KB | Loaded after the first section. | | Delayed JS | 20 KB | Runs 3 s after `load`; still counts toward TBT on slow phones. | -| Preview JS (`live-preview.js`) | 4 KB | Loads only under `/__preview` with `cw_session`, never on a public page. | +| Preview JS (`live-preview.js`) | 4 KB | Loads only on `/__preview` pages showing a draft, never on a public page. | +| Preview CSS (`preview.css`) | 1 KB | Linked only by the live preview script, once the admin frames the page. | | Each block | 3 KB CSS, 4 KB JS | Blocks add up; a block over this needs a recorded reason. | | HTML document | first 14 KB holds head + first section | One round trip to first paint. | | Requests before LCP | ≤ 5 | Document, eager.css, site.js (+ lib.js preloaded), LCP image, first-section block CSS. | diff --git a/packages/frontend/CHANGELOG.md b/packages/frontend/CHANGELOG.md index e1b64c9..f25884d 100644 --- a/packages/frontend/CHANGELOG.md +++ b/packages/frontend/CHANGELOG.md @@ -14,19 +14,20 @@ Bump `version` in `package.json`, add its section here, merge, then push the tag ## Unreleased - Preview links can carry the token in the fragment (`/__preview?entry={id}#token={token}`), so it - never reaches a log or a `Referer`; `?token=` still works. -- Preview pages are ready to be framed by the ContentWorker admin: `frame-ancestors` names the - admin origin only (derived from `CONTENTWORKER`, or the new optional `CONTENTWORKER_ADMIN`), - `Referrer-Policy: no-referrer`, and the preview cookie is `SameSite=None; Secure; Partitioned`. -- Under `/__preview` only, drafts carry `data-cw-slot`, `data-cw-block` and `data-cw-ref`; - `POST /__preview/render` re-renders blocks from unsaved fields; `scripts/live-preview.js` (a stub - until `@contentworker/sdk/live-preview` is published) loads when the URL has `cw_session`. - Public pages are unchanged. -- Grants also clear the unpartitioned `SameSite=Lax` cookie earlier releases set; a preview link - sets the cookie only for a navigation; `/__preview/exit?to=` goes only to a path on the site. -- A malformed `CONTENTWORKER_ADMIN` is logged and turns framing off instead of failing renders. -- In a live preview session, links to the site's pages stay under `/__preview` with the session, - in page renders and in re-rendered blocks. + never reaches a log or a `Referer`; `?token=` still works, and sets the cookie only for a + navigation. `/__preview/exit?to=` goes only to a path on the site. +- Preview pages are ready to be framed by the ContentWorker admin for live preview: + `frame-ancestors` names the admin origin only (derived from `CONTENTWORKER`, or the new optional + `CONTENTWORKER_ADMIN`; never the site's own origin; a malformed value is logged and turns + framing off), `Referrer-Policy: no-referrer`, and the preview cookie is + `SameSite=None; Secure; Partitioned` (grants also clear the older unpartitioned cookie). +- Under `/__preview` only, drafts carry content refs with field paths (`data-cw-ref` on fields and + blocks, `data-cw-slot` on the blocks' container); block renderers mark their own fields with + `ctx.ref(field)`. `POST /__preview/render` re-renders blocks, named by their refs, from unsaved + fields. Links to the site's pages stay under `/__preview`. +- `scripts/live-preview.js` (calls `connectPreview` from `@contentworker/sdk/live-preview` once it + is published; a stub until then) loads on `/__preview` pages showing a draft, and shows + Coworker's proposals as ghosts (`styles/preview.css`). Public pages are unchanged. ## 0.3.0 diff --git a/packages/frontend/budgets.json b/packages/frontend/budgets.json index b5df9b2..932f83d 100644 --- a/packages/frontend/budgets.json +++ b/packages/frontend/budgets.json @@ -17,10 +17,15 @@ "max": 8192 }, { - "name": "preview JS (only /__preview, live)", + "name": "preview JS (only /__preview drafts)", "files": ["scripts/live-preview.js"], "max": 4096 }, + { + "name": "preview CSS (only /__preview drafts)", + "files": ["styles/preview.css"], + "max": 1024 + }, { "name": "delayed JS", "files": ["scripts/delayed.js", "scripts/consent.js", "scripts/consented.js"], diff --git a/packages/frontend/public/blocks/cards/cards.render.ts b/packages/frontend/public/blocks/cards/cards.render.ts index f56742f..95f9310 100644 --- a/packages/frontend/public/blocks/cards/cards.render.ts +++ b/packages/frontend/public/blocks/cards/cards.render.ts @@ -33,7 +33,7 @@ export default function render(entry: Entry, ctx: RenderCtx): Safe { title ? ctx.raw(`<${itemLevel}>${title}`) : '' }${item.body ? ctx.richText(item.body) : ''}
`; }); - return html`${heading ? ctx.raw(`<${level}>${html`${heading}`}`) : ''}
    ${cards}
`; + return html`${heading ? ctx.raw(`<${level}${ctx.ref('heading')}>${html`${heading}`}`) : ''}
    ${cards}
`; } export function markdown(entry: Entry, ctx: MarkdownCtx): string { diff --git a/packages/frontend/public/blocks/cta/cta.render.ts b/packages/frontend/public/blocks/cta/cta.render.ts index e0021f7..1727275 100644 --- a/packages/frontend/public/blocks/cta/cta.render.ts +++ b/packages/frontend/public/blocks/cta/cta.render.ts @@ -17,7 +17,7 @@ export default function render(entry: Entry, ctx: RenderCtx): Safe { const href = ctx.href(link ?? url); const v = VARIANTS.has(variant) ? variant : 'accent'; ctx.headingLevel = 2; - return html`
${heading ? html`

${heading}

` : ''}${body ? ctx.richText(body) : ''}${ + return html`
${heading ? html`${heading}

` : ''}${body ? ctx.richText(body) : ''}${ href && label ? html`

${label}

` : '' diff --git a/packages/frontend/public/blocks/faq/faq.render.ts b/packages/frontend/public/blocks/faq/faq.render.ts index 8801884..2303526 100644 --- a/packages/frontend/public/blocks/faq/faq.render.ts +++ b/packages/frontend/public/blocks/faq/faq.render.ts @@ -25,7 +25,7 @@ export default function render(entry: Entry, ctx: RenderCtx): Safe { const level = `h${n}`; const itemLevel = `h${heading ? n + 1 : Math.max(n, 2)}`; if (heading && n === 1) ctx.headingLevel = 2; - return html`${heading ? ctx.raw(`<${level}>${html`${heading}`}`) : ''}${itemsOf( + return html`${heading ? ctx.raw(`<${level}${ctx.ref('heading')}>${html`${heading}`}`) : ''}${itemsOf( entry, ).map( (i: Fields) => diff --git a/packages/frontend/public/blocks/hero/hero.render.ts b/packages/frontend/public/blocks/hero/hero.render.ts index 2c466af..b521932 100644 --- a/packages/frontend/public/blocks/hero/hero.render.ts +++ b/packages/frontend/public/blocks/hero/hero.render.ts @@ -18,6 +18,6 @@ export default function render(entry: Entry, ctx: RenderCtx): Safe { const Heading = ctx.headingLevel === 1 ? 'h1' : 'h2'; ctx.headingLevel = 2; return html`${image ? html`${ctx.image(image, { sizes: '100vw' })}` : ''}
${ctx.raw( - `<${Heading}>`, + `<${Heading}${ctx.ref('heading')}>`, )}${heading}${ctx.raw(``)}${lead ? ctx.richText(lead) : ''}
`; } diff --git a/packages/frontend/public/scripts/live-preview.js b/packages/frontend/public/scripts/live-preview.js index 1589473..ab302dc 100644 --- a/packages/frontend/public/scripts/live-preview.js +++ b/packages/frontend/public/scripts/live-preview.js @@ -1,41 +1,38 @@ /** - * Live preview, the page side. Loaded only under /__preview, for the draft, when the admin frames - * the page with `cw_session` on its URL (src/render/document.ts); public pages never load it. + * Live preview, the page side. Loaded only on /__preview pages showing a draft; connects only + * when the admin frames the page. `onState` re-renders through POST /__preview/render and swaps + * blocks by their `data-cw-ref`; `view.ghosts` get `data-cw-ghost` (styles/preview.css). * - * The admin holds the unsaved fields and sends edits by postMessage; `startLivePreview` from - * `@contentworker/sdk/live-preview` applies them and calls `onChange`, which asks the Worker to - * re-render with the edited fields (POST /__preview/render) and swaps the result in by - * `data-cw-block`. The Worker renders with the same block renderers and escaping as any page. - * - * STUB: the SDK isn't published yet, so `startLivePreview` below is null and nothing starts. Once - * it is, serve its browser build next to this file (no bundler: the served file is the source) - * and replace the stub with: - * - * import { startLivePreview } from './vendor/live-preview.js'; + * STUB: `connectPreview` is null until @contentworker/sdk/live-preview is published. Then serve + * its browser build beside this file and use `import { connectPreview } from './vendor/live-preview.js'`. */ import { loadSection, loadSections } from './lib.js'; /** - * @typedef {Record>} LiveFields - * @typedef {{ op: string, key?: string, field: string }} LivePatchOp - * @typedef {{ entryId: string, contentType: string, locale: string, version: number, - * seq: number, ops: readonly LivePatchOp[] }} LivePreviewUpdate - * @typedef {{ adminOrigin: string, - * onChange: (fields: LiveFields, update: LivePreviewUpdate) => void | Promise }} LivePreviewOptions - * @typedef {{ readonly active: boolean, refresh(): void, destroy(): void }} LivePreview + * The shapes of `@contentworker/sdk/live-preview` that this file uses. + * @typedef {'select' | 'patch.fields' | 'patch.blocks' | 'proposals' | 'scroll' | 'layout'} Capability + * @typedef {Record} LiveFields + * @typedef {{ readonly rev: number, readonly withProposals: LiveFields, readonly ghosts: { + * readonly inserted: readonly string[], readonly changed: readonly string[], + * readonly removed: readonly string[] } }} LiveView + * @typedef {{ readonly adminOrigin?: string, readonly capabilities: readonly Capability[], + * readonly onState: (entryId: string, locale: string, fields: LiveFields, view: LiveView) => + * void | Promise }} ConnectPreviewOptions + * @typedef {{ readonly active: boolean, readonly connected: boolean, + * on(kind: 'connect', handler: () => void): () => void, + * emit(kind: 'page', body: { url: string, entries: { entryId: string, contentType: string, + * locale: string }[] }): void, refresh(): void, close(): void }} PreviewConnection */ -/** STUB until the SDK is published (see above). @type {((options: LivePreviewOptions) => LivePreview) | null} */ -const startLivePreview = null; +/** STUB until the SDK is published (see above). @type {((options: ConnectPreviewOptions) => PreviewConnection) | null} */ +const connectPreview = null; -/** The next markup `createHTML` may pass: only what render() took from a render response. */ +/** @type {Capability[]} */ +const CAPABILITIES = ['select', 'patch.fields', 'patch.blocks', 'proposals', 'scroll', 'layout']; + +/** The one string `cw-preview` will pass next: a render response's markup, once. */ let allowed = ''; -/** - * The Trusted Types policy only live preview pages allow besides the loader's (src/headers.ts). - * It passes exactly the string `fragment` is about to parse, once, and refuses anything else, so - * no other script on the page can use it as a way around Trusted Types. - */ const htmlPolicy = /** @type {Window & { trustedTypes?: { createPolicy(name: string, * rules: { createHTML(html: string): string }): { createHTML(html: string): string } } }} */ ( window @@ -47,10 +44,7 @@ const htmlPolicy = /** @type {Window & { trustedTypes?: { createPolicy(name: str }, }); -/** - * Parses markup from this origin's render endpoint (escaped there like every page). - * @param {string} html - */ +/** @param {string} html markup from this origin's render endpoint */ function fragment(html) { const template = document.createElement('template'); allowed = html; @@ -59,14 +53,12 @@ function fragment(html) { return template.content; } -/** - * Links a stylesheet in once (not inside
, which a re-render may replace), and - * resolves when it has loaded or failed. - * @param {string} href - */ +/** @param {string} href */ +const linkSelector = (href) => `link[rel="stylesheet"][href="${CSS.escape(href)}"]`; + +/** Links a stylesheet in once (never in
, which a re-render replaces). @param {string} href */ function headStylesheet(href) { - const selector = `link[rel="stylesheet"][href="${CSS.escape(href)}"]`; - if (document.head.querySelector(selector)) return Promise.resolve(); + if (document.head.querySelector(linkSelector(href))) return Promise.resolve(); return /** @type {Promise} */ ( new Promise((resolve) => { const link = document.createElement('link'); @@ -79,32 +71,79 @@ function headStylesheet(href) { ); } -/** - * Drops stylesheet links already has, so a swapped
doesn't repeat them. - * @param {DocumentFragment} frag - */ +/** Drops stylesheet links already has. @param {DocumentFragment} frag */ function dropLinked(frag) { for (const link of frag.querySelectorAll('link[rel="stylesheet"]')) { const href = link.getAttribute('href'); - if (href && document.head.querySelector(`link[rel="stylesheet"][href="${CSS.escape(href)}"]`)) - link.remove(); + if (href && document.head.querySelector(linkSelector(href))) link.remove(); } return frag; } +/** The `_key` a `sections[]` ref names, escapes undone, else undefined. @param {string | null} ref */ +export function blockKeyOfRef(ref) { + const parts = (ref ?? '').split('|'); + if (parts.length !== 6) return undefined; + let field; + try { + field = decodeURIComponent(parts[4] ?? ''); + } catch { + return undefined; + } + const m = /^sections\[([^[\]]+)\]$/.exec(field); + return m?.[1]?.replace(/%5B/gi, '[').replace(/%5D/gi, ']').replace(/%25/g, '%'); +} + +/** Block elements by key (every element, so a caller can refuse to guess). @param {ParentNode} root */ +function blocksOn(root) { + /** @type {Map} */ + const out = new Map(); + for (const el of root.querySelectorAll('[data-cw-ref]')) { + const ref = el.getAttribute('data-cw-ref') ?? ''; + const key = blockKeyOfRef(ref); + if (key) out.set(key, [...(out.get(key) ?? []), { el, ref }]); + } + return out; +} + +/** @param {unknown} a @param {unknown} b */ +const same = (a, b) => JSON.stringify(a) === JSON.stringify(b); + /** - * Block keys a patch touched, or null when it moved, added or removed blocks, or changed another - * field: then the whole of
is re-rendered. - * @param {readonly LivePatchOp[]} ops + * Refs of the blocks to re-render, or null for all of
(another field, or the blocks or + * their order changed). @param {LiveFields | undefined} before @param {LiveFields} after */ -function touchedKeys(ops) { - if (!ops.length) return null; - const keys = new Set(); - for (const op of ops) { - if (op.op !== 'update' || !op.key || op.field !== 'sections') return null; - keys.add(op.key); +function changedBlocks(before, after) { + if (!before) return null; + const { sections: was, ...restWas } = before; + const { sections: now, ...restNow } = after; + if (!same(restWas, restNow) || !Array.isArray(was) || !Array.isArray(now)) return null; + /** @param {unknown} b */ + const keyOf = (b) => /** @type {{ _key?: unknown }} */ (b)?._key; + if (!same(was.map(keyOf), now.map(keyOf))) return null; + const keys = now.filter((b, i) => !same(b, was[i])).map(keyOf); + if (keys.some((k) => typeof k !== 'string')) return null; + const onPage = blocksOn(document); + /** @type {string[]} */ + const refs = []; + for (const key of /** @type {string[]} */ (keys)) { + const found = onPage.get(key); + if (found?.length !== 1 || !found[0]) return null; + refs.push(found[0].ref); + } + return refs; +} + +/** @param {LiveView['ghosts']} ghosts */ +function markGhosts(ghosts) { + for (const el of document.querySelectorAll('[data-cw-ghost]')) + el.removeAttribute('data-cw-ghost'); + const onPage = blocksOn(document); + for (const kind of /** @type {const} */ (['inserted', 'changed', 'removed'])) { + for (const key of ghosts[kind]) { + for (const { el } of onPage.get(key) ?? []) el.setAttribute('data-cw-ghost', kind); + } } - return [...keys]; } let latest = 0; @@ -112,22 +151,25 @@ let latest = 0; let newest = Promise.resolve(); /** @type {AbortController | undefined} */ let inflight; +/** The fields last put on screen. @type {LiveFields | undefined} */ +let shown; /** - * Re-renders the edited fields through the Worker and puts the result on the page. A newer call - * aborts an older one, an older response is never drawn over a newer one, and a superseded call - * settles only when the newest has, so the edit is reported on screen only once it is. - * @param {LiveFields} fields - * @param {LivePreviewUpdate} update + * `onState`. A newer call aborts an older one, which is never drawn and settles only after the + * newest, so `applied` means on screen. + * @param {string} entryId + * @param {string} locale + * @param {LiveFields} _fields + * @param {LiveView} view * @returns {Promise} */ -export function render(fields, update) { +export function onState(entryId, locale, _fields, view) { const seq = ++latest; inflight?.abort(); const controller = new AbortController(); inflight = controller; const stale = () => seq !== latest; - const run = draw(fields, update, controller.signal, stale).then( + const run = draw(entryId, locale, view, controller.signal, stale).then( () => (stale() ? newest : undefined), (error) => { if (stale()) return newest; @@ -139,14 +181,22 @@ export function render(fields, update) { } /** - * @param {LiveFields} fields - * @param {LivePreviewUpdate} update + * @param {string} entryId + * @param {string} locale + * @param {LiveView} view * @param {AbortSignal} signal * @param {() => boolean} stale + * @param {boolean} [whole] * @returns {Promise} */ -async function draw(fields, update, signal, stale) { - const keys = touchedKeys(update.ops); +async function draw(entryId, locale, view, signal, stale, whole = false) { + const fields = view.withProposals; + const refs = whole ? null : changedBlocks(shown, fields); + if (refs && refs.length === 0) { + markGhosts(view.ghosts); + shown = fields; + return; + } const res = await fetch('/__preview/render', { method: 'POST', headers: { 'content-type': 'application/json' }, @@ -154,13 +204,7 @@ async function draw(fields, update, signal, stale) { // Preview pages send no Referer, which would blank Origin; the Worker checks Origin. referrerPolicy: 'same-origin', signal, - body: JSON.stringify({ - entryId: update.entryId, - locale: update.locale, - session: new URL(window.location.href).searchParams.get('cw_session'), - fields, - ...(keys ? { keys } : {}), - }), + body: JSON.stringify({ entryId, locale, fields, ...(refs ? { refs } : {}) }), }); if (!res.ok) throw new Error(`render failed (${res.status})`); /** @type {{ css: string[], main?: string, blocks?: { key: string, html: string }[] }} */ @@ -171,33 +215,50 @@ async function draw(fields, update, signal, stale) { if (out.main !== undefined) { main.replaceChildren(dropLinked(fragment(out.main))); await loadSections(main); - return; - } - const blocks = out.blocks ?? []; - // The server swaps the first block with a key; a page showing a key twice gets
whole. - const targets = blocks.map(({ key }) => - main.querySelectorAll(`[data-cw-block="${CSS.escape(key)}"]`), - ); - if (targets.some((found) => found.length !== 1)) - return draw(fields, { ...update, ops: [] }, signal, stale); - for (const [i, { html }] of blocks.entries()) { - const el = targets[i]?.[0]; - if (!el) continue; - // A block that now renders to nothing leaves the page. - const next = html ? dropLinked(fragment(html)).firstElementChild : null; - if (!(next instanceof HTMLElement)) { - el.remove(); - continue; + } else { + const onPage = blocksOn(main); + for (const { key, html } of out.blocks ?? []) { + const found = onPage.get(key); + if (found?.length !== 1 || !found[0]) return draw(entryId, locale, view, signal, stale, true); + // A block that now renders to nothing leaves the page. + const next = html ? dropLinked(fragment(html)).firstElementChild : null; + if (!(next instanceof HTMLElement)) { + found[0].el.remove(); + continue; + } + found[0].el.replaceWith(next); + await loadSection(next); } - el.replaceWith(next); - await loadSection(next); } + markGhosts(view.ghosts); + shown = fields; } const adminOrigin = document.querySelector('meta[name="cw-admin-origin"]')?.getAttribute('content'); -if (adminOrigin && startLivePreview) { - /** @type {(options: LivePreviewOptions) => LivePreview} */ (startLivePreview)({ +const entryMeta = document.querySelector('meta[name="cw-entry"]'); +const entry = { + entryId: entryMeta?.getAttribute('content') ?? '', + contentType: entryMeta?.getAttribute('data-content-type') ?? '', + locale: entryMeta?.getAttribute('data-locale') ?? '', +}; +if (adminOrigin && entry.entryId && connectPreview) { + const preview = /** @type {(options: ConnectPreviewOptions) => PreviewConnection} */ ( + connectPreview + )({ adminOrigin, - onChange: render, + capabilities: CAPABILITIES, + onState(entryId, locale, fields, view) { + if (entryId !== entry.entryId) return; + return onState(entryId, locale, fields, view); + }, }); + if (preview.active) { + const link = document.createElement('link'); + link.rel = 'stylesheet'; + link.href = new URL('../styles/preview.css', import.meta.url).pathname; + document.head.append(link); + preview.on('connect', () => + preview.emit('page', { url: window.location.href, entries: [entry] }), + ); + } } diff --git a/packages/frontend/public/styles/preview.css b/packages/frontend/public/styles/preview.css new file mode 100644 index 0000000..737d60f --- /dev/null +++ b/packages/frontend/public/styles/preview.css @@ -0,0 +1,29 @@ +/* + * Live preview only: linked by scripts/live-preview.js once the admin frames a /__preview page. + * Coworker's proposed blocks (data-cw-ghost) look provisional, so an editor can tell a proposal + * from their own change. Outlines and opacity only: nothing here moves or resizes a block. + */ +:root { + --ghost-color: var(--link-color); + --ghost-removed-color: #b42318; +} + +[data-cw-ghost] { + outline: 2px dashed var(--ghost-color); + outline-offset: -2px; +} + +[data-cw-ghost="inserted"] { + opacity: 0.7; +} + +[data-cw-ghost="removed"] { + outline-color: var(--ghost-removed-color); + opacity: 0.45; +} + +@media (prefers-reduced-transparency: reduce) { + [data-cw-ghost] { + opacity: 1; + } +} diff --git a/packages/frontend/src/content-ref.ts b/packages/frontend/src/content-ref.ts index 43fa2cf..b3cdece 100644 --- a/packages/frontend/src/content-ref.ts +++ b/packages/frontend/src/content-ref.ts @@ -1,10 +1,12 @@ /** * Content refs: the identity of one editable value on a rendered page, stamped as `data-cw-ref` - * on preview renders so the admin can map a click back to the field it came from. + * on preview renders so the admin can map a click back to the field or block it came from. * - * The same format as `formatContentRef` in `@contentworker/sdk`: six parts (space, environment, - * entry id, content type, field apiId, locale), each URI-encoded and joined with `|`. Encoding each - * part means a part containing `|` can't forge a boundary and shift the parts after it. Kept here + * The same format as `@contentworker/sdk`'s content refs (docs/specs/live-preview-channel.md, + * "Content refs inside blocks"): six parts (space, environment, entry id, content type, field + * path, locale), each URI-encoded and joined with `|`, so a part containing `|` can't forge a + * boundary. The field part is a path: `title`, `sections[]` for a block, and + * `sections[].heading` for a field in it, with a key's `[`, `]` and `%` escaped. Kept here * rather than imported so the Worker doesn't pull the SDK's client into its bundle; the tests hold * it to the SDK's examples. */ @@ -14,11 +16,85 @@ export interface ContentRef { readonly environment: string; readonly entryId: string; readonly contentType: string; - /** apiId of the field, e.g. `title`. */ + /** The field's path: `title`, or `sections[]` and `sections[].heading` in blocks. */ readonly field: string; readonly locale: string; } +/** One step of a field path below its top-level field: into a block by key, or a field by name. */ +export type FieldPathStep = { readonly key: string } | { readonly field: string }; + +/** A field path, parsed: the entry's top-level field, then each step down. */ +export interface FieldPath { + readonly field: string; + readonly steps: readonly FieldPathStep[]; +} + +const NAME = /^[^.[\]]+$/; + +/** A key as a path holds it: `%` first, so an escape can't be forged, then `[` and `]`. */ +const escapeKey = (key: string): string => + key.replace(/%/g, '%25').replace(/\[/g, '%5B').replace(/\]/g, '%5D'); +const unescapeKey = (key: string): string => + key.replace(/%5B/gi, '[').replace(/%5D/gi, ']').replace(/%25/g, '%'); + +/** + * `body`, `body[k1]`, `body[k1].heading`, `body[k1].items[k2].label`. Throws on an empty key, or + * a field name holding `.`, `[` or `]` (an apiId never does). + */ +export function formatFieldPath(path: FieldPath): string { + if (!NAME.test(path.field)) throw new Error(`Not a field name: ${path.field}`); + let out = path.field; + for (const step of path.steps) { + if ('key' in step) { + if (step.key === '') throw new Error('A block key is never empty'); + out += `[${escapeKey(step.key)}]`; + } else { + if (!NAME.test(step.field)) throw new Error(`Not a field name: ${step.field}`); + out += `.${step.field}`; + } + } + return out; +} + +/** Parses a ref's field part; undefined when it isn't a path. A plain apiId has no steps. */ +export function parseFieldPath(value: string): FieldPath | undefined { + const head = /^[^.[\]]+/.exec(value); + if (!head) return undefined; + const steps: FieldPathStep[] = []; + let rest = value.slice(head[0].length); + let last: 'field' | 'key' = 'field'; + while (rest !== '') { + const block = /^\[([^[\]]+)\]/.exec(rest); + const field = /^\.([^.[\]]+)/.exec(rest); + if (block && last === 'field') { + steps.push({ key: unescapeKey(block[1] as string) }); + last = 'key'; + rest = rest.slice(block[0].length); + } else if (field && last === 'key') { + steps.push({ field: field[1] as string }); + last = 'field'; + rest = rest.slice(field[0].length); + } else { + return undefined; + } + } + return { field: head[0], steps }; +} + +/** The top-level field a path is in: everything before the first `[`. */ +export function topLevelField(path: string): string { + const bracket = path.indexOf('['); + return bracket < 0 ? path : path.slice(0, bracket); +} + +/** The `_key` of the block a path names, when it names a block itself (`body[k1]`). */ +export function blockKeyOf(path: string): string | undefined { + const parsed = parseFieldPath(path); + const last = parsed?.steps.at(-1); + return last && 'key' in last ? last.key : undefined; +} + export const CONTENT_REF_ATTRIBUTE = 'data-cw-ref'; const SEPARATOR = '|'; diff --git a/packages/frontend/src/headers.ts b/packages/frontend/src/headers.ts index 0e1fbd3..b880992 100644 --- a/packages/frontend/src/headers.ts +++ b/packages/frontend/src/headers.ts @@ -20,9 +20,9 @@ export const CSP = CSP_DIRECTIVES.join('; '); /** * The policy /__preview responses carry instead. Public pages may only be framed by the site * itself; preview pages only by the ContentWorker admin (live preview), never by the site or - * anyone else, and by nobody when the admin origin isn't known. A live preview page (framed with - * `cw_session`) also allows the Trusted Types policy `cw-preview`, which its script swaps - * re-rendered blocks in through; no other page may create it. + * anyone else, and by nobody when the admin origin isn't known. A page showing the draft (with + * a known admin) runs the live preview script and also allows the Trusted Types policy + * `cw-preview`, which that script swaps re-rendered blocks in through; no other page may create it. */ export function previewCsp(admin: string | null, live = false): string { return CSP_DIRECTIVES.map((d) => @@ -63,7 +63,7 @@ export interface HtmlHeaderOptions { preconnect?: string[]; /** The admin origin allowed to frame a preview page (kind 'preview' only). */ admin?: string | null; - /** A live preview page (kind 'preview' with `cw_session`). */ + /** A live preview page (kind 'preview' showing the draft, admin known). */ live?: boolean; } diff --git a/packages/frontend/src/preview-links.ts b/packages/frontend/src/preview-links.ts index 41a610a..23b2eca 100644 --- a/packages/frontend/src/preview-links.ts +++ b/packages/frontend/src/preview-links.ts @@ -2,10 +2,10 @@ import { escapeHtml } from './html.ts'; import { match, normalize } from './routes.ts'; /** - * Keeps a live preview session inside preview. In the admin's frame, a link to a public page - * would load a page that refuses to be framed, so on pages rendered for a session every link to - * one of this site's pages becomes `/__preview/?cw_session=`: the draft where the - * link leads to it, published content (with the preview bar) everywhere else. + * Keeps browsing inside preview. In the admin's frame, a link to a public page would load a page + * that refuses to be framed, so on every /__preview page each link to one of this site's pages + * becomes `/__preview/`: the draft where the link leads to it, published content (with the + * preview bar) everywhere else. Each page connects to the admin again on its own. * * Runs on the HTML the runtime itself built (every attribute double-quoted and escaped by * `html`/`attrs`), and only rewrites ``. Links to other origins, fragment-only links, @@ -14,7 +14,6 @@ import { match, normalize } from './routes.ts'; */ const ANCHOR_HREF = /(]*?\shref=")([^"]*)(")/g; const PREFIX = '/__preview'; -export const SESSION_PARAM = 'cw_session'; const UNESCAPE: Record = { '&': '&', @@ -24,10 +23,10 @@ const UNESCAPE: Record = { '>': '>', }; -/** `href` (as written in the page) rewritten into the session, or null to leave it alone. */ +/** `href` (as written in the page) rewritten into preview, or null to leave it alone. */ export function previewHref( href: string, - { origins, session }: { origins: readonly string[]; session: string }, + { origins }: { origins: readonly string[] }, ): string | null { if (!href || href.startsWith('#')) return null; const base = origins[0]; @@ -42,15 +41,10 @@ export function previewHref( if (url.pathname === PREFIX || url.pathname.startsWith(`${PREFIX}/`)) return null; const { path } = normalize(url); if (!match(path)) return null; - const search = new URLSearchParams(url.search); - search.set(SESSION_PARAM, session); - return `${PREFIX}${path === '/' ? '/' : path}?${search}${url.hash}`; + return `${PREFIX}${path === '/' ? '/' : path}${url.search}${url.hash}`; } -export function stayInPreview( - html: string, - options: { origins: readonly string[]; session: string }, -): string { +export function stayInPreview(html: string, options: { origins: readonly string[] }): string { return html.replace(ANCHOR_HREF, (whole, open: string, value: string, close: string) => { const href = value.replace(/&(amp|quot|#39|lt|gt);/g, (e) => UNESCAPE[e] ?? e); const next = previewHref(href, options); diff --git a/packages/frontend/src/preview-render.ts b/packages/frontend/src/preview-render.ts index dc0b896..e8c3b67 100644 --- a/packages/frontend/src/preview-render.ts +++ b/packages/frontend/src/preview-render.ts @@ -1,4 +1,5 @@ import type { Backend } from './config.ts'; +import { formatFieldPath, parseContentRef, parseFieldPath } from './content-ref.ts'; import { previewHeaders, textHeaders } from './headers.ts'; import { fetchDraft, jsonBody, readCookie } from './preview.ts'; import { stayInPreview } from './preview-links.ts'; @@ -8,28 +9,27 @@ import { pathFor } from './routes.ts'; import type { Entry } from './types.ts'; /** - * POST /__preview/render: the live preview script's re-render. Takes the draft fields the editor - * holds (not saved yet) and answers the HTML of the blocks they produce, rendered by the same + * POST /__preview/render: the live preview script's re-render. Takes the entry's unsaved fields + * (what `connectPreview`'s `onState` hands the page: `view.withProposals`, one locale's values, + * typed as the Management API types them) and answers the HTML they produce, rendered by the same * block renderers and escaping as any page: * - * { "entryId": "…", "fields": { … }, "locale"?: "en-US", "keys"?: ["<_key>", …] } + * { "entryId": "…", "locale"?: "en-US", "fields": { … }, "refs"?: ["", …] } * - * `fields` are Delivery-shaped (one locale, `{ id, linkType }` links), or locale-keyed as the - * Management API and the live preview protocol hold them when `locale` names the one to render. - * A field left out, or missing in that locale, keeps the draft's value. A link the draft already - * embeds (an image, a linked entry) is resolved from the draft; any other stays a stub, which - * renders as nothing, as on a page. + * `refs` are the `data-cw-ref` values of the blocks to re-render (`sections[]` refs of this + * entry); the key in each names the block. A field left out keeps the draft's value. A link the + * draft already embeds (an image, a linked entry) is resolved from the draft; any other stays a + * stub, which renders as nothing, as on a page. * - * Answers `{ blocks: [{ key, html }], css: [hrefs] }` for `keys`, or `{ main, css }` (all of + * Answers `{ blocks: [{ ref, key, html }], css: [hrefs] }` for `refs`, or `{ main, css }` (all of *
) without them, and also whenever swapping single blocks could leave the page wrong: a key * the fields no longer render (removed, or not there yet), a key on more than one block, or the * first section (it decides the page's h1 and every heading level after it). A block that renders - * to nothing answers `html: ""`. `css` is every block stylesheet the HTML needs. - * - * `session`, the page's `cw_session`, keeps links in the HTML inside the live preview session. + * to nothing answers `html: ""`. `css` is every block stylesheet the HTML needs. Links to the + * site's pages stay under /__preview, as on the page. * * `locale`, when given, must be the site's own (CONTENTWORKER_LOCALE): the page renders one - * locale, and its refs and links say which. + * locale, and its refs say which. * * Only for the grant in this browser's preview cookie, and only for that entry: the token is * checked against the Preview API on every call, as a preview page load does. Same-origin POSTs @@ -37,8 +37,8 @@ import type { Entry } from './types.ts'; * cached and never indexed. */ export const MAX_RENDER_BYTES = 2 * 1024 * 1024; -const MAX_KEYS = 500; -const MAX_KEY_LENGTH = 256; +const MAX_REFS = 500; +const MAX_REF_LENGTH = 2048; const MAX_DEPTH = 64; const MAX_NODES = 200_000; /** Names that reach an object's prototype when assigned; dropped from supplied fields. */ @@ -71,24 +71,26 @@ export async function renderPreviewBlocks({ }: RenderDeps): Promise { const read = await jsonBody(request, url, admin, MAX_RENDER_BYTES); if ('refused' in read) return read.refused; - const { entryId, fields, locale, keys, session } = read.body; + const { entryId, fields, locale, refs } = read.body; if (typeof entryId !== 'string' || !isRecord(fields)) return json(admin, { error: 'Send entryId and fields.' }, 400); - if (locale !== undefined && (typeof locale !== 'string' || !locale || FORBIDDEN.has(locale))) + if (locale !== undefined && (typeof locale !== 'string' || !locale)) return json(admin, { error: 'locale must be a locale code.' }, 400); - if ( - keys !== undefined && - !( - Array.isArray(keys) && - keys.length <= MAX_KEYS && - keys.every((k) => typeof k === 'string' && k && k.length <= MAX_KEY_LENGTH) - ) - ) - return json(admin, { error: `keys must be at most ${MAX_KEYS} block keys.` }, 400); - if (session !== undefined && session !== null && !isSession(session)) - return json(admin, { error: "session must be the page's cw_session." }, 400); if (locale !== undefined && locale !== cw.locale) return json(admin, { error: `This site renders ${cw.locale}; send that locale.` }, 422); + let keys: string[] | null = null; + if (refs !== undefined) { + if (!Array.isArray(refs) || refs.length > MAX_REFS) + return json(admin, { error: `refs must be at most ${MAX_REFS} block refs.` }, 400); + keys = []; + for (const r of refs) { + const key = + typeof r === 'string' && r.length <= MAX_REF_LENGTH ? blockOf(r, cw, entryId) : null; + if (key === null) + return json(admin, { error: "Each ref must name one of this entry's blocks." }, 400); + keys.push(key); + } + } const granted = readCookie(request, entryId); if (!granted || granted.entryId !== entryId) @@ -98,7 +100,7 @@ export async function renderPreviewBlocks({ let entry: Entry; try { - entry = overlay(draft, fields, locale); + entry = overlay(draft, fields); } catch (error) { if (error instanceof TooLarge) return json(admin, { error: error.message }, 413); throw error; @@ -119,35 +121,50 @@ export async function renderPreviewBlocks({ return json(admin, { error: 'These fields could not be rendered.' }, 422); } - // The page's links stay in its live preview session, as the page's own render keeps them. - const links = (h: string) => - typeof session === 'string' && admin - ? stayInPreview(h, { origins: [...new Set([site.origin, url.origin])], session }) - : h; + const origins = [...new Set([site.origin, url.origin])]; + const links = (h: string) => stayInPreview(h, { origins }); const whole = () => json(admin, { main: links(parts.map((p) => p.html).join('')), css: [...new Set(parts.flatMap((p) => p.needs))], }); - if (!Array.isArray(keys)) return whole(); - const wanted = [...new Set(keys as string[])]; + if (!keys) return whole(); const found: { key: string; part: MainPart }[] = []; - for (const key of wanted) { + for (const key of new Set(keys)) { const matches = parts.filter((p) => p.key === key); const part = matches[0]; if (!part || matches.length > 1 || part.index === 0) return whole(); found.push({ key, part }); } return json(admin, { - blocks: found.map(({ key, part }) => ({ key, html: links(part.section) })), + blocks: found.map(({ key, part }) => ({ + ref: marks?.(formatFieldPath({ field: 'sections', steps: [{ key }] })), + key, + html: links(part.section), + })), css: [...new Set(found.flatMap(({ part }) => part.needs))], }); } -class TooLarge extends Error {} +/** The `_key` a block ref names, when it is a `sections[]` ref of this entry; else null. */ +function blockOf(value: string, cw: Backend, entryId: string): string | null { + const ref = parseContentRef(value); + if ( + !ref || + ref.space !== cw.space || + ref.environment !== cw.environment || + ref.entryId !== entryId || + ref.locale !== cw.locale + ) + return null; + const path = parseFieldPath(ref.field); + const step = path?.steps[0]; + if (path?.field !== 'sections' || path.steps.length !== 1 || !step || !('key' in step)) + return null; + return step.key; +} -const isSession = (value: unknown): value is string => - typeof value === 'string' && /^[A-Za-z0-9_-]{8,128}$/.test(value); +class TooLarge extends Error {} function isRecord(value: unknown): value is Record { return typeof value === 'object' && value !== null && !Array.isArray(value); @@ -158,11 +175,7 @@ function isRecord(value: unknown): value is Record { * every supplied value (nothing the caller sent is rendered by reference), drops prototype names, * and refuses values nested deeper than MAX_DEPTH or larger than MAX_NODES. */ -export function overlay( - draft: Entry, - fields: Record, - locale?: string | undefined, -): Entry { +export function overlay(draft: Entry, fields: Record): Entry { const index = new Map(); collect(draft.fields, index); let nodes = 0; @@ -178,14 +191,8 @@ export function overlay( return out; }; const next: Record = { ...draft.fields }; - for (const [name, value] of Object.entries(fields)) { - if (FORBIDDEN.has(name)) continue; - if (locale === undefined) { - next[name] = copy(value, 0); - } else if (isRecord(value) && Object.hasOwn(value, locale)) { - next[name] = copy(value[locale], 0); - } - } + for (const [name, value] of Object.entries(fields)) + if (!FORBIDDEN.has(name)) next[name] = copy(value, 0); return { ...draft, fields: next }; } diff --git a/packages/frontend/src/preview.ts b/packages/frontend/src/preview.ts index 63e3b2e..23b1271 100644 --- a/packages/frontend/src/preview.ts +++ b/packages/frontend/src/preview.ts @@ -22,8 +22,9 @@ import type { Entry, PreviewState } from './types.ts'; * * The admin frames these pages for live preview, so the cookie is `SameSite=None; Partitioned` * (sent inside the admin's iframe, and kept in the admin's partition only) and every response - * names the admin as the only origin that may frame it. With `cw_session` on the URL the page - * also loads the live preview script, which re-renders blocks through POST /__preview/render. + * names the admin as the only origin that may frame it. A page showing the draft also loads the + * live preview script, which connects only inside the admin's frame and re-renders blocks + * through POST /__preview/render. Links to the site's pages stay under /__preview. */ export const PREFIX = '/__preview'; export const RENDER_PATH = `${PREFIX}/render`; @@ -32,9 +33,6 @@ const MAX_AGE = 60 * 60; /** Entry ids are UUIDs (and test ids): no `~`, which separates the cookie's two parts. */ const ENTRY_ID = /^[A-Za-z0-9_-]{1,128}$/; const TOKEN = /^[\w.-]{1,512}$/; -/** A live preview session id, as `@contentworker/sdk/live-preview` checks it. */ -const SESSION = /^[A-Za-z0-9_-]{8,128}$/; -export const SESSION_PARAM = 'cw_session'; const MAX_HANDOFF_BYTES = 4 * 1024; /** Reads one draft entry with its preview token (no API key needed: the token is the grant). */ @@ -136,16 +134,13 @@ function text( }); } -/** Where a valid grant lands: the draft's path, carrying the live preview session through. */ -function landing(draft: Entry, session: string | null): string { +/** Where a valid grant lands: the draft's path under /__preview. */ +function landing(draft: Entry): string { const path = pathFor(draft) ?? '/'; const to = `${PREFIX}${path === '/' ? '/' : path}`; - return session ? `${to}?${new URLSearchParams({ [SESSION_PARAM]: session })}` : to; + return to; } -const sessionOf = (value: unknown): string | null => - typeof value === 'string' && SESSION.test(value) ? value : null; - /** * A POST from this site's own pages: `Origin` must be exactly this origin (and Sec-Fetch-Site, when * sent, `same-origin`). Pages under /__preview send no Referer, which also blanks `Origin` on a @@ -213,7 +208,6 @@ async function grant( admin: string | null, entryId: unknown, token: unknown, - session: string | null, as: 'redirect' | 'json', ): Promise { if ( @@ -225,7 +219,7 @@ async function grant( return text(admin, 'Missing entry or token.', 400); const draft = await fetchDraft(cw, entryId, token); if (!draft) return text(admin, 'This preview link is invalid or has expired.', 403); - const location = landing(draft, session); + const location = landing(draft); const value = `${encodeURIComponent(entryId)}~${token}`; if (as === 'redirect') return new Response(null, { @@ -249,9 +243,9 @@ async function grant( * The fragment handoff, run by the page below. It reads `#token=` and drops the fragment from * history before anything else, so the token is gone from the address bar, history and any * later Referer, then trades it for the cookie and replaces itself with the draft. Reads the - * entry and session from its own URL: nothing from the request is printed into the page. + * entry from its own URL: nothing from the request is printed into the page. */ -export const HANDOFF_SCRIPT = `(()=>{const q=new URLSearchParams(location.search),h=new URLSearchParams(location.hash.slice(1)),t=h.get('token'),s=document.getElementById('cw-status'),say=(m)=>{if(s)s.textContent=m};history.replaceState(null,'',location.pathname+location.search);if(!t){say('This preview link has no token.');return}fetch('${PREFIX}',{method:'POST',headers:{'content-type':'application/json'},credentials:'same-origin',referrerPolicy:'same-origin',body:JSON.stringify({entry:q.get('entry'),token:t,session:q.get('${SESSION_PARAM}')})}).then((r)=>r.ok?r.json():Promise.reject(r.status)).then((d)=>{if(typeof d.location!=='string'||!d.location.startsWith('${PREFIX}/'))throw 0;location.replace(d.location)}).catch((e)=>say(e===403?'This preview link is invalid or has expired.':'The preview could not start. Try the link again.'))})()`; +export const HANDOFF_SCRIPT = `(()=>{const q=new URLSearchParams(location.search),h=new URLSearchParams(location.hash.slice(1)),t=h.get('token'),s=document.getElementById('cw-status'),say=(m)=>{if(s)s.textContent=m};history.replaceState(null,'',location.pathname+location.search);if(!t){say('This preview link has no token.');return}fetch('${PREFIX}',{method:'POST',headers:{'content-type':'application/json'},credentials:'same-origin',referrerPolicy:'same-origin',body:JSON.stringify({entry:q.get('entry'),token:t})}).then((r)=>r.ok?r.json():Promise.reject(r.status)).then((d)=>{if(typeof d.location!=='string'||!d.location.startsWith('${PREFIX}/'))throw 0;location.replace(d.location)}).catch((e)=>say(e===403?'This preview link is invalid or has expired.':'The preview could not start. Try the link again.'))})()`; const HANDOFF_PAGE = `Opening preview

Opening the preview…

`; @@ -301,8 +295,8 @@ export async function handlePreview(deps: PreviewDeps): Promise { if (url.pathname === PREFIX) { const read = await jsonBody(request, url, admin, MAX_HANDOFF_BYTES); if ('refused' in read) return read.refused; - const { entry, token, session } = read.body; - return grant(cw, admin, entry, token, sessionOf(session), 'json'); + const { entry, token } = read.body; + return grant(cw, admin, entry, token, 'json'); } if (url.pathname === RENDER_PATH) return renderPreviewBlocks({ request, url, cw, site, admin }); return text(admin, 'Method not allowed', 405, { allow: 'GET, HEAD' }); @@ -311,10 +305,9 @@ export async function handlePreview(deps: PreviewDeps): Promise { if (url.pathname === PREFIX) { const entryId = url.searchParams.get('entry'); const token = url.searchParams.get('token'); - const session = sessionOf(url.searchParams.get(SESSION_PARAM)); if (token !== null) { if (!isNavigation(request)) return text(admin, 'Open preview links as a page.', 403); - return grant(cw, admin, entryId, token, session, 'redirect'); + return grant(cw, admin, entryId, token, 'redirect'); } if (!entryId || !ENTRY_ID.test(entryId)) return text(admin, 'Missing entry or token.', 400); return handoffPage(admin); @@ -339,7 +332,6 @@ export async function handlePreview(deps: PreviewDeps): Promise { break; } } - const session = sessionOf(url.searchParams.get(SESSION_PARAM)); return render({ path, admin, @@ -347,8 +339,8 @@ export async function handlePreview(deps: PreviewDeps): Promise { entry, path, scope: { space: cw.space, environment: cw.environment, locale: cw.locale }, - live: entry && session && admin ? { admin } : null, - session: session && admin ? session : null, + live: entry && admin ? { admin } : null, + framed: request.headers.get('sec-fetch-dest') === 'iframe', }, }); } diff --git a/packages/frontend/src/render/block-ctx.ts b/packages/frontend/src/render/block-ctx.ts index e247384..8b21576 100644 --- a/packages/frontend/src/render/block-ctx.ts +++ b/packages/frontend/src/render/block-ctx.ts @@ -1,4 +1,7 @@ import { raw } from '../html.ts'; + +const NO_REF = raw(''); + import { pathFor } from '../routes.ts'; import { isEntry, type Menus, type RenderCtx } from '../types.ts'; import { renderEmbedded } from './blocks.ts'; @@ -40,6 +43,7 @@ export function createRenderCtx({ image: (asset, opts) => image(asset, ctx, opts), richText: (doc) => renderRichText(doc, ctx), renderBlock: (e) => renderEmbedded(e, ctx), + ref: () => NO_REF, }; return ctx; } diff --git a/packages/frontend/src/render/blocks.ts b/packages/frontend/src/render/blocks.ts index 0b5e741..dd59e48 100644 --- a/packages/frontend/src/render/blocks.ts +++ b/packages/frontend/src/render/blocks.ts @@ -9,7 +9,7 @@ import * as fragment from '../../public/blocks/fragment/fragment.render.ts'; import * as header from '../../public/blocks/header/header.render.ts'; import * as hero from '../../public/blocks/hero/hero.render.ts'; import * as media from '../../public/blocks/media/media.render.ts'; -import { attrs, html, type Safe } from '../html.ts'; +import { attrs, html, raw, type Safe } from '../html.ts'; import { type BlockModule, type ChromeModule, @@ -74,7 +74,14 @@ export function renderEmbedded(entry: Entry, ctx: RenderCtx): Safe { const mod = BLOCKS.get(entry.contentType); if (!mod) return html``; ctx.usedBlocks.add(mod); - return blockShell(mod, mod.default(entry, ctx)); + // An embedded entry is another entry: the block around it can't name its fields. + const ref = ctx.ref; + ctx.ref = () => raw(''); + try { + return blockShell(mod, mod.default(entry, ctx)); + } finally { + ctx.ref = ref; + } } /** Every block module a section uses, including blocks inside fragments and rich text. */ diff --git a/packages/frontend/src/render/document.ts b/packages/frontend/src/render/document.ts index f0f761a..4ebb20c 100644 --- a/packages/frontend/src/render/document.ts +++ b/packages/frontend/src/render/document.ts @@ -1,5 +1,5 @@ import { toClassName } from '../../public/scripts/shared.js'; -import { type ContentRef, formatContentRef } from '../content-ref.ts'; +import { type ContentRef, formatContentRef, formatFieldPath } from '../content-ref.ts'; import { attrs, html, type Safe } from '../html.ts'; import { stayInPreview } from '../preview-links.ts'; import { @@ -46,14 +46,13 @@ export interface DocumentInput { } export async function* renderDocument(input: DocumentInput): AsyncGenerator { - const session = input.preview?.session; - if (!session) { + if (!input.preview) { yield* renderPage(input); return; } - // Framed for a live preview session: links to the site's pages stay in preview. + // Under /__preview, links to the site's pages stay in preview (and so in the admin's frame). const origins = [...new Set([input.origin, input.url.origin])]; - for await (const chunk of renderPage(input)) yield stayInPreview(chunk, { origins, session }); + for await (const chunk of renderPage(input)) yield stayInPreview(chunk, { origins }); } async function* renderPage(input: DocumentInput): AsyncGenerator { @@ -78,13 +77,14 @@ async function* renderPage(input: DocumentInput): AsyncGenerator { firstCss: blockCss(firstMods, codeBase), lang, }).value; - if (preview?.live) { - // Live preview only (framed by the admin with cw_session): the page side of the protocol. - yield html`` + if (preview?.live && entry) { + // The draft, under /__preview only: the page side of live preview. It connects only when the + // admin frames the page, and does nothing otherwise. + yield html`` .value; } yield ''; - if (preview?.session) { + if (preview?.framed) { // Framed by the admin, which has its own controls: an exit link would load a public page, // and public pages refuse to be framed. yield html`
Previewing a draft.
`.value; @@ -92,7 +92,7 @@ async function* renderPage(input: DocumentInput): AsyncGenerator { yield html`
` .value; } - const slot = marks && isBlocksField(entry?.fields?.sections) ? 'sections' : null; + const slot = marks && isBlocksField(entry?.fields?.sections) ? marks('sections') : null; yield html`
${blockShell(CHROME.header, CHROME.header.default(settings, ctx))}
` .value; @@ -105,7 +105,10 @@ async function* renderPage(input: DocumentInput): AsyncGenerator { .value; } -/** Makes the `data-cw-ref` value for one of the draft's fields, or null outside a draft preview. */ +/** + * Makes the `data-cw-ref` value for a field path of the draft (`title`, `sections[]`, + * `sections[].heading`), or null outside a draft preview. + */ export type Marks = ((field: string) => string) | null; export function marksFor(preview: PreviewState | undefined): Marks { @@ -218,29 +221,44 @@ const titledBy = (section: Entry): boolean => (section.contentType === DEFAULT_CONTENT && Boolean(section.fields.heading)) || Boolean(BLOCKS.get(section.contentType)?.ownsTitle); +/** The ref path of a blocks-field section (`sections[]`), or null. */ +function blockPath(section: Entry): string | null { + const key = blockKey(section); + return key ? formatFieldPath({ field: 'sections', steps: [{ key }] }) : null; +} + function renderSection(section: Entry, index: number, ctx: RenderCtx, marks: Marks): Safe { const style = section.fields?.style ? toClassName(section.fields.style) : null; // Every section starts 'initialized'; scripts/lib.js marks it 'loaded' once its block JS ran. const status = 'initialized'; + const path = marks ? blockPath(section) : null; + const blockRef = marks && path ? marks(path) : null; if (section.contentType === DEFAULT_CONTENT) { - // A page's own body and title (sectionsOf) carry the page's refs; a richText block its key. - const own = marks && PAGE_BODY.has(section) ? marks : null; + // A page's own body and title (sectionsOf) carry the page's refs; a richText block its own. + const own = marks && PAGE_BODY.has(section); const { heading, body } = section.fields; let title: Safe | string = ''; if (heading && index === 0 && ctx.headingLevel === 1) { - title = html`${heading}

`; + const ref = own ? marks('title') : marks && path ? marks(`${path}.heading`) : null; + title = html`${heading}`; ctx.headingLevel = 2; } - return html`
${title}${renderRichText(body, ctx)}
`; + return html`
${title}${renderRichText(body, ctx)}
`; } const mod = BLOCKS.get(section.contentType); if (!mod) return html``; ctx.usedBlocks.add(mod); - return html`
${blockShell(mod, mod.default(section, ctx))}
`; + const ref = ctx.ref; + if (marks && path) ctx.ref = (field) => attrs({ 'data-cw-ref': marks(`${path}.${field}`) }); + try { + return html`
${blockShell(mod, mod.default(section, ctx))}
`; + } finally { + ctx.ref = ref; + } } function notFoundSection() { diff --git a/packages/frontend/src/types.ts b/packages/frontend/src/types.ts index 369b48e..3ca551b 100644 --- a/packages/frontend/src/types.ts +++ b/packages/frontend/src/types.ts @@ -101,6 +101,12 @@ export interface RenderCtx { image: (asset: Asset | null | undefined, opts?: ImageOptions) => Safe; richText: (doc: RichTextDocument | null | undefined) => Safe; renderBlock: (entry: Entry, opts?: { inline?: boolean }) => Safe; + /** + * The `data-cw-ref` attribute for one of the current block's fields (``), + * so the admin can map a click on it back to the field. Empty everywhere but a draft under + * /__preview, so public renders never change. + */ + ref: (field: string) => Safe; } /** What Markdown rendering receives. */ @@ -182,7 +188,7 @@ export function asSection(value: unknown): Entry | null { /** * Blocks-field elements by their `_key`, kept beside the section rather than on it so nothing a - * public render hashes or prints changes. Only preview renders read it (`data-cw-block`). + * public render hashes or prints changes. Only preview renders read it (`data-cw-ref`). */ const KEYS = new WeakMap(); @@ -210,15 +216,15 @@ export interface PreviewState { entry: Entry | null; path: string; /** - * The draft's space, environment and locale, for the editing marks (`data-cw-block`, - * `data-cw-slot`, `data-cw-ref`). Absent, a preview renders without them. + * The draft's space, environment and locale, for the editing marks (`data-cw-ref`, + * `data-cw-slot`). Absent, a preview renders without them. */ scope?: { space: string; environment: string; locale: string } | undefined; - /** Set when the admin frames the page for a live preview session: the origin it listens to. */ - live?: { admin: string } | null | undefined; /** - * The live preview session (`cw_session`) the admin framed the page with, draft shown or not: - * links to the site's pages carry it and stay under /__preview (src/preview-links.ts). + * Set when the page shows the draft and the admin origin is known: the page loads the live + * preview script, which connects only when the admin frames it. */ - session?: string | null | undefined; + live?: { admin: string } | null | undefined; + /** The page was loaded in a frame (Sec-Fetch-Dest: iframe), presumably the admin's. */ + framed?: boolean | undefined; } diff --git a/packages/frontend/test/content-ref.test.ts b/packages/frontend/test/content-ref.test.ts index 90c74bf..08fab64 100644 --- a/packages/frontend/test/content-ref.test.ts +++ b/packages/frontend/test/content-ref.test.ts @@ -1,6 +1,15 @@ import assert from 'node:assert/strict'; import { test } from 'node:test'; -import { type ContentRef, formatContentRef, parseContentRef } from '../src/content-ref.ts'; +import { + blockKeyOf, + type ContentRef, + type FieldPath, + formatContentRef, + formatFieldPath, + parseContentRef, + parseFieldPath, + topLevelField, +} from '../src/content-ref.ts'; // The examples of @contentworker/sdk's own content-ref tests: the formats must stay identical. const ref: ContentRef = { @@ -30,3 +39,71 @@ test('anything that is not a ref parses to undefined', () => { assert.equal(parseContentRef('s1|main|e1|article||en-US'), undefined); assert.equal(parseContentRef('s1|main|e1|article|%E0%A4%A|en-US'), undefined); }); + +// The SDK's field-path examples (packages/sdk/core/test/content-ref-paths.test.ts). + +const base = { + space: 's1', + environment: 'main', + entryId: 'e1', + contentType: 'landing', + locale: 'en-US', +} as const; + +const paths: [string, FieldPath][] = [ + ['title', { field: 'title', steps: [] }], + ['body[0192f]', { field: 'body', steps: [{ key: '0192f' }] }], + ['body[0192f].heading', { field: 'body', steps: [{ key: '0192f' }, { field: 'heading' }] }], + [ + 'body[0192f].ctas[0192e].label', + { + field: 'body', + steps: [{ key: '0192f' }, { field: 'ctas' }, { key: '0192e' }, { field: 'label' }], + }, + ], +]; +for (const [text, path] of paths) { + test(`field path round-trips ${text}`, () => { + assert.equal(formatFieldPath(path), text); + assert.deepEqual(parseFieldPath(text), path); + const r: ContentRef = { ...base, field: text }; + assert.deepEqual(parseContentRef(formatContentRef(r)), r); + }); +} + +test('an old six-part ref still parses; a path ref stays six parts', () => { + assert.deepEqual(parseContentRef('s1|main|e1|landing|title|en-US'), { ...base, field: 'title' }); + const parts = formatContentRef({ ...base, field: 'body[k1].heading' }).split('|'); + assert.equal(parts.length, 6); + assert.equal(decodeURIComponent(parts[4] as string), 'body[k1].heading'); +}); + +test('what is not a path is refused, and names that would make one', () => { + for (const bad of ['', '[k1]', 'body.heading', 'body[k1][k2]', 'body[]', 'body[k1].', 'body[k1']) + assert.equal(parseFieldPath(bad), undefined, bad); + assert.throws(() => formatFieldPath({ field: 'a.b', steps: [] })); + assert.throws(() => formatFieldPath({ field: 'body', steps: [{ key: '' }] })); +}); + +test('any stored key round-trips, brackets and escapes included', () => { + for (const key of ['a]b', '[x]', '100%', '%5B', 'a%25]']) { + const path: FieldPath = { field: 'body', steps: [{ key }, { field: 'heading' }] }; + const text = formatFieldPath(path); + assert.deepEqual(parseFieldPath(text), path); + assert.equal(blockKeyOf(formatFieldPath({ field: 'body', steps: [{ key }] })), key); + const r: ContentRef = { ...base, field: text }; + assert.deepEqual(parseContentRef(formatContentRef(r)), r); + } + assert.equal( + formatFieldPath({ field: 'sections', steps: [{ key: 'a[b]%' }] }), + 'sections[a%5Bb%5D%25]', + ); +}); + +test('the top-level field and the block a path is in', () => { + assert.equal(topLevelField('body[k1].ctas[k2].label'), 'body'); + assert.equal(topLevelField('title'), 'title'); + assert.equal(blockKeyOf('body[k1].ctas[k2]'), 'k2'); + assert.equal(blockKeyOf('body[k1].heading'), undefined); + assert.equal(blockKeyOf('title'), undefined); +}); diff --git a/packages/frontend/test/live-preview.dom.test.ts b/packages/frontend/test/live-preview.dom.test.ts index 5af1be8..555db80 100644 --- a/packages/frontend/test/live-preview.dom.test.ts +++ b/packages/frontend/test/live-preview.dom.test.ts @@ -1,23 +1,41 @@ import assert from 'node:assert/strict'; import { test } from 'node:test'; import { JSDOM } from 'jsdom'; +import { formatContentRef, formatFieldPath } from '../src/content-ref.ts'; type Rules = { createHTML(html: string): string }; -type Render = (fields: unknown, update: unknown) => Promise; +type View = { + rev: number; + withProposals: Record; + ghosts: { inserted: string[]; changed: string[]; removed: string[] }; +}; +type OnState = (entryId: string, locale: string, fields: unknown, view: View) => Promise; +const ref = (key: string) => + formatContentRef({ + space: 'site', + environment: 'main', + entryId: 'p-inline', + contentType: 'page', + field: formatFieldPath({ field: 'sections', steps: [{ key }] }), + locale: 'en-US', + }); const section = (key: string, text: string) => - `

${text}

`; + `

${text}

`; +const block = (key: string, heading: string) => ({ _type: 'cta', _key: key, heading }); +const view = (sections: unknown[], ghosts: Partial = {}): View => ({ + rev: 1, + withProposals: { title: 'T', sections }, + ghosts: { inserted: [], changed: [], removed: [], ...ghosts }, +}); -/** - * The live preview script in jsdom, with fetch answered by `answer` (in call order) and a - * Trusted Types stand-in that records the policy the script creates. - */ +/** The live preview script in jsdom, fetch answered by `answer` in call order. */ async function mount( main: string, answer: (body: Record, n: number) => Promise, ) { const dom = new JSDOM( - `
${main}
`, + `
${main}
`, ); const { window } = dom; let rules: Rules | undefined; @@ -43,103 +61,147 @@ async function mount( }, }); const mod = (await import(`../public/scripts/live-preview.js?${Math.random()}`)) as { - render: Render; + onState: OnState; + blockKeyOfRef: (ref: string | null) => string | undefined; }; - return { window, doc: window.document, render: mod.render, requests, rules: () => rules }; + const doc = window.document; + const html = () => doc.querySelector('main')?.innerHTML ?? ''; + return { window, doc, html, ...mod, requests, rules: () => rules }; } -const update = (ops: unknown[] = []) => ({ - entryId: 'p-inline', - contentType: 'page', - locale: 'en-US', - version: 1, - seq: 1, - ops, +/** Answers a whole-
render from the request's sections, or the requested blocks. */ +const echo = async (body: Record) => { + const sections = (body.fields as { sections: { _key: string; heading: string }[] }).sections; + const keys = (body.refs as string[] | undefined)?.map( + (r) => /sections%5B(.*)%5D/.exec(r)?.[1] ?? '', + ); + if (!keys) return { main: sections.map((s) => section(s._key, s.heading)).join(''), css: [] }; + return { + blocks: keys.map((key) => { + const s = sections.find((x) => x._key === key); + return { key, ref: ref(key), html: s?.heading ? section(key, s.heading) : '' }; + }), + css: [], + }; +}; + +test("reads a block's key from its ref, escapes undone", async () => { + const { blockKeyOfRef } = await mount('', echo); + assert.equal(blockKeyOfRef(ref('k-a')), 'k-a'); + assert.equal(blockKeyOfRef(ref('a[b]%')), 'a[b]%'); + assert.equal( + blockKeyOfRef( + formatContentRef({ + space: 's', + environment: 'e', + entryId: 'x', + contentType: 'page', + field: 'sections[k].heading', + locale: 'en-US', + }), + ), + undefined, + ); + assert.equal(blockKeyOfRef('nope'), undefined); +}); + +test('the first state renders
whole; then only the blocks that changed', async () => { + const { onState, requests, html } = await mount(section('k-a', 'a') + section('k-b', 'b'), echo); + await onState('p-inline', 'en-US', {}, view([block('k-a', 'a'), block('k-b', 'b')])); + assert.equal(requests[0]?.refs, undefined); + assert.equal(requests[0]?.locale, 'en-US'); + await onState('p-inline', 'en-US', {}, view([block('k-a', 'a'), block('k-b', 'B!')])); + assert.deepEqual(requests[1]?.refs, [ref('k-b')]); + assert.match(html(), /

B!<\/p>/); + // A reorder (or another field) re-renders

whole. + await onState('p-inline', 'en-US', {}, view([block('k-b', 'B!'), block('k-a', 'a')])); + assert.equal(requests[2]?.refs, undefined); }); -const touch = (key: string) => update([{ op: 'update', key, field: 'sections', locale: 'en-US' }]); test('an older response never draws over a newer one, and settles only after it', async () => { let release: () => void = () => {}; - const slow = new Promise((r) => (release = r)); - const { doc, render } = await mount(section('k-a', 'old'), async (_b, n) => { + const slow = new Promise((r) => { + release = r; + }); + const { onState, html } = await mount(section('k-a', 'old'), async (body, n) => { if (n === 1) await slow; - return { - blocks: [{ key: 'k-a', html: section('k-a', n === 1 ? 'first' : 'second') }], - css: [], - }; + return echo(body); }); const order: string[] = []; - const first = render({}, touch('k-a')).then(() => order.push('first')); - const second = render({}, touch('k-a')).then(() => order.push('second')); + const first = onState('p-inline', 'en-US', {}, view([block('k-a', 'first')])).then(() => + order.push('first'), + ); + const second = onState('p-inline', 'en-US', {}, view([block('k-a', 'second')])).then(() => + order.push('second'), + ); await second; release(); await first; - assert.match(doc.querySelector('main')?.innerHTML ?? '', /second/); - assert.doesNotMatch(doc.querySelector('main')?.innerHTML ?? '', /first/); + assert.match(html(), /second/); + assert.doesNotMatch(html(), /first/); assert.deepEqual(order, ['second', 'first']); }); -test('swaps one block, removes a block that renders to nothing, and re-renders
for a duplicate key', async () => { - const { doc, render, requests } = await mount( - section('k-a', 'a') + section('k-b', 'b') + section('k-b', 'b again'), - async (body) => - body.keys - ? { - blocks: (body.keys as string[]).map((key) => ({ - key, - html: key === 'k-a' ? section('k-a', 'A!') : '', - })), - css: [], - } - : { main: section('k-a', 'whole'), css: [] }, - ); - await render({}, touch('k-a')); - assert.match(doc.querySelector('[data-cw-block="k-a"]')?.textContent ?? '', /A!/); - await render({}, touch('k-b')); - assert.equal(requests.at(-1)?.keys, undefined, 'k-b is on the page twice: whole
'); - assert.equal( - doc.querySelector('main')?.innerHTML, - section('k-a', 'whole').replace('initialized', 'loaded'), - ); +test('a block re-rendered to nothing leaves the page; a key shown twice re-renders
', async () => { + const { onState, doc, requests } = await mount(section('k-a', 'a') + section('k-b', 'b'), echo); + await onState('p-inline', 'en-US', {}, view([block('k-a', 'a'), block('k-b', 'b')])); + await onState('p-inline', 'en-US', {}, view([block('k-a', 'a'), block('k-b', '')])); + assert.equal(doc.querySelector(`[data-cw-ref="${ref('k-b')}"]`), null); + assert.ok(doc.querySelector(`[data-cw-ref="${ref('k-a')}"]`)); + + const twice = await mount('', echo); + await twice.onState('p-inline', 'en-US', {}, view([block('k-a', 'a'), block('k-c', 'c')])); + // Something on the page (a site script, say) shows the block twice: don't guess which. + twice.doc.querySelector('main')?.insertAdjacentHTML('beforeend', section('k-a', 'copy')); + await twice.onState('p-inline', 'en-US', {}, view([block('k-a', 'A'), block('k-c', 'c')])); + assert.equal(twice.requests.at(-1)?.refs, undefined); + assert.equal(requests.length, 2); }); -test('a block re-rendered to nothing leaves the page', async () => { - const { doc, render } = await mount(section('k-a', 'a') + section('k-b', 'b'), async () => ({ - blocks: [{ key: 'k-b', html: '' }], - css: [], - })); - await render({}, touch('k-b')); - assert.equal(doc.querySelector('[data-cw-block="k-b"]'), null); - assert.ok(doc.querySelector('[data-cw-block="k-a"]')); +test("Coworker's proposals render as ghosts, and only proposals do", async () => { + const { onState, doc, requests } = await mount('', echo); + const sections = [block('k-a', 'a'), block('k-new', 'proposed'), block('k-old', 'going')]; + await onState( + 'p-inline', + 'en-US', + {}, + view(sections, { inserted: ['k-new'], removed: ['k-old'] }), + ); + const ghost = (key: string) => + doc.querySelector(`[data-cw-ref="${ref(key)}"]`)?.getAttribute('data-cw-ghost') ?? null; + assert.equal(ghost('k-new'), 'inserted'); + assert.equal(ghost('k-old'), 'removed'); + assert.equal(ghost('k-a'), null); + // Ghosts changing alone re-marks without a render. + await onState('p-inline', 'en-US', {}, view(sections, { changed: ['k-a'] })); + assert.equal(requests.length, 1); + assert.equal(ghost('k-a'), 'changed'); + assert.equal(ghost('k-new'), null); }); test('a whole-
swap keeps stylesheets in , once', async () => { - const { doc, render, window } = await mount(section('k-a', 'a'), async () => ({ - main: `${section('k-a', 'x')}${section('k-f', 'f')}`, - css: ['/v/b/blocks/hero/hero.css', '/v/b/blocks/faq/faq.css'], + const { doc, onState, window } = await mount(section('k-a', 'a'), async () => ({ + main: `${section('k-a', 'x')}${section('k-f', 'f')}`, + css: ['/v/b/blocks/cta/cta.css', '/v/b/blocks/faq/faq.css'], })); - const done = render({}, update()); - // The new stylesheet goes to ; fire its load so the render can go on. + const done = onState('p-inline', 'en-US', {}, view([block('k-a', 'x'), block('k-f', 'f')])); await new Promise((r) => setTimeout(r, 0)); for (const link of doc.head.querySelectorAll('link')) link.dispatchEvent(new window.Event('load')); await done; assert.deepEqual( [...doc.head.querySelectorAll('link')].map((l) => l.getAttribute('href')), - ['/v/b/blocks/hero/hero.css', '/v/b/blocks/faq/faq.css'], + ['/v/b/blocks/cta/cta.css', '/v/b/blocks/faq/faq.css'], ); assert.equal(doc.querySelector('main')?.querySelectorAll('link').length, 0); }); test('the cw-preview policy passes only the markup a render response brought', async () => { - const { rules, render } = await mount(section('k-a', 'a'), async () => ({ - blocks: [{ key: 'k-a', html: section('k-a', 'ok') }], - css: [], - })); + const { rules, onState } = await mount(section('k-a', 'a'), echo); const policy = rules(); assert.ok(policy); assert.throws(() => policy.createHTML(''), /render responses only/); - await render({}, touch('k-a')); + await onState('p-inline', 'en-US', {}, view([block('k-a', 'ok')])); assert.throws( () => policy.createHTML(section('k-a', 'ok')), /render responses only/, diff --git a/packages/frontend/test/preview-links.test.ts b/packages/frontend/test/preview-links.test.ts index c14ead3..b7a1d80 100644 --- a/packages/frontend/test/preview-links.test.ts +++ b/packages/frontend/test/preview-links.test.ts @@ -4,20 +4,15 @@ import { previewHref, stayInPreview } from '../src/preview-links.ts'; import { doc, p, text } from './fixtures.ts'; import { call, GRANT, post } from './support/preview.ts'; -const SESSION = 'sess_12345678'; -const options = { origins: ['https://contentworker.site'], session: SESSION }; +const options = { origins: ['https://contentworker.site'] }; +const OUTSIDE = /]*\shref="\/(?!__preview\/)[^"]*"/; -test('same-site page links move into preview, carrying the session', () => { - assert.equal(previewHref('/about', options), `/__preview/about?cw_session=${SESSION}`); - assert.equal(previewHref('/', options), `/__preview/?cw_session=${SESSION}`); +test('same-site page links move under /__preview', () => { + assert.equal(previewHref('/about', options), '/__preview/about'); + assert.equal(previewHref('/', options), '/__preview/'); assert.equal( previewHref('https://contentworker.site/blog?page=2#top', options), - `/__preview/blog?page=2&cw_session=${SESSION}#top`, - ); - // A stale session on the link is replaced by the page's own. - assert.equal( - previewHref('/about?cw_session=other_1234', options), - `/__preview/about?cw_session=${SESSION}`, + '/__preview/blog?page=2#top', ); }); @@ -43,41 +38,33 @@ test('only is rewritten, re-escaped; other tags and attributes keep the 'Axskipout'; assert.equal( stayInPreview(html, options), - `Axskipout`, + 'Axskipout', ); }); -test('a live page keeps browsing inside preview', async () => { - const { body } = await call(`/__preview/inline?cw_session=${SESSION}`, { cookie: GRANT }); - assert.match(body, new RegExp(`Docs`)); - assert.match(body, //); +test('a draft page keeps browsing inside preview', async () => { + const { body } = await call('/__preview/inline', { cookie: GRANT }); + assert.match(body, /Docs<\/a>/); + assert.match(body, //); assert.match(body, /href="#main"/); - // Nothing outside preview is linked from the page's own site. - assert.doesNotMatch(body, /]*\shref="\/(?!__preview\/)[^"]*"/); + assert.doesNotMatch(body, OUTSIDE); }); -test('a path with no draft shows published content, the bar and the session, without the live script', async () => { - const { res, body } = await call(`/__preview/?cw_session=${SESSION}`, { cookie: GRANT }); +test('a path with no draft shows published content and the bar, links kept in preview, no live script', async () => { + const { res, body } = await call('/__preview/', { cookie: GRANT }); assert.equal(res.status, 200); assert.match(body, /Content, at the edge/); - assert.match(body, /
Previewing a draft.<\/div>/); - assert.match(body, new RegExp(`href="/__preview/docs\\?cw_session=${SESSION}"`)); + assert.match(body, /class="preview-bar"/); + assert.match(body, /href="\/__preview\/docs"/); + assert.doesNotMatch(body, OUTSIDE); assert.doesNotMatch(body, /live-preview\.js|data-cw-/); - assert.doesNotMatch(res.headers.get('content-security-policy') ?? '', /cw-preview/); }); -test('without a session, preview links stay as they were', async () => { - const { body } = await call('/__preview/inline', { cookie: GRANT }); - assert.match(body, /Docs<\/a>/); - assert.match(body, /__preview\/exit/); -}); - -test('re-rendered blocks keep their links in the session', async () => { +test('re-rendered blocks keep their links in preview', async () => { const { body } = await post( '/__preview/render', { entryId: 'p-inline', - session: SESSION, fields: { sections: [ { @@ -93,12 +80,6 @@ test('re-rendered blocks keep their links in the session', async () => { { cookie: GRANT }, ); const main: string = JSON.parse(body).main; - assert.match(main, new RegExp(`About`)); - assert.doesNotMatch(main, /]*\shref="\/(?!__preview\/)[^"]*"/); - const bad = await post( - '/__preview/render', - { entryId: 'p-inline', fields: {}, session: '' }, - { cookie: GRANT }, - ); - assert.equal(bad.res.status, 400); + assert.match(main, /About<\/a>/); + assert.doesNotMatch(main, OUTSIDE); }); diff --git a/packages/frontend/test/preview-marks.test.ts b/packages/frontend/test/preview-marks.test.ts index 27d2509..715ecc9 100644 --- a/packages/frontend/test/preview-marks.test.ts +++ b/packages/frontend/test/preview-marks.test.ts @@ -12,32 +12,41 @@ const ref = (entryId: string, contentType: string, field: string) => field, locale: 'en-US', }); +const attr = (entryId: string, field: string) => `data-cw-ref="${ref(entryId, 'page', field)}"`; -test('a preview of a blocks-field page marks its slot, its blocks and its title', async () => { +test('a preview of a blocks-field page marks its slot, its blocks and their fields by ref path', async () => { const { body } = await call('/__preview/inline', { cookie: GRANT }); - assert.match(body, /
/); - assert.match( - body, - /
/, + assert.ok( + body.includes(`
`), ); - assert.match( - body, - /
/, + assert.ok( + body.includes( + `
`, + ), + ); + assert.ok(body.includes(`

Inline hero

`)); + assert.ok( + body.includes( + `
`, + ), ); - // An unknown variant renders nothing, so there is nothing to mark. + assert.ok(body.includes(`

Asked

`)); + // The spec marks blocks by ref; there is no separate block attribute. + assert.doesNotMatch(body, /data-cw-block/); assert.doesNotMatch(body, /k-unknown/); - // The hero owns the h1 here; the page's title has no element of its own to mark. - assert.doesNotMatch(body, /data-cw-ref/); +}); + +test('a key holding [, ] or % is escaped in its ref path', async () => { + const { body } = await call('/__preview/odd', { cookie: 'cw_preview=p-odd~pw_good' }); + assert.ok(body.includes(attr('p-odd', 'sections[a%5Bb%5D%25]'))); + assert.ok(body.includes(attr('p-odd', 'sections[a%5Bb%5D%25].heading'))); }); test("a preview of a body page marks its title and body with the page entry's refs", async () => { const { body } = await call('/__preview/about', { cookie: 'cw_preview=p-about~pw_good' }); - assert.ok(body.includes(`data-cw-ref="${ref('p-about', 'page', 'body')}"`)); - assert.ok( - body.includes(`

About (draft)

`), - ); - // A body page has no blocks field. - assert.doesNotMatch(body, /data-cw-slot|data-cw-block/); + assert.ok(body.includes(attr('p-about', 'body'))); + assert.ok(body.includes(`

About (draft)

`)); + assert.doesNotMatch(body, /data-cw-slot/); }); test('published content under /__preview (not the draft) carries no marks', async () => { @@ -51,32 +60,29 @@ test('public pages carry none of the preview marks, scripts or meta', async () = const { res, body } = await call(path, { cookie: GRANT }); const html = body || (await res.text()); assert.ok(html.length > 0, path); - assert.doesNotMatch(html, /data-cw-|cw-admin-origin|live-preview\.js/, path); + assert.doesNotMatch(html, /data-cw-|cw-admin-origin|cw-entry|live-preview\.js/, path); } }); -test('live preview loads only under /__preview, for the draft, with cw_session and a known admin', async () => { - const live = await call('/__preview/inline?cw_session=sess_12345678', { cookie: GRANT }); +test('the live preview script loads on /__preview pages showing the draft, with a known admin', async () => { + const live = await call('/__preview/inline', { cookie: GRANT }); assert.match( live.body, - /`; +/** + * The handoff page. Its own Referrer-Policy is `same-origin` (every other preview response sends + * none): a POST from a page that sends no Referer carries `Origin: null`, and /__preview checks + * Origin. Same-origin only, so nothing leaves the site; the token was never in the URL's query. + */ +const HANDOFF_PAGE = `Opening preview

Opening the preview…

`; function handoffPage(admin: string | null): Response { // The gateway's withNonce stamps this response's nonce on the script and into its CSP. @@ -257,6 +272,7 @@ function handoffPage(admin: string | null): Response { 'cache-control': 'private, no-store', 'x-content-type-options': 'nosniff', ...previewHeaders(admin), + 'referrer-policy': 'same-origin', }, }); } @@ -293,10 +309,10 @@ export async function handlePreview(deps: PreviewDeps): Promise { if (request.method === 'POST') { if (url.pathname === PREFIX) { - const read = await jsonBody(request, url, admin, MAX_HANDOFF_BYTES); + if (!isNavigation(request)) return text(admin, 'Open preview links as a page.', 403); + const read = await formBody(request, url, admin, MAX_HANDOFF_BYTES); if ('refused' in read) return read.refused; - const { entry, token } = read.body; - return grant(cw, admin, entry, token, 'json'); + return grant(cw, admin, read.body.get('entry'), read.body.get('token')); } if (url.pathname === RENDER_PATH) return renderPreviewBlocks({ request, url, cw, site, admin }); return text(admin, 'Method not allowed', 405, { allow: 'GET, HEAD' }); @@ -307,7 +323,7 @@ export async function handlePreview(deps: PreviewDeps): Promise { const token = url.searchParams.get('token'); if (token !== null) { if (!isNavigation(request)) return text(admin, 'Open preview links as a page.', 403); - return grant(cw, admin, entryId, token, 'redirect'); + return grant(cw, admin, entryId, token); } if (!entryId || !ENTRY_ID.test(entryId)) return text(admin, 'Missing entry or token.', 400); return handoffPage(admin); diff --git a/packages/frontend/test/preview.test.ts b/packages/frontend/test/preview.test.ts index 3552b68..3026281 100644 --- a/packages/frontend/test/preview.test.ts +++ b/packages/frontend/test/preview.test.ts @@ -2,7 +2,7 @@ import assert from 'node:assert/strict'; import { test } from 'node:test'; import { runInNewContext } from 'node:vm'; import { HANDOFF_SCRIPT } from '../src/preview.ts'; -import { ADMIN, call, post } from './support/preview.ts'; +import { ADMIN, call, post, SITE } from './support/preview.ts'; const LEGACY_CLEAR = 'cw_preview=; Path=/__preview; HttpOnly; Secure; SameSite=Lax; Max-Age=0'; /** A grant: the old unpartitioned cookie cleared first, then the partitioned one set. */ @@ -17,11 +17,11 @@ const COOKIE = /^cw_preview=p-about~pw_good; Path=\/__preview; HttpOnly; Secure; SameSite=None; Partitioned; Max-Age=3600$/; /** The headers every /__preview response carries. */ -function assertPreviewHeaders(res: Response, admin = ADMIN) { +function assertPreviewHeaders(res: Response, admin = ADMIN, referrer = 'no-referrer') { const csp = res.headers.get('content-security-policy') ?? ''; assert.match(csp, new RegExp(`frame-ancestors ${admin.replace(/[.']/g, '\\$&')}(;|$)`)); assert.doesNotMatch(csp, /frame-ancestors[^;]*('self'|\*)/); - assert.equal(res.headers.get('referrer-policy'), 'no-referrer'); + assert.equal(res.headers.get('referrer-policy'), referrer); assert.equal(res.headers.get('x-robots-tag'), 'noindex'); assert.match(res.headers.get('cache-control') ?? '', /no-store/); } @@ -45,10 +45,14 @@ test('without ?token=, the link answers the fragment handoff page', async () => const { res, body, previewCalls } = await call('/__preview?entry=p-about'); assert.equal(res.status, 200); assert.match(res.headers.get('content-type') ?? '', /^text\/html/); - assertPreviewHeaders(res); + // Same-origin Referer, so its form POST carries Origin; nothing goes to another site. + assertPreviewHeaders(res, ADMIN, 'same-origin'); assert.equal(res.headers.get('cache-tag'), null); assert.match(body, //); - assert.match(body, //); + assert.match( + body, + /