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
replace getCanvasRequestParams with getUserContentParams with a more strict logic
Roman Pominov722fe1636982
diff --git a/apps/designer/.env.example b/apps/designer/.env.exampleindex a5265620f0..fbfd4d7297 100644--- a/apps/designer/.env.example+++ b/apps/designer/.env.example@@ -26,3 +26,11 @@ ASSET_CDN_URL=PUBLISHER_ENDPOINT=PUBLISHER_HOST=PUBLISHER_TOKEN=++# A domain for accessing user-generated content (canvas / preview / etc)+# Will be detected automatically in development environments like localhost or preview deployment+USER_CONTENT_HOST=++# If set to `true`, user-generated content will be available+# only at {project.domain}.{USER_CONTENT_HOST}+USER_CONTENT_REQUIRE_SUBDOMAIN=\ No newline at end of filediff --git a/apps/designer/app/entry.server.tsx b/apps/designer/app/entry.server.tsxindex 286acca6ae..92568534ee 100644--- a/apps/designer/app/entry.server.tsx+++ b/apps/designer/app/entry.server.tsx@@ -4,7 +4,7 @@ import { initSentry } from "./shared/sentry";import { prisma } from "@webstudio-is/prisma-client";import { handleRequest as handleRequestDesigner } from "./shared/remix";import { handleRequest as handleRequestCanvas } from "@webstudio-is/react-sdk";-import { getCanvasRequestParams } from "./shared/router-utils";+import { getUserContentParams } from "./shared/router-utils";initSentry({integrations: [new Sentry.Integrations.Prisma({ client: prisma })],@@ -23,7 +23,7 @@ export default function handleRequest((match) =>match.route.id === "routes/$" || match.route.id === "routes/index") &&- getCanvasRequestParams(request) !== undefined+ getUserContentParams(request) !== undefined) {handle = handleRequestCanvas;}diff --git a/apps/designer/app/routes/$.tsx b/apps/designer/app/routes/$.tsxindex 21ff6aae15..78ff386b0e 100644--- a/apps/designer/app/routes/$.tsx+++ b/apps/designer/app/routes/$.tsx@@ -1,4 +1,9 @@-import { type LoaderFunction, redirect, MetaFunction } from "@remix-run/node";+import {+ type LoaderFunction,+ redirect,+ MetaFunction,+ json,+} from "@remix-run/node";import { useLoaderData } from "@remix-run/react";import { InstanceRoot, Root } from "@webstudio-is/react-sdk";import { loadCanvasData, type CanvasData } from "~/shared/db";@@ -10,7 +15,7 @@ import { Canvas } from "~/canvas";import { ErrorMessage } from "~/shared/error";import {type CanvasRouteMode,- getCanvasRequestParams,+ getUserContentParams,} from "~/shared/router-utils";type Data =@@ -29,7 +34,7 @@ export const loader: LoaderFunction = async ({request,}): Promise<Data | Response> => {try {- const canvasRequest = getCanvasRequestParams(request);+ const canvasRequest = getUserContentParams(request);if (canvasRequest === undefined) {return redirect(config.dashboardPath);@@ -43,7 +48,7 @@ export const loader: LoaderFunction = async ({: await db.project.loadByDomain(canvasRequest.projectDomain);if (project === null) {- throw new Error("Project not found");+ throw json("Project not found", { status: 404 });}const canvasData = await loadCanvasData(@@ -52,8 +57,18 @@ export const loader: LoaderFunction = async ({pathname);+ if (canvasData === undefined) {+ throw json("Page not found", { status: 404 });+ }+return { ...canvasData, env, mode };} catch (error) {+ // If a Response is thrown, we're rethrowing it for Remix to handle.+ // https://remix.run/docs/en/v1/api/conventions#throwing-responses-in-loaders+ if (error instanceof Response) {+ throw error;+ }+sentryException({ error });return {errors: error instanceof Error ? error.message : String(error),diff --git a/apps/designer/app/shared/db/canvas.server.ts b/apps/designer/app/shared/db/canvas.server.tsindex 9ed4fe0fa5..35c344c045 100644--- a/apps/designer/app/shared/db/canvas.server.ts+++ b/apps/designer/app/shared/db/canvas.server.ts@@ -9,7 +9,7 @@ export const loadCanvasData = async (projectId: Project["id"],env: "dev" | "prod",pagePath = ""-): Promise<CanvasData> => {+): Promise<CanvasData | undefined> => {const build =env === "dev"? await db.build.loadByProjectId(projectId, "dev")@@ -22,7 +22,7 @@ export const loadCanvasData = async (const page = utils.pages.findByPath(build.pages, pagePath);if (page === undefined) {- throw new Error(`Page "${pagePath}" not found`);+ return;}const [tree, props, breakpoints] = await Promise.all([diff --git a/apps/designer/app/shared/router-utils/canvas-request-params.test.ts b/apps/designer/app/shared/router-utils/canvas-request-params.test.tsdeleted file mode 100644index c09c7af2e3..0000000000--- a/apps/designer/app/shared/router-utils/canvas-request-params.test.ts+++ /dev/null@@ -1,94 +0,0 @@-import { getCanvasRequestParams } from "./canvas-request-params";--const makeRequest = (url: string, headers: { [key: string]: string }) => ({- url,- headers: {- get: (name: string) => (headers[name] === undefined ? null : headers[name]),- },-});--describe("getCanvasRequestParams", () => {- test("returns undefined if the request is not an canvas request", () => {- expect(- getCanvasRequestParams(makeRequest("https://example.com", {}))- ).toBeUndefined();- });-- test("detects project domain on localhost via `x-forwarded-host` header", () => {- expect(- getCanvasRequestParams(- makeRequest("https://foo.localhost", {- "x-forwarded-host": "foo.localhost",- })- )- ).toMatchInlineSnapshot(`- Object {- "mode": "published",- "pathname": "/",- "projectDomain": "foo",- }- `);- });-- test("detects project domain on localhost via `host` header", () => {- expect(- getCanvasRequestParams(- makeRequest("https://foo.localhost", { host: "foo.localhost" })- )- ).toMatchInlineSnapshot(`- Object {- "mode": "published",- "pathname": "/",- "projectDomain": "foo",- }- `);- });-- test("detects projectId parameter", () => {- expect(- getCanvasRequestParams(- makeRequest("https://foo.localhost?projectId=bar", {})- )- ).toMatchInlineSnapshot(`- Object {- "mode": "published",- "pathname": "/",- "projectId": "bar",- }- `);- });-- test("detects path", () => {- expect(- getCanvasRequestParams(- makeRequest("https://foo.localhost/some/path?projectId=bar", {})- )?.pathname- ).toMatchInlineSnapshot(`"/some/path"`);- });-- test("detects mode", () => {- expect(- getCanvasRequestParams(- makeRequest(- "https://foo.localhost/some/path?projectId=bar&mode=edit",- {}- )- )?.mode- ).toMatchInlineSnapshot(`"edit"`);-- expect(- getCanvasRequestParams(- makeRequest(- "https://foo.localhost/some/path?projectId=bar&mode=preview",- {}- )- )?.mode- ).toMatchInlineSnapshot(`"preview"`);-- expect(- getCanvasRequestParams(- makeRequest("https://foo.localhost/some/path?projectId=bar", {})- )?.mode- ).toMatchInlineSnapshot(`"published"`);- });-});diff --git a/apps/designer/app/shared/router-utils/canvas-request-params.ts b/apps/designer/app/shared/router-utils/canvas-request-params.tsdeleted file mode 100644index bc10e28443..0000000000--- a/apps/designer/app/shared/router-utils/canvas-request-params.ts+++ /dev/null@@ -1,63 +0,0 @@-export type CanvasRouteMode = "edit" | "preview" | "published";--const modes = ["edit", "preview", "published"] as CanvasRouteMode[];--export const getCanvasRequestParams = (request: {- url: string;- headers: { get: (name: string) => string | null };-}):- | {- projectId: string;- mode: CanvasRouteMode;- pathname: string;- }- | {- projectDomain: string;- mode: CanvasRouteMode;- pathname: string;- }- | undefined => {- const url = new URL(request.url);-- const pathname = url.pathname;-- const projectId = url.searchParams.get("projectId");-- let projectDomain = undefined;- if (projectId === null) {- // @todo all this subdomain logic is very hacky- const host =- request.headers.get("x-forwarded-host") ||- request.headers.get("host") ||- "";- const [userDomain, wstdDomain] = host.split(".");- if (wstdDomain === "wstd" || wstdDomain?.includes("localhost")) {- projectDomain = userDomain;- }- }-- const modeParam = url.searchParams.get("mode");- const mode =- modeParam === null ? "published" : modes.find((mode) => mode === modeParam);- if (mode === undefined) {- throw new Error(`Invalid mode "${modeParam}"`);- }-- if (projectId !== null) {- return {- projectId,- mode,- pathname,- };- }-- if (projectDomain !== undefined) {- return {- projectDomain,- mode,- pathname,- };- }-- return;-};diff --git a/apps/designer/app/shared/router-utils/index.ts b/apps/designer/app/shared/router-utils/index.tsindex 79eef16bfe..457ffb59c0 100644--- a/apps/designer/app/shared/router-utils/index.ts+++ b/apps/designer/app/shared/router-utils/index.ts@@ -1 +1 @@-export * from "./canvas-request-params";+export * from "./user-content-params";diff --git a/apps/designer/app/shared/router-utils/user-content-params.test.ts b/apps/designer/app/shared/router-utils/user-content-params.test.tsnew file mode 100644index 0000000000..bed153ef52--- /dev/null+++ b/apps/designer/app/shared/router-utils/user-content-params.test.ts@@ -0,0 +1,127 @@+import {+ getUserContentParams,+ getUserContentHost,+} from "./user-content-params";++const makeRequest = (url: string, headers: { [key: string]: string } = {}) => ({+ url,+ headers: {+ get: (name: string) => {+ if (headers[name] !== undefined) {+ return headers[name];+ }+ if (name === "host" || name === "x-forwarded-host") {+ return new URL(url).host;+ }+ return null;+ },+ },+});++const originalEnv = { ...process.env };+afterEach(() => {+ for (const name of [+ "USER_CONTENT_HOST",+ "USER_CONTENT_REQUIRE_SUBDOMAIN",+ "VERCEL_ENV",+ "VERCEL_URL",+ "NODE_ENV",+ ]) {+ if (originalEnv[name] !== undefined) {+ process.env[name] = originalEnv[name];+ } else {+ // setting process.env.SOMETHING to undefined+ // results in it being set to a string "undefined"+ delete process.env[name];+ }+ }+});++describe("getUserContentHost", () => {+ test("Normal operation", () => {+ process.env.USER_CONTENT_HOST = "foo.com";+ expect(getUserContentHost(makeRequest("https://bar.com"))).toBe("foo.com");+ });++ test("Local development", () => {+ process.env.NODE_ENV = "development";+ expect(getUserContentHost(makeRequest("https://localhost"))).toBe(+ "localhost"+ );+ expect(getUserContentHost(makeRequest("https://localhost:1234"))).toBe(+ "localhost:1234"+ );+ expect(getUserContentHost(makeRequest("https://foo.localhost:1234"))).toBe(+ "localhost:1234"+ );+ });++ test("Vercel preview", () => {+ process.env.VERCEL_ENV = "preview";+ process.env.VERCEL_URL = "bar.foo.com";+ expect(getUserContentHost(makeRequest("https://bar.com"))).toBe(+ "bar.foo.com"+ );+ });+});++describe("getCanvasRequestParams", () => {+ beforeEach(() => {+ process.env.USER_CONTENT_HOST = "foo.com";+ });++ test("detects project domain", () => {+ const request = makeRequest("https://bar.foo.com");+ expect(+ (getUserContentParams(request) as { projectDomain: string }).projectDomain+ ).toBe("bar");+ });++ test("doesn't detect project domain if base domain is not a user content domain", () => {+ const request = makeRequest("https://bar.baz.com");+ expect(getUserContentParams(request)).toBeUndefined();+ });++ test("detects project id", () => {+ const request = makeRequest("https://foo.com?projectId=123");+ expect(+ (getUserContentParams(request) as { projectId: string }).projectId+ ).toBe("123");+ });++ test("doesn't detect project id if domain is not a user content domain", () => {+ const request = makeRequest("https://baz.com?projectId=123");+ expect(getUserContentParams(request)).toBeUndefined();+ });++ test("doesn't detect project id if USER_CONTENT_REQUIRE_SUBDOMAIN is true", () => {+ process.env.USER_CONTENT_REQUIRE_SUBDOMAIN = "true";+ const request = makeRequest("https://foo.com?projectId=123");+ expect(getUserContentParams(request)).toBeUndefined();+ });++ test("detects path", () => {+ expect(+ getUserContentParams(makeRequest("https://bar.foo.com"))?.pathname+ ).toBe("/");+ expect(+ getUserContentParams(makeRequest("https://bar.foo.com/abc"))?.pathname+ ).toBe("/abc");+ expect(+ getUserContentParams(makeRequest("https://bar.foo.com/abc/123"))?.pathname+ ).toBe("/abc/123");+ });++ test("detects mode", () => {+ expect(+ getUserContentParams(makeRequest("https://bar.foo.com?mode=edit"))?.mode+ ).toBe("edit");+ expect(+ getUserContentParams(makeRequest("https://bar.foo.com?mode=preview"))+ ?.mode+ ).toBe("preview");+ expect(getUserContentParams(makeRequest("https://bar.foo.com"))?.mode).toBe(+ "published"+ );+ });+});diff --git a/apps/designer/app/shared/router-utils/user-content-params.ts b/apps/designer/app/shared/router-utils/user-content-params.tsnew file mode 100644index 0000000000..96d6e69e68--- /dev/null+++ b/apps/designer/app/shared/router-utils/user-content-params.ts@@ -0,0 +1,90 @@+export type CanvasRouteMode = "edit" | "preview" | "published";+const modes = ["edit", "preview", "published"] as CanvasRouteMode[];+const getMode = (url: URL): CanvasRouteMode => {+ const modeParam = url.searchParams.get("mode");+ const mode =+ modeParam === null ? "published" : modes.find((mode) => mode === modeParam);+ if (mode === undefined) {+ throw new Error(`Invalid mode "${modeParam}"`);+ }+ return mode;+};++// A subtype of Request. To make testing easier.+type MinimalRequest = {+ url: string;+ headers: { get: (name: string) => string | null };+};++const getRequestHost = (request: MinimalRequest): string =>+ request.headers.get("x-forwarded-host") || request.headers.get("host") || "";++export const getUserContentHost = (request: MinimalRequest): string => {+ const { USER_CONTENT_HOST } = process.env;+ if (USER_CONTENT_HOST !== undefined && USER_CONTENT_HOST !== "") {+ return USER_CONTENT_HOST;+ }++ // Local development special case+ const host = getRequestHost(request);+ if (+ process.env.NODE_ENV === "development" &&+ /^(.*\.)?localhost(:\d+)?$/.test(host)+ ) {+ return host.split(".").pop() as string;+ }++ // Vercel preview special case+ if (+ (process.env.VERCEL_ENV === "preview" ||+ process.env.VERCEL_ENV === "development") &&+ typeof process.env.VERCEL_URL === "string"+ ) {+ return process.env.VERCEL_URL;+ }++ throw new Error("Could not determine user content host");+};++export const getUserContentParams = (+ request: MinimalRequest+):+ | {+ projectId: string;+ mode: CanvasRouteMode;+ pathname: string;+ }+ | {+ projectDomain: string;+ mode: CanvasRouteMode;+ pathname: string;+ }+ | undefined => {+ const url = new URL(request.url);++ const requestHost = getRequestHost(request);+ const userContentHost = getUserContentHost(request);++ if (process.env.USER_CONTENT_REQUIRE_SUBDOMAIN !== "true") {+ const projectId = url.searchParams.get("projectId");+ if (projectId !== null && userContentHost === requestHost) {+ return {+ projectId,+ mode: getMode(url),+ pathname: url.pathname,+ };+ }+ }++ const [projectDomain, ...rest] = requestHost.split(".");+ const baseHost = rest.join(".");+ if (baseHost === userContentHost) {+ return {+ projectDomain,+ mode: getMode(url),+ pathname: url.pathname,+ };+ }++ return;+};diff --git a/apps/designer/env-check.js b/apps/designer/env-check.jsindex 6be9b28154..b100fb600c 100644--- a/apps/designer/env-check.js+++ b/apps/designer/env-check.js@@ -40,6 +40,16 @@ if (process.env.DEPLOYMENT_ENVIRONMENT === "production") {"👉 In production DESIGNER_HOST is required for website functionality. Please set it to your production URL of the designer.");}+ if (!process.env.USER_CONTENT_HOST) {+ errors.push(+ "👉 In production USER_CONTENT_HOST is required for security reasons. Please set it to a value distinct from DESIGNER_HOST / DEPLOYMENT_URL."+ );+ }+ if (process.env.USER_CONTENT_REQUIRE_SUBDOMAIN !== "true") {+ errors.push(+ "👉 In production USER_CONTENT_REQUIRE_SUBDOMAIN must be set to 'true' for security reasons."+ );+ }}// check for when user has some S3 env variables but not all required