Skip to content

Scheduling infrastructure for absolutely everyone.

feat: Use Cloudflare Turnstile in booker (#18755)

Keith Williams3eb5490df956
diff --git a/.env.example b/.env.example
index 3a67898313d..00feb50d8bc 100644
--- a/.env.example
+++ b/.env.example
@@ -242,6 +242,7 @@ E2E_TEST_MAILHOG_ENABLED=
# Cloudflare Turnstile
NEXT_PUBLIC_CLOUDFLARE_SITEKEY=
+NEXT_PUBLIC_CLOUDFLARE_USE_TURNSTILE_IN_BOOKER=
CLOUDFLARE_TURNSTILE_SECRET=
# Set the following value to true if you wish to enable Team Impersonation
diff --git a/apps/web/modules/signup-view.tsx b/apps/web/modules/signup-view.tsx
index a573bb3ce36..84e2abca13c 100644
--- a/apps/web/modules/signup-view.tsx
+++ b/apps/web/modules/signup-view.tsx
@@ -58,7 +58,7 @@ const signupSchema = apiSignupSchema.extend({
cfToken: z.string().optional(),
});
-const TurnstileCaptcha = dynamic(() => import("@components/auth/Turnstile"), { ssr: false });
+const TurnstileCaptcha = dynamic(() => import("@calcom/features/auth/Turnstile"), { ssr: false });
type FormValues = z.infer<typeof signupSchema>;
diff --git a/apps/web/pages/api/book/event.ts b/apps/web/pages/api/book/event.ts
index 21654b543e7..222e675fa72 100644
--- a/apps/web/pages/api/book/event.ts
+++ b/apps/web/pages/api/book/event.ts
@@ -6,10 +6,18 @@ import handleNewBooking from "@calcom/features/bookings/lib/handleNewBooking";
import { checkRateLimitAndThrowError } from "@calcom/lib/checkRateLimitAndThrowError";
import getIP from "@calcom/lib/getIP";
import { defaultResponder } from "@calcom/lib/server";
+import { checkCfTurnstileToken } from "@calcom/lib/server/checkCfTurnstileToken";
async function handler(req: NextApiRequest & { userId?: number }, res: NextApiResponse) {
const userIp = getIP(req);
+ if (process.env.NEXT_PUBLIC_CLOUDFLARE_USE_TURNSTILE_IN_BOOKER === "1") {
+ await checkCfTurnstileToken({
+ token: req.body["cfToken"] as string,
+ remoteIp: userIp,
+ });
+ }
+
await checkRateLimitAndThrowError({
rateLimitingType: "core",
identifier: userIp,
diff --git a/apps/web/pages/api/book/recurring-event.ts b/apps/web/pages/api/book/recurring-event.ts
index 196c773d482..3cdc3e28c3a 100644
--- a/apps/web/pages/api/book/recurring-event.ts
+++ b/apps/web/pages/api/book/recurring-event.ts
@@ -6,12 +6,20 @@ import type { BookingResponse } from "@calcom/features/bookings/types";
import { checkRateLimitAndThrowError } from "@calcom/lib/checkRateLimitAndThrowError";
import getIP from "@calcom/lib/getIP";
import { defaultResponder } from "@calcom/lib/server";
+import { checkCfTurnstileToken } from "@calcom/lib/server/checkCfTurnstileToken";
// @TODO: Didn't look at the contents of this function in order to not break old booking page.
async function handler(req: NextApiRequest & { userId?: number }, res: NextApiResponse) {
const userIp = getIP(req);
+ if (process.env.NEXT_PUBLIC_CLOUDFLARE_USE_TURNSTILE_IN_BOOKER === "1") {
+ await checkCfTurnstileToken({
+ token: req.body[0]["cfToken"] as string,
+ remoteIp: userIp,
+ });
+ }
+
await checkRateLimitAndThrowError({
rateLimitingType: "core",
identifier: userIp,
diff --git a/apps/web/components/auth/Turnstile.tsx b/packages/features/auth/Turnstile.tsx
similarity index 100%
rename from apps/web/components/auth/Turnstile.tsx
rename to packages/features/auth/Turnstile.tsx
diff --git a/packages/features/bookings/Booker/Booker.tsx b/packages/features/bookings/Booker/Booker.tsx
index 4cd6355e6e2..726fcd840d0 100644
--- a/packages/features/bookings/Booker/Booker.tsx
+++ b/packages/features/bookings/Booker/Booker.tsx
@@ -72,6 +72,7 @@ const BookerComponent = ({
areInstantMeetingParametersSet = false,
userLocale,
hasValidLicense,
+ renderCaptcha,
}: BookerProps & WrappedBookerProps) => {
const searchParams = useCompatSearchParams();
const isPlatformBookerEmbed = useIsPlatformBookerEmbed();
@@ -166,6 +167,7 @@ const BookerComponent = ({
return bookerState === "booking" ? (
<BookEventForm
key={key}
+ renderCaptcha={renderCaptcha}
onCancel={() => {
setSelectedTimeslot(null);
if (seatedEventData.bookingUid) {
diff --git a/packages/features/bookings/Booker/components/BookEventForm/BookEventForm.tsx b/packages/features/bookings/Booker/components/BookEventForm/BookEventForm.tsx
index fca672531db..612ac7c7123 100644
--- a/packages/features/bookings/Booker/components/BookEventForm/BookEventForm.tsx
+++ b/packages/features/bookings/Booker/components/BookEventForm/BookEventForm.tsx
@@ -1,12 +1,18 @@
import type { TFunction } from "next-i18next";
import { Trans } from "next-i18next";
+import dynamic from "next/dynamic";
import Link from "next/link";
import { useMemo, useState } from "react";
import type { FieldError } from "react-hook-form";
import { useIsPlatformBookerEmbed } from "@calcom/atoms/monorepo";
import type { BookerEvent } from "@calcom/features/bookings/types";
-import { WEBSITE_PRIVACY_POLICY_URL, WEBSITE_TERMS_URL } from "@calcom/lib/constants";
+import {
+ WEBSITE_PRIVACY_POLICY_URL,
+ WEBSITE_TERMS_URL,
+ CLOUDFLARE_SITE_ID,
+ CLOUDFLARE_USE_TURNSTILE_IN_BOOKER,
+} from "@calcom/lib/constants";
import { getPaymentAppData } from "@calcom/lib/getPaymentAppData";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Alert, Button, EmptyScreen, Form } from "@calcom/ui";
@@ -17,6 +23,8 @@ import type { IUseBookingErrors, IUseBookingLoadingStates } from "../hooks/useBo
import { BookingFields } from "./BookingFields";
import { FormSkeleton } from "./Skeleton";
+const TurnstileCaptcha = dynamic(() => import("@calcom/features/auth/Turnstile"), { ssr: false });
+
type BookEventFormProps = {
onCancel?: () => void;
onSubmit: () => void;
@@ -29,6 +37,7 @@ type BookEventFormProps = {
extraOptions: Record<string, string | string[]>;
isPlatform?: boolean;
isVerificationCodeSending: boolean;
+ renderCaptcha?: boolean;
};
export const BookEventForm = ({
@@ -45,6 +54,7 @@ export const BookEventForm = ({
extraOptions,
isVerificationCodeSending,
isPlatform = false,
+ renderCaptcha,
}: Omit<BookEventFormProps, "event"> & {
eventQuery: {
isError: boolean;
@@ -61,6 +71,10 @@ export const BookEventForm = ({
const isInstantMeeting = useBookerStore((state) => state.isInstantMeeting);
const isPlatformBookerEmbed = useIsPlatformBookerEmbed();
+ // Cloudflare Turnstile Captcha
+ const shouldRenderCaptcha =
+ renderCaptcha && CLOUDFLARE_SITE_ID && CLOUDFLARE_USE_TURNSTILE_IN_BOOKER === "1";
+
const [responseVercelIdHeader] = useState<string | null>(null);
const { t } = useLocale();
@@ -88,6 +102,8 @@ export const BookEventForm = ({
return <Alert severity="warning" message={t("error_booking_event")} />;
}
+ const watchedCfToken = bookingForm.watch("cfToken");
+
return (
<div className="flex h-full flex-col">
<Form
@@ -120,6 +136,15 @@ export const BookEventForm = ({
/>
</div>
)}
+ {/* Cloudflare Turnstile Captcha */}
+ {shouldRenderCaptcha ? (
+ <TurnstileCaptcha
+ appearance="interaction-only"
+ onVerify={(token) => {
+ bookingForm.setValue("cfToken", token);
+ }}
+ />
+ ) : null}
{!isPlatform && (
<div className="text-subtle my-3 w-full text-xs">
<Trans
@@ -143,6 +168,7 @@ export const BookEventForm = ({
/>
</div>
)}
+
{isPlatformBookerEmbed && (
<div className="text-subtle my-3 w-full text-xs">
{t("proceeding_agreement")}{" "}
@@ -176,9 +202,11 @@ export const BookEventForm = ({
{t("back")}
</Button>
)}
+
<Button
type="submit"
color="primary"
+ disabled={!!shouldRenderCaptcha && !watchedCfToken}
loading={
loadingStates.creatingBooking ||
loadingStates.creatingRecurringBooking ||
diff --git a/packages/features/bookings/Booker/components/hooks/useBookingForm.ts b/packages/features/bookings/Booker/components/hooks/useBookingForm.ts
index 6f318dc6f4f..65711da11e9 100644
--- a/packages/features/bookings/Booker/components/hooks/useBookingForm.ts
+++ b/packages/features/bookings/Booker/components/hooks/useBookingForm.ts
@@ -60,6 +60,7 @@ export const useBookingForm = ({
// Key is not really part of form values, but only used to have a key
// to set generic error messages on. Needed until RHF has implemented root error keys.
globalError: undefined;
+ cfToken?: string;
};
const isRescheduling = !!rescheduleUid && !!bookingData;
diff --git a/packages/features/bookings/Booker/types.ts b/packages/features/bookings/Booker/types.ts
index 8e598408513..8a08aed307e 100644
--- a/packages/features/bookings/Booker/types.ts
+++ b/packages/features/bookings/Booker/types.ts
@@ -118,6 +118,7 @@ export type WrappedBookerPropsMain = {
bookerLayout: UseBookerLayoutType;
verifyEmail: UseVerifyEmailReturnType;
customClassNames?: CustomClassNames;
+ renderCaptcha?: boolean;
};
export type WrappedBookerPropsForPlatform = WrappedBookerPropsMain & {
diff --git a/packages/lib/constants.ts b/packages/lib/constants.ts
index b87396279c3..4b70fa2f2d9 100644
--- a/packages/lib/constants.ts
+++ b/packages/lib/constants.ts
@@ -159,6 +159,7 @@ export const BOOKER_NUMBER_OF_DAYS_TO_LOAD = parseInt(
);
export const CLOUDFLARE_SITE_ID = process.env.NEXT_PUBLIC_CLOUDFLARE_SITEKEY;
+export const CLOUDFLARE_USE_TURNSTILE_IN_BOOKER = process.env.NEXT_PUBLIC_CLOUDFLARE_USE_TURNSTILE_IN_BOOKER;
export const MINIMUM_NUMBER_OF_ORG_SEATS = 30;
export const ORG_SELF_SERVE_ENABLED = process.env.NEXT_PUBLIC_ORG_SELF_SERVE_ENABLED === "1";
export const ORG_MINIMUM_PUBLISHED_TEAMS_SELF_SERVE = 0;
diff --git a/packages/lib/server/checkCfTurnstileToken.ts b/packages/lib/server/checkCfTurnstileToken.ts
index 7ea6531d753..7a807186698 100644
--- a/packages/lib/server/checkCfTurnstileToken.ts
+++ b/packages/lib/server/checkCfTurnstileToken.ts
@@ -3,7 +3,7 @@ import { HttpError } from "../http-error";
const TURNSTILE_SECRET_ID = process.env.CLOUDFLARE_TURNSTILE_SECRET;
export async function checkCfTurnstileToken({ token, remoteIp }: { token?: string; remoteIp: string }) {
- // This means the instant doesnt have turnstile enabled - we skip the check and just return success.
+ // This means the instance doesnt have turnstile enabled - we skip the check and just return success.
// OR the instance is running in CI so we skip these checks also
if (!TURNSTILE_SECRET_ID || !!process.env.NEXT_PUBLIC_IS_E2E) {
return {
diff --git a/packages/platform/atoms/booker/BookerWebWrapper.tsx b/packages/platform/atoms/booker/BookerWebWrapper.tsx
index b31dd516710..46a0fa0eddf 100644
--- a/packages/platform/atoms/booker/BookerWebWrapper.tsx
+++ b/packages/platform/atoms/booker/BookerWebWrapper.tsx
@@ -232,6 +232,7 @@ export const BookerWebWrapper = (props: BookerWebWrapperAtomProps) => {
isPlatform={false}
areInstantMeetingParametersSet={areInstantMeetingParametersSet}
userLocale={session?.user.locale}
+ renderCaptcha
/>
);
};
diff --git a/packages/prisma/zod-utils.ts b/packages/prisma/zod-utils.ts
index b5baa1948a3..30284792bf6 100644
--- a/packages/prisma/zod-utils.ts
+++ b/packages/prisma/zod-utils.ts
@@ -270,6 +270,7 @@ export const bookingCreateBodySchema = z.object({
routingFormResponseId: z.number().optional(),
skipContactOwner: z.boolean().optional(),
crmAppSlug: z.string().nullish().optional(),
+ cfToken: z.string().nullish().optional(),
/**
* Holds the corrected responses of the Form for a booking, provided during rerouting
diff --git a/turbo.json b/turbo.json
index 23218031831..5d73dd71355 100644
--- a/turbo.json
+++ b/turbo.json
@@ -357,6 +357,7 @@
"NEXT_PUBLIC_TEAM_IMPERSONATION",
"NEXT_PUBLIC_VERCEL_URL",
"NEXT_PUBLIC_CLOUDFLARE_SITEKEY",
+ "NEXT_PUBLIC_CLOUDFLARE_USE_TURNSTILE_IN_BOOKER",
"NEXT_PUBLIC_VERCEL_ENV",
"NEXT_PUBLIC_VERCEL_BRANCH_URL",
"NEXT_PUBLIC_GTM_ID",