diff --git a/.gitignore b/.gitignore index 544ce26..27f7278 100644 --- a/.gitignore +++ b/.gitignore @@ -3,5 +3,6 @@ node_modules/ .dev.vars .DS_Store packages/frontend/src/assets.generated.ts +packages/frontend/public/scripts/vendor/ packages/frontend/.tmp-site/ packages/frontend/dist/ diff --git a/AGENTS.md b/AGENTS.md index 54f39e9..8a169cd 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-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 49ca790..fedcce5 100644 --- a/README.md +++ b/README.md @@ -134,9 +134,56 @@ 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 submits it in a same-origin form 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. + +A preview link is a bearer link: anyone who opens it sees that entry's draft for an hour, in +their own browser, under `/__preview` only. Share it like a password. Prefer the `#token=` form; +`?token=` puts the token in the request URL, so it can reach request logs. + +### Live preview in the admin + +The ContentWorker admin frames `/__preview` pages (the entry editor's Site pane and the canvas) +and re-renders each unsaved edit in them, through `connectPreview` from +`@contentworker/sdk/live-preview`, which the runtime serves for you. +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 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 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. + +A block that styles itself from content writes CSS custom properties with +`attrs({ style: ctx.cssVars({ '--accent': fields.accent }) })`: every value is checked with the +SDK's `isSafeTokenValue` on every render, and an unsafe one is dropped whole. ## Develop diff --git a/biome.json b/biome.json index 4c286f9..7ef2f0e 100644 --- a/biome.json +++ b/biome.json @@ -7,7 +7,13 @@ }, "files": { "ignoreUnknown": true, - "includes": ["**", "!**/.wrangler", "!**/node_modules", "!**/worker-configuration.d.ts"] + "includes": [ + "**", + "!**/.wrangler", + "!**/node_modules", + "!**/worker-configuration.d.ts", + "!packages/frontend/public/scripts/vendor" + ] }, "formatter": { "enabled": true, diff --git a/docs/budget.md b/docs/budget.md index 555e6ef..a318629 100644 --- a/docs/budget.md +++ b/docs/budget.md @@ -3,16 +3,19 @@ The target is Lighthouse 100 in all four categories, on mobile and desktop, for every page. These budgets keep it there as a site adds blocks. `budgets.json` is enforced by `npm run budgets` in CI. -| What | Budget (gzip) | Why | -| -------------------------------------------------- | -------------------------------------- | --------------------------------------------------------------------------------------------- | -| `styles/critical.css` | 8 KB | The only render-blocking stylesheet. | -| Critical JS (`enhance.js`, `boot.js`, `shared.js`) | 10 KB | Modules never block, but they compete with the LCP image. | -| Deferred CSS (`deferred.css`, `fonts.css`) | 8 KB | Loaded after the first section. | -| Idle JS | 20 KB | Runs 3 s after `load`; still counts toward TBT on slow phones. | -| 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, critical.css, boot.js (+ enhance.js preloaded), LCP image, first-section block CSS. | -| Third-party before `load` | 0 | | +| What | Budget (gzip) | Why | +| -------------------------------------------------- | -------------------------------------- | ------------------------------------------------------------------------------------------------- | +| `styles/critical.css` | 8 KB | The only render-blocking stylesheet. | +| Critical JS (`enhance.js`, `boot.js`, `shared.js`) | 10 KB | Modules never block, but they compete with the LCP image. | +| Deferred CSS (`deferred.css`, `fonts.css`) | 8 KB | Loaded after the first section. | +| Idle JS | 20 KB | Runs 3 s after `load`; still counts toward TBT on slow phones. | +| 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. | +| Vendored live preview SDK (`scripts/vendor/sdk/`) | 20 KB | `@contentworker/sdk/live-preview` as published (16 KB today), imported only by `live-preview.js`. | +| 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, critical.css, boot.js (+ enhance.js preloaded), LCP image, first-section block CSS. | +| Third-party before `load` | 0 | | Field targets (p75): LCP ≤ 1.2 s, CLS ≤ 0.02, INP ≤ 100 ms. Lab: TBT ≤ 50 ms. @@ -30,7 +33,11 @@ Field targets (p75): LCP ≤ 1.2 s, CLS ≤ 0.02, INP ≤ 100 ms. Lab: TBT ≤ 5 Record each raised budget here: the block or file, the new number, the measurement that shows Lighthouse still scores 100, and the date. -_None yet._ +- **Vendored live preview SDK, 20 KB (2026-11-09).** The channel's frontend half + (`connectPreview`, message schemas, patching, layout) as `@contentworker/sdk@0.3.0` publishes it, + copied unminified by `scripts/embed-assets.ts`: 15,966 B gzip. It loads only on `/__preview` + pages showing a draft, after the page has painted, so it never reaches a public page or the + Lighthouse fixtures. The budget leaves room for SDK patch releases; a larger jump needs a look. ## Measured decisions diff --git a/package-lock.json b/package-lock.json index 34695be..068787f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -400,9 +400,9 @@ "link": true }, "node_modules/@contentworker/sdk": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/@contentworker/sdk/-/sdk-0.2.0.tgz", - "integrity": "sha512-4sRrgTyCQDPw3b7OzOsydtvAzwPeqiciU0bF2cDR3JIz3izw3R660P9sPKAOksZW4CUZr7eGcCnExU7n7NdXDw==", + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/@contentworker/sdk/-/sdk-0.3.0.tgz", + "integrity": "sha512-VY1NpNMaSBTa6KGX+KN4u2rScwkQC3z4JJYM4rxa3x/OP5DUB5PImy+czg63wCDaLg9rq5qRNeypsvtQTXRkiA==", "license": "Apache-2.0", "bin": { "contentworker": "dist/bin.js" @@ -4523,7 +4523,7 @@ }, "packages/create-site": { "name": "@contentworker/create-site", - "version": "0.1.2", + "version": "0.1.3", "license": "Apache-2.0", "bin": { "create-site": "dist/cli.js" @@ -4538,10 +4538,10 @@ }, "packages/frontend": { "name": "@contentworker/frontend", - "version": "0.4.0", + "version": "0.5.0", "license": "Apache-2.0", "dependencies": { - "@contentworker/sdk": "^0.2.0" + "@contentworker/sdk": "^0.3.0" }, "bin": { "contentworker-site": "dist/scripts/cli.js" diff --git a/packages/create-site/CHANGELOG.md b/packages/create-site/CHANGELOG.md index 8c232d8..6a0b76f 100644 --- a/packages/create-site/CHANGELOG.md +++ b/packages/create-site/CHANGELOG.md @@ -3,6 +3,10 @@ `@contentworker/create-site` follows semantic versioning. Release it like the runtime: bump `version`, add its section here, merge, then push the tag `create-site@v`. +## 0.1.3 + +- New sites use `@contentworker/frontend` 0.5.0: live preview in the ContentWorker admin. + ## 0.1.2 - New sites use `@contentworker/frontend` 0.4.0, and the `site.css` template names its new diff --git a/packages/create-site/package.json b/packages/create-site/package.json index a30b250..245c7fc 100644 --- a/packages/create-site/package.json +++ b/packages/create-site/package.json @@ -1,6 +1,6 @@ { "name": "@contentworker/create-site", - "version": "0.1.2", + "version": "0.1.3", "description": "npm create @contentworker/site: a new ContentWorker site on @contentworker/frontend, ready to run, optionally with its content model and starter pages.", "keywords": [ "contentworker", diff --git a/packages/create-site/src/templates.ts b/packages/create-site/src/templates.ts index aa7bfbd..2d99530 100644 --- a/packages/create-site/src/templates.ts +++ b/packages/create-site/src/templates.ts @@ -5,7 +5,7 @@ */ /** The @contentworker/frontend range new sites depend on; a test holds it to the package. */ -export const FRONTEND_RANGE = '^0.4.0'; +export const FRONTEND_RANGE = '^0.5.0'; /** wrangler for new sites: the version the runtime is tested with. */ export const WRANGLER_RANGE = '^4.156.1'; export const COMPATIBILITY_DATE = '2026-10-15'; diff --git a/packages/frontend/CHANGELOG.md b/packages/frontend/CHANGELOG.md index 3993927..de844bb 100644 --- a/packages/frontend/CHANGELOG.md +++ b/packages/frontend/CHANGELOG.md @@ -11,6 +11,33 @@ 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. +## 0.5.0 + +- **Live preview in the ContentWorker admin.** Pages under `/__preview` showing a draft load + `scripts/live-preview.js`, which connects through `connectPreview` from + `@contentworker/sdk/live-preview` (0.3, vendored into `scripts/vendor/sdk/` with its own budget) + when the admin frames the page: unsaved edits re-render through `POST /__preview/render`, only + the blocks that changed when that is safe; Coworker's proposals show as ghosts + (`styles/preview.css`); the page reports its entry (at most `PAGE_REPORT_LIMIT`) to each + session and starts over on `disconnect`. +- Under `/__preview` only, drafts carry content refs with field paths (`data-cw-ref` on the page's + fields, each block and the fields in it, `data-cw-slot` on the blocks' container); block + renderers mark their own fields with `ctx.ref(field)`. Links to the site's pages stay under + `/__preview`. Public pages are byte-identical (a golden test holds them). +- Preview links can carry the token in the fragment (`/__preview?entry={id}#token={token}`): a + tiny page reads it, drops it from history and submits it in a same-origin form POST, so it + 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 responses may be framed only by the admin (`frame-ancestors`, derived from + `CONTENTWORKER` or the new optional `CONTENTWORKER_ADMIN`; never the site's own origin; a + malformed value is logged and turns framing off), send no `Referer`, and the preview cookie is + `SameSite=None; Secure; Partitioned` (grants also clear the older unpartitioned cookie). +- `ctx.cssVars({...})` is the one way to write CSS custom properties from content: every value + passes `isSafeTokenValue` from `@contentworker/sdk`, on every render, and an unsafe one is + dropped whole. +- `npm run seed` resolves a signed upload URL relative to the API (a local stack answers one). +- Depends on `@contentworker/sdk` ^0.3.0 (its content-ref helpers replace the runtime's copy). + ## 0.4.0 **Breaking** for sites that override a runtime file, target its markup, or set CSS tokens. The diff --git a/packages/frontend/README.md b/packages/frontend/README.md index 0db3f9c..751d78c 100644 --- a/packages/frontend/README.md +++ b/packages/frontend/README.md @@ -35,5 +35,8 @@ Then `wrangler secret put CONTENTWORKER_KEY` (a Content Delivery API key). `defineSite({ routes })`. - **Any runtime file:** a file at the same path in your `public/` wins. - **Content model and starter content:** `npx contentworker-site seed --dry-run`. +- **Live preview:** set a type's preview URL in ContentWorker to + `https:///__preview?entry={id}#token={token}`; the admin frames it and shows unsaved + edits as you type. `CONTENTWORKER_ADMIN` names the admin when it can't be derived. The full guide is at https://contentworker.site/integrate. diff --git a/packages/frontend/budgets.json b/packages/frontend/budgets.json index 23783d6..31a000c 100644 --- a/packages/frontend/budgets.json +++ b/packages/frontend/budgets.json @@ -16,6 +16,21 @@ "files": ["styles/deferred.css", "styles/fonts.css"], "max": 8192 }, + { + "name": "preview JS (only /__preview drafts)", + "files": ["scripts/live-preview.js"], + "max": 4096 + }, + { + "name": "vendored live preview SDK (only /__preview drafts)", + "dir": "scripts/vendor/sdk", + "max": 20480 + }, + { + "name": "preview CSS (only /__preview drafts)", + "files": ["styles/preview.css"], + "max": 1024 + }, { "name": "idle JS", "files": ["scripts/idle.js", "scripts/consent.js", "scripts/consented.js"], diff --git a/packages/frontend/content-model/seed.ts b/packages/frontend/content-model/seed.ts index 1937923..7f61ade 100644 --- a/packages/frontend/content-model/seed.ts +++ b/packages/frontend/content-model/seed.ts @@ -172,7 +172,8 @@ export async function seed(o: SeedOptions): Promise { contentType: 'image/png', title: { [o.locale]: a.title }, }); - const put = await doFetch(created.upload.url, { + // The signed upload URL may be relative to the API (a local stack answers one). + const put = await doFetch(new URL(created.upload.url, o.api).href, { method: 'PUT', headers: created.upload.headers, body: o.image(a.width, a.height, i + 1), diff --git a/packages/frontend/package.json b/packages/frontend/package.json index 387f673..1135f4e 100644 --- a/packages/frontend/package.json +++ b/packages/frontend/package.json @@ -1,6 +1,6 @@ { "name": "@contentworker/frontend", - "version": "0.4.0", + "version": "0.5.0", "description": "The ContentWorker site runtime: edge-cached rendering from the Delivery API, purge on publish, preview, SEO and GEO, and the primary blocks, styles and scripts. Sites need only a wrangler.jsonc.", "keywords": [ "contentworker", @@ -69,6 +69,6 @@ "provenance": true }, "dependencies": { - "@contentworker/sdk": "^0.2.0" + "@contentworker/sdk": "^0.3.0" } } 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 830c5e5..cc27709 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 new file mode 100644 index 0000000..fd9d048 --- /dev/null +++ b/packages/frontend/public/scripts/live-preview.js @@ -0,0 +1,257 @@ +/** + * Live preview, the page side. Loaded only on /__preview pages showing a draft; `connectPreview` + * (the vendored @contentworker/sdk/live-preview, scripts/embed-assets.ts) 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). + */ +import { enhanceSection, enhanceSections } from './enhance.js'; +import { connectPreview, PAGE_REPORT_LIMIT } from './vendor/sdk/live-preview.js'; + +/** + * @typedef {import('./vendor/sdk/live-preview.js').Capability} Capability + * @typedef {import('./vendor/sdk/live-preview.js').LiveFields} LiveFields + * @typedef {import('./vendor/sdk/live-preview.js').LiveView} LiveView + */ + +/** @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 = ''; + +const htmlPolicy = /** @type {Window & { trustedTypes?: { createPolicy(name: string, + * rules: { createHTML(html: string): string }): { createHTML(html: string): string } } }} */ ( + window +).trustedTypes?.createPolicy('cw-preview', { + createHTML: (html) => { + if (!allowed || html !== allowed) throw new TypeError('cw-preview: render responses only'); + allowed = ''; + return html; + }, +}); + +/** @param {string} html markup from this origin's render endpoint */ +function fragment(html) { + const template = document.createElement('template'); + allowed = html; + template.innerHTML = /** @type {string} */ (htmlPolicy ? htmlPolicy.createHTML(html) : html); + allowed = ''; + return template.content; +} + +/** @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) { + if (document.head.querySelector(linkSelector(href))) 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. @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(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); + +/** + * 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 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); + } + } +} + +let latest = 0; +/** @type {Promise} */ +let newest = Promise.resolve(); +/** @type {AbortController | undefined} */ +let inflight; +/** The fields last put on screen. @type {LiveFields | undefined} */ +let shown; + +/** + * `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 onState(entryId, locale, _fields, view) { + const seq = ++latest; + inflight?.abort(); + const controller = new AbortController(); + inflight = controller; + const stale = () => seq !== latest; + const run = draw(entryId, locale, view, controller.signal, stale).then( + () => (stale() ? newest : undefined), + (error) => { + if (stale()) return newest; + throw error; + }, + ); + newest = run; + return run; +} + +/** + * @param {string} entryId + * @param {string} locale + * @param {LiveView} view + * @param {AbortSignal} signal + * @param {() => boolean} stale + * @param {boolean} [whole] + * @returns {Promise} + */ +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' }, + credentials: 'same-origin', + // Preview pages send no Referer, which would blank Origin; the Worker checks Origin. + referrerPolicy: 'same-origin', + signal, + 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 }[] }} */ + const out = await res.json(); + await Promise.all(out.css.map(headStylesheet)); + const main = document.querySelector('main'); + if (stale() || !main) return; + if (out.main !== undefined) { + main.replaceChildren(dropLinked(fragment(out.main))); + await enhanceSections(main); + } 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 enhanceSection(next); + } + } + markGhosts(view.ghosts); + shown = fields; +} + +/** Forgets what is on screen, so the next state re-renders
whole (a new session). */ +export function reset() { + latest += 1; + inflight?.abort(); + shown = undefined; +} + +const adminOrigin = document.querySelector('meta[name="cw-admin-origin"]')?.getAttribute('content'); +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) { + const preview = connectPreview({ + adminOrigin, + 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); + // The edited entry first; the admin reads at most PAGE_REPORT_LIMIT. + const entries = [entry].slice(0, PAGE_REPORT_LIMIT); + preview.on('connect', () => preview.emit('page', { url: window.location.href, entries })); + // A new session starts from a fresh entry.state: nothing on screen counts as rendered. + preview.on('disconnect', reset); + } +} diff --git a/packages/frontend/public/styles/preview.css b/packages/frontend/public/styles/preview.css new file mode 100644 index 0000000..9fe2b26 --- /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(--color-link); + --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/scripts/check-budgets.ts b/packages/frontend/scripts/check-budgets.ts index fbb2bfb..555993f 100644 --- a/packages/frontend/scripts/check-budgets.ts +++ b/packages/frontend/scripts/check-budgets.ts @@ -7,7 +7,8 @@ import { gzipSync } from 'node:zlib'; const root = new URL('..', import.meta.url).pathname; const pub = join(root, 'public'); interface Budgets { - groups: { name: string; files: string[]; max: number }[]; + /** A group lists its files, or names a directory whose .js files it sums (vendored builds). */ + groups: { name: string; files?: string[]; dir?: string; max: number }[]; perBlock: Record<'css' | 'js', number>; blockExceptions?: Record>>; } @@ -16,7 +17,18 @@ const gz = (file: string): number => gzipSync(readFileSync(file), { level: 9 }). const rows: { name: string; size: number; max: number; error?: string }[] = []; for (const group of budgets.groups) { - const missing = group.files.filter((f: string) => !existsSync(join(pub, f))); + const files = + group.files ?? + (group.dir && existsSync(join(pub, group.dir)) + ? readdirSync(join(pub, group.dir)) + .filter((f) => f.endsWith('.js')) + .map((f) => join(group.dir as string, f)) + : []); + if (!files.length) { + rows.push({ name: group.name, size: 0, max: group.max, error: `no files in ${group.dir}` }); + continue; + } + const missing = files.filter((f: string) => !existsSync(join(pub, f))); if (missing.length) rows.push({ name: group.name, @@ -24,7 +36,7 @@ for (const group of budgets.groups) { max: group.max, error: `missing ${missing.join(', ')}`, }); - const size = group.files + const size = files .filter((f: string) => existsSync(join(pub, f))) .reduce((n, f) => n + gz(join(pub, f)), 0); rows.push({ name: group.name, size, max: group.max }); diff --git a/packages/frontend/scripts/embed-assets.ts b/packages/frontend/scripts/embed-assets.ts index 25dcc94..a4e447a 100644 --- a/packages/frontend/scripts/embed-assets.ts +++ b/packages/frontend/scripts/embed-assets.ts @@ -3,11 +3,58 @@ // them from its Worker bundle without copying anything into its own public/. The bytes served // are exactly the source files: this is packaging, not a build. Runs on install, before tests // and type checks, and on prepack; the output is gitignored. -import { readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'; -import { extname, join, relative } from 'node:path'; +import { + copyFileSync, + mkdirSync, + readdirSync, + readFileSync, + rmSync, + statSync, + writeFileSync, +} from 'node:fs'; +import { dirname, extname, join, relative } from 'node:path'; +import { fileURLToPath } from 'node:url'; const root = new URL('..', import.meta.url).pathname; const pub = join(root, 'public'); + +/** + * The live preview SDK, vendored for the browser: `@contentworker/sdk/live-preview`'s published + * ESM build and the chunks it imports, copied unchanged into public/scripts/vendor/sdk/ (still + * no bundler: its imports are relative files, so they resolve beside it). Rewritten from + * node_modules on every run, gitignored, and packed with the runtime. A sibling .d.ts re-exports + * the package's types, so tsconfig.browser.json checks our calls against them. + */ +function vendorLivePreview(): string[] { + const entry = fileURLToPath(import.meta.resolve('@contentworker/sdk/live-preview')); + const from = dirname(entry); + const to = join(pub, 'scripts/vendor/sdk'); + rmSync(to, { recursive: true, force: true }); + mkdirSync(to, { recursive: true }); + const copied: string[] = []; + const queue = [entry.slice(from.length + 1)]; + while (queue.length) { + const name = queue.shift() as string; + if (copied.includes(name)) continue; + const source = readFileSync(join(from, name), 'utf8'); + for (const m of source.matchAll(/(?:\bfrom|\bimport)\s*["'](\.\/[^"']+)["']/g)) { + const dep = (m[1] as string).slice(2); + if (dep.includes('/')) throw new Error(`vendor: ${name} imports ${dep}, not a sibling file`); + queue.push(dep); + } + if (/\bimport\s*\(|\brequire\s*\(|from\s*["'](?!\.\/)|\bimport\s*["'](?!\.\/)/.test(source)) + throw new Error(`vendor: ${name} imports something other than a sibling file`); + copyFileSync(join(from, name), join(to, name)); + copied.push(name); + } + writeFileSync( + join(to, 'live-preview.d.ts'), + "// Generated by scripts/embed-assets.ts. Types for the vendored build.\nexport * from '@contentworker/sdk/live-preview';\n", + ); + return copied; +} + +const vendored = vendorLivePreview(); const TYPES: Record = { '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', @@ -40,4 +87,6 @@ writeFileSync( join(root, 'src/assets.generated.ts'), `// Generated by scripts/embed-assets.ts from public/. Do not edit.\nexport interface EmbeddedAsset {\n type: string;\n base64: boolean;\n body: string;\n}\n\nexport const EMBEDDED: Record = {\n${entries.join('\n')}\n};\n`, ); -console.log(`embedded ${entries.length} runtime assets`); +console.log( + `embedded ${entries.length} runtime assets (vendored @contentworker/sdk/live-preview: ${vendored.join(', ')})`, +); diff --git a/packages/frontend/src/config.ts b/packages/frontend/src/config.ts index bd86afb..28fc3be 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,70 @@ 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), 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, + delivery: string | null, + preview: string | null, +): string | null { + if (explicit?.trim()) { + 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; + } + const derived = + delivery && /^https?:\/\/cdn\./.test(delivery) + ? previewOrigin(delivery.replace('//cdn.', '//')) + : preview && /^https?:\/\/api\./.test(preview) + ? previewOrigin(preview.replace('//api.', '//')) + : null; + if (derived) + notice( + 'warn', + `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: 'warn' | '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. */ +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..1cbd23b --- /dev/null +++ b/packages/frontend/src/content-ref.ts @@ -0,0 +1,21 @@ +/** + * 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 or block it came from. + * + * `@contentworker/sdk`'s own helpers (docs/specs/live-preview-channel.md, "Content refs inside + * blocks"): six URI-encoded parts joined by `|` (space, environment, entry id, content type, + * field path, locale). 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. Imported + * by name so the Worker bundles only these (the SDK's client stays out). + */ +export { + blockKeyOf, + type ContentRef, + type FieldPath, + type FieldPathStep, + formatContentRef, + formatFieldPath, + parseContentRef, + parseFieldPath, + topLevelField, +} from '@contentworker/sdk'; diff --git a/packages/frontend/src/css-vars.ts b/packages/frontend/src/css-vars.ts new file mode 100644 index 0000000..7029dcd --- /dev/null +++ b/packages/frontend/src/css-vars.ts @@ -0,0 +1,24 @@ +import { isSafeTokenValue } from '@contentworker/sdk/live-preview'; + +/** + * The one way the runtime writes CSS custom properties from content: a `style` attribute value + * of `--name:value` pairs, for `attrs({ style: ctx.cssVars({ '--card-accent': fields.accent }) })`. + * + * Every value goes through `@contentworker/sdk`'s `isSafeTokenValue` (the same check live preview + * applies to token values), on every render, public or preview, whatever the value came from: + * Delivery, a draft, or unsaved fields. A value that fails is dropped whole, never escaped or + * trimmed into something else; so is a name that isn't a custom property name. Numbers are + * written as they are. Null when nothing is left, so `attrs` writes no attribute at all. + */ +const NAME = /^--[A-Za-z][A-Za-z0-9-]{0,63}$/; + +export function cssVars(vars: Record): string | null { + const out: string[] = []; + for (const [name, raw] of Object.entries(vars)) { + if (!NAME.test(name)) continue; + const value = typeof raw === 'number' && Number.isFinite(raw) ? String(raw) : raw; + if (typeof value !== 'string' || !value.trim() || !isSafeTokenValue(value)) continue; + out.push(`${name}:${value.trim()}`); + } + return out.length ? out.join(';') : null; +} diff --git a/packages/frontend/src/headers.ts b/packages/frontend/src/headers.ts index 16955d4..f2b25cf 100644 --- a/packages/frontend/src/headers.ts +++ b/packages/frontend/src/headers.ts @@ -17,6 +17,32 @@ 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. 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) => + d.startsWith('frame-ancestors ') + ? `frame-ancestors ${admin ?? "'none'"}` + : 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, live = false): Record { + return { + 'content-security-policy': previewCsp(admin, live), + 'referrer-policy': 'no-referrer', + 'x-robots-tag': 'noindex', + }; +} + const SECURITY = { 'content-security-policy': CSP, 'strict-transport-security': 'max-age=31536000; includeSubDomains', @@ -28,8 +54,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 +61,10 @@ 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; + /** A live preview page (kind 'preview' showing the draft, admin known). */ + live?: boolean; } export function htmlHeaders({ @@ -45,11 +73,13 @@ export function htmlHeaders({ etag, 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); - h.set('x-robots-tag', 'noindex'); + 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/host.ts b/packages/frontend/src/host.ts index c90a0ba..44dcf63 100644 --- a/packages/frontend/src/host.ts +++ b/packages/frontend/src/host.ts @@ -25,7 +25,8 @@ export function hostRedirect( status, headers: { location: new URL(`${url.pathname}${url.search}`, canonical.origin).href, - 'cache-control': 'public, max-age=86400', + // A preview link's query can hold its token: never let a browser keep that redirect. + 'cache-control': url.pathname.startsWith('/__preview') ? 'no-store' : 'public, max-age=86400', }, }); } diff --git a/packages/frontend/src/nonce.ts b/packages/frontend/src/nonce.ts index b49f534..8b28223 100644 --- a/packages/frontend/src/nonce.ts +++ b/packages/frontend/src/nonce.ts @@ -8,17 +8,45 @@ * 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. + * + * 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 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) => [nameOf(d), d] as const), ); } @@ -46,7 +74,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-links.ts b/packages/frontend/src/preview-links.ts new file mode 100644 index 0000000..23b2eca --- /dev/null +++ b/packages/frontend/src/preview-links.ts @@ -0,0 +1,53 @@ +import { escapeHtml } from './html.ts'; +import { match, normalize } from './routes.ts'; + +/** + * 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, + * 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'; + +const UNESCAPE: Record = { + '&': '&', + '"': '"', + ''': "'", + '<': '<', + '>': '>', +}; + +/** `href` (as written in the page) rewritten into preview, or null to leave it alone. */ +export function previewHref( + href: string, + { origins }: { origins: readonly 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; + return `${PREFIX}${path === '/' ? '/' : path}${url.search}${url.hash}`; +} + +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); + return next === null ? whole : `${open}${escapeHtml(next)}${close}`; + }); +} diff --git a/packages/frontend/src/preview-render.ts b/packages/frontend/src/preview-render.ts new file mode 100644 index 0000000..41cfb60 --- /dev/null +++ b/packages/frontend/src/preview-render.ts @@ -0,0 +1,258 @@ +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'; +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 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": "…", "locale"?: "en-US", "fields": { … }, "refs"?: ["", …] } + * + * `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: [{ 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. 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 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 + * 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_REFS = 500; +const MAX_REF_LENGTH = 2048; +const MAX_DEPTH = 64; +const MAX_NODES = 200_000; +/** The most HTML one re-render answers; a draft rendering more is refused, not streamed. */ +const MAX_HTML_BYTES = 5 * 1024 * 1024; +/** 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 }; + /** The origin allowed to frame preview responses (preview.ts frameAncestor). */ + admin: string | null; +} + +const json = (admin: string | null, body: unknown, status = 200): Response => + new Response(JSON.stringify(body), { + status, + headers: { + ...textHeaders(previewHeaders(admin)), + 'content-type': 'application/json; charset=utf-8', + }, + }); + +export async function renderPreviewBlocks({ + request, + url, + cw, + site, + admin, +}: RenderDeps): Promise { + const read = await jsonBody(request, url, admin, MAX_RENDER_BYTES); + if ('refused' in read) return read.refused; + 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)) + return json(admin, { error: 'locale must be a locale code.' }, 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) + return json(admin, { error: 'No preview grant for this entry.' }, 403); + const draft = await fetchDraft(cw, granted.entryId, granted.token); + if (!draft) return json(admin, { error: 'This preview has expired.' }, 403); + + let entry: Entry; + try { + entry = overlay(draft, fields); + } catch (error) { + if (error instanceof TooLarge) return json(admin, { 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(admin, { error: 'These fields could not be rendered.' }, 422); + } + + if (parts.reduce((n, p) => n + p.html.length, 0) > MAX_HTML_BYTES) + return json(admin, { error: 'These fields render too much to preview.' }, 413); + + 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 (!keys) return whole(); + const found: { key: string; part: MainPart }[] = []; + 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 }) => ({ + ref: marks?.(formatFieldPath({ field: 'sections', steps: [{ key }] })), + key, + html: links(part.section), + })), + css: [...new Set(found.flatMap(({ part }) => part.needs))], + }); +} + +/** 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; +} + +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): Entry { + const index = new Map(); + collect(draft.fields, index); + 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)) { + const embedded = index.get(value.id); + if (!embedded) return { id: value.id, linkType: value.linkType }; + // Each use of an embedded entry renders all of it: charge its size every time, so a few + // bytes of links can't ask for the same entry to render a hundred thousand times. + nodes += embedded.weight; + if (nodes > MAX_NODES) throw new TooLarge('fields are too large to render'); + return embedded.value; + } + 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)) next[name] = copy(value, 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, 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, weight: weigh(value) }); + next.push(...Object.values(value)); + } + level = next; + } +} + +/** How many values a value holds (itself included), counted up to MAX_NODES. */ +function weigh(root: unknown): number { + let n = 0; + const stack: unknown[] = [root]; + while (stack.length && n <= MAX_NODES) { + const v = stack.pop(); + n += 1; + if (Array.isArray(v)) stack.push(...v); + else if (isRecord(v)) stack.push(...Object.values(v)); + } + return n; +} diff --git a/packages/frontend/src/preview.ts b/packages/frontend/src/preview.ts index d3092fd..0d77ef3 100644 --- a/packages/frontend/src/preview.ts +++ b/packages/frontend/src/preview.ts @@ -1,23 +1,39 @@ 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. 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`; 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}$/; +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,74 +50,313 @@ export async function fetchDraft( return (await res.json()) as Entry; } -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; - const [entryId, token] = decodeURIComponent(match.slice(COOKIE.length + 1)).split('~'); - return entryId && token ? { entryId, token } : 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 }); + } + return out; } -const cookie = (value: string, maxAge: number): string => - `${COOKIE}=${value}; Path=${PREFIX}; HttpOnly; Secure; SameSite=Lax; Max-Age=${maxAge}`; +/** 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; +} /** - * @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}`; + +/** 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: { entry: Entry | null; path: string }; + preview: PreviewState; + /** The origin allowed to frame the page (frameAncestor), or null for nobody. */ + admin: string | null; }) => Promise; } -export async function handlePreview({ request, url, cw, render }: PreviewDeps): 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( + admin: string | null, + body: string, + status: number, + extra: Record = {}, +) { + return new Response(body, { + status, + headers: textHeaders({ ...previewHeaders(admin), ...extra }), + }); +} + +/** 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 to; +} + +/** + * 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, + admin: string | null, + max: number, +): Promise<{ body: Record } | { refused: Response }> { + if (!fromOwnPages(request, url)) + return { refused: text(admin, 'Cross-origin request refused.', 403) }; + if (!(request.headers.get('content-type') ?? '').toLowerCase().startsWith('application/json')) + return { refused: text(admin, 'Send application/json.', 415) }; + const raw = await readCapped(request, max); + 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)) + return { body: body as Record }; + } catch { + // fall through + } + return { refused: text(admin, 'Send a JSON object.', 400) }; +} + +/** Checks a token and answers with the grant cookie and a redirect to the draft. */ +async function grant( + cw: Backend, + admin: string | null, + entryId: unknown, + token: unknown, +): Promise { + if ( + typeof entryId !== 'string' || + typeof token !== 'string' || + !ENTRY_ID.test(entryId) || + !TOKEN.test(token) + ) + 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); + const value = `${encodeURIComponent(entryId)}~${token}`; + return new Response(null, { + status: 303, + headers: setCookies( + new Headers(textHeaders({ ...previewHeaders(admin), location })), + value, + MAX_AGE, + ), + }); +} + +/** The fields of a same-origin form POST, or the Response refusing it. */ +async function formBody( + request: Request, + url: URL, + admin: string | null, + max: number, +): Promise<{ body: URLSearchParams } | { refused: Response }> { + if (!fromOwnPages(request, url)) + return { refused: text(admin, 'Cross-origin request refused.', 403) }; + const type = (request.headers.get('content-type') ?? '').toLowerCase(); + if (!type.startsWith('application/x-www-form-urlencoded')) + return { refused: text(admin, 'Send the preview form.', 415) }; + const raw = await readCapped(request, max); + if (raw === null) return { refused: text(admin, 'Request body too large.', 413) }; + return { body: new URLSearchParams(raw) }; +} + +/** + * The fragment handoff, run by the page below while it is still being parsed. 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 submits it in a form POST to /__preview, + * which sets the cookie and redirects to the draft. Submitting during parsing aborts this page + * before its `load`, so a framing admin sees one page load (the draft's), not two. Reads the + * entry from its own URL: nothing from the request is printed into the page. + */ +export const HANDOFF_SCRIPT = `(()=>{const q=new URLSearchParams(location.search),t=new URLSearchParams(location.hash.slice(1)).get('token'),f=document.forms[0];history.replaceState(null,'',location.pathname+location.search);if(!t||!f){const s=document.getElementById('cw-status');if(s)s.textContent='This preview link has no token.';return}f.elements.namedItem('entry').value=q.get('entry')||'';f.elements.namedItem('token').value=t;f.submit()})()`; + +/** + * 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. + return new Response(HANDOFF_PAGE, { + headers: { + 'content-type': 'text/html; charset=utf-8', + 'cache-control': 'private, no-store', + 'x-content-type-options': 'nosniff', + ...previewHeaders(admin), + 'referrer-policy': 'same-origin', + }, + }); +} + +/** + * 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(), + headers: textHeaders(previewHeaders(admin)), }); + if (request.method === 'POST') { + if (url.pathname === PREFIX) { + 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; + 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' }); + } + 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), - }), - }); + if (token !== null) { + if (!isNavigation(request)) return text(admin, 'Open preview links as a page.', 403); + return grant(cw, admin, entryId, token); + } + 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({ 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 grant = readCookie(request); let entry: Entry | null = null; - if (grant) { - const draft = await fetchDraft(cw, grant.entryId, grant.token); - if (draft && pathFor(draft) === path) entry = draft; + // 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; + break; + } } - return render({ path, preview: { entry, path } }); + return render({ + path, + admin, + preview: { + entry, + path, + scope: { space: cw.space, environment: cw.environment, locale: cw.locale }, + 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..2e01a7b 100644 --- a/packages/frontend/src/render/block-ctx.ts +++ b/packages/frontend/src/render/block-ctx.ts @@ -1,4 +1,8 @@ +import { cssVars } from '../css-vars.ts'; 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 +44,8 @@ export function createRenderCtx({ image: (asset, opts) => image(asset, ctx, opts), richText: (doc) => renderRichText(doc, ctx), renderBlock: (e) => renderEmbedded(e, ctx), + ref: () => NO_REF, + cssVars, }; return ctx; } diff --git a/packages/frontend/src/render/blocks.ts b/packages/frontend/src/render/blocks.ts index e664d02..7293eb1 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 c1e9152..70ef8fc 100644 --- a/packages/frontend/src/render/document.ts +++ b/packages/frontend/src/render/document.ts @@ -1,6 +1,16 @@ import { classNameOf } from '../../public/scripts/shared.js'; +import { type ContentRef, formatContentRef, formatFieldPath } from '../content-ref.ts'; import { attrs, html, type Safe } from '../html.ts'; -import { type Entry, type Menus, type RenderCtx, sectionsIn } from '../types.ts'; +import { stayInPreview } from '../preview-links.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,10 +42,20 @@ 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 { + if (!input.preview) { + yield* renderPage(input); + return; + } + // 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 }); +} + +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 } : {}) }); @@ -47,6 +67,7 @@ export async function* renderDocument(input: DocumentInput): AsyncGenerator`; yield renderHead({ @@ -56,56 +77,143 @@ export async function* renderDocument(input: DocumentInput): AsyncGenerator` + .value; + } yield ''; - if (preview) { + 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; + } else if (preview) { yield html`
` .value; } - yield html`
${blockShell(CHROME.header, CHROME.header.default(settings, ctx))}
` + const slot = marks && isBlocksField(entry?.fields?.sections) ? marks('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 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 { + 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; + /** 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. */ + 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), + index: i, + 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,26 +221,44 @@ 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 { +/** 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 ? classNameOf(section.fields.style) : null; // Every section starts 'pending'; scripts/enhance.js marks it 'done' once its block JS ran. const state = 'pending'; + 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 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/render/page.ts b/packages/frontend/src/render/page.ts index bbe14c4..a21ea1a 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,8 @@ export async function renderPage({ etag, codeBase, preconnect: assetOrigins(origin, entry), + admin, + live: Boolean(preview?.live), }); const status = notFound ? 404 : 200; diff --git a/packages/frontend/src/types.ts b/packages/frontend/src/types.ts index d463e4a..8f7c072 100644 --- a/packages/frontend/src/types.ts +++ b/packages/frontend/src/types.ts @@ -101,6 +101,17 @@ 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; + /** + * A `style` value setting CSS custom properties from content, every value checked with + * `isSafeTokenValue` and dropped whole when it fails (src/css-vars.ts). Null when none is left. + */ + cssVars: (vars: Record) => string | null; } /** What Markdown rendering receives. */ @@ -144,6 +155,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 +186,50 @@ 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-ref`). + */ +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-ref`, + * `data-cw-slot`). Absent, a preview renders without them. + */ + scope?: { space: string; environment: string; locale: string } | undefined; + /** + * 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. + */ + 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/src/worker.ts b/packages/frontend/src/worker.ts index f890a87..7f38ac7 100644 --- a/packages/frontend/src/worker.ts +++ b/packages/frontend/src/worker.ts @@ -3,7 +3,7 @@ import { isVersioned } from './assets.ts'; import { ensureCmsRoutes } from './cms-routes.ts'; import { backend, ConfigError } from './config.ts'; import { createDelivery, DeliveryError } from './delivery.ts'; -import { textHeaders } from './headers.ts'; +import { previewHeaders, textHeaders } from './headers.ts'; import { hostRedirect } from './host.ts'; import { withNonce } from './nonce.ts'; import { handlePreview, PREFIX as PREVIEW } from './preview.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, - render: ({ path, preview }) => - renderPage({ env, ctx, url, path, request, preview, delivery: createDelivery(cw) }), + site: { origin: env.SITE_ORIGIN || url.origin, codeBase: `/v/${env.BUILD_ID}` }, + render: ({ path, preview, admin }) => + renderPage({ + env, + ctx, + url, + path, + request, + preview, + admin, + delivery: createDelivery(cw), + }), }); } if (!isVersioned(url.pathname)) { @@ -152,6 +165,8 @@ function forCache(request: Request, url: URL): Request { } function failure(error: unknown, url: URL): Response { + // Preview errors keep preview's policy: never framed, no Referer, never indexed. + const extra = url.pathname.startsWith(PREVIEW) ? previewHeaders(null) : {}; console.error( JSON.stringify({ msg: 'request failed', path: url.pathname, error: String(error) }), ); @@ -160,13 +175,13 @@ function failure(error: unknown, url: URL): Response { const local = /^(localhost|127\.0\.0\.1)$/.test(url.hostname); return new Response(local ? `Configuration: ${error.message}` : 'Site misconfigured.', { status: 500, - headers: textHeaders(), + headers: textHeaders(extra), }); } const status = error instanceof DeliveryError ? 503 : 500; return new Response('This page is temporarily unavailable. Please try again shortly.', { status, - headers: textHeaders({ 'retry-after': '30' }), + headers: textHeaders({ ...extra, 'retry-after': '30' }), }); } diff --git a/packages/frontend/test/canonical-host.test.ts b/packages/frontend/test/canonical-host.test.ts index dd6e0fe..6962425 100644 --- a/packages/frontend/test/canonical-host.test.ts +++ b/packages/frontend/test/canonical-host.test.ts @@ -41,3 +41,19 @@ test('no SITE_ORIGIN, or a malformed one, redirects nothing', () => { assert.equal(hostRedirect(new Request(url), url, undefined), null); assert.equal(hostRedirect(new Request(url), url, 'not a url'), null); }); + +test('a www redirect of a preview link is never cached (its query can hold a token)', async () => { + const { hostRedirect } = await import('../src/host.ts'); + const preview = hostRedirect( + new Request('https://www.contentworker.site/__preview?entry=e&token=pw_x'), + new URL('https://www.contentworker.site/__preview?entry=e&token=pw_x'), + 'https://contentworker.site', + ); + assert.equal(preview?.headers.get('cache-control'), 'no-store'); + const page = hostRedirect( + new Request('https://www.contentworker.site/about'), + new URL('https://www.contentworker.site/about'), + 'https://contentworker.site', + ); + assert.equal(page?.headers.get('cache-control'), 'public, max-age=86400'); +}); diff --git a/packages/frontend/test/config.test.ts b/packages/frontend/test/config.test.ts index c178474..7445cc5 100644 --- a/packages/frontend/test/config.test.ts +++ b/packages/frontend/test/config.test.ts @@ -67,3 +67,71 @@ 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', + ); + // 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.equal( + backend({ + CONTENTWORKER: 'acme/main', + CONTENTWORKER_DELIVERY: binding, + CONTENTWORKER_ADMIN: bad, + ...k, + }).admin, + null, + 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..08fab64 --- /dev/null +++ b/packages/frontend/test/content-ref.test.ts @@ -0,0 +1,109 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +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 = { + 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); +}); + +// 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/css-vars.test.ts b/packages/frontend/test/css-vars.test.ts new file mode 100644 index 0000000..421c06d --- /dev/null +++ b/packages/frontend/test/css-vars.test.ts @@ -0,0 +1,54 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { cssVars } from '../src/css-vars.ts'; +import { attrs, html } from '../src/html.ts'; +import { blockCtx } from './fixtures.ts'; + +test('safe token values become custom properties', () => { + assert.equal( + cssVars({ + '--accent': 'var(--color-link)', + '--gap': 'calc(1rem + 2px)', + '--tone': 'oklch(70% 0.1 250)', + '--cols': 3, + }), + '--accent:var(--color-link);--gap:calc(1rem + 2px);--tone:oklch(70% 0.1 250);--cols:3', + ); +}); + +test('an unsafe value is dropped whole, and so is a name that is not a custom property', () => { + const unsafe = [ + 'url(https://evil.example/x.png)', + 'URL(x)', + 'u\\rl(x)', + 'image-set("x.png" 1x)', + 'red; background: url(x)', + 'red" onmouseover="alert(1)', + "red' x='y", + 'url(x)', + '\n\nSkip to content
\"Alt

Content, at the edge

Lead

Read the getting-started guide

Why <fast>

Second image:

\"Alt

Built on Cloudflare.

© 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 · 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.

© 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 · 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.

© 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 · 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.

© 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 · 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.

© 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 · 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’t here. It may have moved.

Go to the home page

Built on Cloudflare.

© 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..b62ac94 --- /dev/null +++ b/packages/frontend/test/live-preview.dom.test.ts @@ -0,0 +1,279 @@ +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 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}

`; +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, fetch answered by `answer` in call order. */ +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 { + onState: OnState; + blockKeyOfRef: (ref: string | null) => string | undefined; + }; + const doc = window.document; + const html = () => doc.querySelector('main')?.innerHTML ?? ''; + return { window, doc, html, ...mod, requests, rules: () => rules }; +} + +/** 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); +}); + +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 { onState, html } = await mount(section('k-a', 'old'), async (body, n) => { + if (n === 1) await slow; + return echo(body); + }); + const order: string[] = []; + 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(html(), /second/); + assert.doesNotMatch(html(), /first/); + assert.deepEqual(order, ['second', 'first']); +}); + +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("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, 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 = 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/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, onState } = await mount(section('k-a', 'a'), echo); + const policy = rules(); + assert.ok(policy); + assert.throws(() => policy.createHTML(''), /render responses only/); + await onState('p-inline', 'en-US', {}, view([block('k-a', 'ok')])); + assert.throws( + () => policy.createHTML(section('k-a', 'ok')), + /render responses only/, + 'used once', + ); +}); + +test('framed with the admin, the page connects through the SDK, reports its entry and renders state', async () => { + const ADMIN = 'https://admin.example'; + const dom = new JSDOM( + `
${section('k-a', 'a')}
`, + { url: 'https://contentworker.site/__preview/inline', pretendToBeVisual: true }, + ); + const { window } = dom; + const posted: { data: Record; origin: string }[] = []; + const parent = { + postMessage: (data: Record, origin: string) => posted.push({ data, origin }), + }; + Object.defineProperty(window, 'parent', { value: parent }); + if (!window.crypto?.getRandomValues) + Object.defineProperty(window, 'crypto', { value: globalThis.crypto }); + 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); + return { ok: true, status: 200, json: async () => echo(body) }; + }, + }); + await import(`../public/scripts/live-preview.js?${Math.random()}`); + const offer = posted.find((p) => p.data.kind === 'connect.offer'); + assert.ok(offer, 'offered'); + assert.equal(offer.origin, ADMIN); + assert.deepEqual(offer.data.capabilities, [ + 'select', + 'patch.fields', + 'patch.blocks', + 'proposals', + 'scroll', + 'layout', + ]); + assert.ok(window.document.head.querySelector('link[href$="/styles/preview.css"]')); + const channel = offer.data.channel as string; + const version = (offer.data.versions as number[])[0]; + const send = (data: Record) => + window.dispatchEvent( + new window.MessageEvent('message', { + data: { v: version, channel, ...data }, + origin: ADMIN, + source: parent as unknown as Window, + }), + ); + send({ kind: 'connect.accept', version, capabilities: offer.data.capabilities }); + await new Promise((r) => setTimeout(r, 0)); + const page = posted.find((p) => p.data.kind === 'page'); + assert.deepEqual(page?.data.entries, [ + { entryId: 'p-inline', contentType: 'page', locale: 'en-US' }, + ]); + send({ + kind: 'entry.state', + rev: 1, + entryId: 'p-inline', + locale: 'en-US', + fields: { title: 'T', sections: [block('k-a', 'typed')] }, + }); + for (let i = 0; i < 20 && !posted.some((p) => p.data.kind === 'applied'); i += 1) + await new Promise((r) => setTimeout(r, 10)); + assert.equal(requests.length, 1); + assert.match(window.document.querySelector('main')?.innerHTML ?? '', /typed/); + assert.ok(posted.some((p) => p.data.kind === 'applied' && p.data.rev === 1)); +}); diff --git a/packages/frontend/test/preview-links.test.ts b/packages/frontend/test/preview-links.test.ts new file mode 100644 index 0000000..0e3a39d --- /dev/null +++ b/packages/frontend/test/preview-links.test.ts @@ -0,0 +1,85 @@ +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 options = { origins: ['https://contentworker.site'] }; +const OUTSIDE = /]*\shref="\/(?!__preview\/)[^"]*"/; + +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#top', + ); +}); + +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/critical.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 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"/); + assert.doesNotMatch(body, OUTSIDE); +}); + +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, /class="preview-bar"/); + assert.match(body, /href="\/__preview\/docs"/); + assert.doesNotMatch(body, OUTSIDE); + assert.doesNotMatch(body, /live-preview\.js|data-cw-/); +}); + +test('re-rendered blocks keep their links in preview', async () => { + const { body } = await post( + '/__preview/render', + { + entryId: 'p-inline', + 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, /About<\/a>/); + assert.doesNotMatch(main, OUTSIDE); +}); diff --git a/packages/frontend/test/preview-marks.test.ts b/packages/frontend/test/preview-marks.test.ts new file mode 100644 index 0000000..6ac3a95 --- /dev/null +++ b/packages/frontend/test/preview-marks.test.ts @@ -0,0 +1,89 @@ +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', + }); +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 their fields by ref path', async () => { + const { body } = await call('/__preview/inline', { cookie: GRANT }); + assert.ok( + body.includes(`
`), + ); + assert.ok( + body.includes( + `
`, + ), + ); + assert.ok(body.includes(`

Inline hero

`)); + assert.ok( + body.includes( + `
`, + ), + ); + 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/); +}); + +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(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 () => { + 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|cw-entry|live-preview\.js/, path); + } +}); + +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, + /`)); + // 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. */ +function runHandoff(href: string) { + const url = new URL(href); + const log: unknown[] = []; + const status = { textContent: '' }; + const inputs: Record = { entry: { value: '' }, token: { value: '' } }; + const location = { search: url.search, hash: url.hash, pathname: url.pathname }; + const form = { + elements: { namedItem: (name: string) => inputs[name] }, + submit: () => log.push(['submit', { entry: inputs.entry?.value, token: inputs.token?.value }]), + }; + runInNewContext(HANDOFF_SCRIPT, { + URLSearchParams, + location, + document: { + forms: [form], + getElementById: (id: string) => (id === 'cw-status' ? status : null), + }, + history: { + replaceState: (_s: unknown, _t: string, to: string) => { + location.hash = ''; + log.push(['replaceState', to]); + }, + }, + }); + return { log, status: status.textContent }; +} + +test('the handoff script drops the fragment first, then submits the token in its form', () => { + const { log } = runHandoff( + 'https://contentworker.site/__preview?entry=p-about&x=1#token=pw_good', ); + assert.deepEqual(log, [ + ['replaceState', '/__preview?entry=p-about&x=1'], + ['submit', { entry: 'p-about', token: 'pw_good' }], + ]); +}); + +test('without a token in the fragment, the handoff says so and submits nothing', () => { + const { log, status } = runHandoff('https://contentworker.site/__preview?entry=p-about'); + assert.deepEqual(log, [['replaceState', '/__preview?entry=p-about']]); + assert.match(status, /no token/); +}); + +/** The handoff form's POST, as the browser sends it from the handoff page. */ +function postForm(fields: Record, headers: Record = {}) { + return call('/__preview', { + method: 'POST', + headers: { + origin: SITE, + 'sec-fetch-site': 'same-origin', + 'sec-fetch-dest': 'iframe', + 'content-type': 'application/x-www-form-urlencoded', + ...headers, + }, + body: new URLSearchParams(fields).toString(), + }); +} + +test('POST /__preview trades the token for the cookie and redirects to the draft', async () => { + const { res } = await postForm({ entry: 'p-about', token: 'pw_good' }); + assert.equal(res.status, 303); + assert.equal(res.headers.get('location'), '/__preview/about'); + assertGrantCookies(res); + assertPreviewHeaders(res); + const bad = await postForm({ entry: 'p-about', token: 'pw_bad' }); + assert.equal(bad.res.status, 403); + assert.deepEqual(bad.res.headers.getSetCookie(), []); }); -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("POST /__preview takes this site's own form only, from a navigation, and only a little", async () => { + const grant = { entry: 'p-about', token: 'pw_good' }; + const status = async (headers: Record, fields: Record = grant) => + (await postForm(fields, 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); + assert.equal(await status({ 'sec-fetch-dest': 'empty' }), 403, 'a fetch, not a navigation'); + assert.equal(await status({ 'content-type': 'application/json' }), 415); + assert.equal(await status({}, { ...grant, pad: 'x'.repeat(5000) }), 413); + // No Origin at all (a request no browser page made) is refused too. + const bare = await call('/__preview', { + method: 'POST', + headers: { 'content-type': 'application/x-www-form-urlencoded' }, + body: new URLSearchParams(grant).toString(), + }); + assert.equal(bare.res.status, 403); }); -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('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); + // A page showing the draft runs the live preview script, so it may create cw-preview. + 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', 'same-origin'); +}); + 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'), '/'); + 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'), '/'); +}); + +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'), 'same-origin'); + } finally { + 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', 'same-origin'); +}); + +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-ref="site\|main\|p-inline\|page\|sections%5Bk-hero%5D\|en-US"/, + ); +}); + +test('in a frame the preview bar drops its exit link; elsewhere it keeps it', async () => { + const framed = await call('/__preview/inline', { + cookie: 'cw_preview=p-inline~pw_good', + headers: { 'sec-fetch-dest': 'iframe' }, + }); + assert.match(framed.body, /

Previewing a draft.<\/div>/); + assert.doesNotMatch(framed.body, /__preview\/exit/); + const top = await call('/__preview/inline', { cookie: 'cw_preview=p-inline~pw_good' }); + assert.match(top.body, /__preview\/exit/); +}); + +test('a preview page not showing the draft may not create the cw-preview policy', async () => { + const { res } = await call('/__preview/', { cookie: 'cw_preview=p-inline~pw_good' }); + assert.match(res.headers.get('content-security-policy') ?? '', /trusted-types loader(;|$)/); +}); + +test('a preview request that fails keeps the preview policy', async () => { + const { res } = await call('/__preview/about', { + cookie: 'cw_preview=p-about~pw_good', + env: { CONTENTWORKER_DELIVERY: { fetch: async () => new Response('boom', { status: 500 }) } }, + }); + assert.ok(res.status >= 500); + assert.match(res.headers.get('content-security-policy') ?? '', /frame-ancestors 'none'/); + assert.equal(res.headers.get('referrer-policy'), 'no-referrer'); + assert.equal(res.headers.get('x-robots-tag'), 'noindex'); }); diff --git a/packages/frontend/test/public-golden.test.ts b/packages/frontend/test/public-golden.test.ts new file mode 100644 index 0000000..99d31db --- /dev/null +++ b/packages/frontend/test/public-golden.test.ts @@ -0,0 +1,27 @@ +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 (0.4.0, the + * frontend's own names: refactor/own-names at b98dcf8, rendered by that commit's own code): 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, by + * rendering the six paths from the commit before it, 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 82e9ef5..759dd3e 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/seed.test.ts b/packages/frontend/test/seed.test.ts index 27ff72c..664d1e3 100644 --- a/packages/frontend/test/seed.test.ts +++ b/packages/frontend/test/seed.test.ts @@ -11,6 +11,7 @@ import { starterByType } from './starter-delivered.ts'; function fakeManagement({ types = [] as string[], counts = [] as { contentType: string; total: number }[], + relativeUploads = false, } = {}) { const calls: { method: string; path: string; body?: unknown }[] = []; let n = 0; @@ -20,7 +21,8 @@ function fakeManagement({ const path = url.pathname.replace('/spaces/site/environments/main', ''); const body = typeof init.body === 'string' ? JSON.parse(init.body) : init.body; calls.push({ method, path, body }); - if (url.host === 'upload.example') return new Response(null, { status: 200 }); + if (url.host === 'upload.example' || url.pathname.startsWith('/media/')) + return new Response(null, { status: 200 }); if (method === 'GET' && path === '/content-types') return Response.json({ items: types.map((apiId) => ({ apiId })) }); if (method === 'GET' && path === '/content-types/entry-counts') @@ -29,7 +31,10 @@ function fakeManagement({ n += 1; return Response.json({ asset: { id: `asset${n}` }, - upload: { url: `https://upload.example/${n}`, headers: { 'content-type': 'image/png' } }, + upload: { + url: relativeUploads ? `/media/site/main/${n}?sig=x` : `https://upload.example/${n}`, + headers: { 'content-type': 'image/png' }, + }, }); } if (method === 'POST' && path === '/entries') { @@ -165,3 +170,11 @@ test('every starter page renders: one h1, a description, headings in order, no b } } }); + +test('a signed upload URL relative to the API (a local stack answers one) resolves against it', async () => { + const m = fakeManagement({ relativeUploads: true }); + await seed({ ...base, fetch: m.fetch }); + const puts = m.calls.filter((c) => c.method === 'PUT'); + assert.ok(puts.length > 0); + for (const put of puts) assert.match(put.path, /^\/media\/site\/main\/\d+$/); +}); diff --git a/packages/frontend/test/support/preview.ts b/packages/frontend/test/support/preview.ts new file mode 100644 index 0000000..75291e6 --- /dev/null +++ b/packages/frontend/test/support/preview.ts @@ -0,0 +1,103 @@ +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)' } }, + /** A blocks page whose block keys need escaping in a ref path. */ + 'p-odd': { + id: 'p-odd', + contentType: 'page', + fields: { + title: 'Odd (draft)', + slug: 'odd', + sections: [{ _type: 'cta', _key: 'a[b]%', heading: 'Odd key', body: doc(p(text('x'))) }], + }, + }, + /** 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'; +/** 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'; diff --git a/packages/frontend/tsconfig.browser.json b/packages/frontend/tsconfig.browser.json index 3a452ab..7eea696 100644 --- a/packages/frontend/tsconfig.browser.json +++ b/packages/frontend/tsconfig.browser.json @@ -15,5 +15,7 @@ "noEmit": true, "skipLibCheck": true }, - "include": ["public/**/*.js"] + "include": ["public/**/*.js"], + // The vendored SDK build is checked by its own types (the generated .d.ts beside it). + "exclude": ["public/scripts/vendor/**"] }