feat: Enhance private link expiration with usage and date limits (#22304)

* init

* fix type

* fix a re-render infinite loop because of missing readOnly (╯°□°)╯︵ ┻━┻)

* further fixes

* improvement

* fix expiry datetime check

* remove unnecessary prismaMock def

* revert

* fix test

* add test ids

* remove unit tests in favor of e2e

* e2e test update

* fix e2e

* fix e2e

* remove unnecessary change

* abstract into injectable object

* further improvements

* fix label not selecting radio

* fix type

* code improvement

* DI implementation

* fix type

* fix quick copy

* code improvement and a few fixes

* further improvements and NITS

* further into DI

* select

* improve link list sorting

* prep for easier conflict resolution

* add back translations

* using useCopy instead

* improvement

* add index to update salt and have different hash generation

* fix private link description

* fix increment regression in expiry logic

* fixes

* address feedback

* use extractHostTimezone in event type listing

* remove unused function

* remove translationBundler

* -_-

* address feedback

* further changes

* address more feedback

* NIT

* address improvement suggestions

* use extractHostTimezone

* remove console log

* pre update

* code improvement

* further fixes

* cleanup

* -_-
This commit is contained in:
Syed Ali Shahbaz authored and GitHub committed 2025-07-24 19:54:44 +01:00
1 parent b9c49b4567
commit 66b52bb19f
30 files changed
+1564 -220

No files matched your search

@@ -68,6 +68,7 @@ import { getLuckyUser } from "@calcom/lib/server/getLuckyUser";
import { getTranslation } from "@calcom/lib/server/i18n";
import { BookingRepository } from "@calcom/lib/server/repository/booking";
import { WorkflowRepository } from "@calcom/lib/server/repository/workflow";
import { HashedLinkService } from "@calcom/lib/server/service/hashedLinkService";
import { getTimeFormatStringFromUserTimeFormat } from "@calcom/lib/timeFormat";
import prisma from "@calcom/prisma";
import type { AssignmentReasonEnum } from "@calcom/prisma/enums";
@@ -2117,15 +2118,20 @@ async function handler(
}
try {
const hashedLinkService = new HashedLinkService();
if (hasHashedBookingLink && reqBody.hashedLink && !isDryRun) {
await prisma.hashedLink.delete({
where: {
link: reqBody.hashedLink as string,
},
});
await hashedLinkService.validateAndIncrementUsage(reqBody.hashedLink as string);
}
} catch (error) {
loggerWithEventDetails.error("Error while updating hashed link", JSON.stringify({ error }));
// Handle repository errors and convert to HttpErrors
if (error instanceof Error) {
throw new HttpError({ statusCode: 410, message: error.message });
}
// For unexpected errors, provide a generic message
throw new HttpError({ statusCode: 500, message: "Failed to process booking link" });
}
if (!booking) throw new HttpError({ statusCode: 400, message: "Booking failed" });
@@ -1,97 +1,420 @@
import { useAutoAnimate } from "@formkit/auto-animate/react";
import { useState } from "react";
import { Controller, useFormContext } from "react-hook-form";
import dayjs from "@calcom/dayjs";
import type { EventTypeSetupProps } from "@calcom/features/eventtypes/lib/types";
import type { FormValues } from "@calcom/features/eventtypes/lib/types";
import type { FormValues, PrivateLinkWithOptions } from "@calcom/features/eventtypes/lib/types";
import { generateHashedLink } from "@calcom/lib/generateHashedLink";
import { isLinkExpired as utilsIsLinkExpired } from "@calcom/lib/hashedLinksUtils";
import { useCopy } from "@calcom/lib/hooks/useCopy";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Icon } from "@calcom/ui/components/icon";
import { showToast } from "@calcom/ui/components/toast";
import { trpc } from "@calcom/trpc/react";
import classNames from "@calcom/ui/classNames";
import { Badge } from "@calcom/ui/components/badge";
import { Button } from "@calcom/ui/components/button";
import { Dialog, DialogContent } from "@calcom/ui/components/dialog";
import { TextField } from "@calcom/ui/components/form";
import { DatePicker } from "@calcom/ui/components/form";
import { NumberInput } from "@calcom/ui/components/form";
import { RadioAreaGroup as RadioArea } from "@calcom/ui/components/radio";
import { showToast } from "@calcom/ui/components/toast";
import { Tooltip } from "@calcom/ui/components/tooltip";
export const MultiplePrivateLinksController = ({
team,
bookerUrl,
}: Pick<EventTypeSetupProps["eventType"], "team" | "bookerUrl">) => {
setMultiplePrivateLinksVisible,
userTimeZone,
}: Pick<EventTypeSetupProps["eventType"], "team" | "bookerUrl"> & {
setMultiplePrivateLinksVisible?: (isVisible: boolean) => void;
userTimeZone?: string;
}): JSX.Element => {
const formMethods = useFormContext<FormValues>();
const { t } = useLocale();
const { copyToClipboard } = useCopy();
const [animateRef] = useAutoAnimate<HTMLUListElement>();
const [isDialogOpen, setIsDialogOpen] = useState(false);
const [currentLinkIndex, setCurrentLinkIndex] = useState<number | null>(null);
const [selectedType, setSelectedType] = useState<"time" | "usage">("usage");
const [expiryDate, setExpiryDate] = useState<Date>(new Date());
const [maxUsageCount, setMaxUsageCount] = useState<number | null>(1);
// Updates the form data directly when settings change
const updateLinkSettings = (
index: number | null,
type: "time" | "usage",
date?: Date,
usageCount?: number | null
) => {
if (index === null) return;
const currentValue = formMethods.getValues("multiplePrivateLinks") || [];
// Convert any string values to PrivateLinkWithOptions
const convertedValue = currentValue.map((val: string | PrivateLinkWithOptions) =>
typeof val === "string" ? { link: val, expiresAt: null, maxUsageCount: 1, usageCount: 0 } : val
);
if (type === "time") {
const selectedDate = date || expiryDate;
const dateString = dayjs(selectedDate).format("YYYY-MM-DD");
const endOfDayInUTC = dayjs.utc(`${dateString}T23:59:59.999Z`).toDate();
convertedValue[index] = {
...convertedValue[index],
expiresAt: endOfDayInUTC,
maxUsageCount: null,
};
} else if (type === "usage") {
convertedValue[index] = {
...convertedValue[index],
expiresAt: null,
maxUsageCount: usageCount !== undefined ? usageCount : maxUsageCount,
};
}
// Update the form value and trigger form change
// Store the full objects so the UI can display updated settings immediately
formMethods.setValue("multiplePrivateLinks", convertedValue, {
shouldDirty: true,
shouldTouch: true,
shouldValidate: true,
});
};
const openSettingsDialog = (index: number, currentLink: PrivateLinkWithOptions) => {
setCurrentLinkIndex(index);
if (currentLink.expiresAt) {
setSelectedType("time");
const expiryDate = dayjs.utc(currentLink.expiresAt).format("YYYY-MM-DD");
setExpiryDate(dayjs(expiryDate).toDate());
} else {
setSelectedType("usage");
setMaxUsageCount(currentLink.maxUsageCount ?? 1);
}
setIsDialogOpen(true);
};
return (
<Controller
name="multiplePrivateLinks"
control={formMethods.control}
render={({ field: { value, onChange } }) => {
if (!value) {
value = [];
}
const addPrivateLink = () => {
const newPrivateLink = generateHashedLink(formMethods.getValues("users")[0]?.id ?? team?.id);
if (!value) value = [];
value.push(newPrivateLink);
onChange(value);
};
<>
<Controller
name="multiplePrivateLinks"
control={formMethods.control}
render={({ field: { value, onChange } }) => {
if (!value) {
value = [];
}
const removePrivateLink = (index: number) => {
if (!value) value = [];
value.splice(index, 1);
onChange(value);
};
// Convert any string values to PrivateLinkWithOptions
const convertedValue = value.map((val: string | PrivateLinkWithOptions) =>
typeof val === "string" ? { link: val, expiresAt: null, maxUsageCount: null, usageCount: 0 } : val
);
// Query all links at once instead of individually
const { data: allLinksData } = trpc.viewer.eventTypes.getHashedLinks.useQuery(
{ linkIds: convertedValue.map((val) => val.link) },
{
enabled: convertedValue.length > 0,
refetchOnMount: true,
}
);
type HashedLinkData = {
id: number | string;
linkId: string;
expiresAt: Date | null;
maxUsageCount: number | null;
usageCount: number;
};
const linkDataMap = new Map(allLinksData?.map((data: HashedLinkData) => [data.linkId, data]) || []);
const addPrivateLink = () => {
const userId = formMethods.getValues("users")?.[0]?.id ?? team?.id;
if (!userId) return;
const newPrivateLink = {
link: generateHashedLink(userId),
expiresAt: null,
maxUsageCount: 1,
usageCount: 0,
};
const newValue = [...convertedValue, newPrivateLink];
onChange(newValue);
};
const removePrivateLink = (index: number) => {
const newValue = [...convertedValue];
newValue.splice(index, 1);
onChange(newValue);
if (newValue.length === 0 && setMultiplePrivateLinksVisible) {
setMultiplePrivateLinksVisible(false);
}
};
const isLinkExpired = (val: PrivateLinkWithOptions) => {
const latestLinkData = linkDataMap.get(val.link);
const latestUsageCount =
latestLinkData?.usageCount ?? ((val as PrivateLinkWithOptions).usageCount || 0);
return utilsIsLinkExpired(
{
expiresAt: val.expiresAt,
maxUsageCount: val.maxUsageCount,
usageCount: latestUsageCount,
},
userTimeZone
);
};
const getLinkDescription = (link: PrivateLinkWithOptions, latestUsageCount?: number) => {
const isExpired = isLinkExpired(link);
const usageCount = latestUsageCount ?? (link.usageCount || 0);
if (link.expiresAt) {
const expiryDate = dayjs.utc(link.expiresAt).format("MMM DD, YYYY");
return isExpired
? t("link_expired_on_date", { date: expiryDate })
: t("expires_on_date", { date: expiryDate });
} else if (
link.maxUsageCount !== undefined &&
link.maxUsageCount !== null &&
!isNaN(Number(link.maxUsageCount))
) {
const maxUses = link.maxUsageCount;
const remainingUses = maxUses - usageCount;
if (isExpired) {
return t("usage_limit_reached");
} else {
return remainingUses === 1
? t("remainder_of_maximum_use_left_singular", {
remainder: remainingUses,
maximum: maxUses,
})
: t("remainder_of_maximum_uses_left_plural", {
remainder: remainingUses,
maximum: maxUses,
});
}
}
// Default case for links without expiry or usage limits
return t("remainder_of_maximum_use_left_singular", {
remainder: "1",
maximum: "1",
});
};
const sortedLinksWithIndex = convertedValue
.map((val, originalIndex) => {
const expired = isLinkExpired(val);
const hasExpiry = !!val.expiresAt;
const expiryTime = hasExpiry ? new Date(val.expiresAt!).getTime() : null;
return {
val,
originalIndex,
expired,
hasExpiry,
expiryTime,
};
})
.sort((a, b) => {
// Sort expired links last
if (a.expired !== b.expired) {
return a.expired ? 1 : -1;
}
// Both not expired
if (!a.expired && !b.expired) {
// Prefer links with expiry date
if (a.hasExpiry !== b.hasExpiry) {
return a.hasExpiry ? -1 : 1;
}
// Both have expiry, sort by expiry time
if (a.hasExpiry && b.hasExpiry) {
return a.expiryTime! - b.expiryTime!;
}
// Neither has expiry: preserve original order (descending)
return b.originalIndex - a.originalIndex;
}
// Both expired: preserve original order (ascending)
return a.originalIndex - b.originalIndex;
});
return (
<ul ref={animateRef}>
{sortedLinksWithIndex.map(({ val, originalIndex }, key) => {
const singleUseURL = `${bookerUrl}/d/${val.link}/${formMethods.getValues("slug")}`;
const latestLinkData = linkDataMap.get(val.link);
const latestUsageCount =
latestLinkData?.usageCount ?? ((val as PrivateLinkWithOptions).usageCount || 0);
const isExpired = isLinkExpired(val);
const linkDescription = getLinkDescription(val, latestUsageCount);
return (
<ul ref={animateRef}>
{value &&
value.map((val, key) => {
const singleUseURL = `${bookerUrl}/d/${val}/${formMethods.getValues("slug")}`;
return (
<li data-testid="add-single-use-link" className="mb-4 flex items-center" key={val}>
<TextField
containerClassName="w-full"
disabled
data-testid={`generated-hash-url-${key}`}
labelSrOnly
type="text"
defaultValue={singleUseURL}
addOnSuffix={
<Tooltip content={t("copy_to_clipboard")}>
<Button
color="minimal"
size="sm"
type="button"
aria-label="copy link"
onClick={() => {
navigator.clipboard.writeText(singleUseURL);
showToast(t("multiple_private_link_copied"), "success");
}}>
<Icon name="copy" className="ml-1 h-4 w-4" />
</Button>
</Tooltip>
}
/>
{value && value.length > 1 && (
<Button
data-testid={`remove-single-use-link-${key}`}
variant="icon"
StartIcon="trash-2"
color="destructive"
className="ml-2 border-none"
onClick={() => removePrivateLink(key)}
<li data-testid="add-single-use-link" className="mb-4 flex flex-col" key={val.link}>
<div className="flex items-center">
<TextField
containerClassName={classNames("w-full")}
disabled={isExpired}
value={singleUseURL}
readOnly
className={classNames(isExpired ? "bg-red-50 text-gray-400" : "bg-gray-50")}
data-testid="private-link-url"
addOnSuffix={
!isExpired ? (
<Tooltip content={t("copy_link")}>
<Button
type="button"
color="minimal"
size="sm"
StartIcon="copy"
onClick={() => {
copyToClipboard(singleUseURL);
showToast(t("link_copied"), "success");
}}
/>
</Tooltip>
) : (
<Badge data-testid="private-link-expired" variant="red">
{t("expired")}
</Badge>
)
}
/>
)}
<div className="ml-2 flex items-center">
{!isExpired && (
<Button
type="button"
color="minimal"
variant="icon"
StartIcon="settings"
data-testid="private-link-settings"
onClick={() => openSettingsDialog(originalIndex, val)}
/>
)}
<Button
data-testid={`remove-private-link-${originalIndex}`}
variant="icon"
type="button"
StartIcon="trash-2"
color="destructive"
className="ml-1 border-none"
onClick={() => removePrivateLink(originalIndex)}
/>
</div>
</div>
<div data-testid="private-link-description" className="mt-1 text-sm text-gray-500">
{linkDescription}
</div>
</li>
);
})}
<Button
color="minimal"
StartIcon="plus"
onClick={addPrivateLink}
data-testid="add-private-link-button">
{t("add_a_multiple_private_link")}
</Button>
</ul>
);
}}
/>
<Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
<DialogContent title={t("link_settings")} type="creation">
<div className="mb-4 space-y-4">
<RadioArea.Group
className="space-y-2"
value={selectedType}
data-testid="private-link-radio-group"
onValueChange={(value: "time" | "usage") => {
setSelectedType(value);
}}>
<RadioArea.Item value="usage" data-testid="private-link-usage" className="w-full text-sm">
<strong className="mb-1 block">{t("usage_based_expiration")}</strong>
<p>
{selectedType !== "usage"
? t("usage_based_generic_expiration_description")
: t(
maxUsageCount === 1
? "usage_based_expiration_description"
: "usage_based_expiration_description_plural",
{ count: maxUsageCount || 0 }
)}
</p>
{selectedType === "usage" && (
<div className="mt-2 w-[180px]">
<NumberInput
required
min={1}
data-testid="private-link-usage-count"
placeholder={t("number_of_uses")}
value={maxUsageCount === null ? "" : maxUsageCount}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
const value = e.target.value === "" ? null : parseInt(e.target.value);
if (e.target.value === "") {
setMaxUsageCount(null);
} else if (!isNaN(Number(value)) && Number(value) > 0) {
setMaxUsageCount(value);
}
}}
/>
</div>
)}
</RadioArea.Item>
<RadioArea.Item data-testid="private-link-time" value="time" className="w-full text-sm">
<strong className="mb-1 block">{t("time_based_expiration")}</strong>
{selectedType !== "time"
? t("time_based_generic_expiration_description")
: t("time_based_expiration_description", {
date: dayjs(expiryDate).format("MMM DD, YYYY"),
})}
{selectedType === "time" && (
<div className="mt-2 w-[180px]">
<DatePicker
data-testid="private-link-expiration-date"
date={expiryDate}
onDatesChange={(newDate: Date) => {
setExpiryDate(newDate);
}}
/>
</div>
)}
</RadioArea.Item>
</RadioArea.Group>
</div>
<div className="mb-4 mt-4 flex justify-end">
<Button
color="minimal"
StartIcon="plus"
onClick={addPrivateLink}
data-testid="add-single-use-link-button">
{t("add_a_multiple_private_link")}
type="button"
color="primary"
data-testid="private-link-expiration-settings-save"
onClick={() => {
// Save the changes when Save button is clicked
if (selectedType === "time") {
updateLinkSettings(currentLinkIndex, "time", expiryDate);
} else {
updateLinkSettings(currentLinkIndex, "usage", undefined, maxUsageCount);
}
setIsDialogOpen(false);
}}>
{t("save")}
</Button>
</ul>
);
}}
/>
</div>
</DialogContent>
</Dialog>
</>
);
};
@@ -40,6 +40,7 @@ import type { EventNameObjectType } from "@calcom/lib/event";
import { getEventName } from "@calcom/lib/event";
import { generateHashedLink } from "@calcom/lib/generateHashedLink";
import { checkWCAGContrastColor } from "@calcom/lib/getBrandColours";
import { extractHostTimezone } from "@calcom/lib/hashedLinksUtils";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { Prisma } from "@calcom/prisma/client";
import { SchedulingType } from "@calcom/prisma/enums";
@@ -108,7 +109,10 @@ type BookingField = z.infer<typeof fieldSchema>;
export type EventAdvancedBaseProps = Pick<EventTypeSetupProps, "eventType" | "team"> & {
user?: Partial<
Pick<RouterOutputs["viewer"]["me"]["get"], "email" | "secondaryEmails" | "theme" | "defaultBookerLayouts">
Pick<
RouterOutputs["viewer"]["me"]["get"],
"email" | "secondaryEmails" | "theme" | "defaultBookerLayouts" | "timeZone"
>
>;
isUserLoading?: boolean;
showToast: (message: string, variant: "success" | "warning" | "error") => void;
@@ -529,6 +533,14 @@ export const EventAdvancedTab = ({
}
);
const userTimeZone = extractHostTimezone({
userId: eventType.userId,
teamId: eventType.teamId,
hosts: eventType.hosts,
owner: eventType.owner,
team: eventType.team,
});
let verifiedSecondaryEmails = [
{
label: user?.email || "",
@@ -855,7 +867,12 @@ export const EventAdvancedTab = ({
}}>
{!isManagedEventType && (
<div className="border-subtle rounded-b-lg border border-t-0 p-6">
<MultiplePrivateLinksController team={team} bookerUrl={eventType.bookerUrl} />
<MultiplePrivateLinksController
team={team}
bookerUrl={eventType.bookerUrl}
setMultiplePrivateLinksVisible={setMultiplePrivateLinksVisible}
userTimeZone={userTimeZone}
/>
</div>
)}
</SettingsToggle>
+8 -1
View File
@@ -66,6 +66,13 @@ type PhoneCallConfig = {
schedulerName?: string;
};
export type PrivateLinkWithOptions = {
link: string;
expiresAt?: Date | null;
maxUsageCount?: number | null;
usageCount?: number;
};
export type FormValues = {
id: number;
title: string;
@@ -89,7 +96,7 @@ export type FormValues = {
schedulingType: SchedulingType | null;
hidden: boolean;
hideCalendarNotes: boolean;
multiplePrivateLinks: string[] | undefined;
multiplePrivateLinks: (string | PrivateLinkWithOptions)[] | undefined;
eventTypeColor: z.infer<typeof eventTypeColor>;
customReplyToEmail: string | null;
locations: EventLocation[];