Skip to content

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.

feat: Simple bot protection that should elimiminate most of the spam on our forms (#3350)

Ivan Starkov8cdc10326388
diff --git a/fixtures/webstudio-cloudflare-template/app/routes/_index.tsx b/fixtures/webstudio-cloudflare-template/app/routes/_index.tsx
index 5ed3bcbb16..e1800c8845 100644
--- a/fixtures/webstudio-cloudflare-template/app/routes/_index.tsx
+++ b/fixtures/webstudio-cloudflare-template/app/routes/_index.tsx
@@ -11,7 +11,11 @@ import {
} from "@remix-run/server-runtime";
import { useLoaderData } from "@remix-run/react";
import { ReactSdkContext } from "@webstudio-is/react-sdk";
-import { n8nHandler, getFormId } from "@webstudio-is/form-handlers";
+import {
+ n8nHandler,
+ formIdFieldName,
+ formBotFieldName,
+} from "@webstudio-is/form-handlers";
import {
Page,
siteName,
@@ -240,66 +244,86 @@ const getMethod = (value: string | undefined) => {
}
};
-export const action = async ({ request, context }: ActionFunctionArgs) => {
- const formData = await request.formData();
+export const action = async ({
+ request,
+ context,
+}: ActionFunctionArgs): Promise<
+ { success: true } | { success: false; errors: string[] }
+> => {
+ try {
+ const formData = await request.formData();
- const formId = getFormId(formData);
- if (formId === undefined) {
- // We're throwing rather than returning { success: false }
- // because this isn't supposed to happen normally: bug or malicious user
- throw json("Form not found", { status: 404 });
- }
+ const formId = formData.get(formIdFieldName);
- const formProperties = formsProperties.get(formId);
+ if (formId == null || typeof formId !== "string") {
+ throw new Error("No form id in FormData");
+ }
- // form properties are not defined when defaults are used
- const { action, method } = formProperties ?? {};
+ const formBotValue = formData.get(formBotFieldName);
- if (contactEmail === undefined) {
- return { success: false };
- }
+ if (formBotValue == null || typeof formBotValue !== "string") {
+ throw new Error("Form bot field not found");
+ }
- // wrapped in try/catch just in cases new URL() throws
- // (should not happen)
- let pageUrl: URL;
- try {
- pageUrl = new URL(request.url);
+ const submitTime = parseInt(formBotValue, 16);
+ // Assumes that the difference between the server time and the form submission time,
+ // including any client-server time drift, is within a 5-minute range.
+ // Note: submitTime might be NaN because formBotValue can be any string used for logging purposes.
+ // Example: `formBotValue: jsdom`, or `formBotValue: headless-env`
+ if (
+ Number.isNaN(submitTime) ||
+ Math.abs(Date.now() - submitTime) > 1000 * 60 * 5
+ ) {
+ throw new Error(`Form bot value invalid ${formBotValue}`);
+ }
+
+ const formProperties = formsProperties.get(formId);
+
+ // form properties are not defined when defaults are used
+ const { action, method } = formProperties ?? {};
+
+ if (contactEmail === undefined) {
+ throw new Error("Contact email not found");
+ }
+
+ const pageUrl = new URL(request.url);
pageUrl.host = getRequestHost(request);
- } catch {
- return { success: false };
- }
- if (action !== undefined) {
- try {
- // Test that action is full URL
- new URL(action);
- } catch {
- return json(
- {
- success: false,
- error: "Invalid action URL, must be valid http/https protocol",
- },
- { status: 200 }
- );
+ if (action !== undefined) {
+ try {
+ // Test that action is full URL
+ new URL(action);
+ } catch {
+ throw new Error(
+ "Invalid action URL, must be valid http/https protocol"
+ );
+ }
}
- }
- const formInfo = {
- formData,
- projectId,
- action: action ?? null,
- method: getMethod(method),
- pageUrl: pageUrl.toString(),
- toEmail: contactEmail,
- fromEmail: pageUrl.hostname + "@webstudio.email",
- } as const;
-
- const result = await n8nHandler({
- formInfo,
- hookUrl: context.N8N_FORM_EMAIL_HOOK,
- });
+ const formInfo = {
+ formData,
+ projectId,
+ action: action ?? null,
+ method: getMethod(method),
+ pageUrl: pageUrl.toString(),
+ toEmail: contactEmail,
+ fromEmail: pageUrl.hostname + "@webstudio.email",
+ } as const;
+
+ const result = await n8nHandler({
+ formInfo,
+ hookUrl: context.N8N_FORM_EMAIL_HOOK,
+ });
- return result;
+ return result;
+ } catch (error) {
+ console.error(error);
+
+ return {
+ success: false,
+ errors: [error instanceof Error ? error.message : "Unknown error"],
+ };
+ }
};
const Outlet = () => {
diff --git a/fixtures/webstudio-custom-template/app/routes/[script-test]._index.tsx b/fixtures/webstudio-custom-template/app/routes/[script-test]._index.tsx
index 05ee991c11..fab658fbb1 100644
--- a/fixtures/webstudio-custom-template/app/routes/[script-test]._index.tsx
+++ b/fixtures/webstudio-custom-template/app/routes/[script-test]._index.tsx
@@ -11,7 +11,11 @@ import {
} from "@remix-run/server-runtime";
import { useLoaderData } from "@remix-run/react";
import { ReactSdkContext } from "@webstudio-is/react-sdk";
-import { n8nHandler, getFormId } from "@webstudio-is/form-handlers";
+import {
+ n8nHandler,
+ formIdFieldName,
+ formBotFieldName,
+} from "@webstudio-is/form-handlers";
import {
Page,
siteName,
@@ -240,66 +244,86 @@ const getMethod = (value: string | undefined) => {
}
};
-export const action = async ({ request, context }: ActionFunctionArgs) => {
- const formData = await request.formData();
+export const action = async ({
+ request,
+ context,
+}: ActionFunctionArgs): Promise<
+ { success: true } | { success: false; errors: string[] }
+> => {
+ try {
+ const formData = await request.formData();
- const formId = getFormId(formData);
- if (formId === undefined) {
- // We're throwing rather than returning { success: false }
- // because this isn't supposed to happen normally: bug or malicious user
- throw json("Form not found", { status: 404 });
- }
+ const formId = formData.get(formIdFieldName);
- const formProperties = formsProperties.get(formId);
+ if (formId == null || typeof formId !== "string") {
+ throw new Error("No form id in FormData");
+ }
- // form properties are not defined when defaults are used
- const { action, method } = formProperties ?? {};
+ const formBotValue = formData.get(formBotFieldName);
- if (contactEmail === undefined) {
- return { success: false };
- }
+ if (formBotValue == null || typeof formBotValue !== "string") {
+ throw new Error("Form bot field not found");
+ }
- // wrapped in try/catch just in cases new URL() throws
- // (should not happen)
- let pageUrl: URL;
- try {
- pageUrl = new URL(request.url);
+ const submitTime = parseInt(formBotValue, 16);
+ // Assumes that the difference between the server time and the form submission time,
+ // including any client-server time drift, is within a 5-minute range.
+ // Note: submitTime might be NaN because formBotValue can be any string used for logging purposes.
+ // Example: `formBotValue: jsdom`, or `formBotValue: headless-env`
+ if (
+ Number.isNaN(submitTime) ||
+ Math.abs(Date.now() - submitTime) > 1000 * 60 * 5
+ ) {
+ throw new Error(`Form bot value invalid ${formBotValue}`);
+ }
+
+ const formProperties = formsProperties.get(formId);
+
+ // form properties are not defined when defaults are used
+ const { action, method } = formProperties ?? {};
+
+ if (contactEmail === undefined) {
+ throw new Error("Contact email not found");
+ }
+
+ const pageUrl = new URL(request.url);
pageUrl.host = getRequestHost(request);
- } catch {
- return { success: false };
- }
- if (action !== undefined) {
- try {
- // Test that action is full URL
- new URL(action);
- } catch {
- return json(
- {
- success: false,
- error: "Invalid action URL, must be valid http/https protocol",
- },
- { status: 200 }
- );
+ if (action !== undefined) {
+ try {
+ // Test that action is full URL
+ new URL(action);
+ } catch {
+ throw new Error(
+ "Invalid action URL, must be valid http/https protocol"
+ );
+ }
}
- }
- const formInfo = {
- formData,
- projectId,
- action: action ?? null,
- method: getMethod(method),
- pageUrl: pageUrl.toString(),
- toEmail: contactEmail,
- fromEmail: pageUrl.hostname + "@webstudio.email",
- } as const;
-
- const result = await n8nHandler({
- formInfo,
- hookUrl: context.N8N_FORM_EMAIL_HOOK,
- });
+ const formInfo = {
+ formData,
+ projectId,
+ action: action ?? null,
+ method: getMethod(method),
+ pageUrl: pageUrl.toString(),
+ toEmail: contactEmail,
+ fromEmail: pageUrl.hostname + "@webstudio.email",
+ } as const;
+
+ const result = await n8nHandler({
+ formInfo,
+ hookUrl: context.N8N_FORM_EMAIL_HOOK,
+ });
- return result;
+ return result;
+ } catch (error) {
+ console.error(error);
+
+ return {
+ success: false,
+ errors: [error instanceof Error ? error.message : "Unknown error"],
+ };
+ }
};
const Outlet = () => {
diff --git a/fixtures/webstudio-custom-template/app/routes/[world]._index.tsx b/fixtures/webstudio-custom-template/app/routes/[world]._index.tsx
index 0894462f43..8e6a462c0b 100644
--- a/fixtures/webstudio-custom-template/app/routes/[world]._index.tsx
+++ b/fixtures/webstudio-custom-template/app/routes/[world]._index.tsx
@@ -11,7 +11,11 @@ import {
} from "@remix-run/server-runtime";
import { useLoaderData } from "@remix-run/react";
import { ReactSdkContext } from "@webstudio-is/react-sdk";
-import { n8nHandler, getFormId } from "@webstudio-is/form-handlers";
+import {
+ n8nHandler,
+ formIdFieldName,
+ formBotFieldName,
+} from "@webstudio-is/form-handlers";
import {
Page,
siteName,
@@ -240,66 +244,86 @@ const getMethod = (value: string | undefined) => {
}
};
-export const action = async ({ request, context }: ActionFunctionArgs) => {
- const formData = await request.formData();
+export const action = async ({
+ request,
+ context,
+}: ActionFunctionArgs): Promise<
+ { success: true } | { success: false; errors: string[] }
+> => {
+ try {
+ const formData = await request.formData();
- const formId = getFormId(formData);
- if (formId === undefined) {
- // We're throwing rather than returning { success: false }
- // because this isn't supposed to happen normally: bug or malicious user
- throw json("Form not found", { status: 404 });
- }
+ const formId = formData.get(formIdFieldName);
- const formProperties = formsProperties.get(formId);
+ if (formId == null || typeof formId !== "string") {
+ throw new Error("No form id in FormData");
+ }
- // form properties are not defined when defaults are used
- const { action, method } = formProperties ?? {};
+ const formBotValue = formData.get(formBotFieldName);
- if (contactEmail === undefined) {
- return { success: false };
- }
+ if (formBotValue == null || typeof formBotValue !== "string") {
+ throw new Error("Form bot field not found");
+ }
- // wrapped in try/catch just in cases new URL() throws
- // (should not happen)
- let pageUrl: URL;
- try {
- pageUrl = new URL(request.url);
+ const submitTime = parseInt(formBotValue, 16);
+ // Assumes that the difference between the server time and the form submission time,
+ // including any client-server time drift, is within a 5-minute range.
+ // Note: submitTime might be NaN because formBotValue can be any string used for logging purposes.
+ // Example: `formBotValue: jsdom`, or `formBotValue: headless-env`
+ if (
+ Number.isNaN(submitTime) ||
+ Math.abs(Date.now() - submitTime) > 1000 * 60 * 5
+ ) {
+ throw new Error(`Form bot value invalid ${formBotValue}`);
+ }
+
+ const formProperties = formsProperties.get(formId);
+
+ // form properties are not defined when defaults are used
+ const { action, method } = formProperties ?? {};
+
+ if (contactEmail === undefined) {
+ throw new Error("Contact email not found");
+ }
+
+ const pageUrl = new URL(request.url);
pageUrl.host = getRequestHost(request);
- } catch {
- return { success: false };
- }
- if (action !== undefined) {
- try {
- // Test that action is full URL
- new URL(action);
- } catch {
- return json(
- {
- success: false,
- error: "Invalid action URL, must be valid http/https protocol",
- },
- { status: 200 }
- );
+ if (action !== undefined) {
+ try {
+ // Test that action is full URL
+ new URL(action);
+ } catch {
+ throw new Error(
+ "Invalid action URL, must be valid http/https protocol"
+ );
+ }
}
- }
- const formInfo = {
- formData,
- projectId,
- action: action ?? null,
- method: getMethod(method),
- pageUrl: pageUrl.toString(),
- toEmail: contactEmail,
- fromEmail: pageUrl.hostname + "@webstudio.email",
- } as const;
-
- const result = await n8nHandler({
- formInfo,
- hookUrl: context.N8N_FORM_EMAIL_HOOK,
- });
+ const formInfo = {
+ formData,
+ projectId,
+ action: action ?? null,
+ method: getMethod(method),
+ pageUrl: pageUrl.toString(),
+ toEmail: contactEmail,
+ fromEmail: pageUrl.hostname + "@webstudio.email",
+ } as const;
+
+ const result = await n8nHandler({
+ formInfo,
+ hookUrl: context.N8N_FORM_EMAIL_HOOK,
+ });
- return result;
+ return result;
+ } catch (error) {
+ console.error(error);
+
+ return {
+ success: false,
+ errors: [error instanceof Error ? error.message : "Unknown error"],
+ };
+ }
};
const Outlet = () => {
diff --git a/fixtures/webstudio-custom-template/app/routes/_index.tsx b/fixtures/webstudio-custom-template/app/routes/_index.tsx
index 5ed3bcbb16..e1800c8845 100644
--- a/fixtures/webstudio-custom-template/app/routes/_index.tsx
+++ b/fixtures/webstudio-custom-template/app/routes/_index.tsx
@@ -11,7 +11,11 @@ import {
} from "@remix-run/server-runtime";
import { useLoaderData } from "@remix-run/react";
import { ReactSdkContext } from "@webstudio-is/react-sdk";
-import { n8nHandler, getFormId } from "@webstudio-is/form-handlers";
+import {
+ n8nHandler,
+ formIdFieldName,
+ formBotFieldName,
+} from "@webstudio-is/form-handlers";
import {
Page,
siteName,
@@ -240,66 +244,86 @@ const getMethod = (value: string | undefined) => {
}
};
-export const action = async ({ request, context }: ActionFunctionArgs) => {
- const formData = await request.formData();
+export const action = async ({
+ request,
+ context,
+}: ActionFunctionArgs): Promise<
+ { success: true } | { success: false; errors: string[] }
+> => {
+ try {
+ const formData = await request.formData();
- const formId = getFormId(formData);
- if (formId === undefined) {
- // We're throwing rather than returning { success: false }
- // because this isn't supposed to happen normally: bug or malicious user
- throw json("Form not found", { status: 404 });
- }
+ const formId = formData.get(formIdFieldName);
- const formProperties = formsProperties.get(formId);
+ if (formId == null || typeof formId !== "string") {
+ throw new Error("No form id in FormData");
+ }
- // form properties are not defined when defaults are used
- const { action, method } = formProperties ?? {};
+ const formBotValue = formData.get(formBotFieldName);
- if (contactEmail === undefined) {
- return { success: false };
- }
+ if (formBotValue == null || typeof formBotValue !== "string") {
+ throw new Error("Form bot field not found");
+ }
- // wrapped in try/catch just in cases new URL() throws
- // (should not happen)
- let pageUrl: URL;
- try {
- pageUrl = new URL(request.url);
+ const submitTime = parseInt(formBotValue, 16);
+ // Assumes that the difference between the server time and the form submission time,
+ // including any client-server time drift, is within a 5-minute range.
+ // Note: submitTime might be NaN because formBotValue can be any string used for logging purposes.
+ // Example: `formBotValue: jsdom`, or `formBotValue: headless-env`
+ if (
+ Number.isNaN(submitTime) ||
+ Math.abs(Date.now() - submitTime) > 1000 * 60 * 5
+ ) {
+ throw new Error(`Form bot value invalid ${formBotValue}`);
+ }
+
+ const formProperties = formsProperties.get(formId);
+
+ // form properties are not defined when defaults are used
+ const { action, method } = formProperties ?? {};
+
+ if (contactEmail === undefined) {
+ throw new Error("Contact email not found");
+ }
+
+ const pageUrl = new URL(request.url);
pageUrl.host = getRequestHost(request);
- } catch {
- return { success: false };
- }
- if (action !== undefined) {
- try {
- // Test that action is full URL
- new URL(action);
- } catch {
- return json(
- {
- success: false,
- error: "Invalid action URL, must be valid http/https protocol",
- },
- { status: 200 }
- );
+ if (action !== undefined) {
+ try {
+ // Test that action is full URL
+ new URL(action);
+ } catch {
+ throw new Error(
+ "Invalid action URL, must be valid http/https protocol"
+ );
+ }
}
- }
- const formInfo = {
- formData,
- projectId,
- action: action ?? null,
- method: getMethod(method),
- pageUrl: pageUrl.toString(),
- toEmail: contactEmail,
- fromEmail: pageUrl.hostname + "@webstudio.email",
- } as const;
-
- const result = await n8nHandler({
- formInfo,
- hookUrl: context.N8N_FORM_EMAIL_HOOK,
- });
+ const formInfo = {
+ formData,
+ projectId,
+ action: action ?? null,
+ method: getMethod(method),
+ pageUrl: pageUrl.toString(),
+ toEmail: contactEmail,
+ fromEmail: pageUrl.hostname + "@webstudio.email",
+ } as const;
+
+ const result = await n8nHandler({
+ formInfo,
+ hookUrl: context.N8N_FORM_EMAIL_HOOK,
+ });
- return result;
+ return result;
+ } catch (error) {
+ console.error(error);
+
+ return {
+ success: false,
+ errors: [error instanceof Error ? error.message : "Unknown error"],
+ };
+ }
};
const Outlet = () => {
diff --git a/fixtures/webstudio-remix-netlify-edge-functions/app/routes/_index.tsx b/fixtures/webstudio-remix-netlify-edge-functions/app/routes/_index.tsx
index 5ed3bcbb16..e1800c8845 100644
--- a/fixtures/webstudio-remix-netlify-edge-functions/app/routes/_index.tsx
+++ b/fixtures/webstudio-remix-netlify-edge-functions/app/routes/_index.tsx
@@ -11,7 +11,11 @@ import {
} from "@remix-run/server-runtime";
import { useLoaderData } from "@remix-run/react";
import { ReactSdkContext } from "@webstudio-is/react-sdk";
-import { n8nHandler, getFormId } from "@webstudio-is/form-handlers";
+import {
+ n8nHandler,
+ formIdFieldName,
+ formBotFieldName,
+} from "@webstudio-is/form-handlers";
import {
Page,
siteName,
@@ -240,66 +244,86 @@ const getMethod = (value: string | undefined) => {
}
};
-export const action = async ({ request, context }: ActionFunctionArgs) => {
- const formData = await request.formData();
+export const action = async ({
+ request,
+ context,
+}: ActionFunctionArgs): Promise<
+ { success: true } | { success: false; errors: string[] }
+> => {
+ try {
+ const formData = await request.formData();
- const formId = getFormId(formData);
- if (formId === undefined) {
- // We're throwing rather than returning { success: false }
- // because this isn't supposed to happen normally: bug or malicious user
- throw json("Form not found", { status: 404 });
- }
+ const formId = formData.get(formIdFieldName);
- const formProperties = formsProperties.get(formId);
+ if (formId == null || typeof formId !== "string") {
+ throw new Error("No form id in FormData");
+ }
- // form properties are not defined when defaults are used
- const { action, method } = formProperties ?? {};
+ const formBotValue = formData.get(formBotFieldName);
- if (contactEmail === undefined) {
- return { success: false };
- }
+ if (formBotValue == null || typeof formBotValue !== "string") {
+ throw new Error("Form bot field not found");
+ }
- // wrapped in try/catch just in cases new URL() throws
- // (should not happen)
- let pageUrl: URL;
- try {
- pageUrl = new URL(request.url);
+ const submitTime = parseInt(formBotValue, 16);
+ // Assumes that the difference between the server time and the form submission time,
+ // including any client-server time drift, is within a 5-minute range.
+ // Note: submitTime might be NaN because formBotValue can be any string used for logging purposes.
+ // Example: `formBotValue: jsdom`, or `formBotValue: headless-env`
+ if (
+ Number.isNaN(submitTime) ||
+ Math.abs(Date.now() - submitTime) > 1000 * 60 * 5
+ ) {
+ throw new Error(`Form bot value invalid ${formBotValue}`);
+ }
+
+ const formProperties = formsProperties.get(formId);
+
+ // form properties are not defined when defaults are used
+ const { action, method } = formProperties ?? {};
+
+ if (contactEmail === undefined) {
+ throw new Error("Contact email not found");
+ }
+
+ const pageUrl = new URL(request.url);
pageUrl.host = getRequestHost(request);
- } catch {
- return { success: false };
- }
- if (action !== undefined) {
- try {
- // Test that action is full URL
- new URL(action);
- } catch {
- return json(
- {
- success: false,
- error: "Invalid action URL, must be valid http/https protocol",
- },
- { status: 200 }
- );
+ if (action !== undefined) {
+ try {
+ // Test that action is full URL
+ new URL(action);
+ } catch {
+ throw new Error(
+ "Invalid action URL, must be valid http/https protocol"
+ );
+ }
}
- }
- const formInfo = {
- formData,
- projectId,
- action: action ?? null,
- method: getMethod(method),
- pageUrl: pageUrl.toString(),
- toEmail: contactEmail,
- fromEmail: pageUrl.hostname + "@webstudio.email",
- } as const;
-
- const result = await n8nHandler({
- formInfo,
- hookUrl: context.N8N_FORM_EMAIL_HOOK,
- });
+ const formInfo = {
+ formData,
+ projectId,
+ action: action ?? null,
+ method: getMethod(method),
+ pageUrl: pageUrl.toString(),
+ toEmail: contactEmail,
+ fromEmail: pageUrl.hostname + "@webstudio.email",
+ } as const;
+
+ const result = await n8nHandler({
+ formInfo,
+ hookUrl: context.N8N_FORM_EMAIL_HOOK,
+ });
- return result;
+ return result;
+ } catch (error) {
+ console.error(error);
+
+ return {
+ success: false,
+ errors: [error instanceof Error ? error.message : "Unknown error"],
+ };
+ }
};
const Outlet = () => {
diff --git a/fixtures/webstudio-remix-netlify-functions/app/routes/_index.tsx b/fixtures/webstudio-remix-netlify-functions/app/routes/_index.tsx
index 5ed3bcbb16..e1800c8845 100644
--- a/fixtures/webstudio-remix-netlify-functions/app/routes/_index.tsx
+++ b/fixtures/webstudio-remix-netlify-functions/app/routes/_index.tsx
@@ -11,7 +11,11 @@ import {
} from "@remix-run/server-runtime";
import { useLoaderData } from "@remix-run/react";
import { ReactSdkContext } from "@webstudio-is/react-sdk";
-import { n8nHandler, getFormId } from "@webstudio-is/form-handlers";
+import {
+ n8nHandler,
+ formIdFieldName,
+ formBotFieldName,
+} from "@webstudio-is/form-handlers";
import {
Page,
siteName,
@@ -240,66 +244,86 @@ const getMethod = (value: string | undefined) => {
}
};
-export const action = async ({ request, context }: ActionFunctionArgs) => {
- const formData = await request.formData();
+export const action = async ({
+ request,
+ context,
+}: ActionFunctionArgs): Promise<
+ { success: true } | { success: false; errors: string[] }
+> => {
+ try {
+ const formData = await request.formData();
- const formId = getFormId(formData);
- if (formId === undefined) {
- // We're throwing rather than returning { success: false }
- // because this isn't supposed to happen normally: bug or malicious user
- throw json("Form not found", { status: 404 });
- }
+ const formId = formData.get(formIdFieldName);
- const formProperties = formsProperties.get(formId);
+ if (formId == null || typeof formId !== "string") {
+ throw new Error("No form id in FormData");
+ }
- // form properties are not defined when defaults are used
- const { action, method } = formProperties ?? {};
+ const formBotValue = formData.get(formBotFieldName);
- if (contactEmail === undefined) {
- return { success: false };
- }
+ if (formBotValue == null || typeof formBotValue !== "string") {
+ throw new Error("Form bot field not found");
+ }
- // wrapped in try/catch just in cases new URL() throws
- // (should not happen)
- let pageUrl: URL;
- try {
- pageUrl = new URL(request.url);
+ const submitTime = parseInt(formBotValue, 16);
+ // Assumes that the difference between the server time and the form submission time,
+ // including any client-server time drift, is within a 5-minute range.
+ // Note: submitTime might be NaN because formBotValue can be any string used for logging purposes.
+ // Example: `formBotValue: jsdom`, or `formBotValue: headless-env`
+ if (
+ Number.isNaN(submitTime) ||
+ Math.abs(Date.now() - submitTime) > 1000 * 60 * 5
+ ) {
+ throw new Error(`Form bot value invalid ${formBotValue}`);
+ }
+
+ const formProperties = formsProperties.get(formId);
+
+ // form properties are not defined when defaults are used
+ const { action, method } = formProperties ?? {};
+
+ if (contactEmail === undefined) {
+ throw new Error("Contact email not found");
+ }
+
+ const pageUrl = new URL(request.url);
pageUrl.host = getRequestHost(request);
- } catch {
- return { success: false };
- }
- if (action !== undefined) {
- try {
- // Test that action is full URL
- new URL(action);
- } catch {
- return json(
- {
- success: false,
- error: "Invalid action URL, must be valid http/https protocol",
- },
- { status: 200 }
- );
+ if (action !== undefined) {
+ try {
+ // Test that action is full URL
+ new URL(action);
+ } catch {
+ throw new Error(
+ "Invalid action URL, must be valid http/https protocol"
+ );
+ }
}
- }
- const formInfo = {
- formData,
- projectId,
- action: action ?? null,
- method: getMethod(method),
- pageUrl: pageUrl.toString(),
- toEmail: contactEmail,
- fromEmail: pageUrl.hostname + "@webstudio.email",
- } as const;
-
- const result = await n8nHandler({
- formInfo,
- hookUrl: context.N8N_FORM_EMAIL_HOOK,
- });
+ const formInfo = {
+ formData,
+ projectId,
+ action: action ?? null,
+ method: getMethod(method),
+ pageUrl: pageUrl.toString(),
+ toEmail: contactEmail,
+ fromEmail: pageUrl.hostname + "@webstudio.email",
+ } as const;
+
+ const result = await n8nHandler({
+ formInfo,
+ hookUrl: context.N8N_FORM_EMAIL_HOOK,
+ });
- return result;
+ return result;
+ } catch (error) {
+ console.error(error);
+
+ return {
+ success: false,
+ errors: [error instanceof Error ? error.message : "Unknown error"],
+ };
+ }
};
const Outlet = () => {
diff --git a/fixtures/webstudio-remix-vercel/app/routes/[_route_with_symbols_]._index.tsx b/fixtures/webstudio-remix-vercel/app/routes/[_route_with_symbols_]._index.tsx
index 000e76941c..c50fc1587a 100644
--- a/fixtures/webstudio-remix-vercel/app/routes/[_route_with_symbols_]._index.tsx
+++ b/fixtures/webstudio-remix-vercel/app/routes/[_route_with_symbols_]._index.tsx
@@ -11,7 +11,11 @@ import {
} from "@remix-run/server-runtime";
import { useLoaderData } from "@remix-run/react";
import { ReactSdkContext } from "@webstudio-is/react-sdk";
-import { n8nHandler, getFormId } from "@webstudio-is/form-handlers";
+import {
+ n8nHandler,
+ formIdFieldName,
+ formBotFieldName,
+} from "@webstudio-is/form-handlers";
import {
Page,
siteName,
@@ -240,66 +244,86 @@ const getMethod = (value: string | undefined) => {
}
};
-export const action = async ({ request, context }: ActionFunctionArgs) => {
- const formData = await request.formData();
+export const action = async ({
+ request,
+ context,
+}: ActionFunctionArgs): Promise<
+ { success: true } | { success: false; errors: string[] }
+> => {
+ try {
+ const formData = await request.formData();
- const formId = getFormId(formData);
- if (formId === undefined) {
- // We're throwing rather than returning { success: false }
- // because this isn't supposed to happen normally: bug or malicious user
- throw json("Form not found", { status: 404 });
- }
+ const formId = formData.get(formIdFieldName);
- const formProperties = formsProperties.get(formId);
+ if (formId == null || typeof formId !== "string") {
+ throw new Error("No form id in FormData");
+ }
- // form properties are not defined when defaults are used
- const { action, method } = formProperties ?? {};
+ const formBotValue = formData.get(formBotFieldName);
- if (contactEmail === undefined) {
- return { success: false };
- }
+ if (formBotValue == null || typeof formBotValue !== "string") {
+ throw new Error("Form bot field not found");
+ }
- // wrapped in try/catch just in cases new URL() throws
- // (should not happen)
- let pageUrl: URL;
- try {
- pageUrl = new URL(request.url);
+ const submitTime = parseInt(formBotValue, 16);
+ // Assumes that the difference between the server time and the form submission time,
+ // including any client-server time drift, is within a 5-minute range.
+ // Note: submitTime might be NaN because formBotValue can be any string used for logging purposes.
+ // Example: `formBotValue: jsdom`, or `formBotValue: headless-env`
+ if (
+ Number.isNaN(submitTime) ||
+ Math.abs(Date.now() - submitTime) > 1000 * 60 * 5
+ ) {
+ throw new Error(`Form bot value invalid ${formBotValue}`);
+ }
+
+ const formProperties = formsProperties.get(formId);
+
+ // form properties are not defined when defaults are used
+ const { action, method } = formProperties ?? {};
+
+ if (contactEmail === undefined) {
+ throw new Error("Contact email not found");
+ }
+
+ const pageUrl = new URL(request.url);
pageUrl.host = getRequestHost(request);
- } catch {
- return { success: false };
- }
- if (action !== undefined) {
- try {
- // Test that action is full URL
- new URL(action);
- } catch {
- return json(
- {
- success: false,
- error: "Invalid action URL, must be valid http/https protocol",
- },
- { status: 200 }
- );
+ if (action !== undefined) {
+ try {
+ // Test that action is full URL
+ new URL(action);
+ } catch {
+ throw new Error(
+ "Invalid action URL, must be valid http/https protocol"
+ );
+ }
}
- }
- const formInfo = {
- formData,
- projectId,
- action: action ?? null,
- method: getMethod(method),
- pageUrl: pageUrl.toString(),
- toEmail: contactEmail,
- fromEmail: pageUrl.hostname + "@webstudio.email",
- } as const;
-
- const result = await n8nHandler({
- formInfo,
- hookUrl: context.N8N_FORM_EMAIL_HOOK,
- });
+ const formInfo = {
+ formData,
+ projectId,
+ action: action ?? null,
+ method: getMethod(method),
+ pageUrl: pageUrl.toString(),
+ toEmail: contactEmail,
+ fromEmail: pageUrl.hostname + "@webstudio.email",
+ } as const;
+
+ const result = await n8nHandler({
+ formInfo,
+ hookUrl: context.N8N_FORM_EMAIL_HOOK,
+ });
- return result;
+ return result;
+ } catch (error) {
+ console.error(error);
+
+ return {
+ success: false,
+ errors: [error instanceof Error ? error.message : "Unknown error"],
+ };
+ }
};
const Outlet = () => {
diff --git a/fixtures/webstudio-remix-vercel/app/routes/[form]._index.tsx b/fixtures/webstudio-remix-vercel/app/routes/[form]._index.tsx
index e9f7107686..78eda705a1 100644
--- a/fixtures/webstudio-remix-vercel/app/routes/[form]._index.tsx
+++ b/fixtures/webstudio-remix-vercel/app/routes/[form]._index.tsx
@@ -11,7 +11,11 @@ import {
} from "@remix-run/server-runtime";
import { useLoaderData } from "@remix-run/react";
import { ReactSdkContext } from "@webstudio-is/react-sdk";
-import { n8nHandler, getFormId } from "@webstudio-is/form-handlers";
+import {
+ n8nHandler,
+ formIdFieldName,
+ formBotFieldName,
+} from "@webstudio-is/form-handlers";
import {
Page,
siteName,
@@ -240,66 +244,86 @@ const getMethod = (value: string | undefined) => {
}
};
-export const action = async ({ request, context }: ActionFunctionArgs) => {
- const formData = await request.formData();
+export const action = async ({
+ request,
+ context,
+}: ActionFunctionArgs): Promise<
+ { success: true } | { success: false; errors: string[] }
+> => {
+ try {
+ const formData = await request.formData();
- const formId = getFormId(formData);
- if (formId === undefined) {
- // We're throwing rather than returning { success: false }
- // because this isn't supposed to happen normally: bug or malicious user
- throw json("Form not found", { status: 404 });
- }
+ const formId = formData.get(formIdFieldName);
- const formProperties = formsProperties.get(formId);
+ if (formId == null || typeof formId !== "string") {
+ throw new Error("No form id in FormData");
+ }
- // form properties are not defined when defaults are used
- const { action, method } = formProperties ?? {};
+ const formBotValue = formData.get(formBotFieldName);
- if (contactEmail === undefined) {
- return { success: false };
- }
+ if (formBotValue == null || typeof formBotValue !== "string") {
+ throw new Error("Form bot field not found");
+ }
- // wrapped in try/catch just in cases new URL() throws
- // (should not happen)
- let pageUrl: URL;
- try {
- pageUrl = new URL(request.url);
+ const submitTime = parseInt(formBotValue, 16);
+ // Assumes that the difference between the server time and the form submission time,
+ // including any client-server time drift, is within a 5-minute range.
+ // Note: submitTime might be NaN because formBotValue can be any string used for logging purposes.
+ // Example: `formBotValue: jsdom`, or `formBotValue: headless-env`
+ if (
+ Number.isNaN(submitTime) ||
+ Math.abs(Date.now() - submitTime) > 1000 * 60 * 5
+ ) {
+ throw new Error(`Form bot value invalid ${formBotValue}`);
+ }
+
+ const formProperties = formsProperties.get(formId);
+
+ // form properties are not defined when defaults are used
+ const { action, method } = formProperties ?? {};
+
+ if (contactEmail === undefined) {
+ throw new Error("Contact email not found");
+ }
+
+ const pageUrl = new URL(request.url);
pageUrl.host = getRequestHost(request);
- } catch {
- return { success: false };
- }
- if (action !== undefined) {
- try {
- // Test that action is full URL
- new URL(action);
- } catch {
- return json(
- {
- success: false,
- error: "Invalid action URL, must be valid http/https protocol",
- },
- { status: 200 }
- );
+ if (action !== undefined) {
+ try {
+ // Test that action is full URL
+ new URL(action);
+ } catch {
+ throw new Error(
+ "Invalid action URL, must be valid http/https protocol"
+ );
+ }
}
- }
- const formInfo = {
- formData,
- projectId,
- action: action ?? null,
- method: getMethod(method),
- pageUrl: pageUrl.toString(),
- toEmail: contactEmail,
- fromEmail: pageUrl.hostname + "@webstudio.email",
- } as const;
-
- const result = await n8nHandler({
- formInfo,
- hookUrl: context.N8N_FORM_EMAIL_HOOK,
- });
+ const formInfo = {
+ formData,
+ projectId,
+ action: action ?? null,
+ method: getMethod(method),
+ pageUrl: pageUrl.toString(),
+ toEmail: contactEmail,
+ fromEmail: pageUrl.hostname + "@webstudio.email",
+ } as const;
+
+ const result = await n8nHandler({
+ formInfo,
+ hookUrl: context.N8N_FORM_EMAIL_HOOK,
+ });
- return result;
+ return result;
+ } catch (error) {
+ console.error(error);
+
+ return {
+ success: false,
+ errors: [error instanceof Error ? error.message : "Unknown error"],
+ };
+ }
};
const Outlet = () => {
diff --git a/fixtures/webstudio-remix-vercel/app/routes/[heading-with-id]._index.tsx b/fixtures/webstudio-remix-vercel/app/routes/[heading-with-id]._index.tsx
index 184b0966d3..54b3c9b2b0 100644
--- a/fixtures/webstudio-remix-vercel/app/routes/[heading-with-id]._index.tsx
+++ b/fixtures/webstudio-remix-vercel/app/routes/[heading-with-id]._index.tsx
@@ -11,7 +11,11 @@ import {
} from "@remix-run/server-runtime";
import { useLoaderData } from "@remix-run/react";
import { ReactSdkContext } from "@webstudio-is/react-sdk";
-import { n8nHandler, getFormId } from "@webstudio-is/form-handlers";
+import {
+ n8nHandler,
+ formIdFieldName,
+ formBotFieldName,
+} from "@webstudio-is/form-handlers";
import {
Page,
siteName,
@@ -240,66 +244,86 @@ const getMethod = (value: string | undefined) => {
}
};
-export const action = async ({ request, context }: ActionFunctionArgs) => {
- const formData = await request.formData();
+export const action = async ({
+ request,
+ context,
+}: ActionFunctionArgs): Promise<
+ { success: true } | { success: false; errors: string[] }
+> => {
+ try {
+ const formData = await request.formData();
- const formId = getFormId(formData);
- if (formId === undefined) {
- // We're throwing rather than returning { success: false }
- // because this isn't supposed to happen normally: bug or malicious user
- throw json("Form not found", { status: 404 });
- }
+ const formId = formData.get(formIdFieldName);
- const formProperties = formsProperties.get(formId);
+ if (formId == null || typeof formId !== "string") {
+ throw new Error("No form id in FormData");
+ }
- // form properties are not defined when defaults are used
- const { action, method } = formProperties ?? {};
+ const formBotValue = formData.get(formBotFieldName);
- if (contactEmail === undefined) {
- return { success: false };
- }
+ if (formBotValue == null || typeof formBotValue !== "string") {
+ throw new Error("Form bot field not found");
+ }
- // wrapped in try/catch just in cases new URL() throws
- // (should not happen)
- let pageUrl: URL;
- try {
- pageUrl = new URL(request.url);
+ const submitTime = parseInt(formBotValue, 16);
+ // Assumes that the difference between the server time and the form submission time,
+ // including any client-server time drift, is within a 5-minute range.
+ // Note: submitTime might be NaN because formBotValue can be any string used for logging purposes.
+ // Example: `formBotValue: jsdom`, or `formBotValue: headless-env`
+ if (
+ Number.isNaN(submitTime) ||
+ Math.abs(Date.now() - submitTime) > 1000 * 60 * 5
+ ) {
+ throw new Error(`Form bot value invalid ${formBotValue}`);
+ }
+
+ const formProperties = formsProperties.get(formId);
+
+ // form properties are not defined when defaults are used
+ const { action, method } = formProperties ?? {};
+
+ if (contactEmail === undefined) {
+ throw new Error("Contact email not found");
+ }
+
+ const pageUrl = new URL(request.url);
pageUrl.host = getRequestHost(request);
- } catch {
- return { success: false };
- }
- if (action !== undefined) {
- try {
- // Test that action is full URL
- new URL(action);
- } catch {
- return json(
- {
- success: false,
- error: "Invalid action URL, must be valid http/https protocol",
- },
- { status: 200 }
- );
+ if (action !== undefined) {
+ try {
+ // Test that action is full URL
+ new URL(action);
+ } catch {
+ throw new Error(
+ "Invalid action URL, must be valid http/https protocol"
+ );
+ }
}
- }
- const formInfo = {
- formData,
- projectId,
- action: action ?? null,
- method: getMethod(method),
- pageUrl: pageUrl.toString(),
- toEmail: contactEmail,
- fromEmail: pageUrl.hostname + "@webstudio.email",
- } as const;
-
- const result = await n8nHandler({
- formInfo,
- hookUrl: context.N8N_FORM_EMAIL_HOOK,
- });
+ const formInfo = {
+ formData,
+ projectId,
+ action: action ?? null,
+ method: getMethod(method),
+ pageUrl: pageUrl.toString(),
+ toEmail: contactEmail,
+ fromEmail: pageUrl.hostname + "@webstudio.email",
+ } as const;
+
+ const result = await n8nHandler({
+ formInfo,
+ hookUrl: context.N8N_FORM_EMAIL_HOOK,
+ });
- return result;
+ return result;
+ } catch (error) {
+ console.error(error);
+
+ return {
+ success: false,
+ errors: [error instanceof Error ? error.message : "Unknown error"],
+ };
+ }
};
const Outlet = () => {
diff --git a/fixtures/webstudio-remix-vercel/app/routes/[nested].[nested-page]._index.tsx b/fixtures/webstudio-remix-vercel/app/routes/[nested].[nested-page]._index.tsx
index ba9909169c..79ffef799c 100644
--- a/fixtures/webstudio-remix-vercel/app/routes/[nested].[nested-page]._index.tsx
+++ b/fixtures/webstudio-remix-vercel/app/routes/[nested].[nested-page]._index.tsx
@@ -11,7 +11,11 @@ import {
} from "@remix-run/server-runtime";
import { useLoaderData } from "@remix-run/react";
import { ReactSdkContext } from "@webstudio-is/react-sdk";
-import { n8nHandler, getFormId } from "@webstudio-is/form-handlers";
+import {
+ n8nHandler,
+ formIdFieldName,
+ formBotFieldName,
+} from "@webstudio-is/form-handlers";
import {
Page,
siteName,
@@ -240,66 +244,86 @@ const getMethod = (value: string | undefined) => {
}
};
-export const action = async ({ request, context }: ActionFunctionArgs) => {
- const formData = await request.formData();
+export const action = async ({
+ request,
+ context,
+}: ActionFunctionArgs): Promise<
+ { success: true } | { success: false; errors: string[] }
+> => {
+ try {
+ const formData = await request.formData();
- const formId = getFormId(formData);
- if (formId === undefined) {
- // We're throwing rather than returning { success: false }
- // because this isn't supposed to happen normally: bug or malicious user
- throw json("Form not found", { status: 404 });
- }
+ const formId = formData.get(formIdFieldName);
- const formProperties = formsProperties.get(formId);
+ if (formId == null || typeof formId !== "string") {
+ throw new Error("No form id in FormData");
+ }
- // form properties are not defined when defaults are used
- const { action, method } = formProperties ?? {};
+ const formBotValue = formData.get(formBotFieldName);
- if (contactEmail === undefined) {
- return { success: false };
- }
+ if (formBotValue == null || typeof formBotValue !== "string") {
+ throw new Error("Form bot field not found");
+ }
- // wrapped in try/catch just in cases new URL() throws
- // (should not happen)
- let pageUrl: URL;
- try {
- pageUrl = new URL(request.url);
+ const submitTime = parseInt(formBotValue, 16);
+ // Assumes that the difference between the server time and the form submission time,
+ // including any client-server time drift, is within a 5-minute range.
+ // Note: submitTime might be NaN because formBotValue can be any string used for logging purposes.
+ // Example: `formBotValue: jsdom`, or `formBotValue: headless-env`
+ if (
+ Number.isNaN(submitTime) ||
+ Math.abs(Date.now() - submitTime) > 1000 * 60 * 5
+ ) {
+ throw new Error(`Form bot value invalid ${formBotValue}`);
+ }
+
+ const formProperties = formsProperties.get(formId);
+
+ // form properties are not defined when defaults are used
+ const { action, method } = formProperties ?? {};
+
+ if (contactEmail === undefined) {
+ throw new Error("Contact email not found");
+ }
+
+ const pageUrl = new URL(request.url);
pageUrl.host = getRequestHost(request);
- } catch {
- return { success: false };
- }
- if (action !== undefined) {
- try {
- // Test that action is full URL
- new URL(action);
- } catch {
- return json(
- {
- success: false,
- error: "Invalid action URL, must be valid http/https protocol",
- },
- { status: 200 }
- );
+ if (action !== undefined) {
+ try {
+ // Test that action is full URL
+ new URL(action);
+ } catch {
+ throw new Error(
+ "Invalid action URL, must be valid http/https protocol"
+ );
+ }
}
- }
- const formInfo = {
- formData,
- projectId,
- action: action ?? null,
- method: getMethod(method),
- pageUrl: pageUrl.toString(),
- toEmail: contactEmail,
- fromEmail: pageUrl.hostname + "@webstudio.email",
- } as const;
-
- const result = await n8nHandler({
- formInfo,
- hookUrl: context.N8N_FORM_EMAIL_HOOK,
- });
+ const formInfo = {
+ formData,
+ projectId,
+ action: action ?? null,
+ method: getMethod(method),
+ pageUrl: pageUrl.toString(),
+ toEmail: contactEmail,
+ fromEmail: pageUrl.hostname + "@webstudio.email",
+ } as const;
+
+ const result = await n8nHandler({
+ formInfo,
+ hookUrl: context.N8N_FORM_EMAIL_HOOK,
+ });
- return result;
+ return result;
+ } catch (error) {
+ console.error(error);
+
+ return {
+ success: false,
+ errors: [error instanceof Error ? error.message : "Unknown error"],
+ };
+ }
};
const Outlet = () => {
diff --git a/fixtures/webstudio-remix-vercel/app/routes/[radix]._index.tsx b/fixtures/webstudio-remix-vercel/app/routes/[radix]._index.tsx
index ec310daad4..3235310a9d 100644
--- a/fixtures/webstudio-remix-vercel/app/routes/[radix]._index.tsx
+++ b/fixtures/webstudio-remix-vercel/app/routes/[radix]._index.tsx
@@ -11,7 +11,11 @@ import {
} from "@remix-run/server-runtime";
import { useLoaderData } from "@remix-run/react";
import { ReactSdkContext } from "@webstudio-is/react-sdk";
-import { n8nHandler, getFormId } from "@webstudio-is/form-handlers";
+import {
+ n8nHandler,
+ formIdFieldName,
+ formBotFieldName,
+} from "@webstudio-is/form-handlers";
import {
Page,
siteName,
@@ -240,66 +244,86 @@ const getMethod = (value: string | undefined) => {
}
};
-export const action = async ({ request, context }: ActionFunctionArgs) => {
- const formData = await request.formData();
+export const action = async ({
+ request,
+ context,
+}: ActionFunctionArgs): Promise<
+ { success: true } | { success: false; errors: string[] }
+> => {
+ try {
+ const formData = await request.formData();
- const formId = getFormId(formData);
- if (formId === undefined) {
- // We're throwing rather than returning { success: false }
- // because this isn't supposed to happen normally: bug or malicious user
- throw json("Form not found", { status: 404 });
- }
+ const formId = formData.get(formIdFieldName);
- const formProperties = formsProperties.get(formId);
+ if (formId == null || typeof formId !== "string") {
+ throw new Error("No form id in FormData");
+ }
- // form properties are not defined when defaults are used
- const { action, method } = formProperties ?? {};
+ const formBotValue = formData.get(formBotFieldName);
- if (contactEmail === undefined) {
- return { success: false };
- }
+ if (formBotValue == null || typeof formBotValue !== "string") {
+ throw new Error("Form bot field not found");
+ }
- // wrapped in try/catch just in cases new URL() throws
- // (should not happen)
- let pageUrl: URL;
- try {
- pageUrl = new URL(request.url);
+ const submitTime = parseInt(formBotValue, 16);
+ // Assumes that the difference between the server time and the form submission time,
+ // including any client-server time drift, is within a 5-minute range.
+ // Note: submitTime might be NaN because formBotValue can be any string used for logging purposes.
+ // Example: `formBotValue: jsdom`, or `formBotValue: headless-env`
+ if (
+ Number.isNaN(submitTime) ||
+ Math.abs(Date.now() - submitTime) > 1000 * 60 * 5
+ ) {
+ throw new Error(`Form bot value invalid ${formBotValue}`);
+ }
+
+ const formProperties = formsProperties.get(formId);
+
+ // form properties are not defined when defaults are used
+ const { action, method } = formProperties ?? {};
+
+ if (contactEmail === undefined) {
+ throw new Error("Contact email not found");
+ }
+
+ const pageUrl = new URL(request.url);
pageUrl.host = getRequestHost(request);
- } catch {
- return { success: false };
- }
- if (action !== undefined) {
- try {
- // Test that action is full URL
- new URL(action);
- } catch {
- return json(
- {
- success: false,
- error: "Invalid action URL, must be valid http/https protocol",
- },
- { status: 200 }
- );
+ if (action !== undefined) {
+ try {
+ // Test that action is full URL
+ new URL(action);
+ } catch {
+ throw new Error(
+ "Invalid action URL, must be valid http/https protocol"
+ );
+ }
}
- }
- const formInfo = {
- formData,
- projectId,
- action: action ?? null,
- method: getMethod(method),
- pageUrl: pageUrl.toString(),
- toEmail: contactEmail,
- fromEmail: pageUrl.hostname + "@webstudio.email",
- } as const;
-
- const result = await n8nHandler({
- formInfo,
- hookUrl: context.N8N_FORM_EMAIL_HOOK,
- });
+ const formInfo = {
+ formData,
+ projectId,
+ action: action ?? null,
+ method: getMethod(method),
+ pageUrl: pageUrl.toString(),
+ toEmail: contactEmail,
+ fromEmail: pageUrl.hostname + "@webstudio.email",
+ } as const;
+
+ const result = await n8nHandler({
+ formInfo,
+ hookUrl: context.N8N_FORM_EMAIL_HOOK,
+ });
- return result;
+ return result;
+ } catch (error) {
+ console.error(error);
+
+ return {
+ success: false,
+ errors: [error instanceof Error ? error.message : "Unknown error"],
+ };
+ }
};
const Outlet = () => {
diff --git a/fixtures/webstudio-remix-vercel/app/routes/[resources]._index.tsx b/fixtures/webstudio-remix-vercel/app/routes/[resources]._index.tsx
index b7289a4c83..e69b39912f 100644
--- a/fixtures/webstudio-remix-vercel/app/routes/[resources]._index.tsx
+++ b/fixtures/webstudio-remix-vercel/app/routes/[resources]._index.tsx
@@ -11,7 +11,11 @@ import {
} from "@remix-run/server-runtime";
import { useLoaderData } from "@remix-run/react";
import { ReactSdkContext } from "@webstudio-is/react-sdk";
-import { n8nHandler, getFormId } from "@webstudio-is/form-handlers";
+import {
+ n8nHandler,
+ formIdFieldName,
+ formBotFieldName,
+} from "@webstudio-is/form-handlers";
import {
Page,
siteName,
@@ -240,66 +244,86 @@ const getMethod = (value: string | undefined) => {
}
};
-export const action = async ({ request, context }: ActionFunctionArgs) => {
- const formData = await request.formData();
+export const action = async ({
+ request,
+ context,
+}: ActionFunctionArgs): Promise<
+ { success: true } | { success: false; errors: string[] }
+> => {
+ try {
+ const formData = await request.formData();
- const formId = getFormId(formData);
- if (formId === undefined) {
- // We're throwing rather than returning { success: false }
- // because this isn't supposed to happen normally: bug or malicious user
- throw json("Form not found", { status: 404 });
- }
+ const formId = formData.get(formIdFieldName);
- const formProperties = formsProperties.get(formId);
+ if (formId == null || typeof formId !== "string") {
+ throw new Error("No form id in FormData");
+ }
- // form properties are not defined when defaults are used
- const { action, method } = formProperties ?? {};
+ const formBotValue = formData.get(formBotFieldName);
- if (contactEmail === undefined) {
- return { success: false };
- }
+ if (formBotValue == null || typeof formBotValue !== "string") {
+ throw new Error("Form bot field not found");
+ }
- // wrapped in try/catch just in cases new URL() throws
- // (should not happen)
- let pageUrl: URL;
- try {
- pageUrl = new URL(request.url);
+ const submitTime = parseInt(formBotValue, 16);
+ // Assumes that the difference between the server time and the form submission time,
+ // including any client-server time drift, is within a 5-minute range.
+ // Note: submitTime might be NaN because formBotValue can be any string used for logging purposes.
+ // Example: `formBotValue: jsdom`, or `formBotValue: headless-env`
+ if (
+ Number.isNaN(submitTime) ||
+ Math.abs(Date.now() - submitTime) > 1000 * 60 * 5
+ ) {
+ throw new Error(`Form bot value invalid ${formBotValue}`);
+ }
+
+ const formProperties = formsProperties.get(formId);
+
+ // form properties are not defined when defaults are used
+ const { action, method } = formProperties ?? {};
+
+ if (contactEmail === undefined) {
+ throw new Error("Contact email not found");
+ }
+
+ const pageUrl = new URL(request.url);
pageUrl.host = getRequestHost(request);
- } catch {
- return { success: false };
- }
- if (action !== undefined) {
- try {
- // Test that action is full URL
- new URL(action);
- } catch {
- return json(
- {
- success: false,
- error: "Invalid action URL, must be valid http/https protocol",
- },
- { status: 200 }
- );
+ if (action !== undefined) {
+ try {
+ // Test that action is full URL
+ new URL(action);
+ } catch {
+ throw new Error(
+ "Invalid action URL, must be valid http/https protocol"
+ );
+ }
}
- }
- const formInfo = {
- formData,
- projectId,
- action: action ?? null,
- method: getMethod(method),
- pageUrl: pageUrl.toString(),
- toEmail: contactEmail,
- fromEmail: pageUrl.hostname + "@webstudio.email",
- } as const;
-
- const result = await n8nHandler({
- formInfo,
- hookUrl: context.N8N_FORM_EMAIL_HOOK,
- });
+ const formInfo = {
+ formData,
+ projectId,
+ action: action ?? null,
+ method: getMethod(method),
+ pageUrl: pageUrl.toString(),
+ toEmail: contactEmail,
+ fromEmail: pageUrl.hostname + "@webstudio.email",
+ } as const;
+
+ const result = await n8nHandler({
+ formInfo,
+ hookUrl: context.N8N_FORM_EMAIL_HOOK,
+ });
- return result;
+ return result;
+ } catch (error) {
+ console.error(error);
+
+ return {
+ success: false,
+ errors: [error instanceof Error ? error.message : "Unknown error"],
+ };
+ }
};
const Outlet = () => {
diff --git a/fixtures/webstudio-remix-vercel/app/routes/_index.tsx b/fixtures/webstudio-remix-vercel/app/routes/_index.tsx
index 5ed3bcbb16..e1800c8845 100644
--- a/fixtures/webstudio-remix-vercel/app/routes/_index.tsx
+++ b/fixtures/webstudio-remix-vercel/app/routes/_index.tsx
@@ -11,7 +11,11 @@ import {
} from "@remix-run/server-runtime";
import { useLoaderData } from "@remix-run/react";
import { ReactSdkContext } from "@webstudio-is/react-sdk";
-import { n8nHandler, getFormId } from "@webstudio-is/form-handlers";
+import {
+ n8nHandler,
+ formIdFieldName,
+ formBotFieldName,
+} from "@webstudio-is/form-handlers";
import {
Page,
siteName,
@@ -240,66 +244,86 @@ const getMethod = (value: string | undefined) => {
}
};
-export const action = async ({ request, context }: ActionFunctionArgs) => {
- const formData = await request.formData();
+export const action = async ({
+ request,
+ context,
+}: ActionFunctionArgs): Promise<
+ { success: true } | { success: false; errors: string[] }
+> => {
+ try {
+ const formData = await request.formData();
- const formId = getFormId(formData);
- if (formId === undefined) {
- // We're throwing rather than returning { success: false }
- // because this isn't supposed to happen normally: bug or malicious user
- throw json("Form not found", { status: 404 });
- }
+ const formId = formData.get(formIdFieldName);
- const formProperties = formsProperties.get(formId);
+ if (formId == null || typeof formId !== "string") {
+ throw new Error("No form id in FormData");
+ }
- // form properties are not defined when defaults are used
- const { action, method } = formProperties ?? {};
+ const formBotValue = formData.get(formBotFieldName);
- if (contactEmail === undefined) {
- return { success: false };
- }
+ if (formBotValue == null || typeof formBotValue !== "string") {
+ throw new Error("Form bot field not found");
+ }
- // wrapped in try/catch just in cases new URL() throws
- // (should not happen)
- let pageUrl: URL;
- try {
- pageUrl = new URL(request.url);
+ const submitTime = parseInt(formBotValue, 16);
+ // Assumes that the difference between the server time and the form submission time,
+ // including any client-server time drift, is within a 5-minute range.
+ // Note: submitTime might be NaN because formBotValue can be any string used for logging purposes.
+ // Example: `formBotValue: jsdom`, or `formBotValue: headless-env`
+ if (
+ Number.isNaN(submitTime) ||
+ Math.abs(Date.now() - submitTime) > 1000 * 60 * 5
+ ) {
+ throw new Error(`Form bot value invalid ${formBotValue}`);
+ }
+
+ const formProperties = formsProperties.get(formId);
+
+ // form properties are not defined when defaults are used
+ const { action, method } = formProperties ?? {};
+
+ if (contactEmail === undefined) {
+ throw new Error("Contact email not found");
+ }
+
+ const pageUrl = new URL(request.url);
pageUrl.host = getRequestHost(request);
- } catch {
- return { success: false };
- }
- if (action !== undefined) {
- try {
- // Test that action is full URL
- new URL(action);
- } catch {
- return json(
- {
- success: false,
- error: "Invalid action URL, must be valid http/https protocol",
- },
- { status: 200 }
- );
+ if (action !== undefined) {
+ try {
+ // Test that action is full URL
+ new URL(action);
+ } catch {
+ throw new Error(
+ "Invalid action URL, must be valid http/https protocol"
+ );
+ }
}
- }
- const formInfo = {
- formData,
- projectId,
- action: action ?? null,
- method: getMethod(method),
- pageUrl: pageUrl.toString(),
- toEmail: contactEmail,
- fromEmail: pageUrl.hostname + "@webstudio.email",
- } as const;
-
- const result = await n8nHandler({
- formInfo,
- hookUrl: context.N8N_FORM_EMAIL_HOOK,
- });
+ const formInfo = {
+ formData,
+ projectId,
+ action: action ?? null,
+ method: getMethod(method),
+ pageUrl: pageUrl.toString(),
+ toEmail: contactEmail,
+ fromEmail: pageUrl.hostname + "@webstudio.email",
+ } as const;
+
+ const result = await n8nHandler({
+ formInfo,
+ hookUrl: context.N8N_FORM_EMAIL_HOOK,
+ });
- return result;
+ return result;
+ } catch (error) {
+ console.error(error);
+
+ return {
+ success: false,
+ errors: [error instanceof Error ? error.message : "Unknown error"],
+ };
+ }
};
const Outlet = () => {
diff --git a/packages/cli/templates/defaults/app/route-templates/html.tsx b/packages/cli/templates/defaults/app/route-templates/html.tsx
index 2a32792599..c337e6f00d 100644
--- a/packages/cli/templates/defaults/app/route-templates/html.tsx
+++ b/packages/cli/templates/defaults/app/route-templates/html.tsx
@@ -11,7 +11,11 @@ import {
} from "@remix-run/server-runtime";
import { useLoaderData } from "@remix-run/react";
import { ReactSdkContext } from "@webstudio-is/react-sdk";
-import { n8nHandler, getFormId } from "@webstudio-is/form-handlers";
+import {
+ n8nHandler,
+ formIdFieldName,
+ formBotFieldName,
+} from "@webstudio-is/form-handlers";
import {
Page,
siteName,
@@ -240,66 +244,86 @@ const getMethod = (value: string | undefined) => {
}
};
-export const action = async ({ request, context }: ActionFunctionArgs) => {
- const formData = await request.formData();
+export const action = async ({
+ request,
+ context,
+}: ActionFunctionArgs): Promise<
+ { success: true } | { success: false; errors: string[] }
+> => {
+ try {
+ const formData = await request.formData();
- const formId = getFormId(formData);
- if (formId === undefined) {
- // We're throwing rather than returning { success: false }
- // because this isn't supposed to happen normally: bug or malicious user
- throw json("Form not found", { status: 404 });
- }
+ const formId = formData.get(formIdFieldName);
- const formProperties = formsProperties.get(formId);
+ if (formId == null || typeof formId !== "string") {
+ throw new Error("No form id in FormData");
+ }
- // form properties are not defined when defaults are used
- const { action, method } = formProperties ?? {};
+ const formBotValue = formData.get(formBotFieldName);
- if (contactEmail === undefined) {
- return { success: false };
- }
+ if (formBotValue == null || typeof formBotValue !== "string") {
+ throw new Error("Form bot field not found");
+ }
- // wrapped in try/catch just in cases new URL() throws
- // (should not happen)
- let pageUrl: URL;
- try {
- pageUrl = new URL(request.url);
+ const submitTime = parseInt(formBotValue, 16);
+ // Assumes that the difference between the server time and the form submission time,
+ // including any client-server time drift, is within a 5-minute range.
+ // Note: submitTime might be NaN because formBotValue can be any string used for logging purposes.
+ // Example: `formBotValue: jsdom`, or `formBotValue: headless-env`
+ if (
+ Number.isNaN(submitTime) ||
+ Math.abs(Date.now() - submitTime) > 1000 * 60 * 5
+ ) {
+ throw new Error(`Form bot value invalid ${formBotValue}`);
+ }
+
+ const formProperties = formsProperties.get(formId);
+
+ // form properties are not defined when defaults are used
+ const { action, method } = formProperties ?? {};
+
+ if (contactEmail === undefined) {
+ throw new Error("Contact email not found");
+ }
+
+ const pageUrl = new URL(request.url);
pageUrl.host = getRequestHost(request);
- } catch {
- return { success: false };
- }
- if (action !== undefined) {
- try {
- // Test that action is full URL
- new URL(action);
- } catch {
- return json(
- {
- success: false,
- error: "Invalid action URL, must be valid http/https protocol",
- },
- { status: 200 }
- );
+ if (action !== undefined) {
+ try {
+ // Test that action is full URL
+ new URL(action);
+ } catch {
+ throw new Error(
+ "Invalid action URL, must be valid http/https protocol"
+ );
+ }
}
- }
- const formInfo = {
- formData,
- projectId,
- action: action ?? null,
- method: getMethod(method),
- pageUrl: pageUrl.toString(),
- toEmail: contactEmail,
- fromEmail: pageUrl.hostname + "@webstudio.email",
- } as const;
-
- const result = await n8nHandler({
- formInfo,
- hookUrl: context.N8N_FORM_EMAIL_HOOK,
- });
+ const formInfo = {
+ formData,
+ projectId,
+ action: action ?? null,
+ method: getMethod(method),
+ pageUrl: pageUrl.toString(),
+ toEmail: contactEmail,
+ fromEmail: pageUrl.hostname + "@webstudio.email",
+ } as const;
+
+ const result = await n8nHandler({
+ formInfo,
+ hookUrl: context.N8N_FORM_EMAIL_HOOK,
+ });
- return result;
+ return result;
+ } catch (error) {
+ console.error(error);
+
+ return {
+ success: false,
+ errors: [error instanceof Error ? error.message : "Unknown error"],
+ };
+ }
};
const Outlet = () => {
diff --git a/packages/form-handlers/src/index.ts b/packages/form-handlers/src/index.ts
index 27190e8eef..448db2f464 100644
--- a/packages/form-handlers/src/index.ts
+++ b/packages/form-handlers/src/index.ts
@@ -1,2 +1,2 @@
-export { formIdFieldName, getFormId } from "./shared";
+export { formIdFieldName, formBotFieldName } from "./shared";
export { n8nHandler } from "./n8n";
diff --git a/packages/form-handlers/src/n8n.ts b/packages/form-handlers/src/n8n.ts
index 18c73cb66f..22fa52e972 100644
--- a/packages/form-handlers/src/n8n.ts
+++ b/packages/form-handlers/src/n8n.ts
@@ -5,7 +5,7 @@ import {
getFormEntries,
getErrors,
getResponseBody,
- getFormId,
+ formIdFieldName,
} from "./shared";
const getAuth = (hookUrl: string) => {
@@ -40,7 +40,7 @@ export const n8nHandler = async ({
headers["Authorization"] = `Basic ${btoa([username, password].join(":"))}`;
}
- const formId = getFormId(formInfo.formData);
+ const formId = formInfo.formData.get(formIdFieldName);
if (formId === undefined) {
return { success: false, errors: ["No form id in FormData"] };
diff --git a/packages/form-handlers/src/shared.ts b/packages/form-handlers/src/shared.ts
index a4de2bb069..9742deca72 100644
--- a/packages/form-handlers/src/shared.ts
+++ b/packages/form-handlers/src/shared.ts
@@ -1,5 +1,7 @@
const formHiddenFieldPrefix = "ws--form";
export const formIdFieldName = `${formHiddenFieldPrefix}-id`;
+// Used for simlpe protection against non js bots
+export const formBotFieldName = `${formHiddenFieldPrefix}-bot`;
// Input data common for all handlers
export type FormInfo = {
@@ -32,14 +34,6 @@ export const getFormEntries = (formData: FormData): [string, string][] =>
: []
);
-export const getFormId = (formData: FormData) => {
- for (const [key, value] of formData.entries()) {
- if (key === formIdFieldName && typeof value === "string") {
- return value;
- }
- }
-};
-
const getDomain = (url: string) => {
try {
return new URL(url).hostname;
diff --git a/packages/sdk-components-react-remix/src/webhook-form.tsx b/packages/sdk-components-react-remix/src/webhook-form.tsx
index 96f648fe61..0f244bae57 100644
--- a/packages/sdk-components-react-remix/src/webhook-form.tsx
+++ b/packages/sdk-components-react-remix/src/webhook-form.tsx
@@ -8,6 +8,7 @@ import {
import { useFetcher, type Fetcher, type FormProps } from "@remix-run/react";
import { formIdFieldName } from "@webstudio-is/form-handlers";
import { getInstanceIdFromComponentProps } from "@webstudio-is/react-sdk";
+import { formBotFieldName } from "../../form-handlers/src/shared";
export const defaultTag = "form";
@@ -33,6 +34,50 @@ const useOnFetchEnd = <Data,>(
type State = "initial" | "success" | "error";
+// gcd - greatest common divisor
+const gcd = (a: number, b: number): number => (b === 0 ? a : gcd(b, a % b));
+
+const getAspectRatioString = (width: number, height: number) => {
+ const r = gcd(width, height);
+ const aspectRatio = `${width / r}/${height / r}`;
+ return aspectRatio;
+};
+
+/**
+ * jsdom detector, trying to check that matchMedia is working (jsdom has no support of matchMedia and usually simple stub is used)
+ */
+const isJSDom = () => {
+ if (typeof matchMedia === "undefined") {
+ return true;
+ }
+
+ const { width, height } = screen;
+ const deviceAspectRatio = getAspectRatioString(width, height);
+
+ const matchAspectRatio = matchMedia(
+ `(device-aspect-ratio: ${deviceAspectRatio})`
+ ).matches;
+
+ const matchWidthHeight = matchMedia(
+ `(device-width: ${width}px) and (device-height: ${height}px)`
+ ).matches;
+
+ const matchWidthHeightFail = matchMedia(
+ `(device-width: ${width - 1}px) and (device-height: ${height}px)`
+ ).matches;
+
+ const matchLight = matchMedia("(prefers-color-scheme: light)").matches;
+ const matchDark = matchMedia("(prefers-color-scheme: dark)").matches;
+
+ const hasMatchMedia =
+ matchAspectRatio &&
+ matchWidthHeight &&
+ !matchWidthHeightFail &&
+ matchLight !== matchDark;
+
+ return hasMatchMedia === false;
+};
+
export const WebhookForm = forwardRef<
ElementRef<typeof defaultTag>,
ComponentProps<typeof defaultTag> & {
@@ -55,8 +100,29 @@ export const WebhookForm = forwardRef<
onStateChange?.(state);
});
+ /**
+ * Add hidden field generated using js with simple jsdom detector.
+ * This is used to protect form submission against very simple bots.
+ */
+ const handleSubmitAndAddHiddenJsField = (
+ event: React.FormEvent<HTMLFormElement>
+ ) => {
+ const hiddenInput = document.createElement("input");
+ hiddenInput.type = "hidden";
+ hiddenInput.name = formBotFieldName;
+ // Non-numeric values are utilized for logging purposes.
+ hiddenInput.value = isJSDom() ? "jsdom" : Date.now().toString(16);
+ event.currentTarget.appendChild(hiddenInput);
+ };
+
return (
- <fetcher.Form {...rest} method="post" data-state={state} ref={ref}>
+ <fetcher.Form
+ {...rest}
+ method="post"
+ data-state={state}
+ ref={ref}
+ onSubmit={handleSubmitAndAddHiddenJsField}
+ >
<input type="hidden" name={formIdFieldName} value={instanceId} />
{children}
</fetcher.Form>