Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(docsite): give the playground preview an opaque origin (#5523)

Baraa Hamodi4435b62d174f
diff --git a/.github/scripts/ci-docsite-browser.test.mjs b/.github/scripts/ci-docsite-browser.test.mjs
new file mode 100644
index 0000000000..8e5b283d88
--- /dev/null
+++ b/.github/scripts/ci-docsite-browser.test.mjs
@@ -0,0 +1,79 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ci-docsite-browser.test.mjs
+ * @input The docsite jobs in the PR CI workflow
+ * @output Fail-closed coverage for AST-030's existing docsite-test owner
+ * @position Workflow contract: browser failures cannot leave docsite-test green.
+ */
+import fs from 'node:fs';
+import path from 'node:path';
+import {spawnSync} from 'node:child_process';
+import {describe, expect, it} from 'vitest';
+import yaml from 'yaml';
+
+const root = path.resolve(import.meta.dirname, '../..');
+const {jobs} = yaml.parse(
+ fs.readFileSync(path.join(root, '.github/workflows/ci.yml'), 'utf8'),
+);
+const owner = jobs['docsite-test'];
+const browser = jobs['docsite-browser'];
+const guard = owner.steps.find(
+ step => step.name === 'Require successful docsite browser contract',
+);
+const ACTIVE =
+ "needs.check-scope.outputs.spec_only != 'true' && needs.check-scope.outputs.tooling_only != 'true'";
+
+describe('docsite browser required-check projection', () => {
+ it('joins the existing required context and uses the same surface route', () => {
+ expect(owner.needs).toEqual(['check-scope', 'docsite-browser']);
+ expect(owner.if).toBe(
+ "${{ github.event_name != 'workflow_dispatch' && always() && !cancelled() }}",
+ );
+ expect(browser.needs).toEqual(['check-scope']);
+ expect(browser.if).toBe(
+ `github.event_name != 'workflow_dispatch' && ${ACTIVE}`,
+ );
+ expect(guard.if).toBe(ACTIVE);
+ expect(
+ owner.steps.find(step => step.name === 'Generate and test docsite data')
+ .if,
+ ).toBe(ACTIVE);
+ expect(guard.env).toEqual({
+ DOCSITE_BROWSER_RESULT: '${{ needs.docsite-browser.result }}',
+ });
+ expect(owner['continue-on-error']).toBeUndefined();
+ expect(browser['continue-on-error']).toBeUndefined();
+ expect(guard['continue-on-error']).toBeUndefined();
+ const run = browser.steps.find(
+ step => step.name === 'Run docsite browser contracts',
+ );
+ expect(run.run).toBe('pnpm test:docsite-browser');
+ expect(run['continue-on-error']).toBeUndefined();
+ });
+
+ it('uploads the explicit browser output directory and fails if evidence is missing', () => {
+ const configPath = path.join(root, 'apps/docsite/playwright.config.ts');
+ const config = fs.readFileSync(configPath, 'utf8');
+ const outputDir = config.match(/outputDir:\s*'([^']+)'/)?.[1];
+ expect(outputDir).toBe('../../test-results/docsite');
+ const upload = browser.steps.find(
+ step => step.name === 'Upload docsite browser evidence',
+ );
+ expect(upload.if).toBe('always()');
+ expect(upload.with['if-no-files-found']).toBe('error');
+ expect(path.resolve(root, upload.with.path)).toBe(
+ path.resolve(path.dirname(configPath), outputDir),
+ );
+ });
+
+ it.each(['success', 'failure', 'cancelled', 'skipped', ''])(
+ 'fails closed for browser result %j',
+ result => {
+ const check = spawnSync('sh', ['-e', '-c', guard.run], {
+ env: {...process.env, DOCSITE_BROWSER_RESULT: result},
+ });
+ expect(check.status === 0).toBe(result === 'success');
+ },
+ );
+});
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 51a272ba64..129fef6e05 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -137,9 +137,9 @@ jobs:
printf 'docsite_only=false\nspec_only=false\ntooling_only=false\n' \
>> "$GITHUB_OUTPUT"
fi
- # Docsite data extraction tests — always runs, fast (~2s)
+ # Required docsite owner: data tests plus the production browser contract.
docsite-test:
- needs: [check-scope]
+ needs: [check-scope, docsite-browser]
if: ${{ github.event_name != 'workflow_dispatch' && always() && !cancelled() }}
runs-on: 2-core-ubuntu-arm
permissions:
@@ -151,6 +151,12 @@ jobs:
echo "Change scope could not be classified; refusing to skip required work."
exit 1
+ - name: Require successful docsite browser contract
+ if: needs.check-scope.outputs.spec_only != 'true' && needs.check-scope.outputs.tooling_only != 'true'
+ env:
+ DOCSITE_BROWSER_RESULT: ${{ needs.docsite-browser.result }}
+ run: test "$DOCSITE_BROWSER_RESULT" = 'success'
+
- name: Skip docsite work for Node tooling
if: needs.check-scope.outputs.tooling_only == 'true'
run: echo "Node-tooling PR — docsite generation is not an owned check"
@@ -188,6 +194,62 @@ jobs:
if: needs.check-scope.outputs.spec_only != 'true' && needs.check-scope.outputs.tooling_only != 'true'
run: pnpm -F @astryxdesign/docsite generate && pnpm -F @astryxdesign/docsite test
+ # Docsite browser contracts. The playground preview runs user-authored code
+ # in a sandboxed iframe whose only tie to the page is a nonce-attested
+ # MessagePort handshake (apps/docsite/src/app/playground/previewChannel.ts).
+ # jsdom can drive that state machine but cannot prove the integration: that
+ # the frame's real `load` event reaches it, that a replaced document is torn
+ # down and the current code and theme reach its successor, and that a
+ # document previewed code navigated the frame to receives nothing. Only the
+ # production build has the opaque-origin sandbox at all, so this job builds
+ # the docsite and drives `next start` in Chromium. Its outcome feeds the
+ # existing required docsite-test context; it is not another required lane.
+ docsite-browser:
+ needs: [check-scope]
+ if: github.event_name != 'workflow_dispatch' && needs.check-scope.outputs.spec_only != 'true' && needs.check-scope.outputs.tooling_only != 'true'
+ runs-on: 2-core-ubuntu-arm
+ permissions:
+ contents: read
+ steps:
+ - uses: actions/checkout@v7
+
+ - uses: ./.github/actions/setup
+
+ - name: Install Playwright
+ run: npx playwright install chromium
+
+ # The production build imports every theme package's built entry and the
+ # canary component packages, on top of core.
+ - name: Build docsite workspace dependencies
+ run: |
+ pnpm -F @astryxdesign/core build
+ pnpm -F @astryxdesign/lab build
+ pnpm -F @astryxdesign/charts build
+ pnpm -F @astryxdesign/richtext build
+ pnpm -F @astryxdesign/vega build
+ pnpm -F @astryxdesign/theme-neutral build
+ pnpm -F @astryxdesign/theme-matcha build
+ pnpm -F @astryxdesign/theme-stone build
+ pnpm -F @astryxdesign/theme-gothic build
+ pnpm -F @astryxdesign/theme-chocolate build
+ pnpm -F @astryxdesign/theme-y2k build
+ pnpm -F @astryxdesign/theme-butter build
+
+ - name: Build the docsite
+ run: pnpm -F @astryxdesign/docsite build
+
+ - name: Run docsite browser contracts
+ run: pnpm test:docsite-browser
+
+ - name: Upload docsite browser evidence
+ if: always()
+ uses: actions/upload-artifact@v7
+ with:
+ name: docsite-browser-evidence
+ path: test-results/docsite/
+ if-no-files-found: error
+ retention-days: 7
+
# Lightweight check — does the PR touch any published components?
# Gates pr-a11y and pr-rtl to avoid unnecessary work.
#
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 59ff58da48..fcf2cff06e 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -527,6 +527,26 @@ enforces it at author time; `pnpm guard:disabled-cursor --storybook-dir
apps/storybook/dist` hit-tests every disabled element in a built Storybook in
Chromium and fails on any other cursor.
+### Playground preview isolation
+
+The docsite playground runs user-authored code in a sandboxed iframe with an
+opaque origin, tied to the page only by a nonce-attested MessagePort handshake
+(`apps/docsite/src/app/playground/previewChannel.ts`). The `docsite-browser`
+job feeds the existing required `docsite-test` check and proves that boundary
+in Chromium against a production build: a reloaded
+preview document recovers with the current code and theme, and a document that
+previewed code navigated the frame to receives nothing. The sandbox only exists
+in production builds (`next dev` cannot serve its assets to an opaque origin),
+so the specs need a build first:
+
+```bash
+pnpm build # workspace packages the docsite imports
+pnpm -F @astryxdesign/docsite build
+npx playwright install chromium
+
+pnpm test:docsite-browser
+```
+
## Versioning & Releases
We use [Changesets](https://github.com/changesets/changesets) for versioning, with a thin Astryx layer on top so changelogs stay categorized, contributor-attributed, and aligned with our pre-1.0 conventions.
diff --git a/apps/docsite/README.md b/apps/docsite/README.md
index 5430930bca..9a02abb1a5 100644
--- a/apps/docsite/README.md
+++ b/apps/docsite/README.md
@@ -181,8 +181,42 @@ apps/docsite/
| `pnpm test` | Run vitest |
| `pnpm test:watch` | Run vitest in watch mode |
+## Playground preview restrictions
+
+The playground is for trying Astryx code, not saving its runtime data.
+Production previews (including deployed PR previews) are **ephemeral** and run
+with `sandbox="allow-scripts"`: Docsite origin-bound storage and parent-page DOM
+access are unavailable. Local storage may throw; previewed code has no
+persistence guarantee. In-memory interaction still works; the AI Chat template's
+resizable panel already falls back when its storage is unavailable. Reloading or
+replacing the preview resets its runtime state, then restores the editor's current
+code, theme, and mode.
+
+Production Chromium tests also characterize these browser consequences of the
+opaque origin; they do not establish separate playground capability policy:
+
+- **Clipboard and microphone:** Chromium's permission policy denies clipboard
+ writes and microphone access in the preview. Copy did not report success;
+ readable text can still be selected for manual copying. Dictation remained idle
+ while typing worked.
+- **Native pickers:** cross-origin `showPicker()` is restricted for date/time
+ controls; typed entry and Astryx's `nativePicker="never"` surface remain usable.
+ File and color controls have browser-defined exceptions and can still respond
+ to a user gesture. The sandbox is not a blanket ban on every native picker.
+- **Navigation:** previewed Astryx links use native anchors instead of inheriting
+ the docsite's Next router. Fragment links stay in the current document. A
+ non-fragment navigation replaces the document and triggers preview recovery.
+
+`next dev` retains the original same-origin sandbox so development assets load.
+It is not evidence for the production security boundary. Do not add
+`allow-same-origin` to make a production demo work.
+
## Testing
Tests live in `src/__tests__/data-extraction.test.ts` and validate the generated
registries: package discovery, component extraction, theme wiring, etc. Run
`pnpm generate` before running tests since they import from `src/generated/`.
+
+Browser contracts for the playground preview live in `e2e/` and run with
+`pnpm test:docsite-browser` from the repo root against a production build
+(`pnpm build` at the root, then `pnpm build` here); see `playwright.config.ts`.
diff --git a/apps/docsite/e2e/playground-preview-isolation.spec.ts b/apps/docsite/e2e/playground-preview-isolation.spec.ts
new file mode 100644
index 0000000000..e3672a7b69
--- /dev/null
+++ b/apps/docsite/e2e/playground-preview-isolation.spec.ts
@@ -0,0 +1,714 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file playground-preview-isolation.spec.ts
+ * @input A production docsite server (see ../playwright.config.ts)
+ * @output Browser proof of the playground preview's trust boundary
+ * @position Chromium contract for apps/docsite/src/app/playground —
+ * previewChannel.ts, PreviewStage.tsx, PlaygroundClient.tsx, preview/page.tsx.
+ *
+ * jsdom can drive the connector's state machine, and the unit suite does, but
+ * it cannot prove the integration those states describe: that the iframe's
+ * real `load` event is wired to the connector, that a fresh document really
+ * receives the current code and theme, that a sandboxed document really has
+ * no reach into the parent, and that a document previewed code navigated the
+ * frame to really gets nothing. Everything here is an expectation only a
+ * shipping engine can observe.
+ *
+ * Two lifecycles are pinned:
+ *
+ * 1. Reload: the preview document reloads itself (what previewed code calling
+ * `location.reload()` does). The playground must recover on its own — the
+ * replacement document renders the CURRENT code with the ACTIVE theme and
+ * mode before any edit — and an edit made afterwards must render in it.
+ *
+ * 2. Hostile navigation: previewed code navigates the frame to another
+ * origin, carrying the nonce it read from its own URL. That document must
+ * receive no port, no code and no theme, its replayed hello must earn
+ * nothing, and the playground must tear it down and restore a trusted
+ * preview that renders the current code again.
+ */
+
+import {writeFile} from 'node:fs/promises';
+import {expect, test, type Frame, type Page} from '@playwright/test';
+
+const PREVIEW_URL_MARK = '/playground/preview#nonce=';
+const HOSTILE_ORIGIN = 'https://hostile.example';
+
+// Every wait below spans a document lifecycle: the preview loads the
+// TypeScript compiler before it can render, and a recovery is a full
+// teardown, navigation, handshake and render. Wide enough for a cold CI
+// runner; `expect.poll` does not inherit the config's expect timeout.
+const POLL = {timeout: 45_000};
+
+/** The playground's current preview frame, if one is attached right now. */
+function previewFrame(page: Page): Frame | undefined {
+ return page
+ .frames()
+ .find(
+ frame =>
+ frame.parentFrame() === page.mainFrame() &&
+ frame.url().includes(PREVIEW_URL_MARK),
+ );
+}
+
+/** The current preview frame, which the caller has already waited for. */
+function currentPreviewFrame(page: Page): Frame {
+ const frame = previewFrame(page);
+ if (!frame) {
+ throw new Error('no preview frame is attached');
+ }
+ return frame;
+}
+
+/**
+ * Text content of the current preview document, or null while there is none
+ * or it is mid-replacement (a detached frame throws on evaluate).
+ */
+async function previewText(page: Page): Promise<string | null> {
+ const frame = previewFrame(page);
+ if (!frame) {
+ return null;
+ }
+ try {
+ return await frame.evaluate(() => document.body.innerText);
+ } catch {
+ return null;
+ }
+}
+
+async function expectPreviewToRender(page: Page, text: string) {
+ await expect
+ .poll(() => previewText(page), {
+ ...POLL,
+ message: `preview renders "${text}"`,
+ })
+ .toContain(text);
+}
+
+/** The preview's `<Theme>` wrapper as the frame paints it. */
+async function previewTheme(page: Page) {
+ const frame = previewFrame(page);
+ if (!frame) {
+ return null;
+ }
+ try {
+ return await frame.evaluate(() => {
+ // The preview wraps the rendered example in its own <Theme>; the
+ // docsite providers above it contribute another wrapper on the site
+ // theme, so pick the one carrying the playground's theme.
+ const wrappers = Array.from(
+ document.querySelectorAll('div[data-astryx-theme]'),
+ );
+ const wrapper = wrappers[wrappers.length - 1];
+ if (!wrapper) {
+ return null;
+ }
+ const style = getComputedStyle(wrapper);
+ return {
+ mode: wrapper.getAttribute('data-theme'),
+ bodyFont: style.getPropertyValue('--font-family-body').trim(),
+ };
+ });
+ } catch {
+ return null;
+ }
+}
+
+/** Replace the editor's source; the playground debounces and ships it. */
+async function setEditorCode(page: Page, code: string) {
+ await expect
+ .poll(
+ () =>
+ page.evaluate(() => {
+ const monaco = (
+ window as unknown as {
+ monaco?: {editor: {getModels: () => Array<unknown>}};
+ }
+ ).monaco;
+ return monaco?.editor.getModels().length ?? 0;
+ }),
+ POLL,
+ )
+ .toBeGreaterThan(0);
+ await page.evaluate(source => {
+ const monaco = (
+ window as unknown as {
+ monaco: {
+ editor: {getModels: () => Array<{setValue: (v: string) => void}>};
+ };
+ }
+ ).monaco;
+ monaco.editor.getModels()[0].setValue(source);
+ }, code);
+}
+
+function exampleRendering(text: string) {
+ return [
+ `import {Text} from '@astryxdesign/core/Text';`,
+ `export default function Example() {`,
+ ` return <Text>${text}</Text>;`,
+ `}`,
+ ].join('\n');
+}
+
+test.describe('playground preview isolation', () => {
+ test('recovers from a reloaded preview document with the current code, theme and mode', async ({
+ page,
+ }) => {
+ // ?theme=gothic seeds a non-default theme so "active theme" is
+ // distinguishable from the default; Gothic's body face is Fustat.
+ await page.goto('/playground?theme=gothic');
+ await expectPreviewToRender(page, 'Welcome');
+
+ // The production sandbox: an opaque origin with no reach into the parent
+ // and no storage, which is the boundary everything below protects.
+ const frame = currentPreviewFrame(page);
+ expect(
+ await page.locator('iframe[title="Preview"]').getAttribute('sandbox'),
+ ).toBe('allow-scripts');
+ expect(
+ await frame.evaluate(() => {
+ const blocked = (probe: () => unknown) => {
+ try {
+ probe();
+ return false;
+ } catch {
+ return true;
+ }
+ };
+ return {
+ parentDocument: blocked(() => window.parent.document),
+ localStorage: blocked(() => window.localStorage),
+ };
+ }),
+ ).toEqual({parentDocument: true, localStorage: true});
+
+ await page.getByRole('button', {name: 'Switch to dark'}).click();
+ await expect
+ .poll(() => previewTheme(page), POLL)
+ .toMatchObject({
+ mode: 'dark',
+ });
+ expect((await previewTheme(page))?.bodyFont).toContain('Fustat');
+
+ // The preview document reloads itself: same URL, same spent nonce.
+ const replacedUrl = frame.url();
+ await frame.evaluate(() => {
+ setTimeout(() => location.reload(), 0);
+ });
+
+ // The playground notices the second load, tears the frame down and mounts
+ // a fresh one under a new nonce …
+ await expect
+ .poll(() => previewFrame(page)?.url() ?? null, POLL)
+ .not.toBe(replacedUrl);
+ expect(currentPreviewFrame(page).url()).toContain(PREVIEW_URL_MARK);
+
+ // … and the new document renders the current code with the active theme
+ // and mode, with no edit needed to wake it up.
+ await expectPreviewToRender(page, 'Welcome');
+ await expect
+ .poll(() => previewTheme(page), POLL)
+ .toMatchObject({
+ mode: 'dark',
+ });
+ expect((await previewTheme(page))?.bodyFont).toContain('Fustat');
+
+ // An edit made after the reload renders in the replacement document.
+ await setEditorCode(page, exampleRendering('Reloaded and edited'));
+ await expectPreviewToRender(page, 'Reloaded and edited');
+ await expect
+ .poll(() => previewTheme(page), POLL)
+ .toMatchObject({
+ mode: 'dark',
+ });
+ expect((await previewTheme(page))?.bodyFont).toContain('Fustat');
+ });
+
+ test('gives a document that previewed code navigated the frame to nothing, then restores the preview', async ({
+ page,
+ }) => {
+ // Everything the hostile document observes is reported out of band,
+ // because the playground destroys it as soon as it finishes loading.
+ const reports: URL[] = [];
+ await page.route(`${HOSTILE_ORIGIN}/**`, async route => {
+ const url = new URL(route.request().url());
+ if (url.pathname === '/report') {
+ reports.push(url);
+ await route.fulfill({status: 204});
+ return;
+ }
+ if (url.pathname === '/slow.gif') {
+ // Holds the hostile document's `load` event open so it has ample
+ // time to receive anything the playground might send it.
+ await new Promise(resolve => setTimeout(resolve, 1500));
+ await route.fulfill({status: 404});
+ return;
+ }
+ await route.fulfill({
+ status: 200,
+ contentType: 'text/html',
+ body: hostileDocument(url.searchParams.get('nonce') ?? ''),
+ });
+ });
+
+ await page.goto('/playground');
+ await expectPreviewToRender(page, 'Welcome');
+ const trustedUrl = currentPreviewFrame(page).url();
+
+ // Previewed code, running inside the trusted document with everything it
+ // knows, navigates the frame to another origin and takes the nonce along.
+ await setEditorCode(
+ page,
+ [
+ `location.href = '${HOSTILE_ORIGIN}/landing?nonce=' +`,
+ ` encodeURIComponent(new URLSearchParams(location.hash.slice(1)).get('nonce') ?? '');`,
+ `export default function Example() { return null; }`,
+ ].join('\n'),
+ );
+
+ // The hostile document did run (this is not a vacuous pass) and did
+ // replay the nonce.
+ await expect
+ .poll(() => reports.map(r => r.searchParams.get('event')), POLL)
+ .toContain('hello-replayed');
+
+ // Once it has run, take the hostile snippet back out of the editor so the
+ // restored preview does not immediately navigate away again.
+ await setEditorCode(page, exampleRendering('Restored preview'));
+
+ // The playground tears the hostile document down and restores a trusted
+ // preview under a fresh nonce, which renders the current code.
+ await expect
+ .poll(
+ () =>
+ page.frames().some(frame => frame.url().startsWith(HOSTILE_ORIGIN)),
+ POLL,
+ )
+ .toBe(false);
+ await expect
+ .poll(() => previewFrame(page)?.url() ?? null, POLL)
+ .not.toBe(trustedUrl);
+ await expectPreviewToRender(page, 'Restored preview');
+
+ // The hostile document got nothing: no port, so no code and no theme.
+ const received = reports
+ .filter(r => r.searchParams.get('event') === 'received')
+ .map(r => ({
+ type: r.searchParams.get('type'),
+ ports: r.searchParams.get('ports'),
+ via: r.searchParams.get('via'),
+ }));
+ expect(received.filter(r => r.via === 'port')).toEqual([]);
+ expect(received.filter(r => r.ports !== '0')).toEqual([]);
+ expect(received.map(r => r.type)).not.toContain('astryx-preview-connect');
+ expect(received.map(r => r.type)).not.toContain('preview-code');
+ expect(received.map(r => r.type)).not.toContain('preview-theme');
+
+ // And the editor still holds what the user wrote.
+ expect(
+ await page.evaluate(() =>
+ (
+ window as unknown as {
+ monaco: {
+ editor: {getModels: () => Array<{getValue: () => string}>};
+ };
+ }
+ ).monaco.editor
+ .getModels()[0]
+ .getValue(),
+ ),
+ ).toContain('Restored preview');
+ });
+});
+
+test.describe('restricted preview capabilities', () => {
+ test('keeps targeting and property edits on the attested channel', async ({
+ page,
+ }, testInfo) => {
+ await page.goto('/playground');
+ await expectPreviewToRender(page, 'Welcome');
+ await setEditorCode(
+ page,
+ `
+ import {Button} from '@astryxdesign/core/Button';
+ export default function Example() { return <Button label="Edit me" />; }
+ `,
+ );
+ await expectPreviewToRender(page, 'Edit me');
+ const frame = currentPreviewFrame(page);
+ await page
+ .getByRole('button', {name: 'Target element', exact: true})
+ .click();
+ await frame.getByRole('button', {name: 'Edit me', exact: true}).click();
+ await expect(
+ page.getByRole('button', {name: 'Target element', exact: true}),
+ ).toHaveAttribute('aria-pressed', 'false');
+ await frame.getByRole('button', {name: 'Properties', exact: true}).click();
+ await frame
+ .getByRole('textbox', {name: 'label', exact: true})
+ .fill('Edited through properties');
+ await frame.getByRole('button', {name: 'Apply', exact: true}).click();
+ await expectPreviewToRender(page, 'Edited through properties');
+ expect(
+ await page.evaluate(() =>
+ (
+ window as unknown as {
+ monaco: {
+ editor: {getModels: () => Array<{getValue: () => string}>};
+ };
+ }
+ ).monaco.editor
+ .getModels()[0]
+ .getValue(),
+ ),
+ ).toContain('Edited through properties');
+ await page.screenshot({
+ path: testInfo.outputPath('targeting-roundtrip.png'),
+ });
+ });
+
+ test('keeps AI Chat usable without its saved panel width', async ({
+ page,
+ }, testInfo) => {
+ const errors: string[] = [];
+ page.on('pageerror', error => errors.push(error.message));
+ await page.goto('/playground?template=ai-chat');
+ await expectPreviewToRender(page, 'auth-service.ts');
+ const frame = currentPreviewFrame(page);
+ const input = frame.locator('[contenteditable="true"]').first();
+ await input.fill('Draft stays in memory');
+ await expect(input).toHaveText('Draft stays in memory');
+ expect(
+ await frame.evaluate(() => {
+ try {
+ localStorage.setItem('preview-probe', 'blocked');
+ return false;
+ } catch {
+ return true;
+ }
+ }),
+ ).toBe(true);
+ await expect(
+ page.getByText('Ephemeral preview:', {exact: false}),
+ ).toBeVisible();
+ await page.screenshot({path: testInfo.outputPath('ai-chat-ephemeral.png')});
+ expect(errors).toEqual([]);
+ });
+
+ test('denies privileged clipboard and microphone operations while typed input works', async ({
+ page,
+ }, testInfo) => {
+ const errors: string[] = [];
+ page.on('pageerror', error => errors.push(error.message));
+ await page.goto('/playground');
+ await expectPreviewToRender(page, 'Welcome');
+ await setEditorCode(
+ page,
+ `
+ import {useState} from 'react';
+ import {useClipboard} from '@astryxdesign/core/hooks';
+ import {useChatDictation, ChatDictationButton} from '@astryxdesign/core/Chat';
+ export default function Example() {
+ const {copy, isCopied} = useClipboard();
+ const [copyResult, setCopyResult] = useState('Copy not attempted');
+ const [mic, setMic] = useState('Microphone not attempted');
+ const [speechError, setSpeechError] = useState('');
+ const [dictationAttempts, setDictationAttempts] = useState(0);
+ const dictation = useChatDictation({onError: event => setSpeechError(event.error)});
+ const observedDictation = {...dictation, toggle: () => {
+ setDictationAttempts(count => count + 1);
+ dictation.toggle();
+ }};
+ return <div>
+ <p>Restricted capabilities</p>
+ <textarea aria-label="Typed message" defaultValue="Selectable text" />
+ <button onClick={async () => setCopyResult(await copy('Selectable text') ? 'Copied' : 'Copy unavailable')}>Try copy</button>
+ <p>{copyResult}</p><p>{isCopied ? 'Copied state' : 'Not copied'}</p>
+ <button onClick={async () => {
+ if (!navigator.mediaDevices?.getUserMedia) {
+ setMic('Microphone unavailable');
+ return;
+ }
+ try {
+ const stream = await navigator.mediaDevices.getUserMedia({audio: true});
+ stream.getTracks().forEach(track => track.stop());
+ setMic('Microphone allowed');
+ } catch (error) { setMic('Microphone denied: ' + error.name); }
+ }}>Try microphone</button>
+ <p>{mic}</p>
+ <p>{dictation.isSupported ? 'Dictation available' : 'Dictation unavailable'}</p>
+ <ChatDictationButton dictation={observedDictation} label="Try dictation" />
+ <p>Dictation attempts: {dictationAttempts}</p>
+ <p>{dictation.isListening ? 'Listening' : 'Not listening'}</p>
+ <p>{speechError}</p>
+ </div>;
+ }
+ `,
+ );
+ await expectPreviewToRender(page, 'Restricted capabilities');
+ const frame = currentPreviewFrame(page);
+ const capabilities = await frame.evaluate(() => {
+ const policy = (
+ document as Document & {
+ featurePolicy: {allowsFeature: (feature: string) => boolean};
+ }
+ ).featurePolicy;
+ return {
+ secureContext: window.isSecureContext,
+ clipboard: typeof navigator.clipboard,
+ getUserMedia: typeof navigator.mediaDevices?.getUserMedia,
+ speechRecognition:
+ 'SpeechRecognition' in window || 'webkitSpeechRecognition' in window,
+ microphoneAllowed: policy.allowsFeature('microphone'),
+ clipboardWriteAllowed: policy.allowsFeature('clipboard-write'),
+ };
+ });
+ await writeFile(
+ testInfo.outputPath('browser-capabilities.json'),
+ JSON.stringify(capabilities, null, 2),
+ );
+ // CI has no physical microphone, and Chromium can report NotFoundError
+ // before a permission error. Pin the real policy independently so missing
+ // hardware cannot make a relaxed sandbox appear to enforce the boundary.
+ expect(capabilities).toMatchObject({
+ microphoneAllowed: false,
+ clipboardWriteAllowed: false,
+ });
+ await frame.getByRole('button', {name: 'Try copy', exact: true}).click();
+ await expect(
+ frame.getByText('Copy unavailable', {exact: true}),
+ ).toBeVisible();
+ await expect(frame.getByText('Not copied', {exact: true})).toBeVisible();
+ await frame
+ .getByRole('button', {name: 'Try microphone', exact: true})
+ .click();
+ await expect(
+ frame.getByText(
+ /^Microphone (unavailable|denied: (SecurityError|NotAllowedError|NotFoundError))$/,
+ ),
+ ).toBeVisible();
+ if (
+ await frame
+ .getByRole('button', {name: 'Try dictation', exact: true})
+ .count()
+ ) {
+ await frame
+ .getByRole('button', {name: 'Try dictation', exact: true})
+ .click();
+ // SpeechRecognition can expose its constructor without delivering an
+ // asynchronous error in headless Chromium. Prove the real hook was
+ // activated, retain its observed outcome, and require usable typed input.
+ // Permission policy above—not a service callback—is the denial oracle.
+ await expect(
+ frame.getByText('Dictation attempts: 1', {exact: true}),
+ ).toBeVisible();
+ } else {
+ await expect(
+ frame.getByText('Dictation unavailable', {exact: true}),
+ ).toBeVisible();
+ }
+ await expect(frame.getByText('Not listening', {exact: true})).toBeVisible();
+ await frame
+ .getByRole('textbox', {name: 'Typed message'})
+ .fill('Typing still works');
+ await expect(
+ frame.getByRole('textbox', {name: 'Typed message'}),
+ ).toHaveValue('Typing still works');
+ await writeFile(
+ testInfo.outputPath('capability-outcomes.txt'),
+ await frame.locator('body').innerText(),
+ );
+ await page.screenshot({
+ path: testInfo.outputPath('restricted-capabilities.png'),
+ });
+ expect(errors).toEqual([]);
+ });
+
+ test('retains typed dates and user-activated file pickers without origin privileges', async ({
+ page,
+ }, testInfo) => {
+ const errors: string[] = [];
+ page.on('pageerror', error => errors.push(error.message));
+ await page.goto('/playground');
+ await expectPreviewToRender(page, 'Welcome');
+ await setEditorCode(
+ page,
+ `
+ import {useState, useRef} from 'react';
+ import {DateInput} from '@astryxdesign/core/DateInput';
+ export default function Example() {
+ const [date, setDate] = useState('2026-09-23');
+ const [picker, setPicker] = useState('Picker not attempted');
+ const [file, setFile] = useState('No file');
+ const input = useRef(null);
+ return <div>
+ <p>Native picker restrictions</p>
+ <DateInput label="Appointment" nativePicker="always" value={date} onChange={setDate} />
+ <p>Selected date: {date}</p>
+ <input ref={input} type="date" aria-label="Native date probe" />
+ <button onClick={() => {
+ try { input.current.showPicker(); setPicker('Date picker allowed'); }
+ catch (error) { setPicker('Date picker denied: ' + error.name); }
+ }}>Try date picker</button>
+ <p>{picker}</p>
+ <input type="file" aria-label="Choose file" onChange={event => setFile(event.target.files[0]?.name ?? 'No file')} />
+ <p>{file}</p>
+ <input type="color" aria-label="Choose color" defaultValue="#0064e0" onClick={event => {
+ try { event.currentTarget.showPicker(); setPicker('Color picker allowed'); }
+ catch (error) { setPicker('Color picker denied: ' + error.name); }
+ }} />
+ </div>;
+ }
+ `,
+ );
+ await expectPreviewToRender(page, 'Native picker restrictions');
+ const frame = currentPreviewFrame(page);
+ await frame
+ .getByRole('button', {name: 'Try date picker', exact: true})
+ .click();
+ await expect(
+ frame.getByText('Date picker denied: SecurityError', {exact: true}),
+ ).toBeVisible();
+ await frame
+ .getByRole('button', {name: 'Open calendar', exact: true})
+ .click();
+ const date = frame.locator('input[type="date"]').first();
+ await expect(date).toBeFocused();
+ await date.fill('2026-10-05');
+ await date.press('Tab');
+ await expect(
+ frame.getByText('Selected date: 2026-10-05', {exact: true}),
+ ).toBeVisible();
+ const chooserEvent = page.waitForEvent('filechooser');
+ await frame.getByLabel('Choose file', {exact: true}).click();
+ const chooser = await chooserEvent;
+ await chooser.setFiles({
+ name: 'example.txt',
+ mimeType: 'text/plain',
+ buffer: Buffer.from('Selected by the user'),
+ });
+ await expect(frame.getByText('example.txt', {exact: true})).toBeVisible();
+ // Color is another cross-origin showPicker exception; prove the activated
+ // API call succeeds rather than mistaking a silent click for an open picker.
+ await frame.getByLabel('Choose color', {exact: true}).click();
+ await page.keyboard.press('Escape');
+ await expect(
+ frame.getByText('Color picker allowed', {exact: true}),
+ ).toBeVisible();
+ await page.screenshot({path: testInfo.outputPath('native-pickers.png')});
+ expect(errors).toEqual([]);
+ });
+
+ test('uses native links in the opaque document and recovers from non-fragment navigation', async ({
+ page,
+ }, testInfo) => {
+ const errors: string[] = [];
+ page.on('pageerror', error => errors.push(error.message));
+ let navigated = false;
+ await page.route('**/preview-destination', async route => {
+ navigated = true;
+ await route.fulfill({
+ contentType: 'text/html',
+ body: '<p>Destination reached</p>',
+ });
+ });
+ await page.goto('/playground');
+ await expectPreviewToRender(page, 'Welcome');
+ await setEditorCode(
+ page,
+ `
+ import {Link} from '@astryxdesign/core/Link';
+ export default function Example() {
+ return <div>
+ <p>Preview navigation</p>
+ <Link href="#section">Jump to section</Link>
+ <p id="section">Same-document section</p>
+ <Link href="/preview-destination">Open destination</Link>
+ </div>;
+ }
+ `,
+ );
+ await expectPreviewToRender(page, 'Preview navigation');
+ const frame = currentPreviewFrame(page);
+ const originalSource = await page
+ .locator('iframe[title="Preview"]')
+ .getAttribute('src');
+ await frame
+ .getByRole('link', {name: 'Jump to section', exact: true})
+ .click();
+ await expect.poll(() => frame.url(), POLL).toContain('#section');
+ expect(frame.isDetached()).toBe(false);
+ await expect(page.locator('iframe[title="Preview"]')).toHaveAttribute(
+ 'src',
+ originalSource ?? '',
+ );
+ await frame
+ .getByRole('link', {name: 'Open destination', exact: true})
+ .click();
+ await expect.poll(() => navigated, POLL).toBe(true);
+ await expect.poll(() => frame.isDetached(), POLL).toBe(true);
+ await expectPreviewToRender(page, 'Preview navigation');
+ expect(
+ await page.locator('iframe[title="Preview"]').getAttribute('src'),
+ ).not.toBe(originalSource);
+ await expect(page.locator('iframe[title="Preview"]')).toHaveAttribute(
+ 'sandbox',
+ 'allow-scripts',
+ );
+ await page.screenshot({
+ path: testInfo.outputPath('navigation-restored.png'),
+ });
+ expect(errors).toEqual([]);
+ });
+});
+
+/**
+ * The page previewed code navigates the frame to. It plays the attacker the
+ * reviewers described: it replays the nonce it was handed in a hello — once
+ * immediately, then continuously, so a replay also lands in the window between
+ * the playground discarding the old generation and React committing the new
+ * iframe, while the old frame's window is still the one the playground holds —
+ * adopts any port it is offered, answers `preview-ready` on it to draw out the
+ * code and theme, tries to rewrite the editor, and reports every message it
+ * sees.
+ */
+function hostileDocument(nonce: string): string {
+ return `<!doctype html>
+<html><head><meta charset="utf-8"></head><body>
+<script>
+ var report = function (params) {
+ var url = new URL('${HOSTILE_ORIGIN}/report');
+ Object.keys(params).forEach(function (key) {
+ url.searchParams.set(key, String(params[key]));
+ });
+ fetch(url.toString(), {mode: 'no-cors', keepalive: true}).catch(function () {});
+ };
+ var describe = function (data) {
+ return data && typeof data === 'object' && typeof data.type === 'string'
+ ? data.type
+ : typeof data;
+ };
+ window.addEventListener('message', function (event) {
+ report({event: 'received', via: 'window', type: describe(event.data), ports: event.ports.length});
+ if (event.ports.length > 0) {
+ var port = event.ports[0];
+ port.onmessage = function (portEvent) {
+ report({event: 'received', via: 'port', type: describe(portEvent.data), ports: 0});
+ };
+ port.postMessage({type: 'preview-ready'});
+ port.postMessage({type: 'preview-edit-code', code: 'export default () => "owned";'});
+ }
+ });
+ var replayHello = function () {
+ window.parent.postMessage({type: 'astryx-preview-hello', nonce: ${JSON.stringify(nonce)}}, '*');
+ };
+ report({event: 'loaded'});
+ replayHello();
+ report({event: 'hello-replayed'});
+ setInterval(replayHello, 1);
+</script>
+<img src="${HOSTILE_ORIGIN}/slow.gif" alt="">
+</body></html>`;
+}
diff --git a/apps/docsite/next.config.mjs b/apps/docsite/next.config.mjs
index 231666db9c..5b32c4f4f2 100644
--- a/apps/docsite/next.config.mjs
+++ b/apps/docsite/next.config.mjs
@@ -13,12 +13,12 @@ const nextConfig = {
},
// The playground preview evaluates user-authored code, so it is the one
// route that must never be embeddable by another site and never a loader of
- // third-party script. The origin check on its postMessage channel is the
- // actual guard (playground/previewChannel.ts); these headers are the layer
- // underneath it. 'unsafe-eval' is inherent — the route's whole job is
- // compiling and running TSX in the browser. img/connect stay open so demo
- // code can still fetch and show remote data; the allowed hosts are the ones
- // the site itself loads (Google Fonts, Vercel analytics).
+ // third-party script. The nonce-attested port handshake on its message
+ // channel is the actual guard (playground/previewChannel.ts); these headers
+ // are the layer underneath it. 'unsafe-eval' is inherent — the route's whole
+ // job is compiling and running TSX in the browser. img/connect stay open so
+ // demo code can still fetch and show remote data; the allowed hosts are the
+ // ones the site itself loads (Google Fonts, Vercel analytics).
async headers() {
return [
{
diff --git a/apps/docsite/playwright.config.ts b/apps/docsite/playwright.config.ts
new file mode 100644
index 0000000000..b458d9524b
--- /dev/null
+++ b/apps/docsite/playwright.config.ts
@@ -0,0 +1,66 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file playwright.config.ts
+ * @input Uses @playwright/test; a production build of the docsite in .next
+ * @output Chromium proofs for the docsite behaviors jsdom cannot observe.
+ * @position Run from the repo root with `pnpm test:docsite-browser`, or from
+ * this directory with `pnpm exec playwright test`. Deliberately separate
+ * from `pnpm -F @astryxdesign/docsite test`: the Vitest suite must stay
+ * runnable from a cold clone with no browser and no build, and everything
+ * here needs both.
+ *
+ * The specs run against the PRODUCTION server. That is not a preference: the
+ * playground preview only gets its opaque origin in production builds (see
+ * PreviewStage.tsx), so the isolation these specs prove does not exist under
+ * `next dev`. Build first:
+ *
+ * pnpm -F @astryxdesign/docsite build
+ * pnpm exec playwright install chromium
+ * pnpm test:docsite-browser
+ *
+ * Outside CI an already-running `next start` on the port is reused, so a
+ * server started by hand works too.
+ *
+ * SYNC: When the docsite gains another browser-only contract, add its spec
+ * under e2e/.
+ */
+
+import {defineConfig, devices} from '@playwright/test';
+
+// GitHub Actions sets CI=true; some runners set it to an empty string. One
+// definition, so `forbidOnly` and the reporter choice cannot disagree.
+const isCI = (process.env.CI ?? '') !== '';
+
+// A port no other docsite process on a developer machine is likely to hold.
+const port = Number(process.env.DOCSITE_E2E_PORT ?? 3233);
+const baseURL = `http://127.0.0.1:${port}`;
+
+export default defineConfig({
+ testDir: './e2e',
+ outputDir: '../../test-results/docsite',
+ testMatch: ['**/*.spec.ts'],
+ // The playground specs drive one preview frame through reloads and hostile
+ // navigations; parallel workers would only add timing noise to a lifecycle
+ // that is already asynchronous end to end.
+ workers: 1,
+ fullyParallel: false,
+ forbidOnly: isCI,
+ reporter: isCI ? [['list'], ['github']] : [['list']],
+ // The preview loads the TypeScript compiler before it can render anything,
+ // and each recovery is a full document lifecycle.
+ timeout: 90_000,
+ expect: {timeout: 30_000},
+ use: {
+ ...devices['Desktop Chrome'],
+ baseURL,
+ screenshot: 'only-on-failure',
+ trace: 'retain-on-failure',
+ },
+ webServer: {
+ command: `pnpm exec next start --port ${port}`,
+ url: `${baseURL}/playground/preview`,
+ reuseExistingServer: !isCI,
+ timeout: 120_000,
+ },
+});
diff --git a/apps/docsite/src/__tests__/playground-preview-channel.test.ts b/apps/docsite/src/__tests__/playground-preview-channel.test.ts
index 1e233f3452..bdd94674e5 100644
--- a/apps/docsite/src/__tests__/playground-preview-channel.test.ts
+++ b/apps/docsite/src/__tests__/playground-preview-channel.test.ts
@@ -1,58 +1,376 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
-import {describe, expect, it} from 'vitest';
-import {isTrustedPreviewMessage} from '../app/playground/previewChannel';
-
-const ORIGIN = 'https://astryx.atmeta.com';
+import {once} from 'node:events';
+import {describe, expect, it, vi} from 'vitest';
+import {
+ PREVIEW_CONNECT,
+ PREVIEW_HELLO,
+ acceptPreviewConnect,
+ announcePreview,
+ connectToPreview,
+ createPreviewConnector,
+ createPreviewNonce,
+ previewSrc,
+ readPreviewNonce,
+} from '../app/playground/previewChannel';
const parent = {} as MessageEventSource;
const other = {} as MessageEventSource;
-function event(origin: string, source: MessageEventSource | null) {
- return {origin, source};
+function connectEvent(overrides: {
+ data?: unknown;
+ source?: MessageEventSource | null;
+ ports?: readonly MessagePort[];
+}) {
+ const {port1} = new MessageChannel();
+ return {
+ data: {type: PREVIEW_CONNECT},
+ source: parent,
+ ports: [port1],
+ ...overrides,
+ } as Pick<MessageEvent, 'data' | 'source' | 'ports'>;
}
-describe('isTrustedPreviewMessage', () => {
- it('accepts a message from the expected window on our own origin', () => {
- expect(isTrustedPreviewMessage(event(ORIGIN, parent), ORIGIN, parent)).toBe(
- true,
+describe('acceptPreviewConnect', () => {
+ it('adopts the port from a connect sent by the parent window', () => {
+ const event = connectEvent({});
+ expect(acceptPreviewConnect(event, parent)).toBe(event.ports[0]);
+ });
+
+ it('rejects a connect from a window that is not the parent', () => {
+ expect(acceptPreviewConnect(connectEvent({source: other}), parent)).toBe(
+ null,
);
});
- it('rejects another origin, even from the expected window', () => {
+ it('rejects a connect with no source', () => {
+ expect(acceptPreviewConnect(connectEvent({source: null}), parent)).toBe(
+ null,
+ );
+ });
+
+ it('rejects everything while there is no parent window', () => {
+ expect(acceptPreviewConnect(connectEvent({}), null)).toBe(null);
+ expect(acceptPreviewConnect(connectEvent({}), undefined)).toBe(null);
+ });
+
+ it('rejects a connect that carries no port', () => {
+ expect(acceptPreviewConnect(connectEvent({ports: []}), parent)).toBe(null);
+ });
+
+ it('ignores unrelated message types, ports and all', () => {
expect(
- isTrustedPreviewMessage(
- event('https://evil.example', parent),
- ORIGIN,
+ acceptPreviewConnect(
+ connectEvent({data: {type: 'preview-code'}}),
parent,
),
- ).toBe(false);
+ ).toBe(null);
+ expect(acceptPreviewConnect(connectEvent({data: null}), parent)).toBe(null);
+ expect(acceptPreviewConnect(connectEvent({data: 'connect'}), parent)).toBe(
+ null,
+ );
});
+});
- it('rejects an opaque (sandboxed) origin', () => {
- expect(isTrustedPreviewMessage(event('null', parent), ORIGIN, parent)).toBe(
- false,
- );
+describe('connectToPreview', () => {
+ it('offers the frame one end of a fresh channel and returns the other', () => {
+ const postMessage = vi.fn();
+ const port = connectToPreview({postMessage} as Pick<Window, 'postMessage'>);
+
+ expect(postMessage).toHaveBeenCalledTimes(1);
+ const [message, targetOrigin, transfer] = postMessage.mock.calls[0] as [
+ {type: string},
+ string,
+ MessagePort[],
+ ];
+ expect(message).toEqual({type: PREVIEW_CONNECT});
+ // An opaque origin cannot be named, so the offer necessarily targets '*';
+ // it carries no data and goes only to the window handle of our own iframe.
+ expect(targetOrigin).toBe('*');
+ expect(transfer).toHaveLength(1);
+ expect(transfer[0]).toBeInstanceOf(MessagePort);
+ expect(port).toBeInstanceOf(MessagePort);
+ expect(port).not.toBe(transfer[0]);
});
- it('rejects our own origin sent from a window that is not the counterpart', () => {
- expect(isTrustedPreviewMessage(event(ORIGIN, other), ORIGIN, parent)).toBe(
- false,
- );
+ it('returns entangled ports — a message sent on one arrives on the other', async () => {
+ const captured: MessagePort[] = [];
+ const postMessage = (
+ _msg: unknown,
+ _target: string,
+ transfer: MessagePort[],
+ ) => {
+ captured.push(...transfer);
+ };
+ const local = connectToPreview({
+ postMessage,
+ } as unknown as Pick<Window, 'postMessage'>);
+ const remote = captured[0];
+
+ const received = new Promise<unknown>(resolve => {
+ remote.onmessage = event => resolve(event.data);
+ });
+ local.postMessage({type: 'preview-code', code: 'x'});
+ await expect(received).resolves.toEqual({type: 'preview-code', code: 'x'});
+ local.close();
+ remote.close();
});
+});
- it('rejects everything while the counterpart window does not exist', () => {
- expect(isTrustedPreviewMessage(event(ORIGIN, parent), ORIGIN, null)).toBe(
- false,
+describe('nonce plumbing', () => {
+ it('issues unguessable, distinct nonces', () => {
+ const a = createPreviewNonce();
+ const b = createPreviewNonce();
+ expect(a).toMatch(/^[0-9a-f]{32}$/);
+ expect(b).toMatch(/^[0-9a-f]{32}$/);
+ expect(a).not.toBe(b);
+ });
+
+ it('round-trips the nonce through the frame URL fragment', () => {
+ const nonce = createPreviewNonce();
+ const src = previewSrc(nonce);
+ // Fragment, not query: the nonce never reaches the server or a cache key.
+ expect(src.startsWith('/playground/preview#')).toBe(true);
+ expect(src).not.toContain('?');
+ expect(readPreviewNonce(new URL(src, 'https://example.test').hash)).toBe(
+ nonce,
);
- expect(
- isTrustedPreviewMessage(event(ORIGIN, parent), ORIGIN, undefined),
- ).toBe(false);
});
- it('rejects a message with no source', () => {
- expect(isTrustedPreviewMessage(event(ORIGIN, null), ORIGIN, parent)).toBe(
- false,
+ it('reads no nonce from a URL the playground did not issue', () => {
+ expect(readPreviewNonce('')).toBe(null);
+ expect(readPreviewNonce('#')).toBe(null);
+ expect(readPreviewNonce('#code=abc')).toBe(null);
+ });
+
+ it('announces the nonce to the parent with a wildcard target', () => {
+ const postMessage = vi.fn();
+ announcePreview({postMessage} as Pick<Window, 'postMessage'>, 'n-1');
+ expect(postMessage).toHaveBeenCalledWith(
+ {type: PREVIEW_HELLO, nonce: 'n-1'},
+ '*',
);
});
});
+
+/**
+ * A stand-in for one preview document: the frame window the playground sees,
+ * plus the port it adopts from a connect message.
+ */
+function fakeDocument() {
+ const inbox: Array<{type?: string; code?: string}> = [];
+ let port: MessagePort | null = null;
+ const window = {
+ postMessage: (
+ _message: unknown,
+ _target: string,
+ transfer: MessagePort[],
+ ) => {
+ port = transfer[0];
+ port.onmessage = event => inbox.push(event.data);
+ },
+ } as unknown as Window;
+ return {
+ window,
+ inbox,
+ get port() {
+ return port;
+ },
+ hello(nonce: unknown, source: MessageEventSource | null = window) {
+ return {data: {type: PREVIEW_HELLO, nonce}, source} as MessageEvent;
+ },
+ };
+}
+
+function connectorHarness() {
+ let current = fakeDocument();
+ const nonces: string[] = [];
+ let counter = 0;
+ const received: Array<{type?: string}> = [];
+ const onReplaced = vi.fn();
+ const connector = createPreviewConnector({
+ onMessage: event => received.push(event.data as {type?: string}),
+ onReplaced,
+ nonce: () => {
+ const next = `nonce-${(counter += 1)}`;
+ nonces.push(next);
+ return next;
+ },
+ });
+ return {
+ connector,
+ nonces,
+ received,
+ onReplaced,
+ get doc() {
+ return current;
+ },
+ /**
+ * What the host does for a generation: issue() a nonce, then mount a fresh
+ * iframe element for it, which hands the connector its window on mount.
+ */
+ mountGeneration() {
+ const nonce = connector.issue();
+ current = fakeDocument();
+ connector.attachFrame(current.window);
+ return {nonce, doc: current};
+ },
+ };
+}
+
+describe('createPreviewConnector', () => {
+ it('transfers a port only to the current frame window echoing the outstanding nonce, once', () => {
+ const h = connectorHarness();
+ const stranger = fakeDocument();
+
+ // Nothing is outstanding before issue(): no hello can be accepted.
+ h.connector.attachFrame(h.doc.window);
+ h.connector.handleWindowMessage(h.doc.hello('nonce-1'));
+ expect(h.doc.port).toBe(null);
+
+ const {nonce, doc} = h.mountGeneration();
+ expect(nonce).toBe('nonce-1');
+
+ // Wrong nonce, missing nonce, wrong window, no window: all rejected.
+ h.connector.handleWindowMessage(doc.hello('nonce-guess'));
+ h.connector.handleWindowMessage(doc.hello(null));
+ h.connector.handleWindowMessage(doc.hello(undefined));
+ h.connector.handleWindowMessage(doc.hello(nonce, stranger.window));
+ h.connector.handleWindowMessage(doc.hello(nonce, null));
+ h.connector.handleWindowMessage({
+ data: {type: 'preview-ready'},
+ source: doc.window,
+ } as MessageEvent);
+ expect(doc.port).toBe(null);
+ expect(stranger.port).toBe(null);
+ expect(h.connector.isAttested()).toBe(false);
+
+ // The right hello from the right window earns exactly one port.
+ h.connector.handleWindowMessage(doc.hello(nonce));
+ expect(doc.port).toBeInstanceOf(MessagePort);
+ expect(h.connector.isAttested()).toBe(true);
+ const firstPort = doc.port;
+ h.connector.handleWindowMessage(doc.hello(nonce));
+ expect(doc.port).toBe(firstPort);
+ });
+
+ it('flows traffic over the adopted pair in both directions', async () => {
+ const h = connectorHarness();
+ const {nonce, doc} = h.mountGeneration();
+ h.connector.handleWindowMessage(doc.hello(nonce));
+
+ h.connector.post({type: 'preview-code', code: 'A'});
+ doc.port!.postMessage({type: 'preview-ready'});
+ // A timer turn does not guarantee delivery from Node's MessagePort queue.
+ await vi.waitFor(() => {
+ expect(doc.inbox.map(m => m.code)).toEqual(['A']);
+ expect(h.received.map(m => m.type)).toEqual(['preview-ready']);
+ });
+ h.connector.stop();
+ doc.port!.close();
+ });
+
+ it('accepts nothing from any window between issue() and the new element attaching', () => {
+ const h = connectorHarness();
+ const first = h.mountGeneration();
+ h.connector.handleWindowMessage(first.doc.hello(first.nonce));
+ expect(first.doc.port).toBeInstanceOf(MessagePort);
+
+ // A new generation is issued while the old element — and whatever
+ // document it shows — is still alive, until React commits the new one.
+ const nonce = h.connector.issue();
+ h.connector.handleWindowMessage(first.doc.hello(nonce));
+ h.connector.handleWindowMessage(first.doc.hello(first.nonce));
+ expect(h.connector.isAttested()).toBe(false);
+
+ // Once the new element attaches, the old window is still worthless and
+ // the new one is answered.
+ const next = fakeDocument();
+ h.connector.attachFrame(next.window);
+ h.connector.handleWindowMessage(first.doc.hello(nonce));
+ expect(h.connector.isAttested()).toBe(false);
+ h.connector.handleWindowMessage(next.hello(nonce));
+ expect(next.port).toBeInstanceOf(MessagePort);
+ });
+
+ it('treats the first load of a generation as the attested document arriving', () => {
+ const h = connectorHarness();
+ const {nonce, doc} = h.mountGeneration();
+
+ // Load before hello (subresources were quick) …
+ h.connector.handleFrameLoad();
+ expect(h.onReplaced).not.toHaveBeenCalled();
+ h.connector.handleWindowMessage(doc.hello(nonce));
+ expect(doc.port).toBeInstanceOf(MessagePort);
+
+ // … and hello before load (the compiler script was still downloading).
+ const second = h.mountGeneration();
+ h.connector.handleWindowMessage(second.doc.hello(second.nonce));
+ expect(second.doc.port).toBeInstanceOf(MessagePort);
+ h.connector.handleFrameLoad();
+ expect(h.onReplaced).not.toHaveBeenCalled();
+ expect(h.connector.isAttested()).toBe(true);
+ });
+
+ it('on a later load, discards the port and nonce before asking for a new generation', async () => {
+ const h = connectorHarness();
+ const {nonce, doc: oldDoc} = h.mountGeneration();
+ h.connector.handleFrameLoad();
+ h.connector.handleWindowMessage(oldDoc.hello(nonce));
+
+ // Previewed code navigated the frame: a second load in this generation.
+ // Whatever the frame shows now is not the document we attested.
+ const closed = once(oldDoc.port!, 'close');
+ h.connector.handleFrameLoad();
+ await closed;
+ expect(h.onReplaced).toHaveBeenCalledTimes(1);
+ expect(h.connector.isAttested()).toBe(false);
+
+ // The replacement document learned the old nonce from the document it
+ // displaced and posts from the frame window we used to hold; replaying it
+ // earns nothing.
+ const hijacker = fakeDocument();
+ h.connector.handleWindowMessage(hijacker.hello(nonce, oldDoc.window));
+ expect(hijacker.port).toBe(null);
+ expect(h.connector.isAttested()).toBe(false);
+
+ // Nothing posted now reaches anyone: the old port is closed.
+ h.connector.post({type: 'preview-code', code: 'secret'});
+ expect(oldDoc.inbox.map(m => m.code)).not.toContain('secret');
+
+ // The host issues a new generation and mounts a fresh frame; only the
+ // document that loads there with the NEW nonce is answered.
+ const {nonce: fresh, doc: next} = h.mountGeneration();
+ expect(fresh).not.toBe(nonce);
+ h.connector.handleWindowMessage(next.hello(nonce));
+ expect(next.port).toBe(null);
+ h.connector.handleWindowMessage(next.hello(fresh));
+ expect(next.port).toBeInstanceOf(MessagePort);
+ h.connector.handleFrameLoad();
+ expect(h.onReplaced).toHaveBeenCalledTimes(1);
+
+ // The reload-then-edit lifecycle end to end: an edit reaches the NEW
+ // document and only it.
+ h.connector.post({type: 'preview-code', code: 'B'});
+ await vi.waitFor(() => {
+ expect(next.inbox.map(m => m.code)).toEqual(['B']);
+ });
+ expect(oldDoc.inbox.map(m => m.code)).toEqual([]);
+ h.connector.stop();
+ next.port!.close();
+ });
+
+ it('stop() closes the port and forgets the nonce and window', async () => {
+ const h = connectorHarness();
+ const {nonce, doc} = h.mountGeneration();
+ h.connector.handleWindowMessage(doc.hello(nonce));
+ const closed = once(doc.port!, 'close');
+ h.connector.stop();
+ await closed;
+ expect(h.connector.isAttested()).toBe(false);
+ h.connector.post({type: 'preview-code', code: 'late'});
+ expect(doc.inbox).toEqual([]);
+ h.connector.handleWindowMessage(doc.hello(nonce));
+ expect(h.connector.isAttested()).toBe(false);
+ });
+});
diff --git a/apps/docsite/src/app/playground/PlaygroundClient.tsx b/apps/docsite/src/app/playground/PlaygroundClient.tsx
index d98861b09e..5f474c3173 100644
--- a/apps/docsite/src/app/playground/PlaygroundClient.tsx
+++ b/apps/docsite/src/app/playground/PlaygroundClient.tsx
@@ -3,7 +3,8 @@
/**
* @file PlaygroundClient.tsx
* @input URL hash or template query, user edits, and knob edits
- * @output Full-page two-panel playground (editor + live preview)
+ * @output Full-page two-panel playground (editor + live preview), with a
+ * production-only notice explaining the ephemeral preview's restrictions
* @position app/playground — the interactive Astryx code playground.
*
* AppShell: side-nav-only shell; desktop nav is controlled collapsed to
@@ -37,7 +38,8 @@ import dynamic from 'next/dynamic';
import * as stylex from '@stylexjs/stylex';
import {AppShell} from '@astryxdesign/core/AppShell';
import {compressCode, decompressCode} from '../../lib/compress';
-import {isTrustedPreviewMessage, trustedPreviewOrigin} from './previewChannel';
+import {createPreviewConnector, previewSrc} from './previewChannel';
+import type {PreviewConnector} from './previewChannel';
import {Button} from '@astryxdesign/core/Button';
import {Link} from '@astryxdesign/core/Link';
import {HStack, VStack} from '@astryxdesign/core/Layout';
@@ -231,6 +233,11 @@ const s = stylex.create({
overflow: 'hidden',
backgroundColor: 'var(--color-background-muted)',
},
+ previewNotice: {
+ flexShrink: 0,
+ paddingInline: 'var(--spacing-4)',
+ paddingBlockEnd: 'var(--spacing-2)',
+ },
buildStatus: {
transitionProperty: 'opacity',
transitionDuration: '0.5s',
@@ -261,6 +268,12 @@ export function PlaygroundClient() {
const {mode: siteMode} = useThemeMode();
const editorTheme = siteMode === 'dark' ? 'github-dark' : 'github-light';
const [code, setCode] = useState(getInitialCode);
+ // Mirror of `code` for event handlers with stable identities (the frame
+ // load handler resends the current code after a preview reload).
+ const codeRef = useRef(code);
+ useEffect(() => {
+ codeRef.current = code;
+ }, [code]);
const [mode, setMode] = useState<'light' | 'dark'>('light');
// A ?theme=<value> query param (e.g. from the themes gallery's "Open in
// Playground") seeds the Theme view and preview. useSearchParams reads it
@@ -306,9 +319,19 @@ export function PlaygroundClient() {
string | null
>(null);
- const iframeRef = useRef<HTMLIFrameElement>(null);
const readyRef = useRef(false);
const pendingRef = useRef<string | null>(null);
+ // The preview frame generation: a fresh iframe element (key) navigated to
+ // the preview URL with a fresh nonce (src). Issued on the client only, and
+ // re-issued whenever the attested preview document is replaced — see
+ // previewChannel.ts for the trust model.
+ const [frame, setFrame] = useState<{key: number; src: string} | null>(null);
+ const frameGenerationRef = useRef(0);
+ // The channel's trust state machine (see previewChannel.ts) and the current
+ // port message handler — refs so the connector's port always dispatches
+ // into the latest closure.
+ const connectorRef = useRef<PreviewConnector | null>(null);
+ const portHandlerRef = useRef<((e: MessageEvent) => void) | null>(null);
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const editorRef = useRef<MonacoTypes.editor.IStandaloneCodeEditor | null>(
null,
@@ -371,12 +394,9 @@ export function PlaygroundClient() {
}
}, [themeParam]);
- // Single channel to the preview iframe; no-ops until the iframe exists.
+ // Single channel to the preview iframe; no-ops until the handshake lands.
const postToPreview = useCallback((message: unknown) => {
- iframeRef.current?.contentWindow?.postMessage(
- message,
- trustedPreviewOrigin(),
- );
+ connectorRef.current?.post(message);
}, []);
const send = useCallback(
@@ -423,17 +443,10 @@ export function PlaygroundClient() {
[postToPreview],
);
+ // Messages from the preview arrive only on the port the handshake below
+ // transfers — the window listener hears nothing but the hello.
useEffect(() => {
const handler = (e: MessageEvent) => {
- if (
- !isTrustedPreviewMessage(
- e,
- trustedPreviewOrigin(),
- iframeRef.current?.contentWindow,
- )
- ) {
- return;
- }
if (e.data?.type === 'preview-ready') {
readyRef.current = true;
setPreviewReady(true);
@@ -465,20 +478,66 @@ export function PlaygroundClient() {
setIsTargeting(false);
}
};
- window.addEventListener('message', handler);
- return () => window.removeEventListener('message', handler);
+ portHandlerRef.current = handler;
+ return () => {
+ portHandlerRef.current = null;
+ };
}, [postCode, postToPreview]);
+ // Handshake (previewChannel.ts): mount a fresh iframe navigated to the
+ // preview URL with a nonce only this page knows; the preview document echoes
+ // it from its own URL, and the connector answers that one hello with a port.
+ // The window listener goes up BEFORE the frame is issued so the hello cannot
+ // arrive unheard.
useEffect(() => {
- const interval = setInterval(() => {
- if (readyRef.current) {
- clearInterval(interval);
- return;
- }
- postToPreview({type: 'preview-ping'});
- }, 300);
- return () => clearInterval(interval);
- }, [postToPreview]);
+ const issueFrame = () => {
+ frameGenerationRef.current += 1;
+ setFrame({
+ key: frameGenerationRef.current,
+ src: previewSrc(connector.issue()),
+ });
+ };
+ const connector = createPreviewConnector({
+ onMessage: e => portHandlerRef.current?.(e),
+ // The attested preview document is gone (previewed code navigated or
+ // reloaded its frame). Its port and nonce are already discarded; start
+ // a new generation and queue the current code so the fresh document
+ // picks up exactly where the old one was — the preview-ready handler
+ // flushes it and the theme effect re-sends on the previewReady flip.
+ onReplaced: () => {
+ readyRef.current = false;
+ setPreviewReady(false);
+ pendingRef.current = codeRef.current;
+ issueFrame();
+ },
+ });
+ connectorRef.current = connector;
+ const onWindowMessage = (e: MessageEvent) =>
+ connector.handleWindowMessage(e);
+ window.addEventListener('message', onWindowMessage);
+ issueFrame();
+ return () => {
+ window.removeEventListener('message', onWindowMessage);
+ connector.stop();
+ connectorRef.current = null;
+ };
+ }, []);
+
+ // The iframe element of the current generation, once React has mounted it:
+ // only its window can earn a port. React clears the old element's ref before
+ // attaching the new one's, and the connector forgets its window on every
+ // issue() anyway, so the null on unmount carries nothing it needs.
+ const attachFrame = useCallback((element: HTMLIFrameElement | null) => {
+ if (element?.contentWindow) {
+ connectorRef.current?.attachFrame(element.contentWindow);
+ }
+ }, []);
+
+ // Every load of the iframe goes to the connector: the first in a generation
+ // is the document we navigated to arriving, any later one is a replacement.
+ const handleFrameLoad = useCallback(() => {
+ connectorRef.current?.handleFrameLoad();
+ }, []);
// Debounced push of code → preview + URL hash
useEffect(() => {
@@ -1153,11 +1212,20 @@ export function PlaygroundClient() {
}
/>
)}
+ {process.env.NODE_ENV !== 'development' && (
+ <Text type="supporting" color="secondary" xstyle={s.previewNotice}>
+ Ephemeral preview: no local storage or parent-page access.
+ Reloading or navigating the preview resets runtime state, then
+ restores your code and theme.
+ </Text>
+ )}
<PreviewStage
viewport={isMobile ? 'phone' : viewport}
isFullscreen={isFullscreen}
onExitFullscreen={() => setIsFullscreen(false)}
- iframeRef={iframeRef}
+ frameRef={attachFrame}
+ frame={frame}
+ onFrameLoad={handleFrameLoad}
isInteractionDisabled={isResizing}
isFullBleed={isMobile}
/>
diff --git a/apps/docsite/src/app/playground/PreviewStage.tsx b/apps/docsite/src/app/playground/PreviewStage.tsx
index b62ca012d4..9100e11593 100644
--- a/apps/docsite/src/app/playground/PreviewStage.tsx
+++ b/apps/docsite/src/app/playground/PreviewStage.tsx
@@ -2,14 +2,18 @@
/**
* @file PreviewStage.tsx
- * @input viewport size, fullscreen flag, iframe ref
+ * @input viewport size, fullscreen flag, a ref for the iframe element, the
+ * current preview frame generation (key + src)
* @output Responsive preview frame hosting the /playground/preview iframe
* @position Playground right panel — preview surface.
*
* Keeps a SINGLE iframe element mounted across viewport + fullscreen changes
- * (only the wrapper styles change) so the parent's postMessage channel to the
- * preview never resets. Desktop = fill; Phone = a fixed 402px-wide frame
- * (content reflows natively at mobile width, no scaling).
+ * (only the wrapper styles change) so the parent's channel to the preview
+ * never resets. The one thing that DOES replace the element is the playground
+ * starting a new frame generation (see previewChannel.ts): the iframe is keyed
+ * on it, so a replaced preview document is torn down with its whole browsing
+ * context rather than navigated in place. Desktop = fill; Phone = a fixed
+ * 402px-wide frame (content reflows natively at mobile width, no scaling).
*/
'use client';
@@ -22,6 +26,15 @@ import {Minimize2} from 'lucide-react';
export type Viewport = 'desktop' | 'phone';
+// Under `next dev` the preview frame keeps the site origin (the sandbox the
+// preview always had before isolation): the dev server serves its /_next
+// assets only to requests that name an allowlisted host in Origin or Referer,
+// and a document with an opaque origin sends neither, so an isolated preview
+// cannot load its own scripts there. Production builds, which is where
+// untrusted code meets real users, get the opaque origin — see the iframe
+// below. `process.env.NODE_ENV` is inlined at build time.
+const PREVIEW_KEEPS_SITE_ORIGIN = process.env.NODE_ENV === 'development';
+
// iPhone 17 logical viewport (402 × 874 CSS px, ~9:19.5).
const PHONE_WIDTH = 402;
const PHONE_HEIGHT = 874;
@@ -105,7 +118,24 @@ interface PreviewStageProps {
viewport: Viewport;
isFullscreen: boolean;
onExitFullscreen: () => void;
- iframeRef: React.RefObject<HTMLIFrameElement | null>;
+ /**
+ * Receives the iframe element of the current generation when it mounts —
+ * the playground hands its window to the channel (see previewChannel.ts).
+ */
+ frameRef: React.Ref<HTMLIFrameElement>;
+ /**
+ * The current preview frame generation: a key that remounts the iframe and
+ * the nonce-carrying URL it must load (see previewChannel.ts). Null until
+ * the playground has issued one on the client — the nonce must never be
+ * baked into server-rendered HTML.
+ */
+ frame: {key: number; src: string} | null;
+ /**
+ * Fires on every load of the preview document — including a replaced one
+ * (previewed code navigating or reloading its own frame), which is what
+ * tells the playground the attested document is gone (previewChannel.ts).
+ */
+ onFrameLoad?: () => void;
/** Disable iframe pointer events (e.g. while the panel is being resized). */
isInteractionDisabled?: boolean;
/** Render the iframe directly, without the preview card/device frame. */
@@ -116,7 +146,9 @@ export function PreviewStage({
viewport,
isFullscreen,
onExitFullscreen,
- iframeRef,
+ frameRef,
+ frame,
+ onFrameLoad,
isInteractionDisabled = false,
isFullBleed = false,
}: PreviewStageProps) {
@@ -153,13 +185,41 @@ export function PreviewStage({
isFullBleed && !isFullscreen && s.cardFullBleed,
dynamic.size(width, height),
]}>
- <iframe
- ref={iframeRef}
- src="/playground/preview"
- sandbox="allow-scripts allow-same-origin"
- title="Preview"
- {...stylex.props(s.iframe, isInteractionDisabled && s.iframeInert)}
- />
+ {frame != null &&
+ // Two elements rather than one with a computed `sandbox`: the lint
+ // rule guarding iframes wants the attribute spelled out, and so does
+ // a reader auditing the boundary.
+ (PREVIEW_KEEPS_SITE_ORIGIN ? (
+ <iframe
+ key={frame.key}
+ ref={frameRef}
+ onLoad={onFrameLoad}
+ src={frame.src}
+ sandbox="allow-scripts allow-same-origin"
+ title="Preview"
+ {...stylex.props(
+ s.iframe,
+ isInteractionDisabled && s.iframeInert,
+ )}
+ />
+ ) : (
+ // No allow-same-origin: the preview document gets an opaque
+ // origin, so the code it compiles and runs holds no cookies, no
+ // storage, and no reach into this page — see previewChannel.ts
+ // for how the two ends talk without a nameable origin.
+ <iframe
+ key={frame.key}
+ ref={frameRef}
+ onLoad={onFrameLoad}
+ src={frame.src}
+ sandbox="allow-scripts"
+ title="Preview"
+ {...stylex.props(
+ s.iframe,
+ isInteractionDisabled && s.iframeInert,
+ )}
+ />
+ ))}
</Card>
</Center>
);
diff --git a/apps/docsite/src/app/playground/preview/page.tsx b/apps/docsite/src/app/playground/preview/page.tsx
index 094e546518..a79c89b340 100644
--- a/apps/docsite/src/app/playground/preview/page.tsx
+++ b/apps/docsite/src/app/playground/preview/page.tsx
@@ -1,5 +1,12 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
+/**
+ * @file page.tsx
+ * @input Attested preview channel, editor code, and active theme
+ * @output Isolated live preview with native navigation in production
+ * @position Playground runner; platform restrictions never grant parent privileges.
+ */
+
'use client';
import React, {
@@ -20,10 +27,31 @@ import {
refreshTargetLabels,
setActiveSiteMode,
setCleanSource,
+ setPostToParent,
} from '../propertyEditor/targetingOverlay';
import {runCode, setTypeScript} from './runner';
-import {isTrustedPreviewMessage, trustedPreviewOrigin} from '../previewChannel';
+import {
+ acceptPreviewConnect,
+ announcePreview,
+ readPreviewNonce,
+} from '../previewChannel';
import type * as TS from 'typescript';
+import NextLink from 'next/link';
+import {LinkProvider} from '@astryxdesign/core/Link';
+
+// Next's client router mutates history, which an opaque-origin document cannot
+// do for another path. Native links keep fragment navigation usable and let
+// full document navigation reach the existing replacement/recovery boundary.
+const PreviewLink = process.env.NODE_ENV === 'development' ? NextLink : 'a';
+
+// How long after the compiler is ready the readiness announcement waits for
+// this document's own `load` event before giving up on it. The wait exists so
+// no previewed code runs before the frame's first load event (see
+// previewChannel.ts, "The handshake", step 4); the cap keeps a stalled
+// third-party subresource from stalling the preview. Past the cap only
+// recovery from hostile code that navigates away within its first
+// milliseconds is at stake, never isolation.
+const DOCUMENT_LOAD_WAIT_MS = 5000;
const FALLBACK_THEME =
themeByValue[DEFAULT_PLAYGROUND_THEME] ?? Object.values(themeByValue)[0];
@@ -34,7 +62,6 @@ const useIsomorphicLayoutEffect =
typeof window !== 'undefined' ? useLayoutEffect : useEffect;
type PreviewMessage =
- | {type: 'preview-ping'}
| {type: 'preview-code'; code: string; source: string}
| {type: 'preview-clear'}
| {
@@ -90,11 +117,17 @@ export default function PreviewPage() {
const [customTheme, setCustomTheme] = useState<DefinedTheme | null>(null);
const [resetKey, setResetKey] = useState(0);
const [tsReady, setTsReady] = useState(false);
+ // Whether this document's own `load` event has fired (or the wait for it
+ // ran out); readiness is announced only after it.
+ const [documentLoaded, setDocumentLoaded] = useState(false);
+ // The channel adopted from the playground's connect handshake.
+ const [port, setPort] = useState<MessagePort | null>(null);
// Whether the rendered output should fill the stage (full-page templates) vs
// be centered as a small example. Defaults to fill so templates are never
// shrunk; the layout effect downgrades small content to centered.
const [fill, setFill] = useState(true);
- const readyRef = useRef(false);
+ // The port readiness was last announced on.
+ const readyRef = useRef<MessagePort | null>(null);
const stageRef = useRef<HTMLDivElement>(null);
const contentRef = useRef<HTMLDivElement>(null);
@@ -116,14 +149,18 @@ export default function PreviewPage() {
const theme = customTheme ?? themeByValue[themeName] ?? FALLBACK_THEME;
+ // Everything back to the playground travels over the adopted port (see
+ // previewChannel.ts); until the handshake lands there is nobody to talk to.
+ const portRef = useRef<MessagePort | null>(null);
const postToParent = useCallback((msg: Record<string, unknown>) => {
- window.parent.postMessage(msg, trustedPreviewOrigin());
+ portRef.current?.postMessage(msg);
}, []);
const targetingRef = useRef<ReturnType<
typeof createTargetingController
> | null>(null);
if (targetingRef.current == null && typeof window !== 'undefined') {
+ setPostToParent(postToParent);
targetingRef.current = createTargetingController(postToParent);
}
@@ -192,27 +229,65 @@ export default function PreviewPage() {
[],
);
+ // Prove to the playground that this document is the one it navigated the
+ // frame to, and adopt the channel it answers with. Attached from mount (not
+ // gated on tsReady) so the answer is never missed — the ready reply below
+ // waits for tsReady instead.
+ useEffect(() => {
+ function onWindowMessage(event: MessageEvent) {
+ // The port handler below evaluates attacker-controllable source, so a
+ // port is adopted only from a connect handshake sent by our own parent
+ // window (see previewChannel.ts) — nothing else on the window is heard.
+ const next = acceptPreviewConnect(event, window.parent);
+ if (next == null) {
+ return;
+ }
+ portRef.current?.close();
+ portRef.current = next;
+ setPort(next);
+ }
+ window.addEventListener('message', onWindowMessage);
+ // The nonce came in with the navigation the playground issued; echoing it
+ // is what earns this document a port. A document that reached the frame
+ // any other way holds a nonce the playground has already spent.
+ announcePreview(window.parent, readPreviewNonce(window.location.hash));
+ return () => window.removeEventListener('message', onWindowMessage);
+ }, []);
+
+ // Track this document's own load so readiness — and with it the first run
+ // of previewed code — waits for it (see DOCUMENT_LOAD_WAIT_MS).
+ useEffect(() => {
+ if (document.readyState === 'complete') {
+ setDocumentLoaded(true);
+ return;
+ }
+ const onLoad = () => setDocumentLoaded(true);
+ window.addEventListener('load', onLoad);
+ return () => window.removeEventListener('load', onLoad);
+ }, []);
+
useEffect(() => {
- if (!tsReady) {
+ if (!tsReady || documentLoaded) {
+ return;
+ }
+ const timer = setTimeout(
+ () => setDocumentLoaded(true),
+ DOCUMENT_LOAD_WAIT_MS,
+ );
+ return () => clearTimeout(timer);
+ }, [tsReady, documentLoaded]);
+
+ useEffect(() => {
+ if (!tsReady || !documentLoaded || port == null) {
return;
}
function onMessage(event: MessageEvent) {
- // The switch below evaluates attacker-controllable source, so nothing is
- // read off `event` until the sender is known to be our own playground.
- if (
- !isTrustedPreviewMessage(event, trustedPreviewOrigin(), window.parent)
- ) {
- return;
- }
if (!isPreviewMessage(event.data)) {
return;
}
switch (event.data.type) {
- case 'preview-ping':
- postToParent({type: 'preview-ready'});
- break;
case 'preview-code':
// Keep the clean source current for the badge popover, then refresh
// any live badges so an open popover re-parses against it.
@@ -235,15 +310,30 @@ export default function PreviewPage() {
}
}
- window.addEventListener('message', onMessage);
+ port.onmessage = onMessage;
- if (!readyRef.current) {
- readyRef.current = true;
+ // Announce readiness once per adopted port. The playground flushes the
+ // current code on hearing it, so this is the moment previewed code first
+ // runs — after this document's own load, by the effect's guard.
+ if (readyRef.current !== port) {
+ readyRef.current = port;
postToParent({type: 'preview-ready'});
}
- return () => window.removeEventListener('message', onMessage);
- }, [tsReady, postToParent, handleCode, handleClear, handleTheme]);
+ return () => {
+ if (port.onmessage === onMessage) {
+ port.onmessage = null;
+ }
+ };
+ }, [
+ tsReady,
+ documentLoaded,
+ port,
+ postToParent,
+ handleCode,
+ handleClear,
+ handleTheme,
+ ]);
// After each successful render (measured in fill/block layout), decide
// whether the content is a small example that should be centered. Full-page
@@ -290,7 +380,9 @@ export default function PreviewPage() {
{Component && (
<div ref={contentRef} {...stylex.props(fill && styles.contentFill)}>
<ErrorBoundary resetKey={resetKey} onError={handleBoundaryError}>
- <Component />
+ <LinkProvider component={PreviewLink}>
+ <Component />
+ </LinkProvider>
</ErrorBoundary>
</div>
)}
diff --git a/apps/docsite/src/app/playground/previewChannel.ts b/apps/docsite/src/app/playground/previewChannel.ts
index 2d9f6117d6..63945c1d29 100644
--- a/apps/docsite/src/app/playground/previewChannel.ts
+++ b/apps/docsite/src/app/playground/previewChannel.ts
@@ -2,45 +2,269 @@
/**
* @file previewChannel.ts
- * @input An incoming MessageEvent plus the window we expect to hear from
- * @output Whether the message may be acted on
+ * @input Playground side: the preview iframe's window plus its `load` and the
+ * page's `message` events. Preview side: the document's own URL and the
+ * incoming `message` events.
+ * @output A dedicated MessagePort pair that only the playground and a preview
+ * document the playground itself navigated to can hold.
* @position Playground <-> preview iframe — the postMessage trust boundary.
*
+ * ## Why there is a boundary at all
+ *
* The preview iframe compiles and evaluates whatever source arrives on this
- * channel, so an unchecked `message` listener lets any window that can reach
- * the frame run code in this site's origin. `window.postMessage` is delivered
- * to every listener regardless of sender, so both ends must gate on the
- * sender's identity themselves: the origin the message came from AND the
- * window object it came from.
+ * channel. It runs in a sandbox without `allow-same-origin`, so its document
+ * has an opaque origin: no cookies, no storage, no reach into the parent
+ * document — and no origin string that could identify either end. Origin
+ * checks are therefore unavailable, and the trust anchor is a MessagePort
+ * handshake instead: all traffic flows over a port pair, which no third window
+ * can reach because ports are transferable capabilities, not broadcasts.
+ *
+ * ## Who is who
+ *
+ * - The PLAYGROUND (this site's origin) owns the iframe element and decides
+ * what URL it navigates to.
+ * - The PREVIEW DOCUMENT is the site's own preview page, loaded at that URL.
+ * It is trusted code, but it hosts the previewed code with full authority
+ * over its own window: everything the document knows, previewed code knows,
+ * and previewed code can navigate the frame anywhere.
+ * - A REPLACEMENT DOCUMENT is whatever the frame shows after previewed code
+ * navigated it (another origin, a data: URL, or a reload of the preview
+ * page itself). Only the playground can tell the two apart, and only by
+ * whether it navigated the frame there.
+ *
+ * ## The handshake
+ *
+ * 1. The playground navigates a FRESH iframe element to the preview URL with
+ * a random nonce in the fragment ({@link previewSrc}). The nonce exists
+ * only in the playground's memory and in that navigation's URL; a document
+ * already in the frame cannot read either (the iframe element lives in the
+ * parent's DOM, across the origin boundary).
+ * 2. The preview document reads the nonce from its own URL and posts a hello
+ * carrying it to its parent window ({@link announcePreview}).
+ * 3. The playground accepts a hello only from the current iframe's window,
+ * only while a nonce is outstanding, only when the nonce matches, and only
+ * once ({@link createPreviewConnector}). It answers by transferring one end
+ * of a fresh MessageChannel in a connect message; the preview adopts a port
+ * only from a connect sent by its own parent ({@link acceptPreviewConnect}),
+ * and `frame-ancestors 'self'` on the route pins who that parent can be.
+ * 4. The preview document sends `preview-ready` over the port once its
+ * compiler is loaded AND its own document has finished loading. Nothing
+ * previewed runs before that, so the frame's first `load` event in a
+ * generation always belongs to the attested document.
+ * 5. Every later `load` event means the attested document was replaced. The
+ * playground closes the port, discards the nonce (a hello replaying it is
+ * now worthless), and REMOUNTS the iframe with a new nonce. A new element
+ * is a new browsing context: the replacement document is destroyed along
+ * with any navigation it had in flight, so it cannot race the restore,
+ * and a same-path reload cannot degrade into a fragment navigation. Until
+ * the new element has mounted and handed over its window, the playground
+ * holds no frame window at all, so a hello landing in that gap — from the
+ * old frame, still alive until React commits — is rejected before the
+ * nonce is even compared.
*
- * The preview is always served from this site (the iframe uses a relative
- * src), so "trusted" is same-origin — no host allowlist to keep in sync with
- * production, Vercel previews, and localhost.
+ * A replacement document can post any message it likes to the parent, but the
+ * only message the playground acts on is a hello with the outstanding nonce,
+ * which it never saw. Code, theme, and targeting commands travel only over the
+ * port, and the port is only ever transferred to the window of a fresh frame
+ * that just proved it loaded the URL the playground chose.
*/
-/** The origin both ends of the channel must be on. */
-export function trustedPreviewOrigin(): string {
- return window.location.origin;
+/** Playground -> preview, on the window: the port transfer. */
+export const PREVIEW_CONNECT = 'astryx-preview-connect';
+/** Preview -> playground, on the window: "I am the document you navigated to". */
+export const PREVIEW_HELLO = 'astryx-preview-hello';
+
+const PREVIEW_PATH = '/playground/preview';
+const NONCE_PARAM = 'nonce';
+
+/** A fresh, unguessable nonce for one preview document generation. */
+export function createPreviewNonce(): string {
+ const bytes = new Uint8Array(16);
+ crypto.getRandomValues(bytes);
+ return Array.from(bytes, b => b.toString(16).padStart(2, '0')).join('');
}
/**
- * True when `event` came from the window we expect, on our own origin.
- *
- * `expectedSource` is the counterpart window: the frame's parent (in the
- * preview) or the iframe's contentWindow (in the playground). A nullish
- * expected source means the counterpart does not exist yet, so nothing can be
- * trusted.
+ * The URL a fresh preview iframe navigates to. The nonce rides in the
+ * fragment: it never reaches the server or a CDN cache key, and the preview
+ * page reads it from its own `location`.
+ */
+export function previewSrc(nonce: string): string {
+ return `${PREVIEW_PATH}#${NONCE_PARAM}=${encodeURIComponent(nonce)}`;
+}
+
+/** Preview side: the nonce the playground put in this document's URL, if any. */
+export function readPreviewNonce(hash: string): string | null {
+ return new URLSearchParams(hash.replace(/^#/, '')).get(NONCE_PARAM);
+}
+
+/**
+ * Preview side: tell the parent which navigation this document came from.
+ * The target is `'*'` because an opaque-origin document cannot name its
+ * embedder either; `frame-ancestors 'self'` guarantees the embedder is this
+ * site, and the nonce is useless to anything that is not also the frame's
+ * parent.
+ */
+export function announcePreview(
+ parent: Pick<Window, 'postMessage'>,
+ nonce: string | null,
+): void {
+ parent.postMessage({type: PREVIEW_HELLO, nonce}, '*');
+}
+
+/**
+ * Playground side: open a fresh channel to the preview frame and return the
+ * local port. The remote port travels inside the connect message. The
+ * wildcard target is required — an opaque origin cannot be named in
+ * `targetOrigin` — and the message carries no data beyond the port itself.
+ */
+export function connectToPreview(
+ frame: Pick<Window, 'postMessage'>,
+): MessagePort {
+ const channel = new MessageChannel();
+ frame.postMessage({type: PREVIEW_CONNECT}, '*', [channel.port2]);
+ return channel.port1;
+}
+
+/**
+ * Preview side: the port from a connect handshake sent by this frame's own
+ * parent, or null for anything else — other windows, self-sends, connects
+ * without a port, unrelated messages. A nullish `parentWindow` means there is
+ * no embedder, so nothing can be trusted.
*/
-export function isTrustedPreviewMessage(
- event: Pick<MessageEvent, 'origin' | 'source'>,
- expectedOrigin: string,
- expectedSource: MessageEventSource | null | undefined,
-): boolean {
- if (event.origin !== expectedOrigin) {
- return false;
+export function acceptPreviewConnect(
+ event: Pick<MessageEvent, 'data' | 'source' | 'ports'>,
+ parentWindow: MessageEventSource | null | undefined,
+): MessagePort | null {
+ const type = (event.data as {type?: unknown} | null)?.type;
+ if (type !== PREVIEW_CONNECT) {
+ return null;
}
- if (expectedSource == null || event.source == null) {
- return false;
+ if (parentWindow == null || event.source == null) {
+ return null;
}
- return event.source === expectedSource;
+ if (event.source !== parentWindow) {
+ return null;
+ }
+ return event.ports[0] ?? null;
+}
+
+export interface PreviewConnector {
+ /**
+ * Start a new frame generation: forget the previous document, its port,
+ * its nonce and its window, and return the nonce the next iframe must be
+ * navigated with (see {@link previewSrc}). The caller mounts a fresh iframe
+ * element for it and hands over its window with {@link attachFrame}.
+ */
+ issue: () => string;
+ /**
+ * The window of the iframe element mounted for the current generation.
+ * Nothing is accepted from any window until this has been called.
+ */
+ attachFrame: (frame: MessageEventSource) => void;
+ /**
+ * Window `message` listener for the playground page. Acts on exactly one
+ * thing: a hello from the current frame's window carrying the outstanding
+ * nonce, which is answered with a port transfer.
+ */
+ handleWindowMessage: (event: MessageEvent) => void;
+ /**
+ * The iframe's `load` event. The first load of a generation is the attested
+ * document arriving; any later one means it was replaced, and `onReplaced`
+ * fires after the port and nonce have been discarded.
+ */
+ handleFrameLoad: () => void;
+ /** Send to the attested document; a no-op while there is none. */
+ post: (message: unknown) => void;
+ /** Whether a document has attested in the current generation. */
+ isAttested: () => boolean;
+ /** Close the port and forget everything. */
+ stop: () => void;
+}
+
+/**
+ * Playground side: the trust state machine described in the file header.
+ */
+export function createPreviewConnector({
+ onMessage,
+ onReplaced,
+ nonce = createPreviewNonce,
+}: {
+ /** Receives every message that arrives on the adopted port. */
+ onMessage: (event: MessageEvent) => void;
+ /**
+ * The attested document is gone. The caller must `issue()` a new
+ * generation and mount a fresh iframe for it.
+ */
+ onReplaced: () => void;
+ /** Nonce source; injectable for tests. */
+ nonce?: () => string;
+}): PreviewConnector {
+ let outstanding: string | null = null;
+ let frame: MessageEventSource | null = null;
+ let attested = false;
+ let loads = 0;
+ let port: MessagePort | null = null;
+
+ function discard() {
+ port?.close();
+ port = null;
+ outstanding = null;
+ frame = null;
+ attested = false;
+ loads = 0;
+ }
+
+ return {
+ issue() {
+ discard();
+ outstanding = nonce();
+ return outstanding;
+ },
+
+ attachFrame(next) {
+ frame = next;
+ },
+
+ handleWindowMessage(event) {
+ const data = event.data as {type?: unknown; nonce?: unknown} | null;
+ if (data?.type !== PREVIEW_HELLO) {
+ return;
+ }
+ // One nonce, one document, one answer. A replacement document that
+ // learned the nonce from the document it displaced finds it spent.
+ if (outstanding == null || attested) {
+ return;
+ }
+ if (typeof data.nonce !== 'string' || data.nonce !== outstanding) {
+ return;
+ }
+ if (frame == null || event.source == null || event.source !== frame) {
+ return;
+ }
+ attested = true;
+ port = connectToPreview(frame as Pick<Window, 'postMessage'>);
+ port.onmessage = onMessage;
+ },
+
+ handleFrameLoad() {
+ loads += 1;
+ if (loads === 1) {
+ // The document this generation was navigated to. Its hello may have
+ // arrived already (scripts run before subresources finish) or may
+ // still be coming; either way nothing previewed has run yet.
+ return;
+ }
+ discard();
+ onReplaced();
+ },
+
+ post(message) {
+ port?.postMessage(message);
+ },
+
+ isAttested: () => attested,
+
+ stop: discard,
+ };
}
diff --git a/apps/docsite/src/app/playground/propertyEditor/targetingOverlay.tsx b/apps/docsite/src/app/playground/propertyEditor/targetingOverlay.tsx
index e176c116ea..5f3135097c 100644
--- a/apps/docsite/src/app/playground/propertyEditor/targetingOverlay.tsx
+++ b/apps/docsite/src/app/playground/propertyEditor/targetingOverlay.tsx
@@ -28,7 +28,6 @@ import {Theme, MediaTheme} from '@astryxdesign/core/theme';
import type {ThemeMode} from '@astryxdesign/core/theme';
import {astryxTheme} from '../../../themes/astryx';
import {PropertyEditor} from './PropertyEditor';
-import {trustedPreviewOrigin} from '../previewChannel';
const styles = stylex.create({
badge: {minHeight: 32},
@@ -129,11 +128,20 @@ export function setCleanSource(source: string) {
cleanSource = source;
}
+/**
+ * The channel back to the playground, set by the preview page once its port
+ * handshake lands (see previewChannel.ts). Module-level like the site-mode and
+ * clean-source setters above, because the popover roots render outside the
+ * page's React tree.
+ */
+let postToParentFn: (msg: Record<string, unknown>) => void = () => {};
+
+export function setPostToParent(fn: (msg: Record<string, unknown>) => void) {
+ postToParentFn = fn;
+}
+
function postEditToParent(code: string) {
- window.parent.postMessage(
- {type: 'preview-edit-code', code},
- trustedPreviewOrigin(),
- );
+ postToParentFn({type: 'preview-edit-code', code});
}
function renderTargetLabel(label: HTMLDivElement) {
diff --git a/package.json b/package.json
index 97467b1104..bb9ea2bd5b 100644
--- a/package.json
+++ b/package.json
@@ -11,6 +11,7 @@
"test:watch": "vitest",
"test:coverage": "vitest --coverage",
"test:a11y-contract": "playwright test --config playwright.config.ts --project chromium",
+ "test:docsite-browser": "playwright test --config apps/docsite/playwright.config.ts",
"check:package-boundaries": "node scripts/check-package-boundaries.js",
"check:repo": "pnpm check:visual-owner && pnpm check:sync && pnpm check:knowledge && pnpm check:package-boundaries && pnpm check:changesets && pnpm check:demo-media && pnpm check:executable-bits && pnpm check:cli-structure && pnpm check:use-client && pnpm check:portable-scripts && pnpm check:i18n-catalog && pnpm check:cldr-weekdays && pnpm check:fixtures && pnpm check:setup-contract",
"check:visual-owner": "node scripts/check-visual-workflow-owner.mjs",