Skip to content

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

TypeScript

fix(docsite): verify the sender on the playground preview channel (#5263)

Cindy Zhang8f7a21fb4196
diff --git a/apps/docsite/next.config.mjs b/apps/docsite/next.config.mjs
index 432ed37889..7e73c3f92e 100644
--- a/apps/docsite/next.config.mjs
+++ b/apps/docsite/next.config.mjs
@@ -11,6 +11,36 @@ const nextConfig = {
async rewrites() {
return [{source: '/blog/:slug.txt', destination: '/blog/txt/:slug'}];
},
+ // 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).
+ async headers() {
+ return [
+ {
+ source: '/playground/preview',
+ headers: [
+ {key: 'X-Frame-Options', value: 'SAMEORIGIN'},
+ {
+ key: 'Content-Security-Policy',
+ value: [
+ "frame-ancestors 'self'",
+ "base-uri 'none'",
+ "object-src 'none'",
+ "form-action 'self'",
+ "script-src 'self' 'unsafe-inline' 'unsafe-eval' https://va.vercel-scripts.com",
+ "style-src 'self' 'unsafe-inline' https://fonts.googleapis.com",
+ "font-src 'self' https://fonts.gstatic.com data:",
+ ].join('; '),
+ },
+ ],
+ },
+ ];
+ },
webpack: config => {
// Webpack's CSS @import resolver doesn't follow package.json "exports".
// Map each theme's /theme.css subpath to the actual dist file.
diff --git a/apps/docsite/src/__tests__/playground-preview-channel.test.ts b/apps/docsite/src/__tests__/playground-preview-channel.test.ts
new file mode 100644
index 0000000000..1e233f3452
--- /dev/null
+++ b/apps/docsite/src/__tests__/playground-preview-channel.test.ts
@@ -0,0 +1,58 @@
+// 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';
+
+const parent = {} as MessageEventSource;
+const other = {} as MessageEventSource;
+
+function event(origin: string, source: MessageEventSource | null) {
+ return {origin, source};
+}
+
+describe('isTrustedPreviewMessage', () => {
+ it('accepts a message from the expected window on our own origin', () => {
+ expect(isTrustedPreviewMessage(event(ORIGIN, parent), ORIGIN, parent)).toBe(
+ true,
+ );
+ });
+
+ it('rejects another origin, even from the expected window', () => {
+ expect(
+ isTrustedPreviewMessage(
+ event('https://evil.example', parent),
+ ORIGIN,
+ parent,
+ ),
+ ).toBe(false);
+ });
+
+ it('rejects an opaque (sandboxed) origin', () => {
+ expect(isTrustedPreviewMessage(event('null', parent), ORIGIN, parent)).toBe(
+ false,
+ );
+ });
+
+ it('rejects our own origin sent from a window that is not the counterpart', () => {
+ expect(isTrustedPreviewMessage(event(ORIGIN, other), ORIGIN, parent)).toBe(
+ false,
+ );
+ });
+
+ it('rejects everything while the counterpart window does not exist', () => {
+ expect(isTrustedPreviewMessage(event(ORIGIN, parent), ORIGIN, null)).toBe(
+ false,
+ );
+ 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,
+ );
+ });
+});
diff --git a/apps/docsite/src/app/playground/PlaygroundClient.tsx b/apps/docsite/src/app/playground/PlaygroundClient.tsx
index c5e863d768..dcc52e165d 100644
--- a/apps/docsite/src/app/playground/PlaygroundClient.tsx
+++ b/apps/docsite/src/app/playground/PlaygroundClient.tsx
@@ -37,6 +37,7 @@ 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 {Button} from '@astryxdesign/core/Button';
import {Link} from '@astryxdesign/core/Link';
import {HStack, VStack} from '@astryxdesign/core/Layout';
@@ -357,7 +358,7 @@ export function PlaygroundClient() {
const postToPreview = useCallback((message: unknown) => {
iframeRef.current?.contentWindow?.postMessage(
message,
- window.location.origin,
+ trustedPreviewOrigin(),
);
}, []);
@@ -407,7 +408,13 @@ export function PlaygroundClient() {
useEffect(() => {
const handler = (e: MessageEvent) => {
- if (e.source !== iframeRef.current?.contentWindow) {
+ if (
+ !isTrustedPreviewMessage(
+ e,
+ trustedPreviewOrigin(),
+ iframeRef.current?.contentWindow,
+ )
+ ) {
return;
}
if (e.data?.type === 'preview-ready') {
diff --git a/apps/docsite/src/app/playground/preview/page.tsx b/apps/docsite/src/app/playground/preview/page.tsx
index f358dd525d..094e546518 100644
--- a/apps/docsite/src/app/playground/preview/page.tsx
+++ b/apps/docsite/src/app/playground/preview/page.tsx
@@ -22,6 +22,7 @@ import {
setCleanSource,
} from '../propertyEditor/targetingOverlay';
import {runCode, setTypeScript} from './runner';
+import {isTrustedPreviewMessage, trustedPreviewOrigin} from '../previewChannel';
import type * as TS from 'typescript';
const FALLBACK_THEME =
@@ -116,7 +117,7 @@ export default function PreviewPage() {
const theme = customTheme ?? themeByValue[themeName] ?? FALLBACK_THEME;
const postToParent = useCallback((msg: Record<string, unknown>) => {
- window.parent.postMessage(msg, '*');
+ window.parent.postMessage(msg, trustedPreviewOrigin());
}, []);
const targetingRef = useRef<ReturnType<
@@ -197,6 +198,13 @@ export default function PreviewPage() {
}
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;
}
diff --git a/apps/docsite/src/app/playground/previewChannel.ts b/apps/docsite/src/app/playground/previewChannel.ts
new file mode 100644
index 0000000000..2d9f6117d6
--- /dev/null
+++ b/apps/docsite/src/app/playground/previewChannel.ts
@@ -0,0 +1,46 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file previewChannel.ts
+ * @input An incoming MessageEvent plus the window we expect to hear from
+ * @output Whether the message may be acted on
+ * @position Playground <-> preview iframe — the postMessage trust boundary.
+ *
+ * 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.
+ *
+ * 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.
+ */
+
+/** The origin both ends of the channel must be on. */
+export function trustedPreviewOrigin(): string {
+ return window.location.origin;
+}
+
+/**
+ * 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.
+ */
+export function isTrustedPreviewMessage(
+ event: Pick<MessageEvent, 'origin' | 'source'>,
+ expectedOrigin: string,
+ expectedSource: MessageEventSource | null | undefined,
+): boolean {
+ if (event.origin !== expectedOrigin) {
+ return false;
+ }
+ if (expectedSource == null || event.source == null) {
+ return false;
+ }
+ return event.source === expectedSource;
+}
diff --git a/apps/docsite/src/app/playground/propertyEditor/targetingOverlay.tsx b/apps/docsite/src/app/playground/propertyEditor/targetingOverlay.tsx
index ffbaeae750..e176c116ea 100644
--- a/apps/docsite/src/app/playground/propertyEditor/targetingOverlay.tsx
+++ b/apps/docsite/src/app/playground/propertyEditor/targetingOverlay.tsx
@@ -28,6 +28,7 @@ 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,7 +130,10 @@ export function setCleanSource(source: string) {
}
function postEditToParent(code: string) {
- window.parent.postMessage({type: 'preview-edit-code', code}, '*');
+ window.parent.postMessage(
+ {type: 'preview-edit-code', code},
+ trustedPreviewOrigin(),
+ );
}
function renderTargetLabel(label: HTMLDivElement) {