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

@@ -6,9 +6,11 @@ import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
import { getBookingForReschedule, getMultipleDurationValue } from "@calcom/features/bookings/lib/get-booking";
import type { GetBookingType } from "@calcom/features/bookings/lib/get-booking";
import { orgDomainConfig } from "@calcom/features/ee/organizations/lib/orgDomains";
import { FeaturesRepository } from "@calcom/features/flags/features.repository";
import { shouldHideBrandingForTeamEvent, shouldHideBrandingForUserEvent } from "@calcom/lib/hideBranding";
import { EventRepository } from "@calcom/lib/server/repository/event";
import { UserRepository } from "@calcom/lib/server/repository/user";
import { HashedLinkService } from "@calcom/lib/server/service/hashedLinkService";
import slugify from "@calcom/lib/slugify";
import prisma from "@calcom/prisma";
import { RedirectType } from "@calcom/prisma/enums";
@@ -25,43 +27,6 @@ async function getUserPageProps(context: GetServerSidePropsContext) {
const { currentOrgDomain, isValidOrgDomain } = orgDomainConfig(context.req);
const org = isValidOrgDomain ? currentOrgDomain : null;
const hashedLink = await prisma.hashedLink.findUnique({
where: {
link,
},
select: {
eventTypeId: true,
eventType: {
select: {
users: {
select: {
username: true,
profiles: {
select: {
id: true,
organizationId: true,
username: true,
},
},
},
},
team: {
select: {
id: true,
slug: true,
hideBranding: true,
parent: {
select: {
hideBranding: true,
},
},
},
},
},
},
},
});
let name: string;
let hideBranding = false;
@@ -69,9 +34,22 @@ async function getUserPageProps(context: GetServerSidePropsContext) {
notFound: true,
} as const;
// Use centralized validation logic to avoid duplication
const hashedLinkService = new HashedLinkService();
try {
await hashedLinkService.validate(link);
} catch (error) {
// Link is expired, invalid, or doesn't exist
return notFound;
}
// If validation passes, fetch the complete data needed for rendering
const hashedLink = await hashedLinkService.findLinkWithDetails(link);
if (!hashedLink) {
return notFound;
}
const username = hashedLink.eventType.users[0]?.username;
const profileUsername = hashedLink.eventType.users[0]?.profiles[0]?.username;
@@ -139,8 +117,20 @@ async function getUserPageProps(context: GetServerSidePropsContext) {
return notFound;
}
// Check if team has API v2 feature flag enabled (same logic as team pages)
let useApiV2 = false;
if (isTeamEvent && hashedLink.eventType.team?.id) {
const featureRepo = new FeaturesRepository();
const teamHasApiV2Route = await featureRepo.checkIfTeamHasFeature(
hashedLink.eventType.team.id,
"use-api-v2-for-team-slots"
);
useApiV2 = teamHasApiV2Route;
}
return {
props: {
useApiV2,
eventData,
entity: eventData.entity,
duration: getMultipleDurationValue(
@@ -156,7 +146,7 @@ async function getUserPageProps(context: GetServerSidePropsContext) {
// Sending the team event from the server, because this template file
// is reused for both team and user events.
isTeamEvent,
hashedLink: link,
hashedLink: hashedLink?.link,
},
};
}
@@ -19,6 +19,7 @@ export default function Type({
hashedLink,
durationConfig,
eventData,
useApiV2,
}: PageProps) {
return (
<BookingPageErrorBoundary>
@@ -34,6 +35,7 @@ export default function Type({
duration={duration}
hashedLink={hashedLink}
durationConfig={durationConfig}
useApiV2={useApiV2}
/>
</main>
</BookingPageErrorBoundary>
@@ -16,6 +16,8 @@ import CreateEventTypeDialog from "@calcom/features/eventtypes/components/Create
import { DuplicateDialog } from "@calcom/features/eventtypes/components/DuplicateDialog";
import { InfiniteSkeletonLoader } from "@calcom/features/eventtypes/components/SkeletonLoader";
import { APP_NAME, WEBSITE_URL } from "@calcom/lib/constants";
import { extractHostTimezone } from "@calcom/lib/hashedLinksUtils";
import { filterActiveLinks } from "@calcom/lib/hashedLinksUtils";
import { useCopy } from "@calcom/lib/hooks/useCopy";
import { useDebounce } from "@calcom/lib/hooks/useDebounce";
import { useInViewObserver } from "@calcom/lib/hooks/useInViewObserver";
@@ -467,6 +469,14 @@ export const InfiniteEventTypeList = ({
return deleteDialogTypeSchedulingType === SchedulingType.MANAGED ? "_managed" : "";
};
const userTimezone = extractHostTimezone({
userId: firstItem.userId,
teamId: firstItem?.teamId,
hosts: firstItem?.hosts,
owner: firstItem?.owner,
team: firstItem?.team,
});
return (
<div className="bg-default border-subtle flex flex-col overflow-hidden rounded-md border">
<ul ref={parent} className="divide-subtle !static w-full divide-y" data-testid="event-types">
@@ -474,11 +484,17 @@ export const InfiniteEventTypeList = ({
return page?.eventTypes?.map((type, index) => {
const embedLink = `${group.profile.slug}/${type.slug}`;
const calLink = `${bookerUrl}/${embedLink}`;
const activeHashedLinks = type.hashedLink ? filterActiveLinks(type.hashedLink, userTimezone) : [];
// Ensure index is within bounds for active links
const currentIndex = privateLinkCopyIndices[type.slug] ?? 0;
const safeIndex = activeHashedLinks.length > 0 ? currentIndex % activeHashedLinks.length : 0;
const isPrivateURLEnabled =
type.hashedLink && type.hashedLink.length > 0
? type.hashedLink[privateLinkCopyIndices[type.slug] ?? 0]?.link
: "";
activeHashedLinks.length > 0 ? activeHashedLinks[safeIndex]?.link : "";
const placeholderHashedLink = `${bookerUrl}/d/${isPrivateURLEnabled}/${type.slug}`;
const isManagedEventType = type.schedulingType === SchedulingType.MANAGED;
const isChildrenManagedEventType =
type.metadata?.managedEventConfig !== undefined &&
@@ -580,8 +596,8 @@ export const InfiniteEventTypeList = ({
copyToClipboard(placeholderHashedLink);
setPrivateLinkCopyIndices((prev) => {
const prevIndex = prev[type.slug] ?? 0;
prev[type.slug] = (prevIndex + 1) % type.hashedLink.length;
return prev;
const nextIndex = (prevIndex + 1) % activeHashedLinks.length;
return { ...prev, [type.slug]: nextIndex };
});
}}
/>
+147 -29
View File
@@ -7,10 +7,9 @@ import {
submitAndWaitForResponse,
} from "./lib/testUtils";
test.describe.configure({ mode: "parallel" });
test.describe.configure({ mode: "serial" });
// TODO: This test is very flaky. Feels like tossing a coin and hope that it won't fail. Needs to be revisited.
test.describe("hash my url", () => {
test.describe("private links creation and usage", () => {
test.beforeEach(async ({ users }) => {
const user = await users.create();
await user.apiLogin();
@@ -18,25 +17,29 @@ test.describe("hash my url", () => {
test.afterEach(async ({ users }) => {
await users.deleteAll();
});
test("generate url hash", async ({ page }) => {
test("generate private link and make a booking with it", async ({ page }) => {
await page.goto("/event-types");
// We wait until loading is finished
await page.waitForSelector('[data-testid="event-types"]');
await page.locator("ul[data-testid=event-types] > li a").first().click();
await expect(page.getByTestId("vertical-tab-event_setup_tab_title")).toHaveAttribute(
"aria-current",
"page"
); // fix the race condition
await expect(page.getByTestId("vertical-tab-event_setup_tab_title")).toContainText("Event Setup"); //fix the race condition
await Promise.all([
page.waitForURL("**/event-types"),
page.getByTestId("event-types").locator("li a").first().click(),
]);
await expect(page.locator("[data-testid=event-title]")).toBeVisible();
// We wait for the page to load
await page.locator(".primary-navigation >> text=Advanced").click();
await page.locator("[data-testid=vertical-tab-event_advanced_tab_title]").click();
const hashedLinkCheck = page.locator('[data-testid="multiplePrivateLinksCheck"]');
await expect(hashedLinkCheck).toBeVisible();
// ignore if it is already checked, and click if unchecked
const hashedLinkCheck = await page.locator('[data-testid="multiplePrivateLinksCheck"]');
if (!(await hashedLinkCheck.isChecked())) {
await hashedLinkCheck.click();
}
await hashedLinkCheck.click();
// we wait for the hashedLink setting to load
const $url = await page.locator('//*[@data-testid="generated-hash-url-0"]').inputValue();
// Wait for the private link URL input to be visible and get its value
const $url = await page.locator('[data-testid="private-link-url"]').inputValue();
// click update
await submitAndWaitForResponse(page, "/api/trpc/eventTypes/update?batch=1", {
@@ -47,33 +50,148 @@ test.describe("hash my url", () => {
await selectFirstAvailableTimeSlotNextMonth(page);
await bookTimeSlot(page);
// Make sure we're navigated to the success page
await expect(page.locator("[data-testid=success-page]")).toBeVisible();
const successPage = page.getByTestId("success-page");
await expect(successPage).toBeVisible();
// hash regenerates after successful booking
// hash regenerates after successful booking (only for usage-based links)
await page.goto("/event-types");
// We wait until loading is finished
await page.waitForSelector('[data-testid="event-types"]');
await page.reload(); // ensure fresh state
await page.locator("ul[data-testid=event-types] > li a").first().click();
// We wait for the page to load
await page.locator(".primary-navigation >> text=Advanced").click();
await page.locator("[data-testid=vertical-tab-event_advanced_tab_title]").click();
const hashedLinkCheck2 = await page.locator('[data-testid="multiplePrivateLinksCheck"]');
await hashedLinkCheck2.click();
// we wait for the hashedLink setting to load
const $newUrl = await page.locator('//*[@data-testid="generated-hash-url-0"]').inputValue();
expect($url !== $newUrl).toBeTruthy();
// After booking with a usage-based private link, the link should be expired
await expect(page.locator('[data-testid="private-link-description"]')).toContainText(
"Usage limit reached"
);
// Ensure that private URL is enabled after modifying the event type.
// Additionally, if the slug is changed, ensure that the private URL is updated accordingly.
await page.getByTestId("vertical-tab-event_setup_tab_title").click();
await page.locator("[data-testid=event-title]").first().fill("somethingrandom");
await page.locator("[data-testid=event-slug]").first().fill("somethingrandom");
await expect(page.locator('[data-testid="event-slug"]').first()).toHaveValue("somethingrandom");
await submitAndWaitForResponse(page, "/api/trpc/eventTypes/update?batch=1", {
action: () => page.locator("[data-testid=update-eventtype]").click(),
});
await page.locator(".primary-navigation >> text=Advanced").click();
const $url2 = await page.locator('//*[@data-testid="generated-hash-url-0"]').inputValue();
await page.locator("[data-testid=vertical-tab-event_advanced_tab_title]").click();
// Wait for the private link URL input to be visible and get its value
const $url2 = await page.locator('[data-testid="private-link-url"]').inputValue();
expect($url2.includes("somethingrandom")).toBeTruthy();
});
test("generate private link with future expiration date and make a booking with it", async ({ page }) => {
await page.goto("/event-types");
// We wait until loading is finished
await Promise.all([
page.waitForURL("**/event-types"),
page.getByTestId("event-types").locator("li a").first().click(),
]);
await expect(page.locator("[data-testid=event-title]")).toBeVisible();
// We wait for the page to load
await page.locator("[data-testid=vertical-tab-event_advanced_tab_title]").click();
const privateLinkCheck = page.locator('[data-testid="multiplePrivateLinksCheck"]');
await expect(privateLinkCheck).toBeVisible();
// ignore if it is already checked, and click if unchecked
if (!(await privateLinkCheck.isChecked())) {
await privateLinkCheck.click();
}
// Wait for the private link URL input to be visible and get its value
const $url = await page.locator('[data-testid="private-link-url"]').inputValue();
await page.locator('[data-testid="private-link-settings"]').click();
await expect(page.locator('[data-testid="private-link-radio-group"]')).toBeVisible();
await page.locator('[data-testid="private-link-time"]').click();
await page.locator('[data-testid="private-link-expiration-settings-save"]').click();
await page.waitForLoadState("networkidle");
// click update
await submitAndWaitForResponse(page, "/api/trpc/eventTypes/update?batch=1", {
action: () => page.locator("[data-testid=update-eventtype]").click(),
});
// book using generated url hash
await page.goto($url);
await selectFirstAvailableTimeSlotNextMonth(page);
await bookTimeSlot(page);
// Make sure we're navigated to the success page
await expect(page.getByTestId("success-page")).toBeVisible();
// hash regenerates after successful booking (only for usage-based links)
await page.goto("/event-types");
await page.waitForSelector('[data-testid="event-types"]');
await page.reload(); // ensure fresh state
await page.locator("ul[data-testid=event-types] > li a").first().click();
// We wait for the page to load
await page.locator("[data-testid=vertical-tab-event_advanced_tab_title]").click();
// After booking with a expiration date based private link, the link should still be valid
await expect(page.locator('[data-testid="private-link-expired"]')).toBeHidden();
});
test("generate private link with 2 usages and make 2 bookings with it", async ({ page }) => {
await page.goto("/event-types");
// We wait until loading is finished
await Promise.all([
page.waitForURL("**/event-types"),
page.getByTestId("event-types").locator("li a").first().click(),
]);
await expect(page.locator("[data-testid=event-title]")).toBeVisible();
// We wait for the page to load
await page.locator("[data-testid=vertical-tab-event_advanced_tab_title]").click();
const privateLinkCheck = page.locator('[data-testid="multiplePrivateLinksCheck"]');
await expect(privateLinkCheck).toBeVisible();
// ignore if it is already checked, and click if unchecked
if (!(await privateLinkCheck.isChecked())) {
await privateLinkCheck.click();
}
// Wait for the private link URL input to be visible and get its value
const $url = await page.locator('[data-testid="private-link-url"]').inputValue();
await page.locator('[data-testid="private-link-settings"]').click();
await expect(page.locator('[data-testid="private-link-radio-group"]')).toBeVisible();
await page.locator('[data-testid="private-link-usage-count"]').fill("2");
await page.locator('[data-testid="private-link-expiration-settings-save"]').click();
await page.waitForLoadState("networkidle");
// click update
await submitAndWaitForResponse(page, "/api/trpc/eventTypes/update?batch=1", {
action: () => page.locator("[data-testid=update-eventtype]").click(),
});
// book using generated url hash
await page.goto($url);
await selectFirstAvailableTimeSlotNextMonth(page);
await bookTimeSlot(page);
// Make sure we're navigated to the success page
await expect(page.getByTestId("success-page")).toBeVisible();
// book again using generated url hash
await page.goto($url);
await selectFirstAvailableTimeSlotNextMonth(page);
await bookTimeSlot(page);
// Make sure we're navigated to the success page
await expect(page.getByTestId("success-page")).toBeVisible();
await page.goto("/event-types");
await page.waitForSelector('[data-testid="event-types"]');
await page.reload(); // ensure fresh state
await page.locator("ul[data-testid=event-types] > li a").first().click();
// We wait for the page to load
await page.locator("[data-testid=vertical-tab-event_advanced_tab_title]").click();
// After booking twice with a 2 usages based private link, the link should be expired
await expect(page.locator('[data-testid="private-link-description"]')).toContainText(
"Usage limit reached"
);
});
});
+23 -1
View File
@@ -961,7 +961,7 @@
"copy_private_link_to_event": "Copy private link to event",
"private_link_description": "Generate a private URL to share without exposing your {{appName}} username",
"multiple_private_links_title": "Private Links",
"multiple_private_links_description": "Generate private URLs without exposing the username, which will be destroyed once used",
"multiple_private_links_description": "Generate private URLs without exposing the username, with configurable expiry and usage limits",
"add_a_multiple_private_link": "Add new link",
"multiple_private_link_copied": "Private link copied",
"invitees_can_schedule": "Invitees can schedule",
@@ -2511,6 +2511,9 @@
"extensive_whitelabeling": "Extensive Whitelabeling",
"extensive_whitelabeling_description": "Customize your scheduling experience with your own logo, colors, and more",
"unlimited_teams": "Unlimited Teams",
"verify_email": "Verify email",
"proceed_with_cancellation_description": "Please enter the email address used for this booking to proceed with cancellation",
"proceed_with_cancellation_error": "Email doesn't match the booking email",
"unlimited_teams_description": "Add as many subteams as you need to your organization",
"unified_billing": "Unified Billing",
"advanced_managed_events": "Advanced Managed Event Types",
@@ -3396,5 +3399,24 @@
"error_deleting_cache": "Error deleting cache",
"confirm_delete_cache": "Are you sure you want to delete the cached data? This action cannot be undone.",
"yes_delete_cache": "Yes, delete cache",
"remainder_of_maximum_uses_left_plural": "{{remainder}} of {{maximum}} uses left",
"remainder_of_maximum_use_left_singular": "{{remainder}} of {{maximum}} use left",
"expires_on_date": "Expires on {{date}}, end of day",
"single_use": "Single use",
"time_based_expiration": "Time-based expiration",
"usage_based_expiration": "Usage-based expiration",
"number_of_uses": "Number of uses",
"expires_on": "Expires on",
"max_usage_count": "Maximum number of uses",
"link_settings": "Link Settings",
"link_expired_on_date": "This link expired on {{date}}, end of day",
"usage_limit_reached": "Usage limit reached",
"usage_count_error": "Maximum usage count must be greater than current usage count",
"private_link_expired": "This link has expired",
"time_based_expiration_description": "This link can be used for bookings until the end of {{date}}",
"time_based_generic_expiration_description": "This link can be configured to expire after a set date",
"usage_based_expiration_description": "This link can be used for {{count}} booking",
"usage_based_generic_expiration_description": "This link can be configured to expire after a set number of bookings",
"usage_based_expiration_description_plural": "This link can be used for {{count}} bookings",
"ADD_NEW_STRINGS_ABOVE_THIS_LINE_TO_PREVENT_MERGE_CONFLICTS": "↑↑↑↑↑↑↑↑↑↑↑↑↑ Add your new strings above here ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑"
}
@@ -8,7 +8,16 @@ describe("Tests to Check if Event Types have empty Assignment", () => {
checkForEmptyAssignment({
assignedUsers: [],
assignAllTeamMembers: false,
hosts: [{ userId: 101, isFixed: false, priority: 2, weight: 100, scheduleId: null }],
hosts: [
{
userId: 101,
isFixed: false,
priority: 2,
weight: 100,
scheduleId: null,
user: { timeZone: "America/New_York" },
},
],
isManagedEventType: true,
})
).toBe(true);
@@ -61,7 +70,16 @@ describe("Tests to Check if Event Types have empty Assignment", () => {
checkForEmptyAssignment({
assignedUsers: [],
assignAllTeamMembers: false,
hosts: [{ userId: 101, isFixed: false, priority: 2, weight: 100, scheduleId: null }],
hosts: [
{
userId: 101,
isFixed: false,
priority: 2,
weight: 100,
scheduleId: null,
user: { timeZone: "America/New_York" },
},
],
isManagedEventType: false,
})
).toBe(false);
@@ -94,7 +112,16 @@ describe("Tests to Check if Event Types have empty Assignment", () => {
},
],
assignAllTeamMembers: false,
hosts: [],
hosts: [
{
userId: 101,
isFixed: false,
priority: 2,
weight: 100,
scheduleId: null,
user: { timeZone: "America/New_York" },
},
],
isManagedEventType: true,
})
).toBe(false);