Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.
TypeScript accessibilityalternativecloudflarecloudflare-workersdesignfreefrontendopen-sourceradix-uireactremixweb-developmentwebflowwebsite-builderwebsite-developmentwebsiteswebstudio
chore: Add postMessage token to secure against Canvas script execution (#4060)
Ivan Starkov87bfd994be82
diff --git a/apps/builder/app/builder/builder.tsx b/apps/builder/app/builder/builder.tsxindex 3cee1f6ab8..40558d26a5 100644--- a/apps/builder/app/builder/builder.tsx+++ b/apps/builder/app/builder/builder.tsx@@ -57,6 +57,7 @@ import { initBuilderApi } from "~/shared/builder-api";import { updateWebstudioData } from "~/shared/instance-utils";import { migrateWebstudioDataMutable } from "~/shared/webstudio-data-migrator";import { Loading, LoadingBackground } from "./shared/loading";+import { mergeRefs } from "@react-aria/utils";registerContainers();@@ -288,13 +289,10 @@ export const Builder = ({// because the events will fire in either one, depending on where the focus isuseCopyPaste();useSetWindowTitle();- const iframeRefCallback = useCallback(- (element: HTMLIFrameElement) => {- publishRef.current = element;- onRefReadCanvas(element);- },- [publishRef, onRefReadCanvas]- );++ const iframeRefCallback = mergeRefs((element: HTMLIFrameElement | null) => {+ onRefReadCanvas(element);+ }, publishRef);const { navigatorLayout } = useStore($settings);const dataLoadingState = useStore($dataLoadingState);diff --git a/apps/builder/app/shared/pubsub/create.ts b/apps/builder/app/shared/pubsub/create.tsindex 1cf0c4eac9..70bcfb5351 100644--- a/apps/builder/app/shared/pubsub/create.ts+++ b/apps/builder/app/shared/pubsub/create.ts@@ -1,6 +1,22 @@import { createNanoEvents } from "nanoevents";import { useCallback, useEffect, useRef } from "react";import { batchUpdate } from "./raf-queue";+import { useEffectEvent } from "../hook-utils/effect-event";+import invariant from "tiny-invariant";++const apiTokenKey = "__webstudio__$__api_token";++declare global {+ interface Window {+ [apiTokenKey]: string | undefined;+ }+}++const getRandomToken = () => {+ const randomBytes = new Uint8Array(10);+ window.crypto.getRandomValues(randomBytes);+ return btoa(String.fromCharCode(...randomBytes));+};export const createPubsub = <PublishMap>() => {type Action<Type extends keyof PublishMap> =@@ -8,51 +24,137 @@ export const createPubsub = <PublishMap>() => {? { type: Type; payload?: undefined }: { type: Type; payload: PublishMap[Type] };+ if (typeof window === "undefined") {+ return {+ publish: () => {+ throw new Error("publish is not available in this environment");+ },+ usePublish: () => {+ throw new Error("usePublish is not available in this environment");+ },+ useSubscribe: () => {+ throw new Error("useSubscribe is not available in this environment");+ },+ subscribe: () => {+ throw new Error("subscribe is not available in this environment");+ },+ } as never; // Prevent type exposure+ }++ /**+ * To avoid postMessage interception from the canvas, i.e., `globalThis.postMessage = () => console.log('INTERCEPTED');`,+ */+ const postMessageInternal = window.postMessage;+ const parentPostMessageInternal = window.parent.postMessage;++ /**+ * Similar to a CSRF token, we use a token to ensure that the postMessage is coming from a trusted source.+ */+ let token =+ window.self === window.top ? getRandomToken() : window.top?.[apiTokenKey];++ if (window.top) {+ // Initialize token at the Builder, reset it on the Canvas after reading+ window.top[apiTokenKey] = window.self === window.top ? token : undefined;+ }++ // Use a fixed token in development to handle HMR updates consistently+ if (process.env.NODE_ENV !== "production") {+ token = "development-token";+ }+// eslint-disable-next-line @typescript-eslint/no-explicit-anyconst emitter = createNanoEvents<Record<any, any>>();- if (typeof window === "object") {- window.addEventListener(- "message",- (event: MessageEvent) => {- // @todo this has no type safety built in, could be anything from any source.- // we could potentially maintain a list of valid event types at runtime- // at the very least we could add a brand property or something to our events- if (typeof event.data?.type === "string") {- // Execute all updates within a single batch to improve performance- batchUpdate(() => emitter.emit(event.data.type, event.data.payload));- }- },- false- );- }+ const wrapAction = (action: unknown) => {+ return { action, token };+ };++ const unwrapAction = (payload: unknown) => {+ if (typeof payload !== "object" || payload === null) {+ console.error("Invalid payload", payload);+ throw new Error("Invalid payload");+ }++ if (false === "token" in payload) {+ throw new Error("Invalid payload, not wrapped");+ }++ if (payload.token !== token) {+ throw new Error("Invalid token");+ }++ if (false === "action" in payload) {+ throw new Error("Invalid payload, not wrapped");+ }++ // Hide the token from the subsequent subscribers+ payload.token = undefined;+ return payload.action as Action<keyof PublishMap>;+ };++ const handleMessage = (event: MessageEvent) => {+ const action = unwrapAction(event.data);+ const type = action.type;+ // Execute all updates within a single batch to improve performance+ batchUpdate(() => emitter.emit(type, action.payload));+ };++ window.addEventListener("message", handleMessage, false);return {/*** To publish a postMessage event on the current window and parent window from the iframe.*/publish<Type extends keyof PublishMap>(action: Action<Type>) {- window.parent.postMessage(action, "*");- window.postMessage(action, "*");+ invariant(+ window.self !== window.top,+ "publish is not available in the Builder environment"+ );++ parentPostMessageInternal(wrapAction(action), "*");+ postMessageInternal(wrapAction(action), "*");},/*** To publish a postMessage event on the iframe and parent window from the parent window.*/usePublish() {- const iframeRef = useRef<HTMLIFrameElement | null>(null);- const publishCallback = useCallback(+ const postMessageRef = useRef<typeof window.postMessage>();++ const iframeRefCallback = useCallback(+ (element: HTMLIFrameElement | null) => {+ if (element == null) {+ postMessageRef.current = undefined;+ return;+ }+ /**+ * To avoid postMessage interception from the canvas, i.e., `globalThis.postMessage = () => console.log('INTERCEPTED');`,+ */+ postMessageRef.current = element.contentWindow!.postMessage;+ },+ []+ );++ const publish = useCallback(<Type extends keyof PublishMap>(action: Action<Type>) => {- const element = iframeRef.current;- if (element?.contentWindow == null) {+ invariant(+ window.self === window.top,+ "publish is not available in the Canvas environment"+ );++ if (postMessageRef.current === undefined) {return;}- element.contentWindow.postMessage(action, "*");- window.postMessage(action, "*");+ // This ensures the method is called with the correct context.+ const postMessageIframe = postMessageRef.current;++ postMessageIframe(wrapAction(action), "*");+ postMessageInternal(wrapAction(action), "*");},- [iframeRef]+ []);- return [publishCallback, iframeRef] as const;+ return [publish, iframeRefCallback] as const;},/**@@ -62,9 +164,11 @@ export const createPubsub = <PublishMap>() => {type: Type,onAction: (payload: PublishMap[Type]) => void) {+ const handleOnAction = useEffectEvent(onAction);+useEffect(() => {- return emitter.on(type, onAction);- }, [type, onAction]);+ return emitter.on(type, handleOnAction);+ }, [type, handleOnAction]);},subscribe<Type extends keyof PublishMap>(